blob: 8d066a0ac2b9d4d96e5c499b2596f0c3a2c926ee [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.");
Larisse Voufoef4579c2013-08-06 01:03:05 +0000955
956 // Create a local instantiation scope for this variable template, which
957 // will contain the instantiations of the template parameters.
958 LocalInstantiationScope Scope(SemaRef);
959 TemplateParameterList *TempParams = D->getTemplateParameters();
960 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
961 if (!InstParams)
962 return NULL;
963
964 VarDecl *Pattern = D->getTemplatedDecl();
965 VarTemplateDecl *PrevVarTemplate = 0;
966
967 if (Pattern->getPreviousDecl()) {
968 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
969 if (!Found.empty())
970 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
971 }
972
Richard Smithdd9459f2013-08-13 18:18:50 +0000973 VarDecl *VarInst =
974 cast_or_null<VarDecl>(VisitVarDecl(Pattern, /*ForVarTemplate=*/ true));
Larisse Voufoef4579c2013-08-06 01:03:05 +0000975
976 DeclContext *DC = Owner;
977
Larisse Voufoef4579c2013-08-06 01:03:05 +0000978 VarTemplateDecl *Inst = VarTemplateDecl::Create(
979 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
980 VarInst, PrevVarTemplate);
981 VarInst->setDescribedVarTemplate(Inst);
982
983 Inst->setAccess(D->getAccess());
984 if (!PrevVarTemplate)
985 Inst->setInstantiatedFromMemberTemplate(D);
986
987 if (D->isOutOfLine()) {
988 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
989 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
990 }
991
992 Owner->addDecl(Inst);
993
994 if (!PrevVarTemplate) {
995 // Queue up any out-of-line partial specializations of this member
996 // variable template; the client will force their instantiation once
997 // the enclosing class has been instantiated.
998 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
999 D->getPartialSpecializations(PartialSpecs);
1000 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1001 if (PartialSpecs[I]->isOutOfLine())
1002 OutOfLineVarPartialSpecs.push_back(
1003 std::make_pair(Inst, PartialSpecs[I]));
1004 }
1005
1006 return Inst;
1007}
1008
1009Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1010 VarTemplatePartialSpecializationDecl *D) {
1011 assert(D->isStaticDataMember() &&
1012 "Only static data member templates are allowed.");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001013
1014 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1015
1016 // Lookup the already-instantiated declaration and return that.
1017 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1018 assert(!Found.empty() && "Instantiation found nothing?");
1019
1020 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1021 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1022
1023 if (VarTemplatePartialSpecializationDecl *Result =
1024 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1025 return Result;
1026
1027 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1028}
1029
Douglas Gregor7974c3b2009-10-07 17:21:34 +00001030Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +00001031TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001032 // Create a local instantiation scope for this function template, which
1033 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001034 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +00001035 // itself.
John McCall2a7fb272010-08-25 05:32:35 +00001036 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +00001037
Douglas Gregord60e1052009-08-27 16:57:43 +00001038 TemplateParameterList *TempParams = D->getTemplateParameters();
1039 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +00001040 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +00001041 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001042
Douglas Gregora735b202009-10-13 14:39:41 +00001043 FunctionDecl *Instantiated = 0;
1044 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001045 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +00001046 InstParams));
1047 else
1048 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001049 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +00001050 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001051
Douglas Gregora735b202009-10-13 14:39:41 +00001052 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +00001053 return 0;
1054
Mike Stump1eb44332009-09-09 15:08:12 +00001055 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +00001056 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001057 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +00001058 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +00001059 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001060 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +00001061 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +00001062
John McCallb1a56e72010-03-26 23:10:15 +00001063 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1064
John McCalle976ffe2009-12-14 23:19:40 +00001065 // Link the instantiation back to the pattern *unless* this is a
1066 // non-definition friend declaration.
1067 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +00001068 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +00001069 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001070
John McCallb1a56e72010-03-26 23:10:15 +00001071 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +00001072 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001073 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +00001074 } else if (InstTemplate->getDeclContext()->isRecord() &&
1075 !D->getPreviousDecl()) {
1076 SemaRef.CheckFriendAccess(InstTemplate);
1077 }
John McCallb1a56e72010-03-26 23:10:15 +00001078
Douglas Gregord60e1052009-08-27 16:57:43 +00001079 return InstTemplate;
1080}
1081
Douglas Gregord475b8d2009-03-25 21:17:03 +00001082Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1083 CXXRecordDecl *PrevDecl = 0;
1084 if (D->isInjectedClassName())
1085 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +00001086 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001087 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +00001088 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +00001089 TemplateArgs);
1090 if (!Prev) return 0;
1091 PrevDecl = cast<CXXRecordDecl>(Prev);
1092 }
Douglas Gregord475b8d2009-03-25 21:17:03 +00001093
1094 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +00001095 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001096 D->getLocStart(), D->getLocation(),
1097 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00001098
1099 // Substitute the nested name specifier, if any.
1100 if (SubstQualifier(D, Record))
1101 return 0;
1102
Douglas Gregord475b8d2009-03-25 21:17:03 +00001103 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001104 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1105 // the tag decls introduced by friend class declarations don't have an access
1106 // specifier. Remove once this area of the code gets sorted out.
1107 if (D->getAccess() != AS_none)
1108 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001109 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001110 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001111
John McCall02cace72009-08-28 07:59:38 +00001112 // If the original function was part of a friend declaration,
1113 // inherit its namespace state.
Richard Smith22050f22013-07-17 23:53:16 +00001114 if (D->getFriendObjectKind())
1115 Record->setObjectOfFriendDecl();
John McCall02cace72009-08-28 07:59:38 +00001116
Douglas Gregor9901c572010-05-21 00:31:19 +00001117 // Make sure that anonymous structs and unions are recorded.
1118 if (D->isAnonymousStructOrUnion()) {
1119 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001120 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001121 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1122 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001123
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001124 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001125 return Record;
1126}
1127
Douglas Gregor71074fd2012-09-13 21:56:43 +00001128/// \brief Adjust the given function type for an instantiation of the
1129/// given declaration, to cope with modifications to the function's type that
1130/// aren't reflected in the type-source information.
1131///
1132/// \param D The declaration we're instantiating.
1133/// \param TInfo The already-instantiated type.
1134static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1135 FunctionDecl *D,
1136 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001137 const FunctionProtoType *OrigFunc
1138 = D->getType()->castAs<FunctionProtoType>();
1139 const FunctionProtoType *NewFunc
1140 = TInfo->getType()->castAs<FunctionProtoType>();
1141 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1142 return TInfo->getType();
1143
1144 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1145 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1146 return Context.getFunctionType(NewFunc->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00001147 NewFunc->getArgTypes(), NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001148}
1149
John McCall02cace72009-08-28 07:59:38 +00001150/// Normal class members are of more specific types and therefore
1151/// don't make it here. This function serves two purposes:
1152/// 1) instantiating function templates
1153/// 2) substituting friend declarations
1154/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001155Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001156 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001157 // Check whether there is already a function template specialization for
1158 // this declaration.
1159 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001160 if (FunctionTemplate && !TemplateParams) {
Richard Smithc95d4132013-05-03 23:46:09 +00001161 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001162
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001163 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001164 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001165 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001166 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Douglas Gregor127102b2009-06-29 20:59:39 +00001168 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001169 if (SpecFunc)
1170 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001171 }
Mike Stump1eb44332009-09-09 15:08:12 +00001172
John McCallb0cb0222010-03-27 05:57:59 +00001173 bool isFriend;
1174 if (FunctionTemplate)
1175 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1176 else
1177 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1178
Douglas Gregor79c22782010-01-16 20:21:20 +00001179 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001180 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001181 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001182 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001183 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Chris Lattner5f9e2722011-07-23 10:55:15 +00001185 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001186 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001187 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001188 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001189 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001190
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001191 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1192 if (QualifierLoc) {
1193 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1194 TemplateArgs);
1195 if (!QualifierLoc)
1196 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001197 }
1198
John McCall68b6b872010-02-06 01:50:47 +00001199 // If we're instantiating a local function declaration, put the result
1200 // in the owner; otherwise we need to find the instantiated context.
1201 DeclContext *DC;
1202 if (D->getDeclContext()->isFunctionOrMethod())
1203 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001204 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001205 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001206 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001207 DC = SemaRef.computeDeclContext(SS);
1208 if (!DC) return 0;
1209 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001210 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001211 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001212 }
John McCall68b6b872010-02-06 01:50:47 +00001213
John McCall02cace72009-08-28 07:59:38 +00001214 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001215 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001216 D->getNameInfo(), T, TInfo,
Rafael Espindola459ef032013-04-16 02:29:15 +00001217 D->getCanonicalDecl()->getStorageClass(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001218 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001219 D->isConstexpr());
Enea Zaffanellade9ed712013-07-19 18:02:36 +00001220 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCallb6217662010-03-15 10:12:16 +00001221
Richard Smithd4497dd2013-01-25 00:08:28 +00001222 if (D->isInlined())
1223 Function->setImplicitlyInline();
1224
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001225 if (QualifierLoc)
1226 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001227
John McCallb1a56e72010-03-26 23:10:15 +00001228 DeclContext *LexicalDC = Owner;
1229 if (!isFriend && D->isOutOfLine()) {
1230 assert(D->getDeclContext()->isFileContext());
1231 LexicalDC = D->getDeclContext();
1232 }
1233
1234 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001235
Douglas Gregore53060f2009-06-25 22:08:12 +00001236 // Attach the parameters
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001237 for (unsigned P = 0; P < Params.size(); ++P)
1238 if (Params[P])
1239 Params[P]->setOwningFunction(Function);
David Blaikie4278c652011-09-21 18:16:56 +00001240 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001241
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001242 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001243 if (TemplateParams) {
1244 // Our resulting instantiation is actually a function template, since we
1245 // are substituting only the outer template parameters. For example, given
1246 //
1247 // template<typename T>
1248 // struct X {
1249 // template<typename U> friend void f(T, U);
1250 // };
1251 //
1252 // X<int> x;
1253 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001254 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001255 // which means substituting int for T, but leaving "f" as a friend function
1256 // template.
1257 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001258 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001259 Function->getLocation(),
1260 Function->getDeclName(),
1261 TemplateParams, Function);
1262 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001263
1264 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001265
1266 if (isFriend && D->isThisDeclarationADefinition()) {
1267 // TODO: should we remember this connection regardless of whether
1268 // the friend declaration provided a body?
1269 FunctionTemplate->setInstantiatedFromMemberTemplate(
1270 D->getDescribedFunctionTemplate());
1271 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001272 } else if (FunctionTemplate) {
1273 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001274 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001275 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001276 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001277 Innermost.begin(),
1278 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001279 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001280 } else if (isFriend) {
1281 // Note, we need this connection even if the friend doesn't have a body.
1282 // Its body may exist but not have been attached yet due to deferred
1283 // parsing.
1284 // FIXME: It might be cleaner to set this when attaching the body to the
1285 // friend function declaration, however that would require finding all the
1286 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001287 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001288 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001289
Douglas Gregore53060f2009-06-25 22:08:12 +00001290 if (InitFunctionInstantiation(Function, D))
1291 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001292
John McCallaf2094e2010-04-08 09:05:18 +00001293 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001294
John McCall68263142009-11-18 22:49:29 +00001295 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1296 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1297
John McCallaf2094e2010-04-08 09:05:18 +00001298 if (DependentFunctionTemplateSpecializationInfo *Info
1299 = D->getDependentSpecializationInfo()) {
1300 assert(isFriend && "non-friend has dependent specialization info?");
1301
1302 // This needs to be set now for future sanity.
Richard Smith22050f22013-07-17 23:53:16 +00001303 Function->setObjectOfFriendDecl();
John McCallaf2094e2010-04-08 09:05:18 +00001304
1305 // Instantiate the explicit template arguments.
1306 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1307 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001308 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1309 ExplicitArgs, TemplateArgs))
1310 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001311
1312 // Map the candidate templates to their instantiations.
1313 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1314 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1315 Info->getTemplate(I),
1316 TemplateArgs);
1317 if (!Temp) return 0;
1318
1319 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1320 }
1321
1322 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1323 &ExplicitArgs,
1324 Previous))
1325 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001326
John McCallaf2094e2010-04-08 09:05:18 +00001327 isExplicitSpecialization = true;
1328
1329 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001330 // Look only into the namespace where the friend would be declared to
1331 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001332 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001333 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001334
Douglas Gregora735b202009-10-13 14:39:41 +00001335 // In C++, the previous declaration we find might be a tag type
1336 // (class or enum). In this case, the new declaration will hide the
1337 // tag type. Note that this does does not apply if we're declaring a
1338 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001339 if (Previous.isSingleTagDecl())
1340 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001341 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001342
John McCall9f54ad42009-12-10 09:41:52 +00001343 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001344 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001345
John McCall76d32642010-04-24 01:30:58 +00001346 NamedDecl *PrincipalDecl = (TemplateParams
1347 ? cast<NamedDecl>(FunctionTemplate)
1348 : Function);
1349
Douglas Gregora735b202009-10-13 14:39:41 +00001350 // If the original function was part of a friend declaration,
1351 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001352 if (isFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00001353 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001354 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001355
Gabor Greif77535df2010-08-30 22:25:56 +00001356 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001357
Richard Smith53e53512011-10-19 00:54:10 +00001358 // C++98 [temp.friend]p5: When a function is defined in a friend function
1359 // declaration in a class template, the function is defined at each
1360 // instantiation of the class template. The function is defined even if it
1361 // is never used.
1362 // C++11 [temp.friend]p4: When a function is defined in a friend function
1363 // declaration in a class template, the function is instantiated when the
1364 // function is odr-used.
1365 //
1366 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1367 // redefinition, but don't instantiate the function.
Richard Smith80ad52f2013-01-02 11:42:31 +00001368 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smith53e53512011-10-19 00:54:10 +00001369 SemaRef.Diags.getDiagnosticLevel(
1370 diag::warn_cxx98_compat_friend_redefinition,
1371 Function->getLocation())
1372 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001373 D->isThisDeclarationADefinition()) {
1374 // Check for a function body.
1375 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001376 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001377 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001378 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001379 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001380 diag::warn_cxx98_compat_friend_redefinition :
1381 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001382 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001383 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001384 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001385 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001386 // Check for redefinitions due to other instantiations of this or
1387 // a similar friend function.
1388 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1389 REnd = Function->redecls_end();
1390 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001391 if (*R == Function)
1392 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001393 switch (R->getFriendObjectKind()) {
1394 case Decl::FOK_None:
Richard Smith80ad52f2013-01-02 11:42:31 +00001395 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith53e53512011-10-19 00:54:10 +00001396 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001397 if (MemberSpecializationInfo *MSInfo
1398 = Function->getMemberSpecializationInfo()) {
1399 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1400 SourceLocation Loc = R->getLocation(); // FIXME
1401 MSInfo->setPointOfInstantiation(Loc);
1402 SemaRef.PendingLocalImplicitInstantiations.push_back(
1403 std::make_pair(Function, Loc));
1404 queuedInstantiation = true;
1405 }
1406 }
1407 }
1408 break;
1409 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001410 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001411 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001412 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001413 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001414 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001415 diag::warn_cxx98_compat_friend_redefinition :
1416 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001417 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001418 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001419 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001420 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001421 break;
1422 }
1423 }
1424 }
1425 }
Douglas Gregora735b202009-10-13 14:39:41 +00001426 }
1427
John McCall76d32642010-04-24 01:30:58 +00001428 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1429 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1430 PrincipalDecl->setNonMemberOperator();
1431
Sean Hunteb88ae52011-05-23 21:07:59 +00001432 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001433 return Function;
1434}
1435
Douglas Gregord60e1052009-08-27 16:57:43 +00001436Decl *
1437TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001438 TemplateParameterList *TemplateParams,
1439 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001440 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregord60e1052009-08-27 16:57:43 +00001441 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001442 // We are creating a function template specialization from a function
1443 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001444 // specialization for this particular set of template arguments.
Richard Smithc95d4132013-05-03 23:46:09 +00001445 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001447 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001448 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001449 = FunctionTemplate->findSpecialization(Innermost.begin(),
1450 Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001451 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001452
Douglas Gregor6b906862009-08-21 00:16:32 +00001453 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001454 if (SpecFunc)
1455 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001456 }
1457
John McCallb0cb0222010-03-27 05:57:59 +00001458 bool isFriend;
1459 if (FunctionTemplate)
1460 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1461 else
1462 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1463
Douglas Gregor79c22782010-01-16 20:21:20 +00001464 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001465 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001466 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001467 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001468
John McCall4eab39f2010-10-19 02:26:41 +00001469 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001470 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001471 unsigned NumTempParamLists = 0;
1472 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1473 TempParamLists.set_size(NumTempParamLists);
1474 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1475 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1476 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1477 if (!InstParams)
1478 return NULL;
1479 TempParamLists[I] = InstParams;
1480 }
1481 }
1482
Chris Lattner5f9e2722011-07-23 10:55:15 +00001483 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramerdc370c12012-01-20 14:42:32 +00001484 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001485 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001486 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001487 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001488
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001489 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1490 if (QualifierLoc) {
1491 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001492 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001493 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001494 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001495 }
1496
1497 DeclContext *DC = Owner;
1498 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001499 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001500 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001501 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001502 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001503
1504 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1505 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001506 } else {
1507 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1508 D->getDeclContext(),
1509 TemplateArgs);
1510 }
1511 if (!DC) return 0;
1512 }
1513
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001514 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001515 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001516 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001517
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001518 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001519 DeclarationNameInfo NameInfo
1520 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001521 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001522 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001523 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001524 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001525 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001526 false, Constructor->isConstexpr());
Richard Smithb5eb3f52013-05-17 02:19:35 +00001527
Richard Smith4841ca52013-04-10 05:48:59 +00001528 // Claim that the instantiation of a constructor or constructor template
1529 // inherits the same constructor that the template does.
Richard Smithb5eb3f52013-05-17 02:19:35 +00001530 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1531 Constructor->getInheritedConstructor())) {
1532 // If we're instantiating a specialization of a function template, our
1533 // "inherited constructor" will actually itself be a function template.
1534 // Instantiate a declaration of it, too.
1535 if (FunctionTemplate) {
1536 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1537 !Inh->getParent()->isDependentContext() &&
1538 "inheriting constructor template in dependent context?");
1539 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1540 Inh);
1541 if (Inst)
1542 return 0;
1543 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1544 LocalInstantiationScope LocalScope(SemaRef);
1545
1546 // Use the same template arguments that we deduced for the inheriting
1547 // constructor. There's no way they could be deduced differently.
1548 MultiLevelTemplateArgumentList InheritedArgs;
1549 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1550 Inh = cast_or_null<CXXConstructorDecl>(
1551 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1552 if (!Inh)
1553 return 0;
1554 }
Richard Smith4841ca52013-04-10 05:48:59 +00001555 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smithb5eb3f52013-05-17 02:19:35 +00001556 }
Douglas Gregor17e32f32009-08-21 22:43:28 +00001557 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001558 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001559 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001560 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001561 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001562 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001563 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001564 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001565 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001566 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001567 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001568 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001569 } else {
Rafael Espindola72fdc892013-04-15 12:38:20 +00001570 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnara25777432010-08-11 22:01:17 +00001571 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001572 StartLoc, NameInfo, T, TInfo,
Rafael Espindola72fdc892013-04-15 12:38:20 +00001573 SC, D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001574 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001575 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001576
Richard Smithd4497dd2013-01-25 00:08:28 +00001577 if (D->isInlined())
1578 Method->setImplicitlyInline();
1579
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001580 if (QualifierLoc)
1581 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001582
Douglas Gregord60e1052009-08-27 16:57:43 +00001583 if (TemplateParams) {
1584 // Our resulting instantiation is actually a function template, since we
1585 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001586 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001587 // template<typename T>
1588 // struct X {
1589 // template<typename U> void f(T, U);
1590 // };
1591 //
1592 // X<int> x;
1593 //
1594 // We are instantiating the member template "f" within X<int>, which means
1595 // substituting int for T, but leaving "f" as a member function template.
1596 // Build the function template itself.
1597 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1598 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001599 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001600 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001601 if (isFriend) {
1602 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001603 FunctionTemplate->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001604 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001605 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001606 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001607 } else if (FunctionTemplate) {
1608 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001609 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001610 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001611 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001612 Innermost.begin(),
1613 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001614 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001615 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001616 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001617 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001618 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001619
Mike Stump1eb44332009-09-09 15:08:12 +00001620 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001621 // out-of-line, the instantiation will have the same lexical
1622 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001623 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001624 if (NumTempParamLists)
1625 Method->setTemplateParameterListsInfo(SemaRef.Context,
1626 NumTempParamLists,
1627 TempParamLists.data());
1628
John McCallb0cb0222010-03-27 05:57:59 +00001629 Method->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001630 Method->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001631 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001632 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Douglas Gregor5545e162009-03-24 00:38:23 +00001634 // Attach the parameters
1635 for (unsigned P = 0; P < Params.size(); ++P)
1636 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001637 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001638
1639 if (InitMethodInstantiation(Method, D))
1640 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001641
Abramo Bagnara25777432010-08-11 22:01:17 +00001642 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1643 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001644
John McCallb0cb0222010-03-27 05:57:59 +00001645 if (!FunctionTemplate || TemplateParams || isFriend) {
1646 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001647
Douglas Gregordec06662009-08-21 18:42:58 +00001648 // In C++, the previous declaration we find might be a tag type
1649 // (class or enum). In this case, the new declaration will hide the
1650 // tag type. Note that this does does not apply if we're declaring a
1651 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001652 if (Previous.isSingleTagDecl())
1653 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001654 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001655
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001656 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001657 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001658
Douglas Gregor4ba31362009-12-01 17:24:26 +00001659 if (D->isPure())
1660 SemaRef.CheckPureMethod(Method, SourceRange());
1661
John McCall1f2e1a92012-08-10 03:15:35 +00001662 // Propagate access. For a non-friend declaration, the access is
1663 // whatever we're propagating from. For a friend, it should be the
1664 // previous declaration we just found.
1665 if (isFriend && Method->getPreviousDecl())
1666 Method->setAccess(Method->getPreviousDecl()->getAccess());
1667 else
1668 Method->setAccess(D->getAccess());
1669 if (FunctionTemplate)
1670 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001671
Anders Carlsson9eefa222011-01-20 06:52:44 +00001672 SemaRef.CheckOverrideControl(Method);
1673
Eli Friedman3bc45152011-11-15 22:39:08 +00001674 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithac713512012-12-08 02:53:02 +00001675 if (D->isExplicitlyDefaulted())
1676 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001677 if (D->isDeletedAsWritten())
Richard Smithac713512012-12-08 02:53:02 +00001678 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001679
John McCall1f2e1a92012-08-10 03:15:35 +00001680 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001681 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001682 // do nothing
1683
1684 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001685 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001686 // do nothing
1687
1688 // Otherwise, check access to friends and make them visible.
1689 } else if (isFriend) {
1690 // We only need to re-check access for methods which we didn't
1691 // manage to match during parsing.
1692 if (!D->getPreviousDecl())
1693 SemaRef.CheckFriendAccess(Method);
1694
1695 Record->makeDeclVisibleInContext(Method);
1696
1697 // Otherwise, add the declaration. We don't need to do this for
1698 // class-scope specializations because we'll have matched them with
1699 // the appropriate template.
1700 } else if (!IsClassScopeSpecialization) {
1701 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001702 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001703
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001704 return Method;
1705}
1706
Douglas Gregor615c5d42009-03-24 16:43:20 +00001707Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001708 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001709}
1710
Douglas Gregor03b2b072009-03-24 00:15:49 +00001711Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001712 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001713}
1714
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001715Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001716 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001717}
1718
Eli Friedmanded99792013-06-27 23:21:55 +00001719Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie66874fb2013-02-21 01:47:18 +00001720 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1721 /*ExpectParameterPack=*/ false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001722}
1723
John McCalle29ba202009-08-20 01:44:21 +00001724Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1725 TemplateTypeParmDecl *D) {
1726 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001727 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001728
John McCalle29ba202009-08-20 01:44:21 +00001729 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001730 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1731 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001732 D->getDepth() - TemplateArgs.getNumLevels(),
1733 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001734 D->wasDeclaredWithTypename(),
1735 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001736 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001737
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001738 if (D->hasDefaultArgument())
1739 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1740
1741 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001742 // scope.
1743 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001744
John McCalle29ba202009-08-20 01:44:21 +00001745 return Inst;
1746}
1747
Douglas Gregor33642df2009-10-23 23:25:44 +00001748Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1749 NonTypeTemplateParmDecl *D) {
1750 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001751 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001752 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1753 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001754 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001755 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001756 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001757 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001758
1759 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001760 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001761 // expansion of types. Substitute into each of the expanded types.
1762 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1763 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1764 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1765 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1766 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001767 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001768 D->getDeclName());
1769 if (!NewDI)
1770 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001771
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001772 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1773 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1774 D->getLocation());
1775 if (NewT.isNull())
1776 return 0;
1777 ExpandedParameterPackTypes.push_back(NewT);
1778 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001779
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001780 IsExpandedParameterPack = true;
1781 DI = D->getTypeSourceInfo();
1782 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001783 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001784 // The non-type template parameter pack's type is a pack expansion of types.
1785 // Determine whether we need to expand this parameter pack into separate
1786 // types.
David Blaikie39e6ab42013-02-18 22:06:02 +00001787 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001788 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001789 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001790 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001791
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001792 // Determine whether the set of unexpanded parameter packs can and should
1793 // be expanded.
1794 bool Expand = true;
1795 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001796 Optional<unsigned> OrigNumExpansions
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001797 = Expansion.getTypePtr()->getNumExpansions();
David Blaikiedc84cd52013-02-20 22:23:23 +00001798 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001799 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1800 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001801 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001802 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001803 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001804 NumExpansions))
1805 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001806
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001807 if (Expand) {
1808 for (unsigned I = 0; I != *NumExpansions; ++I) {
1809 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1810 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001811 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001812 D->getDeclName());
1813 if (!NewDI)
1814 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001815
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001816 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1817 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1818 NewDI->getType(),
1819 D->getLocation());
1820 if (NewT.isNull())
1821 return 0;
1822 ExpandedParameterPackTypes.push_back(NewT);
1823 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001824
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001825 // Note that we have an expanded parameter pack. The "type" of this
1826 // expanded parameter pack is the original expansion type, but callers
1827 // will end up using the expanded parameter pack types for type-checking.
1828 IsExpandedParameterPack = true;
1829 DI = D->getTypeSourceInfo();
1830 T = DI->getType();
1831 } else {
1832 // We cannot fully expand the pack expansion now, so substitute into the
1833 // pattern and create a new pack expansion type.
1834 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1835 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001836 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001837 D->getDeclName());
1838 if (!NewPattern)
1839 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001840
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001841 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1842 NumExpansions);
1843 if (!DI)
1844 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001845
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001846 T = DI->getType();
1847 }
1848 } else {
1849 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001850 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001851 D->getLocation(), D->getDeclName());
1852 if (!DI)
1853 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001854
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001855 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001856 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001857 D->getLocation());
1858 if (T.isNull()) {
1859 T = SemaRef.Context.IntTy;
1860 Invalid = true;
1861 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001862 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001863
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001864 NonTypeTemplateParmDecl *Param;
1865 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001866 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001867 D->getInnerLocStart(),
1868 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001869 D->getDepth() - TemplateArgs.getNumLevels(),
1870 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001871 D->getIdentifier(), T,
1872 DI,
1873 ExpandedParameterPackTypes.data(),
1874 ExpandedParameterPackTypes.size(),
1875 ExpandedParameterPackTypesAsWritten.data());
1876 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001877 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001878 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001879 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001880 D->getDepth() - TemplateArgs.getNumLevels(),
1881 D->getPosition(),
1882 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001883 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001884
Douglas Gregor9a299e02011-03-04 17:52:15 +00001885 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001886 if (Invalid)
1887 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001888
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001889 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001890
1891 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001892 // scope.
1893 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001894 return Param;
1895}
1896
Richard Smith6964b3f2012-09-07 02:06:42 +00001897static void collectUnexpandedParameterPacks(
1898 Sema &S,
1899 TemplateParameterList *Params,
1900 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1901 for (TemplateParameterList::const_iterator I = Params->begin(),
1902 E = Params->end(); I != E; ++I) {
1903 if ((*I)->isTemplateParameterPack())
1904 continue;
1905 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1906 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1907 Unexpanded);
1908 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1909 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1910 Unexpanded);
1911 }
1912}
1913
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001914Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001915TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1916 TemplateTemplateParmDecl *D) {
1917 // Instantiate the template parameter list of the template template parameter.
1918 TemplateParameterList *TempParams = D->getTemplateParameters();
1919 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001920 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1921
1922 bool IsExpandedParameterPack = false;
1923
1924 if (D->isExpandedParameterPack()) {
1925 // The template template parameter pack is an already-expanded pack
1926 // expansion of template parameters. Substitute into each of the expanded
1927 // parameters.
1928 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1929 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1930 I != N; ++I) {
1931 LocalInstantiationScope Scope(SemaRef);
1932 TemplateParameterList *Expansion =
1933 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1934 if (!Expansion)
1935 return 0;
1936 ExpandedParams.push_back(Expansion);
1937 }
1938
1939 IsExpandedParameterPack = true;
1940 InstParams = TempParams;
1941 } else if (D->isPackExpansion()) {
1942 // The template template parameter pack expands to a pack of template
1943 // template parameters. Determine whether we need to expand this parameter
1944 // pack into separate parameters.
1945 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1946 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1947 Unexpanded);
1948
1949 // Determine whether the set of unexpanded parameter packs can and should
1950 // be expanded.
1951 bool Expand = true;
1952 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001953 Optional<unsigned> NumExpansions;
Richard Smith6964b3f2012-09-07 02:06:42 +00001954 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1955 TempParams->getSourceRange(),
1956 Unexpanded,
1957 TemplateArgs,
1958 Expand, RetainExpansion,
1959 NumExpansions))
1960 return 0;
1961
1962 if (Expand) {
1963 for (unsigned I = 0; I != *NumExpansions; ++I) {
1964 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1965 LocalInstantiationScope Scope(SemaRef);
1966 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1967 if (!Expansion)
1968 return 0;
1969 ExpandedParams.push_back(Expansion);
1970 }
1971
1972 // Note that we have an expanded parameter pack. The "type" of this
1973 // expanded parameter pack is the original expansion type, but callers
1974 // will end up using the expanded parameter pack types for type-checking.
1975 IsExpandedParameterPack = true;
1976 InstParams = TempParams;
1977 } else {
1978 // We cannot fully expand the pack expansion now, so just substitute
1979 // into the pattern.
1980 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1981
1982 LocalInstantiationScope Scope(SemaRef);
1983 InstParams = SubstTemplateParams(TempParams);
1984 if (!InstParams)
1985 return 0;
1986 }
1987 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00001988 // Perform the actual substitution of template parameters within a new,
1989 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001990 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001991 InstParams = SubstTemplateParams(TempParams);
1992 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00001993 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001994 }
1995
Douglas Gregor9106ef72009-11-11 16:58:32 +00001996 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00001997 TemplateTemplateParmDecl *Param;
1998 if (IsExpandedParameterPack)
1999 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2000 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002001 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00002002 D->getPosition(),
2003 D->getIdentifier(), InstParams,
2004 ExpandedParams);
2005 else
2006 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2007 D->getLocation(),
2008 D->getDepth() - TemplateArgs.getNumLevels(),
2009 D->getPosition(),
2010 D->isParameterPack(),
2011 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00002012 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00002013 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002014
2015 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00002016 // scope.
2017 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002018
Douglas Gregor9106ef72009-11-11 16:58:32 +00002019 return Param;
2020}
2021
Douglas Gregor48c32a72009-11-17 06:07:40 +00002022Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00002023 // Using directives are never dependent (and never contain any types or
2024 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002025
Douglas Gregor48c32a72009-11-17 06:07:40 +00002026 UsingDirectiveDecl *Inst
2027 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002028 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00002029 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002030 D->getIdentLocation(),
2031 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00002032 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00002033
2034 // Add the using directive to its declaration context
2035 // only if this is not a function or method.
2036 if (!Owner->isFunctionOrMethod())
2037 Owner->addDecl(Inst);
2038
Douglas Gregor48c32a72009-11-17 06:07:40 +00002039 return Inst;
2040}
2041
John McCalled976492009-12-04 22:46:56 +00002042Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00002043
2044 // The nested name specifier may be dependent, for example
2045 // template <typename T> struct t {
2046 // struct s1 { T f1(); };
2047 // struct s2 : s1 { using s1::f1; };
2048 // };
2049 // template struct t<int>;
2050 // Here, in using s1::f1, s1 refers to t<T>::s1;
2051 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00002052 NestedNameSpecifierLoc QualifierLoc
2053 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2054 TemplateArgs);
2055 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00002056 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00002057
2058 // The name info is non-dependent, so no transformation
2059 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002060 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00002061
John McCall9f54ad42009-12-10 09:41:52 +00002062 // We only need to do redeclaration lookups if we're in a class
2063 // scope (in fact, it's not really even possible in non-class
2064 // scopes).
2065 bool CheckRedeclaration = Owner->isRecord();
2066
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002067 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2068 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00002069
John McCalled976492009-12-04 22:46:56 +00002070 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002071 D->getUsingLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002072 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002073 NameInfo,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002074 D->hasTypename());
John McCalled976492009-12-04 22:46:56 +00002075
Douglas Gregor5149f372011-02-25 15:54:31 +00002076 CXXScopeSpec SS;
2077 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00002078 if (CheckRedeclaration) {
2079 Prev.setHideTags(false);
2080 SemaRef.LookupQualifiedName(Prev, Owner);
2081
2082 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002083 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2084 D->hasTypename(), SS,
John McCall9f54ad42009-12-10 09:41:52 +00002085 D->getLocation(), Prev))
2086 NewUD->setInvalidDecl();
2087
2088 }
2089
2090 if (!NewUD->isInvalidDecl() &&
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002091 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCalled976492009-12-04 22:46:56 +00002092 D->getLocation()))
2093 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002094
John McCalled976492009-12-04 22:46:56 +00002095 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2096 NewUD->setAccess(D->getAccess());
2097 Owner->addDecl(NewUD);
2098
John McCall9f54ad42009-12-10 09:41:52 +00002099 // Don't process the shadow decls for an invalid decl.
2100 if (NewUD->isInvalidDecl())
2101 return NewUD;
2102
Richard Smithc5a89a12012-04-02 01:30:27 +00002103 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2104 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2105 NewUD->setInvalidDecl();
2106 return NewUD;
2107 }
2108
John McCall323c3102009-12-22 22:26:37 +00002109 bool isFunctionScope = Owner->isFunctionOrMethod();
2110
John McCall9f54ad42009-12-10 09:41:52 +00002111 // Process the shadow decls.
2112 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2113 I != E; ++I) {
2114 UsingShadowDecl *Shadow = *I;
2115 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002116 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2117 Shadow->getLocation(),
2118 Shadow->getTargetDecl(),
2119 TemplateArgs));
2120 if (!InstTarget)
2121 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002122
2123 if (CheckRedeclaration &&
2124 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2125 continue;
2126
2127 UsingShadowDecl *InstShadow
2128 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2129 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002130
2131 if (isFunctionScope)
2132 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002133 }
John McCalled976492009-12-04 22:46:56 +00002134
2135 return NewUD;
2136}
2137
2138Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002139 // Ignore these; we handle them in bulk when processing the UsingDecl.
2140 return 0;
John McCalled976492009-12-04 22:46:56 +00002141}
2142
John McCall7ba107a2009-11-18 02:36:19 +00002143Decl * TemplateDeclInstantiator
2144 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002145 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002146 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002147 TemplateArgs);
2148 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002149 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002151 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002152 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002153
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002154 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002155 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002156 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002157 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002158 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002159 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002160 /*instantiation*/ true,
2161 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002162 if (UD)
John McCalled976492009-12-04 22:46:56 +00002163 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2164
John McCall7ba107a2009-11-18 02:36:19 +00002165 return UD;
2166}
2167
2168Decl * TemplateDeclInstantiator
2169 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002170 NestedNameSpecifierLoc QualifierLoc
2171 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2172 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002173 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002174
John McCall7ba107a2009-11-18 02:36:19 +00002175 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002176 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002177
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002178 DeclarationNameInfo NameInfo
2179 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2180
John McCall7ba107a2009-11-18 02:36:19 +00002181 NamedDecl *UD =
2182 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002183 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002184 /*instantiation*/ true,
2185 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002186 if (UD)
John McCalled976492009-12-04 22:46:56 +00002187 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2188
Anders Carlsson0d8df782009-08-29 19:37:28 +00002189 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002190}
2191
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002192
2193Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2194 ClassScopeFunctionSpecializationDecl *Decl) {
2195 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002196 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2197 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002198
2199 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2200 Sema::ForRedeclaration);
2201
Nico Weber6b020092012-06-25 17:21:05 +00002202 TemplateArgumentListInfo TemplateArgs;
2203 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2204 if (Decl->hasExplicitTemplateArgs()) {
2205 TemplateArgs = Decl->templateArgs();
2206 TemplateArgsPtr = &TemplateArgs;
2207 }
2208
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002209 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002210 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2211 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002212 NewFD->setInvalidDecl();
2213 return NewFD;
2214 }
2215
2216 // Associate the specialization with the pattern.
2217 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2218 assert(Specialization && "Class scope Specialization is null");
2219 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2220
2221 return NewFD;
2222}
2223
Alexey Bataevc6400582013-03-22 06:34:35 +00002224Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2225 OMPThreadPrivateDecl *D) {
Alexey Bataev6af701f2013-05-13 04:18:18 +00002226 SmallVector<Expr *, 5> Vars;
2227 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2228 E = D->varlist_end();
Alexey Bataevc6400582013-03-22 06:34:35 +00002229 I != E; ++I) {
2230 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2231 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6af701f2013-05-13 04:18:18 +00002232 Vars.push_back(Var);
Alexey Bataevc6400582013-03-22 06:34:35 +00002233 }
2234
2235 OMPThreadPrivateDecl *TD =
2236 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2237
2238 return TD;
2239}
2240
Eli Friedmanded99792013-06-27 23:21:55 +00002241Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2242 return VisitFunctionDecl(D, 0);
2243}
2244
2245Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2246 return VisitCXXMethodDecl(D, 0);
2247}
2248
2249Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2250 llvm_unreachable("There are only CXXRecordDecls in C++");
2251}
2252
2253Decl *
2254TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2255 ClassTemplateSpecializationDecl *D) {
2256 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2257 "inside templates");
2258}
2259
Larisse Voufoef4579c2013-08-06 01:03:05 +00002260Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2261 VarTemplateSpecializationDecl *D) {
2262
2263 TemplateArgumentListInfo VarTemplateArgsInfo;
2264 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2265 assert(VarTemplate &&
2266 "A template specialization without specialized template?");
2267
2268 // Substitute the current template arguments.
2269 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2270 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2271 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2272
2273 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2274 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2275 return 0;
2276
2277 // Check that the template argument list is well-formed for this template.
2278 SmallVector<TemplateArgument, 4> Converted;
2279 bool ExpansionIntoFixedList = false;
2280 if (SemaRef.CheckTemplateArgumentList(
2281 VarTemplate, VarTemplate->getLocStart(),
2282 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2283 Converted, &ExpansionIntoFixedList))
2284 return 0;
2285
2286 // Find the variable template specialization declaration that
2287 // corresponds to these arguments.
2288 void *InsertPos = 0;
2289 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2290 Converted.data(), Converted.size(), InsertPos))
2291 // If we already have a variable template specialization, return it.
2292 return VarSpec;
2293
2294 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2295 VarTemplateArgsInfo, Converted);
2296}
2297
2298Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2299 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2300 const TemplateArgumentListInfo &TemplateArgsInfo,
2301 SmallVectorImpl<TemplateArgument> &Converted) {
2302
2303 // If this is the variable for an anonymous struct or union,
2304 // instantiate the anonymous struct/union type first.
2305 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2306 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2307 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2308 return 0;
2309
2310 // Do substitution on the type of the declaration
2311 TypeSourceInfo *DI =
2312 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2313 D->getTypeSpecStartLoc(), D->getDeclName());
2314 if (!DI)
2315 return 0;
2316
2317 if (DI->getType()->isFunctionType()) {
2318 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2319 << D->isStaticDataMember() << DI->getType();
2320 return 0;
2321 }
2322
2323 // Build the instantiated declaration
2324 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2325 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2326 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2327 Converted.size());
2328 Var->setTemplateArgsInfo(TemplateArgsInfo);
2329 VarTemplate->AddSpecialization(Var, InsertPos);
2330
2331 // Substitute the nested name specifier, if any.
2332 if (SubstQualifier(D, Var))
2333 return 0;
2334
2335 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
2336 StartingScope);
2337
2338 return Var;
2339}
2340
Eli Friedmanded99792013-06-27 23:21:55 +00002341Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2342 llvm_unreachable("@defs is not supported in Objective-C++");
2343}
2344
2345Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2346 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2347 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2348 DiagnosticsEngine::Error,
2349 "cannot instantiate %0 yet");
2350 SemaRef.Diag(D->getLocation(), DiagID)
2351 << D->getDeclKindName();
2352
2353 return 0;
2354}
2355
2356Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2357 llvm_unreachable("Unexpected decl");
2358}
2359
John McCallce3ff2b2009-08-25 22:02:44 +00002360Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002361 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002362 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002363 if (D->isInvalidDecl())
2364 return 0;
2365
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002366 return Instantiator.Visit(D);
2367}
2368
John McCalle29ba202009-08-20 01:44:21 +00002369/// \brief Instantiates a nested template parameter list in the current
2370/// instantiation context.
2371///
2372/// \param L The parameter list to instantiate
2373///
2374/// \returns NULL if there was an error
2375TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002376TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002377 // Get errors for all the parameters before bailing out.
2378 bool Invalid = false;
2379
2380 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002381 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002382 ParamVector Params;
2383 Params.reserve(N);
2384 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2385 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002386 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002387 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002388 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002389 }
2390
2391 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002392 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002393 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002394
2395 TemplateParameterList *InstL
2396 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2397 L->getLAngleLoc(), &Params.front(), N,
2398 L->getRAngleLoc());
2399 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002400}
John McCalle29ba202009-08-20 01:44:21 +00002401
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002402/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002403/// specialization.
2404///
2405/// \param ClassTemplate the (instantiated) class template that is partially
2406// specialized by the instantiation of \p PartialSpec.
2407///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002408/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002409/// specialization that we are instantiating.
2410///
Douglas Gregord65587f2010-11-10 19:44:59 +00002411/// \returns The instantiated partial specialization, if successful; otherwise,
2412/// NULL to indicate an error.
2413ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002414TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2415 ClassTemplateDecl *ClassTemplate,
2416 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002417 // Create a local instantiation scope for this class template partial
2418 // specialization, which will contain the instantiations of the template
2419 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002420 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002421
Douglas Gregored9c0f92009-10-29 00:04:11 +00002422 // Substitute into the template parameters of the class template partial
2423 // specialization.
2424 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2425 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2426 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002427 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002428
Douglas Gregored9c0f92009-10-29 00:04:11 +00002429 // Substitute into the template arguments of the class template partial
2430 // specialization.
Enea Zaffanellac1cef082013-08-10 07:24:53 +00002431 const ASTTemplateArgumentListInfo *TemplArgInfo
2432 = PartialSpec->getTemplateArgsAsWritten();
2433 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2434 TemplArgInfo->RAngleLoc);
2435 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2436 TemplArgInfo->NumTemplateArgs,
Douglas Gregore02e2622010-12-22 21:19:48 +00002437 InstTemplateArgs, TemplateArgs))
2438 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002439
Douglas Gregored9c0f92009-10-29 00:04:11 +00002440 // Check that the template argument list is well-formed for this
2441 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002442 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002443 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002444 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002445 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002446 false,
2447 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002448 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002449
2450 // Figure out where to insert this class template partial specialization
2451 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002452 void *InsertPos = 0;
2453 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002454 = ClassTemplate->findPartialSpecialization(Converted.data(),
2455 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002456
Douglas Gregored9c0f92009-10-29 00:04:11 +00002457 // Build the canonical type that describes the converted template
2458 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002459 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002460 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002461 Converted.data(),
2462 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002463
2464 // Build the fully-sugared type for this class template
2465 // specialization as the user wrote in the specialization
2466 // itself. This means that we'll pretty-print the type retrieved
2467 // from the specialization's declaration the way that the user
2468 // actually wrote the specialization, rather than formatting the
2469 // name based on the "canonical" representation used to store the
2470 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002471 TypeSourceInfo *WrittenTy
2472 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2473 TemplateName(ClassTemplate),
2474 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002475 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002476 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002477
Douglas Gregored9c0f92009-10-29 00:04:11 +00002478 if (PrevDecl) {
2479 // We've already seen a partial specialization with the same template
2480 // parameters and template arguments. This can happen, for example, when
2481 // substituting the outer template arguments ends up causing two
2482 // class template partial specializations of a member class template
2483 // to have identical forms, e.g.,
2484 //
2485 // template<typename T, typename U>
2486 // struct Outer {
2487 // template<typename X, typename Y> struct Inner;
2488 // template<typename Y> struct Inner<T, Y>;
2489 // template<typename Y> struct Inner<U, Y>;
2490 // };
2491 //
2492 // Outer<int, int> outer; // error: the partial specializations of Inner
2493 // // have the same signature.
2494 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002495 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002496 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2497 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002498 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002499 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002500
2501
Douglas Gregored9c0f92009-10-29 00:04:11 +00002502 // Create the class template partial specialization declaration.
2503 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002504 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002505 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002506 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002507 PartialSpec->getLocStart(),
2508 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002509 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002510 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002511 Converted.data(),
2512 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002513 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002514 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002515 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002516 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002517 // Substitute the nested name specifier, if any.
2518 if (SubstQualifier(PartialSpec, InstPartialSpec))
2519 return 0;
2520
Douglas Gregored9c0f92009-10-29 00:04:11 +00002521 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002522 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002523
Douglas Gregored9c0f92009-10-29 00:04:11 +00002524 // Add this partial specialization to the set of class template partial
2525 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002526 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002527 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002528}
2529
Larisse Voufoef4579c2013-08-06 01:03:05 +00002530/// \brief Instantiate the declaration of a variable template partial
2531/// specialization.
2532///
2533/// \param VarTemplate the (instantiated) variable template that is partially
2534/// specialized by the instantiation of \p PartialSpec.
2535///
2536/// \param PartialSpec the (uninstantiated) variable template partial
2537/// specialization that we are instantiating.
2538///
2539/// \returns The instantiated partial specialization, if successful; otherwise,
2540/// NULL to indicate an error.
2541VarTemplatePartialSpecializationDecl *
2542TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2543 VarTemplateDecl *VarTemplate,
2544 VarTemplatePartialSpecializationDecl *PartialSpec) {
2545 // Create a local instantiation scope for this variable template partial
2546 // specialization, which will contain the instantiations of the template
2547 // parameters.
2548 LocalInstantiationScope Scope(SemaRef);
2549
2550 // Substitute into the template parameters of the variable template partial
2551 // specialization.
2552 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2553 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2554 if (!InstParams)
2555 return 0;
2556
2557 // Substitute into the template arguments of the variable template partial
2558 // specialization.
Enea Zaffanellac1cef082013-08-10 07:24:53 +00002559 const ASTTemplateArgumentListInfo *TemplArgInfo
2560 = PartialSpec->getTemplateArgsAsWritten();
2561 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2562 TemplArgInfo->RAngleLoc);
2563 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2564 TemplArgInfo->NumTemplateArgs,
Larisse Voufoef4579c2013-08-06 01:03:05 +00002565 InstTemplateArgs, TemplateArgs))
2566 return 0;
2567
2568 // Check that the template argument list is well-formed for this
2569 // class template.
2570 SmallVector<TemplateArgument, 4> Converted;
2571 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2572 InstTemplateArgs, false, Converted))
2573 return 0;
2574
2575 // Figure out where to insert this variable template partial specialization
2576 // in the member template's set of variable template partial specializations.
2577 void *InsertPos = 0;
2578 VarTemplateSpecializationDecl *PrevDecl =
2579 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2580 InsertPos);
2581
2582 // Build the canonical type that describes the converted template
2583 // arguments of the variable template partial specialization.
2584 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2585 TemplateName(VarTemplate), Converted.data(), Converted.size());
2586
2587 // Build the fully-sugared type for this variable template
2588 // specialization as the user wrote in the specialization
2589 // itself. This means that we'll pretty-print the type retrieved
2590 // from the specialization's declaration the way that the user
2591 // actually wrote the specialization, rather than formatting the
2592 // name based on the "canonical" representation used to store the
2593 // template arguments in the specialization.
2594 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2595 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2596 CanonType);
2597
2598 if (PrevDecl) {
2599 // We've already seen a partial specialization with the same template
2600 // parameters and template arguments. This can happen, for example, when
2601 // substituting the outer template arguments ends up causing two
2602 // variable template partial specializations of a member variable template
2603 // to have identical forms, e.g.,
2604 //
2605 // template<typename T, typename U>
2606 // struct Outer {
2607 // template<typename X, typename Y> pair<X,Y> p;
2608 // template<typename Y> pair<T, Y> p;
2609 // template<typename Y> pair<U, Y> p;
2610 // };
2611 //
2612 // Outer<int, int> outer; // error: the partial specializations of Inner
2613 // // have the same signature.
2614 SemaRef.Diag(PartialSpec->getLocation(),
2615 diag::err_var_partial_spec_redeclared)
2616 << WrittenTy->getType();
2617 SemaRef.Diag(PrevDecl->getLocation(),
2618 diag::note_var_prev_partial_spec_here);
2619 return 0;
2620 }
2621
2622 // Do substitution on the type of the declaration
2623 TypeSourceInfo *DI = SemaRef.SubstType(
2624 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2625 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2626 if (!DI)
2627 return 0;
2628
2629 if (DI->getType()->isFunctionType()) {
2630 SemaRef.Diag(PartialSpec->getLocation(),
2631 diag::err_variable_instantiates_to_function)
2632 << PartialSpec->isStaticDataMember() << DI->getType();
2633 return 0;
2634 }
2635
2636 // Create the variable template partial specialization declaration.
2637 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2638 VarTemplatePartialSpecializationDecl::Create(
2639 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2640 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2641 DI, PartialSpec->getStorageClass(), Converted.data(),
2642 Converted.size(), InstTemplateArgs,
2643 VarTemplate->getNextPartialSpecSequenceNumber());
2644
2645 // Substitute the nested name specifier, if any.
2646 if (SubstQualifier(PartialSpec, InstPartialSpec))
2647 return 0;
2648
2649 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2650 InstPartialSpec->setTypeAsWritten(WrittenTy);
2651
2652 InstPartialSpec->setAccess(PartialSpec->getAccess());
Larisse Voufoef4579c2013-08-06 01:03:05 +00002653
2654 // Add this partial specialization to the set of variable template partial
2655 // specializations. The instantiation of the initializer is not necessary.
2656 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Larisse Voufo04592e72013-08-22 00:28:27 +00002657
2658 // Set the initializer, to use as pattern for initialization.
2659 if (VarDecl *Def = PartialSpec->getDefinition(SemaRef.getASTContext()))
2660 PartialSpec = cast<VarTemplatePartialSpecializationDecl>(Def);
2661 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
2662 LateAttrs, StartingScope);
2663 InstPartialSpec->setInit(PartialSpec->getInit());
2664
Larisse Voufoef4579c2013-08-06 01:03:05 +00002665 return InstPartialSpec;
2666}
2667
John McCall21ef0fa2010-03-11 09:03:00 +00002668TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002669TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002670 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002671 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2672 assert(OldTInfo && "substituting function without type source info");
2673 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002674
2675 CXXRecordDecl *ThisContext = 0;
2676 unsigned ThisTypeQuals = 0;
2677 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithcafeb942013-06-07 02:33:37 +00002678 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002679 ThisTypeQuals = Method->getTypeQualifiers();
2680 }
2681
John McCall6cd3b9f2010-04-09 17:38:44 +00002682 TypeSourceInfo *NewTInfo
2683 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2684 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002685 D->getDeclName(),
2686 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002687 if (!NewTInfo)
2688 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002689
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002690 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2691 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2692 if (NewTInfo != OldTInfo) {
2693 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002694 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002695 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith500d7292012-07-18 01:29:05 +00002696 unsigned NewIdx = 0;
David Blaikie39e6ab42013-02-18 22:06:02 +00002697 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregor12c9c002011-01-07 16:43:16 +00002698 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002699 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002700 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2701
David Blaikiedc84cd52013-02-20 22:23:23 +00002702 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith500d7292012-07-18 01:29:05 +00002703 if (OldParam->isParameterPack())
2704 NumArgumentsInExpansion =
2705 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2706 TemplateArgs);
2707 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002708 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002709 // instantiated to a (still-dependent) parameter pack.
David Blaikie39e6ab42013-02-18 22:06:02 +00002710 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002711 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002712 Scope->InstantiatedLocal(OldParam, NewParam);
2713 } else {
2714 // Parameter pack expansion: make the instantiation an argument pack.
2715 Scope->MakeInstantiatedLocalArgPack(OldParam);
2716 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002717 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith500d7292012-07-18 01:29:05 +00002718 Params.push_back(NewParam);
2719 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2720 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002721 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002722 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002723 } else {
2724 // The function type itself was not dependent and therefore no
2725 // substitution occurred. However, we still need to instantiate
2726 // the function parameters themselves.
2727 const FunctionProtoType *OldProto =
2728 cast<FunctionProtoType>(OldProtoLoc.getType());
David Blaikie39e6ab42013-02-18 22:06:02 +00002729 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002730 ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2731 if (!OldParam) {
2732 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2733 D, D->getLocation(), OldProto->getArgType(i)));
2734 continue;
2735 }
2736
Eli Friedmanded99792013-06-27 23:21:55 +00002737 ParmVarDecl *Parm =
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002738 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002739 if (!Parm)
2740 return 0;
2741 Params.push_back(Parm);
2742 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002743 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002744 } else {
2745 // If the type of this function, after ignoring parentheses, is not
2746 // *directly* a function type, then we're instantiating a function that
2747 // was declared via a typedef or with attributes, e.g.,
2748 //
2749 // typedef int functype(int, int);
2750 // functype func;
2751 // int __cdecl meth(int, int);
2752 //
2753 // In this case, we'll just go instantiate the ParmVarDecls that we
2754 // synthesized in the method declaration.
2755 SmallVector<QualType, 4> ParamTypes;
2756 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2757 D->getNumParams(), TemplateArgs, ParamTypes,
2758 &Params))
2759 return 0;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002760 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002761
John McCall21ef0fa2010-03-11 09:03:00 +00002762 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002763}
2764
Richard Smithe6975e92012-04-17 00:58:00 +00002765/// Introduce the instantiated function parameters into the local
2766/// instantiation scope, and set the parameter names to those used
2767/// in the template.
2768static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2769 const FunctionDecl *PatternDecl,
2770 LocalInstantiationScope &Scope,
2771 const MultiLevelTemplateArgumentList &TemplateArgs) {
2772 unsigned FParamIdx = 0;
2773 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2774 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2775 if (!PatternParam->isParameterPack()) {
2776 // Simple case: not a parameter pack.
2777 assert(FParamIdx < Function->getNumParams());
2778 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2779 FunctionParam->setDeclName(PatternParam->getDeclName());
2780 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2781 ++FParamIdx;
2782 continue;
2783 }
2784
2785 // Expand the parameter pack.
2786 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikiedc84cd52013-02-20 22:23:23 +00002787 Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002788 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002789 assert(NumArgumentsInExpansion &&
2790 "should only be called when all template arguments are known");
2791 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002792 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2793 FunctionParam->setDeclName(PatternParam->getDeclName());
2794 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2795 ++FParamIdx;
2796 }
2797 }
2798}
2799
2800static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2801 const FunctionProtoType *Proto,
2802 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002803 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2804
Richard Smithe6975e92012-04-17 00:58:00 +00002805 // C++11 [expr.prim.general]p3:
2806 // If a declaration declares a member function or member function
2807 // template of a class X, the expression this is a prvalue of type
2808 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2809 // and the end of the function-definition, member-declarator, or
2810 // declarator.
2811 CXXRecordDecl *ThisContext = 0;
2812 unsigned ThisTypeQuals = 0;
2813 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2814 ThisContext = Method->getParent();
2815 ThisTypeQuals = Method->getTypeQualifiers();
2816 }
2817 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith80ad52f2013-01-02 11:42:31 +00002818 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithe6975e92012-04-17 00:58:00 +00002819
2820 // The function has an exception specification or a "noreturn"
2821 // attribute. Substitute into each of the exception types.
2822 SmallVector<QualType, 4> Exceptions;
2823 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2824 // FIXME: Poor location information!
2825 if (const PackExpansionType *PackExpansion
2826 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2827 // We have a pack expansion. Instantiate it.
2828 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2829 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2830 Unexpanded);
2831 assert(!Unexpanded.empty() &&
2832 "Pack expansion without parameter packs?");
2833
2834 bool Expand = false;
2835 bool RetainExpansion = false;
Richard Smithcafeb942013-06-07 02:33:37 +00002836 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithe6975e92012-04-17 00:58:00 +00002837 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2838 SourceRange(),
2839 Unexpanded,
2840 TemplateArgs,
2841 Expand,
2842 RetainExpansion,
2843 NumExpansions))
2844 break;
2845
2846 if (!Expand) {
2847 // We can't expand this pack expansion into separate arguments yet;
2848 // just substitute into the pattern and create a new pack expansion
2849 // type.
2850 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2851 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2852 TemplateArgs,
2853 New->getLocation(), New->getDeclName());
2854 if (T.isNull())
2855 break;
2856
2857 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2858 Exceptions.push_back(T);
2859 continue;
2860 }
2861
2862 // Substitute into the pack expansion pattern for each template
2863 bool Invalid = false;
2864 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2865 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2866
2867 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2868 TemplateArgs,
2869 New->getLocation(), New->getDeclName());
2870 if (T.isNull()) {
2871 Invalid = true;
2872 break;
2873 }
2874
2875 Exceptions.push_back(T);
2876 }
2877
2878 if (Invalid)
2879 break;
2880
2881 continue;
2882 }
2883
2884 QualType T
2885 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2886 New->getLocation(), New->getDeclName());
2887 if (T.isNull() ||
2888 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2889 continue;
2890
2891 Exceptions.push_back(T);
2892 }
2893 Expr *NoexceptExpr = 0;
2894 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2895 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2896 Sema::ConstantEvaluated);
2897 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2898 if (E.isUsable())
2899 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2900
2901 if (E.isUsable()) {
2902 NoexceptExpr = E.take();
2903 if (!NoexceptExpr->isTypeDependent() &&
2904 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002905 NoexceptExpr
2906 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2907 0, diag::err_noexcept_needs_constant_expression,
2908 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002909 }
2910 }
2911
2912 // Rebuild the function type
2913 const FunctionProtoType *NewProto
2914 = New->getType()->getAs<FunctionProtoType>();
2915 assert(NewProto && "Template instantiation without function prototype?");
2916
2917 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2918 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2919 EPI.NumExceptions = Exceptions.size();
2920 EPI.Exceptions = Exceptions.data();
2921 EPI.NoexceptExpr = NoexceptExpr;
2922
2923 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002924 NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002925}
2926
2927void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2928 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002929 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2930 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002931 return;
2932
2933 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2934 InstantiatingTemplate::ExceptionSpecification());
Richard Smithb9d0b762012-07-27 04:22:15 +00002935 if (Inst) {
2936 // We hit the instantiation depth limit. Clear the exception specification
2937 // so that our callers don't have to cope with EST_Uninstantiated.
2938 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2939 EPI.ExceptionSpecType = EST_None;
2940 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002941 Proto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002942 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002943 }
Richard Smithe6975e92012-04-17 00:58:00 +00002944
2945 // Enter the scope of this instantiation. We don't use
2946 // PushDeclContext because we don't have a scope.
2947 Sema::ContextRAII savedContext(*this, Decl);
2948 LocalInstantiationScope Scope(*this);
2949
2950 MultiLevelTemplateArgumentList TemplateArgs =
2951 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2952
Richard Smith13bffc52012-04-19 00:08:28 +00002953 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2954 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002955
Richard Smith13bffc52012-04-19 00:08:28 +00002956 ::InstantiateExceptionSpec(*this, Decl,
2957 Template->getType()->castAs<FunctionProtoType>(),
2958 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002959}
2960
Mike Stump1eb44332009-09-09 15:08:12 +00002961/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002962/// declaration (New) from the corresponding fields of its template (Tmpl).
2963///
2964/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002965bool
2966TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002967 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00002968 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00002969 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002970
Douglas Gregorcca9e962009-07-01 22:01:06 +00002971 // If we are performing substituting explicitly-specified template arguments
2972 // or deduced template arguments into a function template and we reach this
2973 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002974 // to keeping the new function template specialization. We therefore
2975 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002976 // into a template instantiation for this specific function template
2977 // specialization, which is not a SFINAE context, so that we diagnose any
2978 // further errors in the declaration itself.
2979 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2980 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2981 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2982 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002983 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002984 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002985 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002986 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002987 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002988 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002989 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002990 }
2991 }
Mike Stump1eb44332009-09-09 15:08:12 +00002992
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002993 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2994 assert(Proto && "Function template without prototype?");
2995
Sebastian Redl60618fa2011-03-12 11:50:43 +00002996 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00002997 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00002998
Richard Smithe6975e92012-04-17 00:58:00 +00002999 // DR1330: In C++11, defer instantiation of a non-trivial
3000 // exception specification.
Richard Smith80ad52f2013-01-02 11:42:31 +00003001 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithe6975e92012-04-17 00:58:00 +00003002 EPI.ExceptionSpecType != EST_None &&
3003 EPI.ExceptionSpecType != EST_DynamicNone &&
3004 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00003005 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3006 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3007 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith4841ca52013-04-10 05:48:59 +00003008 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3009 if (EPI.ExceptionSpecType == EST_Unevaluated)
3010 NewEST = EST_Unevaluated;
Richard Smith13bffc52012-04-19 00:08:28 +00003011
Richard Smithe6975e92012-04-17 00:58:00 +00003012 // Mark the function has having an uninstantiated exception specification.
3013 const FunctionProtoType *NewProto
3014 = New->getType()->getAs<FunctionProtoType>();
3015 assert(NewProto && "Template instantiation without function prototype?");
3016 EPI = NewProto->getExtProtoInfo();
Richard Smith4841ca52013-04-10 05:48:59 +00003017 EPI.ExceptionSpecType = NewEST;
Richard Smithe6975e92012-04-17 00:58:00 +00003018 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00003019 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner0567a792013-06-10 20:51:09 +00003020 New->setType(SemaRef.Context.getFunctionType(
3021 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00003022 } else {
3023 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3024 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00003025 }
3026
Rafael Espindola19f74ac2011-07-06 15:46:09 +00003027 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00003028 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00003029 Tmpl->isDefined(Definition);
3030
DeLesley Hutchins23323e02012-01-20 22:50:54 +00003031 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3032 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00003033
Douglas Gregore53060f2009-06-25 22:08:12 +00003034 return false;
3035}
3036
Douglas Gregor5545e162009-03-24 00:38:23 +00003037/// \brief Initializes common fields of an instantiated method
3038/// declaration (New) from the corresponding fields of its template
3039/// (Tmpl).
3040///
3041/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00003042bool
3043TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00003044 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003045 if (InitFunctionInstantiation(New, Tmpl))
3046 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Douglas Gregor5545e162009-03-24 00:38:23 +00003048 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00003049 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00003050 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00003051
Douglas Gregor5545e162009-03-24 00:38:23 +00003052 // FIXME: New needs a pointer to Tmpl
3053 return false;
3054}
Douglas Gregora58861f2009-05-13 20:28:22 +00003055
3056/// \brief Instantiate the definition of the given function from its
3057/// template.
3058///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003059/// \param PointOfInstantiation the point at which the instantiation was
3060/// required. Note that this is not precisely a "point of instantiation"
3061/// for the function, but it's close.
3062///
Douglas Gregora58861f2009-05-13 20:28:22 +00003063/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003064/// function template specialization or member function of a class template
3065/// specialization.
3066///
3067/// \param Recursive if true, recursively instantiates any functions that
3068/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003069///
3070/// \param DefinitionRequired if true, then we are performing an explicit
3071/// instantiation where the body of the function is required. Complain if
3072/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003073void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003074 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003075 bool Recursive,
3076 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00003077 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003078 return;
3079
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003080 // Never instantiate an explicit specialization except if it is a class scope
3081 // explicit specialization.
3082 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3083 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003084 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00003085
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003086 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00003087 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00003088 assert(PatternDecl && "instantiating a non-template");
3089
3090 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3091 assert(PatternDecl && "template definition is not a template");
3092 if (!Pattern) {
3093 // Try to find a defaulted definition
3094 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00003095 }
Sean Huntf996e052011-05-27 20:00:14 +00003096 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003097
Francois Pichet8387e2a2011-04-22 22:18:13 +00003098 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00003099 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00003100 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00003101 PendingInstantiations.push_back(
3102 std::make_pair(Function, PointOfInstantiation));
3103 return;
3104 }
3105
David Majnemer360d23e2013-08-16 08:29:13 +00003106 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003107 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00003108 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00003109 LateTemplateParser) {
Richard Smithac32d902013-08-07 21:41:30 +00003110 // FIXME: Optimize to allow individual templates to be deserialized.
3111 if (PatternDecl->isFromASTFile())
3112 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3113
3114 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3115 assert(LPT && "missing LateParsedTemplate");
3116 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet8387e2a2011-04-22 22:18:13 +00003117 Pattern = PatternDecl->getBody(PatternDecl);
3118 }
3119
Sean Huntf996e052011-05-27 20:00:14 +00003120 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003121 if (DefinitionRequired) {
3122 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003123 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003124 diag::err_explicit_instantiation_undefined_func_template)
3125 << Function->getPrimaryTemplate();
3126 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003127 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003128 diag::err_explicit_instantiation_undefined_member)
3129 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003130
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003131 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003132 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003133 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00003134 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00003135 } else if (Function->getTemplateSpecializationKind()
3136 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003137 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003138 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003139 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00003140
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003141 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003142 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003143
Richard Smith60e141e2013-05-04 07:00:32 +00003144 // C++1y [temp.explicit]p10:
3145 // Except for inline functions, declarations with types deduced from their
3146 // initializer or return value, and class template specializations, other
3147 // explicit instantiation declarations have the effect of suppressing the
3148 // implicit instantiation of the entity to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00003149 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003150 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith60e141e2013-05-04 07:00:32 +00003151 !PatternDecl->isInlined() &&
Richard Smith37e849a2013-08-14 20:16:31 +00003152 !PatternDecl->getResultType()->getContainedAutoType())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003153 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003154
Richard Smithd4497dd2013-01-25 00:08:28 +00003155 if (PatternDecl->isInlined())
3156 Function->setImplicitlyInline();
3157
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003158 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
3159 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003160 return;
3161
Abramo Bagnarae9946242011-11-18 08:08:52 +00003162 // Copy the inner loc start from the pattern.
3163 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3164
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003165 // If we're performing recursive template instantiation, create our own
3166 // queue of pending implicit instantiations that we will instantiate later,
3167 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003168 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003169 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Faisal Vali86648b12013-06-26 02:34:24 +00003170 std::deque<PendingImplicitInstantiation>
3171 SavedPendingLocalImplicitInstantiations;
3172 SavedPendingLocalImplicitInstantiations.swap(
3173 PendingLocalImplicitInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003174 if (Recursive) {
3175 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003176 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003177 }
Mike Stump1eb44332009-09-09 15:08:12 +00003178
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003179 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00003180 Sema::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003181
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003182 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00003183 // recorded, unless we're actually a member function within a local
3184 // class, in which case we need to merge our results with the parent
3185 // scope (of the enclosing function).
3186 bool MergeWithParentScope = false;
3187 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3188 MergeWithParentScope = Rec->isLocalClass();
3189
3190 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00003191
Richard Smith1d28caf2012-12-11 01:14:52 +00003192 if (PatternDecl->isDefaulted())
Sean Huntcd10dec2011-05-23 23:14:04 +00003193 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smith1d28caf2012-12-11 01:14:52 +00003194 else {
3195 ActOnStartOfFunctionDef(0, Function);
3196
3197 // Enter the scope of this instantiation. We don't use
3198 // PushDeclContext because we don't have a scope.
3199 Sema::ContextRAII savedContext(*this, Function);
3200
3201 MultiLevelTemplateArgumentList TemplateArgs =
3202 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3203
3204 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3205 TemplateArgs);
3206
Sean Huntcd10dec2011-05-23 23:14:04 +00003207 // If this is a constructor, instantiate the member initializers.
3208 if (const CXXConstructorDecl *Ctor =
3209 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3210 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3211 TemplateArgs);
3212 }
3213
3214 // Instantiate the function body.
3215 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3216
3217 if (Body.isInvalid())
3218 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003219
Sean Huntcd10dec2011-05-23 23:14:04 +00003220 ActOnFinishFunctionBody(Function, Body.get(),
3221 /*IsInstantiation=*/true);
Richard Smith1d28caf2012-12-11 01:14:52 +00003222
3223 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3224
3225 savedContext.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00003226 }
3227
Douglas Gregoraba43bb2009-05-26 20:50:29 +00003228 DeclGroupRef DG(Function);
3229 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Douglas Gregor60406be2010-01-16 22:29:39 +00003231 // This class may have local implicit instantiations that need to be
3232 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003233 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00003234 Scope.Exit();
3235
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003236 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003237 // Define any pending vtables.
3238 DefineUsedVTables();
3239
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003240 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003241 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003242 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003244 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00003245 assert(VTableUses.empty() &&
3246 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003247 VTableUses.swap(SavedVTableUses);
3248
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003249 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003250 assert(PendingInstantiations.empty() &&
3251 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003252 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003253 }
Faisal Vali86648b12013-06-26 02:34:24 +00003254 SavedPendingLocalImplicitInstantiations.swap(
3255 PendingLocalImplicitInstantiations);
Douglas Gregora58861f2009-05-13 20:28:22 +00003256}
3257
Larisse Voufoef4579c2013-08-06 01:03:05 +00003258VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3259 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3260 const TemplateArgumentList &TemplateArgList,
3261 const TemplateArgumentListInfo &TemplateArgsInfo,
3262 SmallVectorImpl<TemplateArgument> &Converted,
3263 SourceLocation PointOfInstantiation, void *InsertPos,
3264 LateInstantiatedAttrVec *LateAttrs,
3265 LocalInstantiationScope *StartingScope) {
3266 if (FromVar->isInvalidDecl())
3267 return 0;
3268
3269 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
3270 if (Inst)
3271 return 0;
3272
3273 MultiLevelTemplateArgumentList TemplateArgLists;
3274 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3275
3276 TemplateDeclInstantiator Instantiator(
3277 *this, VarTemplate->getDeclContext(),
3278 MultiLevelTemplateArgumentList(TemplateArgList));
3279
3280 // TODO: Set LateAttrs and StartingScope ...
3281
3282 return cast_or_null<VarTemplateSpecializationDecl>(
3283 Instantiator.VisitVarTemplateSpecializationDecl(
3284 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3285}
3286
3287/// \brief Instantiates a variable template specialization by completing it
3288/// with appropriate type information and initializer.
3289VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3290 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3291 const MultiLevelTemplateArgumentList &TemplateArgs) {
3292
3293 // Do substitution on the type of the declaration
Larisse Voufo04592e72013-08-22 00:28:27 +00003294 MultiLevelTemplateArgumentList Innermost;
3295 Innermost.addOuterTemplateArguments(TemplateArgs.getInnermost());
Larisse Voufoef4579c2013-08-06 01:03:05 +00003296 TypeSourceInfo *DI =
Larisse Voufo04592e72013-08-22 00:28:27 +00003297 SubstType(PatternDecl->getTypeSourceInfo(), Innermost,
Larisse Voufoef4579c2013-08-06 01:03:05 +00003298 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3299 if (!DI)
3300 return 0;
3301
3302 // Update the type of this variable template specialization.
3303 VarSpec->setType(DI->getType());
3304
3305 // Instantiate the initializer.
3306 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3307
3308 return VarSpec;
3309}
3310
3311/// BuildVariableInstantiation - Used after a new variable has been created.
3312/// Sets basic variable data and decides whether to postpone the
3313/// variable instantiation.
3314void Sema::BuildVariableInstantiation(
3315 VarDecl *NewVar, VarDecl *OldVar,
3316 const MultiLevelTemplateArgumentList &TemplateArgs,
3317 LateInstantiatedAttrVec *LateAttrs,
3318 LocalInstantiationScope *StartingScope,
3319 bool ForVarTemplate) {
3320
3321 // If we are instantiating a static data member defined
3322 // out-of-line, the instantiation will have the same lexical
3323 // context (which will be a namespace scope) as the template.
3324 if (OldVar->isOutOfLine())
3325 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3326 NewVar->setTSCSpec(OldVar->getTSCSpec());
3327 NewVar->setInitStyle(OldVar->getInitStyle());
3328 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3329 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithdd9459f2013-08-13 18:18:50 +00003330 NewVar->setPreviousDeclInSameBlockScope(
3331 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufoef4579c2013-08-06 01:03:05 +00003332 NewVar->setAccess(OldVar->getAccess());
3333
3334 if (!OldVar->isStaticDataMember()) {
3335 NewVar->setUsed(OldVar->isUsed(false));
3336 NewVar->setReferenced(OldVar->isReferenced());
3337 }
3338
3339 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3340
3341 if (NewVar->hasAttrs())
3342 CheckAlignasUnderalignment(NewVar);
3343
Larisse Voufoef4579c2013-08-06 01:03:05 +00003344 LookupResult Previous(*this, NewVar->getDeclName(), NewVar->getLocation(),
3345 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
3346
Richard Smithdd9459f2013-08-13 18:18:50 +00003347 if (NewVar->getLexicalDeclContext()->isFunctionOrMethod() &&
3348 OldVar->getPreviousDecl()) {
3349 // We have a previous declaration. Use that one, so we merge with the
3350 // right type.
3351 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3352 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3353 Previous.addDecl(NewPrev);
3354 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3355 OldVar->hasLinkage())
Larisse Voufoef4579c2013-08-06 01:03:05 +00003356 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
3357
Larisse Voufo4a919892013-08-14 03:09:19 +00003358 CheckVariableDeclaration(NewVar, Previous, ForVarTemplate);
Larisse Voufoef4579c2013-08-06 01:03:05 +00003359
3360 if (OldVar->isOutOfLine()) {
3361 OldVar->getLexicalDeclContext()->addDecl(NewVar);
3362 if (!ForVarTemplate)
3363 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
3364 } else {
3365 if (!ForVarTemplate)
3366 NewVar->getDeclContext()->addDecl(NewVar);
3367 if (NewVar->getDeclContext()->isFunctionOrMethod())
3368 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3369 }
3370
3371 // Link instantiations of static data members back to the template from
3372 // which they were instantiated.
3373 if (NewVar->isStaticDataMember() && !ForVarTemplate)
3374 NewVar->setInstantiationOfStaticDataMember(OldVar,
3375 TSK_ImplicitInstantiation);
3376
3377 if (isa<VarTemplateSpecializationDecl>(NewVar)) {
3378 // Do not instantiate the variable just yet.
Larisse Voufo04592e72013-08-22 00:28:27 +00003379 } else if (ForVarTemplate) {
3380 assert(!NewVar->getInit() &&
3381 "A variable should not have an initializer if it is templated"
3382 " and we are instantiating its template");
3383 NewVar->setInit(OldVar->getInit());
Larisse Voufoef4579c2013-08-06 01:03:05 +00003384 } else
3385 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3386
3387 // Diagnose unused local variables with dependent types, where the diagnostic
3388 // will have been deferred.
3389 if (!NewVar->isInvalidDecl() &&
3390 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3391 OldVar->getType()->isDependentType())
3392 DiagnoseUnusedDecl(NewVar);
3393}
3394
3395/// \brief Instantiate the initializer of a variable.
3396void Sema::InstantiateVariableInitializer(
3397 VarDecl *Var, VarDecl *OldVar,
3398 const MultiLevelTemplateArgumentList &TemplateArgs) {
3399
3400 if (Var->getAnyInitializer())
3401 // We already have an initializer in the class.
3402 return;
3403
3404 if (OldVar->getInit()) {
3405 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3406 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3407 else
3408 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3409
3410 // Instantiate the initializer.
3411 ExprResult Init =
3412 SubstInitializer(OldVar->getInit(), TemplateArgs,
3413 OldVar->getInitStyle() == VarDecl::CallInit);
3414 if (!Init.isInvalid()) {
3415 bool TypeMayContainAuto = true;
3416 if (Init.get()) {
3417 bool DirectInit = OldVar->isDirectInit();
3418 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3419 } else
3420 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3421 } else {
3422 // FIXME: Not too happy about invalidating the declaration
3423 // because of a bogus initializer.
3424 Var->setInvalidDecl();
3425 }
3426
3427 PopExpressionEvaluationContext();
3428 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3429 !Var->isCXXForRangeDecl())
3430 ActOnUninitializedDecl(Var, false);
3431}
3432
Douglas Gregora58861f2009-05-13 20:28:22 +00003433/// \brief Instantiate the definition of the given variable from its
3434/// template.
3435///
Douglas Gregor7caa6822009-07-24 20:34:43 +00003436/// \param PointOfInstantiation the point at which the instantiation was
3437/// required. Note that this is not precisely a "point of instantiation"
3438/// for the function, but it's close.
3439///
3440/// \param Var the already-instantiated declaration of a static member
3441/// variable of a class template specialization.
3442///
3443/// \param Recursive if true, recursively instantiates any functions that
3444/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003445///
3446/// \param DefinitionRequired if true, then we are performing an explicit
3447/// instantiation where an out-of-line definition of the member variable
3448/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00003449void Sema::InstantiateStaticDataMemberDefinition(
3450 SourceLocation PointOfInstantiation,
3451 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003452 bool Recursive,
3453 bool DefinitionRequired) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003454 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3455 DefinitionRequired);
3456}
3457
3458void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3459 VarDecl *Var, bool Recursive,
3460 bool DefinitionRequired) {
3461
Douglas Gregor7caa6822009-07-24 20:34:43 +00003462 if (Var->isInvalidDecl())
3463 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003464
Larisse Voufoef4579c2013-08-06 01:03:05 +00003465 VarTemplateSpecializationDecl *VarSpec =
3466 dyn_cast<VarTemplateSpecializationDecl>(Var);
3467 assert((VarSpec || Var->isStaticDataMember()) &&
3468 "Not a static data member, nor a variable template specialization?");
3469 VarDecl *PatternDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Larisse Voufoef4579c2013-08-06 01:03:05 +00003471 // If this is a variable template specialization, make sure that it is
3472 // non-dependent, then find its instantiation pattern.
3473 if (VarSpec) {
3474 bool InstantiationDependent = false;
3475 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3476 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3477 "Only instantiate variable template specializations that are "
3478 "not type-dependent");
Larisse Voufo3151b7c2013-08-06 03:57:41 +00003479 (void)InstantiationDependent;
Larisse Voufoef4579c2013-08-06 01:03:05 +00003480
3481 // Find the variable initialization that we'll be substituting.
3482 assert(VarSpec->getSpecializedTemplate() &&
3483 "Specialization without specialized template?");
3484 llvm::PointerUnion<VarTemplateDecl *,
3485 VarTemplatePartialSpecializationDecl *> PatternPtr =
3486 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufo439d6652013-08-13 02:02:26 +00003487 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003488 PatternDecl = cast<VarDecl>(
3489 PatternPtr.get<VarTemplatePartialSpecializationDecl *>());
Larisse Voufo439d6652013-08-13 02:02:26 +00003490
3491 // Find actual definition
3492 if (VarDecl *Def = PatternDecl->getDefinition(getASTContext()))
3493 PatternDecl = Def;
3494 } else {
3495 VarTemplateDecl *PatternTemplate = PatternPtr.get<VarTemplateDecl *>();
3496
3497 // Find actual definition
3498 if (VarTemplateDecl *Def = PatternTemplate->getDefinition())
3499 PatternTemplate = Def;
3500
3501 PatternDecl = PatternTemplate->getTemplatedDecl();
3502 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00003503 assert(PatternDecl && "instantiating a non-template");
3504 }
3505
3506 // If this is a static data member, find its out-of-line definition.
3507 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
3508 if (Var->isStaticDataMember()) {
3509 assert(Def && "This data member was not instantiated from a template?");
3510 assert(Def->isStaticDataMember() && "Not a static data member?");
3511 Def = Def->getOutOfLineDefinition();
3512 }
3513
3514 // If the instantiation pattern does not have an initializer, or if an
3515 // out-of-line definition is not found, we won't perform any instantiation.
3516 // Rather, we rely on the user to instantiate this definition (or provide
3517 // a specialization for it) in another translation unit.
3518 if ((VarSpec && !PatternDecl->getInit()) ||
3519 (!VarSpec && Var->isStaticDataMember() && !Def)) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003520 if (DefinitionRequired) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003521 if (!Var->isStaticDataMember()) {
3522 Diag(PointOfInstantiation,
3523 diag::err_explicit_instantiation_undefined_var_template)
3524 << PatternDecl;
3525 Diag(PatternDecl->getLocation(),
3526 diag::note_explicit_instantiation_here);
3527 } else {
3528 Def = Var->getInstantiatedFromStaticDataMember();
3529 Diag(PointOfInstantiation,
3530 diag::err_explicit_instantiation_undefined_member)
3531 << 3 << Var->getDeclName() << Var->getDeclContext();
3532 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
3533 }
3534 if (VarSpec)
3535 Var->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00003536 } else if (Var->getTemplateSpecializationKind()
3537 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003538 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003539 std::make_pair(Var, PointOfInstantiation));
3540 }
3541
Douglas Gregor7caa6822009-07-24 20:34:43 +00003542 return;
3543 }
3544
Rafael Espindola234fe652012-03-05 10:54:55 +00003545 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3546
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003547 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00003548 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003549 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003550
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003551 // C++0x [temp.explicit]p9:
3552 // Except for inline functions, other explicit instantiation declarations
3553 // have the effect of suppressing the implicit instantiation of the entity
3554 // to which they refer.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003555 //
3556 // C++11 [temp.explicit]p10:
3557 // Except for inline functions, [...] explicit instantiation declarations
3558 // have the effect of suppressing the implicit instantiation of the entity
3559 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00003560 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003561 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003562
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003563 // Make sure to pass the instantiated variable to the consumer at the end.
3564 struct PassToConsumerRAII {
3565 ASTConsumer &Consumer;
3566 VarDecl *Var;
3567
3568 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3569 : Consumer(Consumer), Var(Var) { }
3570
3571 ~PassToConsumerRAII() {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003572 if (Var->isStaticDataMember())
3573 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3574 else {
3575 DeclGroupRef DG(Var);
3576 Consumer.HandleTopLevelDecl(DG);
3577 }
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003578 }
3579 } PassToConsumerRAII(Consumer, Var);
Rafael Espindola02503932012-03-08 15:51:03 +00003580
Larisse Voufoef4579c2013-08-06 01:03:05 +00003581 if (!VarSpec) {
3582 // If we already have a definition, we're done.
3583 if (VarDecl *Def = Var->getDefinition()) {
3584 // We may be explicitly instantiating something we've already implicitly
3585 // instantiated.
3586 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3587 PointOfInstantiation);
3588 return;
3589 }
Nick Lewycky95e38722012-04-04 02:38:36 +00003590 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003591
Douglas Gregor7caa6822009-07-24 20:34:43 +00003592 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3593 if (Inst)
3594 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Douglas Gregor7caa6822009-07-24 20:34:43 +00003596 // If we're performing recursive template instantiation, create our own
3597 // queue of pending implicit instantiations that we will instantiate later,
3598 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003599 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003600 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00003601 if (Recursive) {
3602 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003603 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00003604 }
Mike Stump1eb44332009-09-09 15:08:12 +00003605
Douglas Gregor7caa6822009-07-24 20:34:43 +00003606 // Enter the scope of this instantiation. We don't use
3607 // PushDeclContext because we don't have a scope.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003608 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003609 LocalInstantiationScope Local(*this);
John McCallf5ba7e02011-02-14 20:37:25 +00003610
Larisse Voufoef4579c2013-08-06 01:03:05 +00003611 VarDecl *OldVar = Var;
3612 if (!VarSpec)
3613 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
3614 getTemplateInstantiationArgs(Var)));
3615 else
3616 // Construct a VarTemplateSpecializationDecl to avoid name clashing with
3617 // the primary template. (Note that unlike function declarations, variable
3618 // declarations cannot be overloaded.)
3619 // In fact, there is no need to construct a new declaration from scratch.
3620 // Thus, simply complete its definition with an appropriately substituted
3621 // type and initializer.
3622 Var = CompleteVarTemplateSpecializationDecl(
3623 VarSpec, PatternDecl, getTemplateInstantiationArgs(Var));
3624
3625 PreviousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003626
3627 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00003628 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
Larisse Voufoef4579c2013-08-06 01:03:05 +00003629 if (!VarSpec)
3630 assert(MSInfo && "Missing member specialization information?");
3631
3632 PassToConsumerRAII.Var = Var;
3633 if (MSInfo)
3634 Var->setTemplateSpecializationKind(
3635 MSInfo->getTemplateSpecializationKind(),
3636 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00003637 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00003638
3639 // This variable may have local implicit instantiations that need to be
3640 // instantiated within this scope.
3641 PerformPendingInstantiations(/*LocalOnly=*/true);
3642
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003643 Local.Exit();
3644
Douglas Gregor7caa6822009-07-24 20:34:43 +00003645 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00003646 // Define any newly required vtables.
3647 DefineUsedVTables();
3648
Douglas Gregor7caa6822009-07-24 20:34:43 +00003649 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003650 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003651 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003652
Nick Lewycky81559102011-05-31 07:58:42 +00003653 // Restore the set of pending vtables.
3654 assert(VTableUses.empty() &&
Larisse Voufoef4579c2013-08-06 01:03:05 +00003655 "VTableUses should be empty before it is discarded.");
Nick Lewycky81559102011-05-31 07:58:42 +00003656 VTableUses.swap(SavedVTableUses);
3657
Douglas Gregor7caa6822009-07-24 20:34:43 +00003658 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003659 assert(PendingInstantiations.empty() &&
Larisse Voufoef4579c2013-08-06 01:03:05 +00003660 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003661 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00003662 }
Douglas Gregora58861f2009-05-13 20:28:22 +00003663}
Douglas Gregor815215d2009-05-27 05:35:12 +00003664
Anders Carlsson09025312009-08-29 05:16:22 +00003665void
3666Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3667 const CXXConstructorDecl *Tmpl,
3668 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Richard Trieu90ab75b2011-09-09 03:18:59 +00003670 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003671 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003672
Anders Carlsson09025312009-08-29 05:16:22 +00003673 // Instantiate all the initializers.
3674 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003675 InitsEnd = Tmpl->init_end();
3676 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003677 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003678
Chandler Carruth030ef472010-09-03 21:54:20 +00003679 // Only instantiate written initializers, let Sema re-construct implicit
3680 // ones.
3681 if (!Init->isWritten())
3682 continue;
3683
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003684 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003685
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003686 if (Init->isPackExpansion()) {
3687 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003688 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky98a75582013-06-13 00:45:47 +00003689 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003690 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky98a75582013-06-13 00:45:47 +00003691 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003692 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003693 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00003694 Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003695 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003696 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003697 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003698 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003699 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003700 NumExpansions)) {
3701 AnyErrors = true;
3702 New->setInvalidDecl();
3703 continue;
3704 }
3705 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003706
3707 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003708 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003709 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3710
3711 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003712 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3713 /*CXXDirectInit=*/true);
3714 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003715 AnyErrors = true;
3716 break;
3717 }
3718
3719 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003720 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003721 TemplateArgs,
3722 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003723 New->getDeclName());
3724 if (!BaseTInfo) {
3725 AnyErrors = true;
3726 break;
3727 }
3728
3729 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003730 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003731 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003732 New->getParent(),
3733 SourceLocation());
3734 if (NewInit.isInvalid()) {
3735 AnyErrors = true;
3736 break;
3737 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003738
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003739 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003740 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003741
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003742 continue;
3743 }
3744
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003745 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003746 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3747 /*CXXDirectInit=*/true);
3748 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003749 AnyErrors = true;
3750 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003751 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003752
Anders Carlsson09025312009-08-29 05:16:22 +00003753 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003754 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3755 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3756 TemplateArgs,
3757 Init->getSourceLocation(),
3758 New->getDeclName());
3759 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003760 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003761 New->setInvalidDecl();
3762 continue;
3763 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003764
Douglas Gregor76852c22011-11-01 01:16:03 +00003765 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003766 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003767 New->getParent(), EllipsisLoc);
3768 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003769 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003770 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003771 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003772 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003773 Init->getMemberLocation(),
3774 Init->getMember(),
3775 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003776 if (!Member) {
3777 AnyErrors = true;
3778 New->setInvalidDecl();
3779 continue;
3780 }
Mike Stump1eb44332009-09-09 15:08:12 +00003781
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003782 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003783 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003784 } else if (Init->isIndirectMemberInitializer()) {
3785 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003786 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003787 Init->getMemberLocation(),
3788 Init->getIndirectMember(), TemplateArgs));
3789
Douglas Gregorb7107222011-03-04 19:46:35 +00003790 if (!IndirectMember) {
3791 AnyErrors = true;
3792 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003793 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003794 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003795
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003796 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003797 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003798 }
3799
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003800 if (NewInit.isInvalid()) {
3801 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003802 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003803 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003804 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003805 }
3806 }
Mike Stump1eb44332009-09-09 15:08:12 +00003807
Anders Carlsson09025312009-08-29 05:16:22 +00003808 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003809 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003810 /*FIXME: ColonLoc */
3811 SourceLocation(),
David Blaikie93c86172013-01-17 05:26:25 +00003812 NewInits,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003813 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003814}
3815
John McCall52a575a2009-08-29 08:11:13 +00003816// TODO: this could be templated if the various decl types used the
3817// same method name.
3818static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3819 ClassTemplateDecl *Instance) {
3820 Pattern = Pattern->getCanonicalDecl();
3821
3822 do {
3823 Instance = Instance->getCanonicalDecl();
3824 if (Pattern == Instance) return true;
3825 Instance = Instance->getInstantiatedFromMemberTemplate();
3826 } while (Instance);
3827
3828 return false;
3829}
3830
Douglas Gregor0d696532009-09-28 06:34:35 +00003831static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3832 FunctionTemplateDecl *Instance) {
3833 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003834
Douglas Gregor0d696532009-09-28 06:34:35 +00003835 do {
3836 Instance = Instance->getCanonicalDecl();
3837 if (Pattern == Instance) return true;
3838 Instance = Instance->getInstantiatedFromMemberTemplate();
3839 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003840
Douglas Gregor0d696532009-09-28 06:34:35 +00003841 return false;
3842}
3843
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003844static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003845isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3846 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003847 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003848 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3849 do {
3850 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3851 Instance->getCanonicalDecl());
3852 if (Pattern == Instance)
3853 return true;
3854 Instance = Instance->getInstantiatedFromMember();
3855 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003856
Douglas Gregored9c0f92009-10-29 00:04:11 +00003857 return false;
3858}
3859
John McCall52a575a2009-08-29 08:11:13 +00003860static bool isInstantiationOf(CXXRecordDecl *Pattern,
3861 CXXRecordDecl *Instance) {
3862 Pattern = Pattern->getCanonicalDecl();
3863
3864 do {
3865 Instance = Instance->getCanonicalDecl();
3866 if (Pattern == Instance) return true;
3867 Instance = Instance->getInstantiatedFromMemberClass();
3868 } while (Instance);
3869
3870 return false;
3871}
3872
3873static bool isInstantiationOf(FunctionDecl *Pattern,
3874 FunctionDecl *Instance) {
3875 Pattern = Pattern->getCanonicalDecl();
3876
3877 do {
3878 Instance = Instance->getCanonicalDecl();
3879 if (Pattern == Instance) return true;
3880 Instance = Instance->getInstantiatedFromMemberFunction();
3881 } while (Instance);
3882
3883 return false;
3884}
3885
3886static bool isInstantiationOf(EnumDecl *Pattern,
3887 EnumDecl *Instance) {
3888 Pattern = Pattern->getCanonicalDecl();
3889
3890 do {
3891 Instance = Instance->getCanonicalDecl();
3892 if (Pattern == Instance) return true;
3893 Instance = Instance->getInstantiatedFromMemberEnum();
3894 } while (Instance);
3895
3896 return false;
3897}
3898
John McCalled976492009-12-04 22:46:56 +00003899static bool isInstantiationOf(UsingShadowDecl *Pattern,
3900 UsingShadowDecl *Instance,
3901 ASTContext &C) {
3902 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3903}
3904
3905static bool isInstantiationOf(UsingDecl *Pattern,
3906 UsingDecl *Instance,
3907 ASTContext &C) {
3908 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3909}
3910
John McCall7ba107a2009-11-18 02:36:19 +00003911static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3912 UsingDecl *Instance,
3913 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003914 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003915}
3916
3917static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003918 UsingDecl *Instance,
3919 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003920 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003921}
3922
John McCall52a575a2009-08-29 08:11:13 +00003923static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3924 VarDecl *Instance) {
3925 assert(Instance->isStaticDataMember());
3926
3927 Pattern = Pattern->getCanonicalDecl();
3928
3929 do {
3930 Instance = Instance->getCanonicalDecl();
3931 if (Pattern == Instance) return true;
3932 Instance = Instance->getInstantiatedFromStaticDataMember();
3933 } while (Instance);
3934
3935 return false;
3936}
3937
John McCalled976492009-12-04 22:46:56 +00003938// Other is the prospective instantiation
3939// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003940static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003941 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003942 if (UnresolvedUsingTypenameDecl *UUD
3943 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3944 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3945 return isInstantiationOf(UUD, UD, Ctx);
3946 }
3947 }
3948
3949 if (UnresolvedUsingValueDecl *UUD
3950 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003951 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3952 return isInstantiationOf(UUD, UD, Ctx);
3953 }
3954 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003955
Anders Carlsson0d8df782009-08-29 19:37:28 +00003956 return false;
3957 }
Mike Stump1eb44332009-09-09 15:08:12 +00003958
John McCall52a575a2009-08-29 08:11:13 +00003959 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3960 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003961
John McCall52a575a2009-08-29 08:11:13 +00003962 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3963 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003964
John McCall52a575a2009-08-29 08:11:13 +00003965 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3966 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003967
Douglas Gregor7caa6822009-07-24 20:34:43 +00003968 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003969 if (Var->isStaticDataMember())
3970 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3971
3972 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3973 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003974
Douglas Gregor0d696532009-09-28 06:34:35 +00003975 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3976 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3977
Douglas Gregored9c0f92009-10-29 00:04:11 +00003978 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3979 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3980 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3981 PartialSpec);
3982
Anders Carlssond8b285f2009-09-01 04:26:58 +00003983 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3984 if (!Field->getDeclName()) {
3985 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00003986 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00003987 cast<FieldDecl>(D);
3988 }
3989 }
Mike Stump1eb44332009-09-09 15:08:12 +00003990
John McCalled976492009-12-04 22:46:56 +00003991 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3992 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3993
3994 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3995 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3996
Douglas Gregor815215d2009-05-27 05:35:12 +00003997 return D->getDeclName() && isa<NamedDecl>(Other) &&
3998 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3999}
4000
4001template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00004002static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00004003 NamedDecl *D,
4004 ForwardIterator first,
4005 ForwardIterator last) {
4006 for (; first != last; ++first)
4007 if (isInstantiationOf(Ctx, D, *first))
4008 return cast<NamedDecl>(*first);
4009
4010 return 0;
4011}
4012
John McCall02cace72009-08-28 07:59:38 +00004013/// \brief Finds the instantiation of the given declaration context
4014/// within the current instantiation.
4015///
4016/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004017DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00004018 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00004019 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004020 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00004021 return cast_or_null<DeclContext>(ID);
4022 } else return DC;
4023}
4024
Douglas Gregored961e72009-05-27 17:54:46 +00004025/// \brief Find the instantiation of the given declaration within the
4026/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00004027///
4028/// This routine is intended to be used when \p D is a declaration
4029/// referenced from within a template, that needs to mapped into the
4030/// corresponding declaration within an instantiation. For example,
4031/// given:
4032///
4033/// \code
4034/// template<typename T>
4035/// struct X {
4036/// enum Kind {
4037/// KnownValue = sizeof(T)
4038/// };
4039///
4040/// bool getKind() const { return KnownValue; }
4041/// };
4042///
4043/// template struct X<int>;
4044/// \endcode
4045///
Serge Pavlov041d10c2013-07-10 04:59:14 +00004046/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4047/// \p EnumConstantDecl for \p KnownValue (which refers to
4048/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4049/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4050/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004051NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00004052 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00004053 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00004054 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00004055 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00004056 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4057 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00004058 // D is a local of some kind. Look into the map of local
4059 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00004060 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4061 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4062 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004063
Chris Lattner57ad3782011-02-17 20:34:02 +00004064 if (Found) {
4065 if (Decl *FD = Found->dyn_cast<Decl *>())
4066 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004067
Richard Smith9a4db032012-09-12 00:56:43 +00004068 int PackIdx = ArgumentPackSubstitutionIndex;
4069 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00004070 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4071 }
4072
Serge Pavlovdc49d522013-07-15 06:14:07 +00004073 // If we're performing a partial substitution during template argument
4074 // deduction, we may not have values for template parameters yet. They
4075 // just map to themselves.
4076 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4077 isa<TemplateTemplateParmDecl>(D))
4078 return D;
4079
Serge Pavlov29a46e62013-08-10 12:00:21 +00004080 if (D->isInvalidDecl())
4081 return 0;
4082
Chris Lattner57ad3782011-02-17 20:34:02 +00004083 // If we didn't find the decl, then we must have a label decl that hasn't
4084 // been found yet. Lazily instantiate it and return it now.
4085 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004086
Chris Lattner57ad3782011-02-17 20:34:02 +00004087 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4088 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004089
Chris Lattner57ad3782011-02-17 20:34:02 +00004090 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4091 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00004092 }
Douglas Gregor815215d2009-05-27 05:35:12 +00004093
Larisse Voufoef4579c2013-08-06 01:03:05 +00004094 // For variable template specializations, update those that are still
4095 // type-dependent.
4096 if (VarTemplateSpecializationDecl *VarSpec =
4097 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4098 bool InstantiationDependent = false;
4099 const TemplateArgumentListInfo &VarTemplateArgs =
4100 VarSpec->getTemplateArgsInfo();
4101 if (TemplateSpecializationType::anyDependentTemplateArguments(
4102 VarTemplateArgs, InstantiationDependent))
4103 D = cast<NamedDecl>(
4104 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4105 return D;
4106 }
4107
Douglas Gregore95b4092009-09-16 18:34:49 +00004108 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4109 if (!Record->isDependentContext())
4110 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004111
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004112 // Determine whether this record is the "templated" declaration describing
4113 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00004114 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004115 if (ClassTemplate)
4116 ClassTemplate = ClassTemplate->getCanonicalDecl();
4117 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4118 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4119 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufoef4579c2013-08-06 01:03:05 +00004120
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004121 // Walk the current context to find either the record or an instantiation of
4122 // it.
4123 DeclContext *DC = CurContext;
4124 while (!DC->isFileContext()) {
4125 // If we're performing substitution while we're inside the template
4126 // definition, we'll find our own context. We're done.
4127 if (DC->Equals(Record))
4128 return Record;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004129
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004130 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4131 // Check whether we're in the process of instantiating a class template
4132 // specialization of the template we're mapping.
4133 if (ClassTemplateSpecializationDecl *InstSpec
4134 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4135 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4136 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4137 return InstRecord;
4138 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004139
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004140 // Check whether we're in the process of instantiating a member class.
4141 if (isInstantiationOf(Record, InstRecord))
4142 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00004143 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004144
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004145 // Move to the outer template scope.
4146 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4147 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4148 DC = FD->getLexicalDeclContext();
4149 continue;
4150 }
John McCall52a575a2009-08-29 08:11:13 +00004151 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004152
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004153 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00004154 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00004155
Douglas Gregore95b4092009-09-16 18:34:49 +00004156 // Fall through to deal with other dependent record types (e.g.,
4157 // anonymous unions in class templates).
4158 }
John McCall52a575a2009-08-29 08:11:13 +00004159
Douglas Gregore95b4092009-09-16 18:34:49 +00004160 if (!ParentDC->isDependentContext())
4161 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004162
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004163 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004164 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00004165 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Douglas Gregor815215d2009-05-27 05:35:12 +00004167 if (ParentDC != D->getDeclContext()) {
4168 // We performed some kind of instantiation in the parent context,
4169 // so now we need to look into the instantiated parent context to
4170 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004171
John McCall3cb0ebd2010-03-10 03:28:59 +00004172 // If our context used to be dependent, we may need to instantiate
4173 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004174 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00004175 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004176 if (!Spec->isDependentContext()) {
4177 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00004178 const RecordType *Tag = T->getAs<RecordType>();
4179 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004180 if (Tag->isBeingDefined())
4181 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00004182 if (!Tag->isBeingDefined() &&
4183 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4184 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00004185
4186 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004187 }
4188 }
4189
Douglas Gregor815215d2009-05-27 05:35:12 +00004190 NamedDecl *Result = 0;
4191 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004192 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00004193 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor815215d2009-05-27 05:35:12 +00004194 } else {
4195 // Since we don't have a name for the entity we're looking for,
4196 // our only option is to walk through all of the declarations to
4197 // find that name. This will occur in a few cases:
4198 //
4199 // - anonymous struct/union within a template
4200 // - unnamed class/struct/union/enum within a template
4201 //
4202 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00004203 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004204 ParentDC->decls_begin(),
4205 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00004206 }
Mike Stump1eb44332009-09-09 15:08:12 +00004207
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004208 if (!Result) {
4209 if (isa<UsingShadowDecl>(D)) {
4210 // UsingShadowDecls can instantiate to nothing because of using hiding.
4211 } else if (Diags.hasErrorOccurred()) {
4212 // We've already complained about something, so most likely this
4213 // declaration failed to instantiate. There's no point in complaining
4214 // further, since this is normal in invalid code.
4215 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004216 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004217 // instantiated, and we haven't gotten around to instantiating this
4218 // member yet. This can happen when the code uses forward declarations
4219 // of member classes, and introduces ordering dependencies via
4220 // template instantiation.
4221 Diag(Loc, diag::err_member_not_yet_instantiated)
4222 << D->getDeclName()
4223 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4224 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00004225 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4226 // This enumeration constant was found when the template was defined,
4227 // but can't be found in the instantiation. This can happen if an
4228 // unscoped enumeration member is explicitly specialized.
4229 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4230 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4231 TemplateArgs));
4232 assert(Spec->getTemplateSpecializationKind() ==
4233 TSK_ExplicitSpecialization);
4234 Diag(Loc, diag::err_enumerator_does_not_exist)
4235 << D->getDeclName()
4236 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4237 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4238 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004239 } else {
4240 // We should have found something, but didn't.
4241 llvm_unreachable("Unable to find instantiation of declaration!");
4242 }
4243 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004244
Douglas Gregor815215d2009-05-27 05:35:12 +00004245 D = Result;
4246 }
4247
Douglas Gregor815215d2009-05-27 05:35:12 +00004248 return D;
4249}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004250
Mike Stump1eb44332009-09-09 15:08:12 +00004251/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004252/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00004253void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00004254 // Load pending instantiations from the external source.
4255 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00004256 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00004257 ExternalSource->ReadPendingInstantiations(Pending);
4258 PendingInstantiations.insert(PendingInstantiations.begin(),
4259 Pending.begin(), Pending.end());
4260 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004261
Douglas Gregor60406be2010-01-16 22:29:39 +00004262 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00004263 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00004264 PendingImplicitInstantiation Inst;
4265
4266 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00004267 Inst = PendingInstantiations.front();
4268 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00004269 } else {
4270 Inst = PendingLocalImplicitInstantiations.front();
4271 PendingLocalImplicitInstantiations.pop_front();
4272 }
Mike Stump1eb44332009-09-09 15:08:12 +00004273
Douglas Gregor7caa6822009-07-24 20:34:43 +00004274 // Instantiate function definitions
4275 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00004276 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4277 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00004278 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4279 TSK_ExplicitInstantiationDefinition;
4280 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4281 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00004282 continue;
4283 }
Mike Stump1eb44332009-09-09 15:08:12 +00004284
Larisse Voufoef4579c2013-08-06 01:03:05 +00004285 // Instantiate variable definitions
Douglas Gregor7caa6822009-07-24 20:34:43 +00004286 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufoef4579c2013-08-06 01:03:05 +00004287
4288 assert((Var->isStaticDataMember() ||
4289 isa<VarTemplateSpecializationDecl>(Var)) &&
4290 "Not a static data member, nor a variable template"
4291 " specialization?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00004292
Chandler Carruth291b4412010-02-13 10:17:50 +00004293 // Don't try to instantiate declarations if the most recent redeclaration
4294 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004295 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00004296 continue;
4297
4298 // Check if the most recent declaration has changed the specialization kind
4299 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004300 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00004301 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00004302 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00004303 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00004304 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00004305 continue; // No longer need to instantiate this type.
4306 case TSK_ExplicitInstantiationDefinition:
4307 // We only need an instantiation if the pending instantiation *is* the
4308 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004309 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00004310 case TSK_ImplicitInstantiation:
4311 break;
4312 }
4313
Larisse Voufoef4579c2013-08-06 01:03:05 +00004314 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4315 "instantiating variable definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00004316 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4317 TSK_ExplicitInstantiationDefinition;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004318
4319 // Instantiate static data member definitions or variable template
4320 // specializations.
4321 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4322 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004323 }
4324}
John McCall0c01d182010-03-24 05:22:00 +00004325
4326void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4327 const MultiLevelTemplateArgumentList &TemplateArgs) {
4328 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
4329 E = Pattern->ddiag_end(); I != E; ++I) {
4330 DependentDiagnostic *DD = *I;
4331
4332 switch (DD->getKind()) {
4333 case DependentDiagnostic::Access:
4334 HandleDependentAccessCheck(*DD, TemplateArgs);
4335 break;
4336 }
4337 }
4338}