blob: 2015c33e4fd6d170da2a0c775c9737e1e767e930 [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
Rafael Espindolabc650912013-10-17 15:37:26 +0000257 Typedef->setPreviousDecl(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)
Rafael Espindolabc650912013-10-17 15:37:26 +0000309 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3e4c6c42011-05-05 21:57:07 +0000310
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
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000321Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo567f9172013-08-22 00:59:14 +0000322 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000323}
324
Larisse Voufo567f9172013-08-22 00:59:14 +0000325Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
326 bool InstantiatingVarTemplate) {
Larisse Voufoef4579c2013-08-06 01:03:05 +0000327
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
Richard Smitha41c97a2013-09-20 01:15:31 +0000349 DeclContext *DC = Owner;
350 if (D->isLocalExternDecl())
351 SemaRef.adjustContextForLocalExternDecl(DC);
352
Larisse Voufoef4579c2013-08-06 01:03:05 +0000353 // Build the instantiated declaration.
Richard Smitha41c97a2013-09-20 01:15:31 +0000354 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000355 D->getLocation(), D->getIdentifier(),
Larisse Voufoef4579c2013-08-06 01:03:05 +0000356 DI->getType(), DI, D->getStorageClass());
Mike Stump1eb44332009-09-09 15:08:12 +0000357
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000358 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000359 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000360 SemaRef.inferObjCARCLifetime(Var))
361 Var->setInvalidDecl();
362
Larisse Voufoef4579c2013-08-06 01:03:05 +0000363 // Substitute the nested name specifier, if any.
364 if (SubstQualifier(D, Var))
365 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Richard Smitha41c97a2013-09-20 01:15:31 +0000367 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo567f9172013-08-22 00:59:14 +0000368 StartingScope, InstantiatingVarTemplate);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000369 return Var;
370}
371
Abramo Bagnara6206d532010-06-05 05:09:32 +0000372Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
373 AccessSpecDecl* AD
374 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
375 D->getAccessSpecifierLoc(), D->getColonLoc());
376 Owner->addHiddenDecl(AD);
377 return AD;
378}
379
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000380Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
381 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000382 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000383 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000384 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000385 DI = SemaRef.SubstType(DI, TemplateArgs,
386 D->getLocation(), D->getDeclName());
387 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000388 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000389 Invalid = true;
390 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000391 // C++ [temp.arg.type]p3:
392 // If a declaration acquires a function type through a type
393 // dependent on a template-parameter and this causes a
394 // declaration that does not use the syntactic form of a
395 // function declarator to have function type, the program is
396 // ill-formed.
397 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000398 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000399 Invalid = true;
400 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000401 } else {
402 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000403 }
404
405 Expr *BitWidth = D->getBitWidth();
406 if (Invalid)
407 BitWidth = 0;
408 else if (BitWidth) {
Richard Smithf6702a32011-12-20 02:08:33 +0000409 // The bit-width expression is a constant expression.
410 EnterExpressionEvaluationContext Unevaluated(SemaRef,
411 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000412
John McCall60d7b3a2010-08-24 06:29:42 +0000413 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000414 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000415 if (InstantiatedBitWidth.isInvalid()) {
416 Invalid = true;
417 BitWidth = 0;
418 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000419 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000420 }
421
John McCall07fb6be2009-10-22 23:33:21 +0000422 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
423 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000424 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000425 D->getLocation(),
426 D->isMutable(),
427 BitWidth,
Richard Smithca523302012-06-10 03:12:00 +0000428 D->getInClassInitStyle(),
Richard Smith703b6012012-05-23 04:22:22 +0000429 D->getInnerLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 D->getAccess(),
431 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000432 if (!Field) {
433 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000434 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000435 }
Mike Stump1eb44332009-09-09 15:08:12 +0000436
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000437 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000438
Richard Smithbe507b62013-02-01 08:12:08 +0000439 if (Field->hasAttrs())
440 SemaRef.CheckAlignasUnderalignment(Field);
441
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000442 if (Invalid)
443 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000445 if (!Field->getDeclName()) {
446 // Keep track of where this decl came from.
447 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000448 }
Douglas Gregor9901c572010-05-21 00:31:19 +0000449 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
450 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000451 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000452 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000453 }
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000455 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000456 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000457 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000458
459 return Field;
460}
461
John McCall76da55d2013-04-16 07:28:30 +0000462Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
463 bool Invalid = false;
464 TypeSourceInfo *DI = D->getTypeSourceInfo();
465
466 if (DI->getType()->isVariablyModifiedType()) {
467 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
468 << D->getName();
469 Invalid = true;
470 } else if (DI->getType()->isInstantiationDependentType()) {
471 DI = SemaRef.SubstType(DI, TemplateArgs,
472 D->getLocation(), D->getDeclName());
473 if (!DI) {
474 DI = D->getTypeSourceInfo();
475 Invalid = true;
476 } else if (DI->getType()->isFunctionType()) {
477 // C++ [temp.arg.type]p3:
478 // If a declaration acquires a function type through a type
479 // dependent on a template-parameter and this causes a
480 // declaration that does not use the syntactic form of a
481 // function declarator to have function type, the program is
482 // ill-formed.
483 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
484 << DI->getType();
485 Invalid = true;
486 }
487 } else {
488 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
489 }
490
491 MSPropertyDecl *Property = new (SemaRef.Context)
492 MSPropertyDecl(Owner, D->getLocation(),
493 D->getDeclName(), DI->getType(), DI,
494 D->getLocStart(),
495 D->getGetterId(), D->getSetterId());
496
497 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
498 StartingScope);
499
500 if (Invalid)
501 Property->setInvalidDecl();
502
503 Property->setAccess(D->getAccess());
504 Owner->addDecl(Property);
505
506 return Property;
507}
508
Francois Pichet87c2e122010-11-21 06:08:52 +0000509Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
510 NamedDecl **NamedChain =
511 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
512
513 int i = 0;
514 for (IndirectFieldDecl::chain_iterator PI =
515 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000516 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000517 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000518 TemplateArgs);
519 if (!Next)
520 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000521
Douglas Gregorb7107222011-03-04 19:46:35 +0000522 NamedChain[i++] = Next;
523 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000524
Francois Pichet40e17752010-12-09 10:07:54 +0000525 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000526 IndirectFieldDecl* IndirectField
527 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000528 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000529 NamedChain, D->getChainingSize());
530
531
532 IndirectField->setImplicit(D->isImplicit());
533 IndirectField->setAccess(D->getAccess());
534 Owner->addDecl(IndirectField);
535 return IndirectField;
536}
537
John McCall02cace72009-08-28 07:59:38 +0000538Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000539 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000540 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000541 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000542 TypeSourceInfo *InstTy;
543 // If this is an unsupported friend, don't bother substituting template
544 // arguments into it. The actual type referred to won't be used by any
545 // parts of Clang, and may not be valid for instantiating. Just use the
546 // same info for the instantiated friend.
547 if (D->isUnsupportedFriend()) {
548 InstTy = Ty;
549 } else {
550 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
551 D->getLocation(), DeclarationName());
552 }
553 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000554 return 0;
John McCall02cace72009-08-28 07:59:38 +0000555
Richard Smithd6f80da2012-09-20 01:31:00 +0000556 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara0216df82011-10-29 20:52:52 +0000557 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000558 if (!FD)
559 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000560
Douglas Gregor06245bf2010-04-07 17:57:12 +0000561 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000562 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000563 Owner->addDecl(FD);
564 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000565 }
566
Douglas Gregor06245bf2010-04-07 17:57:12 +0000567 NamedDecl *ND = D->getFriendDecl();
568 assert(ND && "friend decl must be a decl or a type!");
569
John McCallaf2094e2010-04-08 09:05:18 +0000570 // All of the Visit implementations for the various potential friend
571 // declarations have to be carefully written to work for friend
572 // objects, with the most important detail being that the target
573 // decl should almost certainly not be placed in Owner.
574 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000575 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCall02cace72009-08-28 07:59:38 +0000577 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000578 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000579 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000580 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000581 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000582 Owner->addDecl(FD);
583 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000584}
585
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000586Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
587 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000588
Richard Smithf6702a32011-12-20 02:08:33 +0000589 // The expression in a static assertion is a constant expression.
590 EnterExpressionEvaluationContext Unevaluated(SemaRef,
591 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000592
John McCall60d7b3a2010-08-24 06:29:42 +0000593 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000594 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000595 if (InstantiatedAssertExpr.isInvalid())
596 return 0;
597
Richard Smithe3f470a2012-07-11 22:37:56 +0000598 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000599 InstantiatedAssertExpr.get(),
Richard Smithe3f470a2012-07-11 22:37:56 +0000600 D->getMessage(),
601 D->getRParenLoc(),
602 D->isFailed());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000603}
604
605Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith38f0df32012-03-26 04:58:10 +0000606 EnumDecl *PrevDecl = 0;
607 if (D->getPreviousDecl()) {
608 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
609 D->getPreviousDecl(),
610 TemplateArgs);
611 if (!Prev) return 0;
612 PrevDecl = cast<EnumDecl>(Prev);
613 }
614
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000615 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000616 D->getLocation(), D->getIdentifier(),
Richard Smith38f0df32012-03-26 04:58:10 +0000617 PrevDecl, D->isScoped(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000618 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000619 if (D->isFixed()) {
Richard Smithf1c66b42012-03-14 23:13:10 +0000620 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000621 // If we have type source information for the underlying type, it means it
622 // has been explicitly set by the user. Perform substitution on it before
623 // moving on.
624 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smithf1c66b42012-03-14 23:13:10 +0000625 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
626 DeclarationName());
627 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000628 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smithf1c66b42012-03-14 23:13:10 +0000629 else
630 Enum->setIntegerTypeSourceInfo(NewTI);
631 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000632 assert(!D->getIntegerType()->isDependentType()
633 && "Dependent type without type source info");
634 Enum->setIntegerType(D->getIntegerType());
635 }
636 }
637
John McCall5b629aa2010-10-22 23:36:17 +0000638 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
639
Richard Smithf1c66b42012-03-14 23:13:10 +0000640 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000641 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000642 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000643 Owner->addDecl(Enum);
Richard Smithf1c66b42012-03-14 23:13:10 +0000644
Richard Smith4ca93d92012-03-26 04:08:46 +0000645 EnumDecl *Def = D->getDefinition();
646 if (Def && Def != D) {
647 // If this is an out-of-line definition of an enum member template, check
648 // that the underlying types match in the instantiation of both
649 // declarations.
650 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
651 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
652 QualType DefnUnderlying =
653 SemaRef.SubstType(TI->getType(), TemplateArgs,
654 UnderlyingLoc, DeclarationName());
655 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
656 DefnUnderlying, Enum);
657 }
658 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000659
Douglas Gregor96084f12010-03-01 19:00:07 +0000660 if (D->getDeclContext()->isFunctionOrMethod())
661 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000662
Richard Smithf1c66b42012-03-14 23:13:10 +0000663 // C++11 [temp.inst]p1: The implicit instantiation of a class template
664 // specialization causes the implicit instantiation of the declarations, but
665 // not the definitions of scoped member enumerations.
666 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith38f0df32012-03-26 04:58:10 +0000667 // within a block scope, but we treat that much like a member template. Only
668 // instantiate the definition when visiting the definition in that case, since
669 // we will visit all redeclarations.
670 if (!Enum->isScoped() && Def &&
671 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith4ca93d92012-03-26 04:08:46 +0000672 InstantiateEnumDefinition(Enum, Def);
Richard Smithf1c66b42012-03-14 23:13:10 +0000673
674 return Enum;
675}
676
677void TemplateDeclInstantiator::InstantiateEnumDefinition(
678 EnumDecl *Enum, EnumDecl *Pattern) {
679 Enum->startDefinition();
680
Richard Smith1af83c42012-03-23 03:33:32 +0000681 // Update the location to refer to the definition.
682 Enum->setLocation(Pattern->getLocation());
683
Chris Lattner5f9e2722011-07-23 10:55:15 +0000684 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000685
686 EnumConstantDecl *LastEnumConst = 0;
Richard Smithf1c66b42012-03-14 23:13:10 +0000687 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
688 ECEnd = Pattern->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000689 EC != ECEnd; ++EC) {
690 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000691 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000692 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +0000693 // The enumerator's value expression is a constant expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000694 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smithf6702a32011-12-20 02:08:33 +0000695 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000696
John McCallce3ff2b2009-08-25 22:02:44 +0000697 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000698 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000699
700 // Drop the initial value and continue.
701 bool isInvalid = false;
702 if (Value.isInvalid()) {
703 Value = SemaRef.Owned((Expr *)0);
704 isInvalid = true;
705 }
706
Mike Stump1eb44332009-09-09 15:08:12 +0000707 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000708 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
709 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000710 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000711
712 if (isInvalid) {
713 if (EnumConst)
714 EnumConst->setInvalidDecl();
715 Enum->setInvalidDecl();
716 }
717
718 if (EnumConst) {
David Blaikie581deb32012-06-06 20:45:41 +0000719 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall5b629aa2010-10-22 23:36:17 +0000720
John McCall3b85ecf2010-01-23 22:37:59 +0000721 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000722 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000723 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000724 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000725
Richard Smithf1c66b42012-03-14 23:13:10 +0000726 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
727 !Enum->isScoped()) {
Douglas Gregor96084f12010-03-01 19:00:07 +0000728 // If the enumeration is within a function or method, record the enum
729 // constant as a local.
David Blaikie581deb32012-06-06 20:45:41 +0000730 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregor96084f12010-03-01 19:00:07 +0000731 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000732 }
733 }
Mike Stump1eb44332009-09-09 15:08:12 +0000734
Richard Smithf1c66b42012-03-14 23:13:10 +0000735 // FIXME: Fixup LBraceLoc
736 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
737 Enum->getRBraceLoc(), Enum,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +0000738 Enumerators,
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000739 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000740}
741
Douglas Gregor6477b692009-03-25 15:04:13 +0000742Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000743 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000744}
745
John McCalle29ba202009-08-20 01:44:21 +0000746Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000747 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
748
Douglas Gregor550d9b22009-10-31 17:21:17 +0000749 // Create a local instantiation scope for this class template, which
750 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000751 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000752 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000753 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000754 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000755 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000756
757 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000758
759 // Instantiate the qualifier. We have to do this first in case
760 // we're a friend declaration, because if we are then we need to put
761 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000762 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
763 if (QualifierLoc) {
764 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
765 TemplateArgs);
766 if (!QualifierLoc)
767 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000768 }
769
770 CXXRecordDecl *PrevDecl = 0;
771 ClassTemplateDecl *PrevClassTemplate = 0;
772
Douglas Gregoref96ee02012-01-14 16:38:05 +0000773 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky37574f52010-11-08 23:29:42 +0000774 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000775 if (!Found.empty()) {
776 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky37574f52010-11-08 23:29:42 +0000777 if (PrevClassTemplate)
778 PrevDecl = PrevClassTemplate->getTemplatedDecl();
779 }
780 }
781
John McCall93ba8572010-03-25 06:39:04 +0000782 // If this isn't a friend, then it's a member template, in which
783 // case we just want to build the instantiation in the
784 // specialization. If it is a friend, we want to build it in
785 // the appropriate context.
786 DeclContext *DC = Owner;
787 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000788 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000789 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000790 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000791 DC = SemaRef.computeDeclContext(SS);
792 if (!DC) return 0;
793 } else {
794 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
795 Pattern->getDeclContext(),
796 TemplateArgs);
797 }
798
799 // Look for a previous declaration of the template in the owning
800 // context.
801 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
802 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
803 SemaRef.LookupQualifiedName(R, DC);
804
805 if (R.isSingleResult()) {
806 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
807 if (PrevClassTemplate)
808 PrevDecl = PrevClassTemplate->getTemplatedDecl();
809 }
810
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000811 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000812 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000813 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000814 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000815 return 0;
816 }
817
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000818 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000819 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000820 bool Complain = true;
821
822 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
823 // template for struct std::tr1::__detail::_Map_base, where the
824 // template parameters of the friend declaration don't match the
825 // template parameters of the original declaration. In this one
826 // case, we don't complain about the ill-formed friend
827 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000828 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000829 Pattern->getIdentifier()->isStr("_Map_base") &&
830 DC->isNamespace() &&
831 cast<NamespaceDecl>(DC)->getIdentifier() &&
832 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
833 DeclContext *DCParent = DC->getParent();
834 if (DCParent->isNamespace() &&
835 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
836 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
837 DeclContext *DCParent2 = DCParent->getParent();
838 if (DCParent2->isNamespace() &&
839 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
840 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
841 DCParent2->getParent()->isTranslationUnit())
842 Complain = false;
843 }
844 }
845
John McCall93ba8572010-03-25 06:39:04 +0000846 TemplateParameterList *PrevParams
847 = PrevClassTemplate->getTemplateParameters();
848
849 // Make sure the parameter lists match.
850 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000851 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000852 Sema::TPL_TemplateMatch)) {
853 if (Complain)
854 return 0;
855
856 AdoptedPreviousTemplateParams = true;
857 InstParams = PrevParams;
858 }
John McCall93ba8572010-03-25 06:39:04 +0000859
860 // Do some additional validation, then merge default arguments
861 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000862 if (!AdoptedPreviousTemplateParams &&
863 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000864 Sema::TPC_ClassTemplate))
865 return 0;
866 }
867 }
868
John McCalle29ba202009-08-20 01:44:21 +0000869 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000870 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000871 Pattern->getLocStart(), Pattern->getLocation(),
872 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000873 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000874
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000875 if (QualifierLoc)
876 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000877
John McCalle29ba202009-08-20 01:44:21 +0000878 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000879 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
880 D->getIdentifier(), InstParams, RecordInst,
881 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000882 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000883
John McCall93ba8572010-03-25 06:39:04 +0000884 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000885 if (PrevClassTemplate)
886 Inst->setAccess(PrevClassTemplate->getAccess());
887 else
888 Inst->setAccess(D->getAccess());
889
Richard Smith22050f22013-07-17 23:53:16 +0000890 Inst->setObjectOfFriendDecl();
John McCall93ba8572010-03-25 06:39:04 +0000891 // TODO: do we want to track the instantiation progeny of this
892 // friend target decl?
893 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000894 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000895 if (!PrevClassTemplate)
896 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000897 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000898
Douglas Gregorf0510d42009-10-12 23:11:44 +0000899 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000900 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000901 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000902
Douglas Gregor259571e2009-10-30 22:42:42 +0000903 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000904 if (isFriend) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000905 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000906 Inst->setLexicalDeclContext(Owner);
907 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000908 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000909 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000910
Abramo Bagnara4c515482011-11-26 13:33:46 +0000911 if (D->isOutOfLine()) {
912 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
913 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
914 }
915
John McCalle29ba202009-08-20 01:44:21 +0000916 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000917
918 if (!PrevClassTemplate) {
919 // Queue up any out-of-line partial specializations of this member
920 // class template; the client will force their instantiation once
921 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000922 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000923 D->getPartialSpecializations(PartialSpecs);
924 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindolabc650912013-10-17 15:37:26 +0000925 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregord65587f2010-11-10 19:44:59 +0000926 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
927 }
928
John McCalle29ba202009-08-20 01:44:21 +0000929 return Inst;
930}
931
Douglas Gregord60e1052009-08-27 16:57:43 +0000932Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000933TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
934 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000935 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000936
Douglas Gregored9c0f92009-10-29 00:04:11 +0000937 // Lookup the already-instantiated declaration in the instantiation
938 // of the class template and return that.
939 DeclContext::lookup_result Found
940 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000941 if (Found.empty())
Douglas Gregored9c0f92009-10-29 00:04:11 +0000942 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000943
Douglas Gregored9c0f92009-10-29 00:04:11 +0000944 ClassTemplateDecl *InstClassTemplate
David Blaikie3bc93e32012-12-19 00:45:41 +0000945 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregored9c0f92009-10-29 00:04:11 +0000946 if (!InstClassTemplate)
947 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000948
Douglas Gregord65587f2010-11-10 19:44:59 +0000949 if (ClassTemplatePartialSpecializationDecl *Result
950 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
951 return Result;
952
953 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000954}
955
Larisse Voufoef4579c2013-08-06 01:03:05 +0000956Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
957 assert(D->getTemplatedDecl()->isStaticDataMember() &&
958 "Only static data member templates are allowed.");
Larisse Voufoef4579c2013-08-06 01:03:05 +0000959
960 // Create a local instantiation scope for this variable template, which
961 // will contain the instantiations of the template parameters.
962 LocalInstantiationScope Scope(SemaRef);
963 TemplateParameterList *TempParams = D->getTemplateParameters();
964 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
965 if (!InstParams)
966 return NULL;
967
968 VarDecl *Pattern = D->getTemplatedDecl();
969 VarTemplateDecl *PrevVarTemplate = 0;
970
971 if (Pattern->getPreviousDecl()) {
972 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
973 if (!Found.empty())
974 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
975 }
976
Richard Smithdd9459f2013-08-13 18:18:50 +0000977 VarDecl *VarInst =
Larisse Voufo567f9172013-08-22 00:59:14 +0000978 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
979 /*InstantiatingVarTemplate=*/true));
Larisse Voufoef4579c2013-08-06 01:03:05 +0000980
981 DeclContext *DC = Owner;
982
Larisse Voufoef4579c2013-08-06 01:03:05 +0000983 VarTemplateDecl *Inst = VarTemplateDecl::Create(
984 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
985 VarInst, PrevVarTemplate);
986 VarInst->setDescribedVarTemplate(Inst);
987
988 Inst->setAccess(D->getAccess());
989 if (!PrevVarTemplate)
990 Inst->setInstantiatedFromMemberTemplate(D);
991
992 if (D->isOutOfLine()) {
993 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
994 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
995 }
996
997 Owner->addDecl(Inst);
998
999 if (!PrevVarTemplate) {
1000 // Queue up any out-of-line partial specializations of this member
1001 // variable template; the client will force their instantiation once
1002 // the enclosing class has been instantiated.
1003 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1004 D->getPartialSpecializations(PartialSpecs);
1005 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindolabc650912013-10-17 15:37:26 +00001006 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufoef4579c2013-08-06 01:03:05 +00001007 OutOfLineVarPartialSpecs.push_back(
1008 std::make_pair(Inst, PartialSpecs[I]));
1009 }
1010
1011 return Inst;
1012}
1013
1014Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1015 VarTemplatePartialSpecializationDecl *D) {
1016 assert(D->isStaticDataMember() &&
1017 "Only static data member templates are allowed.");
Larisse Voufoef4579c2013-08-06 01:03:05 +00001018
1019 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1020
1021 // Lookup the already-instantiated declaration and return that.
1022 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1023 assert(!Found.empty() && "Instantiation found nothing?");
1024
1025 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1026 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1027
1028 if (VarTemplatePartialSpecializationDecl *Result =
1029 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1030 return Result;
1031
1032 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1033}
1034
Douglas Gregor7974c3b2009-10-07 17:21:34 +00001035Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +00001036TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001037 // Create a local instantiation scope for this function template, which
1038 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001039 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +00001040 // itself.
John McCall2a7fb272010-08-25 05:32:35 +00001041 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +00001042
Douglas Gregord60e1052009-08-27 16:57:43 +00001043 TemplateParameterList *TempParams = D->getTemplateParameters();
1044 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +00001045 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +00001046 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001047
Douglas Gregora735b202009-10-13 14:39:41 +00001048 FunctionDecl *Instantiated = 0;
1049 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001050 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +00001051 InstParams));
1052 else
1053 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001054 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +00001055 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001056
Douglas Gregora735b202009-10-13 14:39:41 +00001057 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +00001058 return 0;
1059
Mike Stump1eb44332009-09-09 15:08:12 +00001060 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +00001061 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001062 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +00001063 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +00001064 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001065 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +00001066 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +00001067
John McCallb1a56e72010-03-26 23:10:15 +00001068 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1069
John McCalle976ffe2009-12-14 23:19:40 +00001070 // Link the instantiation back to the pattern *unless* this is a
1071 // non-definition friend declaration.
1072 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +00001073 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +00001074 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001075
John McCallb1a56e72010-03-26 23:10:15 +00001076 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +00001077 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001078 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +00001079 } else if (InstTemplate->getDeclContext()->isRecord() &&
1080 !D->getPreviousDecl()) {
1081 SemaRef.CheckFriendAccess(InstTemplate);
1082 }
John McCallb1a56e72010-03-26 23:10:15 +00001083
Douglas Gregord60e1052009-08-27 16:57:43 +00001084 return InstTemplate;
1085}
1086
Douglas Gregord475b8d2009-03-25 21:17:03 +00001087Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1088 CXXRecordDecl *PrevDecl = 0;
1089 if (D->isInjectedClassName())
1090 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +00001091 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001092 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +00001093 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +00001094 TemplateArgs);
1095 if (!Prev) return 0;
1096 PrevDecl = cast<CXXRecordDecl>(Prev);
1097 }
Douglas Gregord475b8d2009-03-25 21:17:03 +00001098
1099 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +00001100 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001101 D->getLocStart(), D->getLocation(),
1102 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00001103
1104 // Substitute the nested name specifier, if any.
1105 if (SubstQualifier(D, Record))
1106 return 0;
1107
Douglas Gregord475b8d2009-03-25 21:17:03 +00001108 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001109 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1110 // the tag decls introduced by friend class declarations don't have an access
1111 // specifier. Remove once this area of the code gets sorted out.
1112 if (D->getAccess() != AS_none)
1113 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001114 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001115 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001116
John McCall02cace72009-08-28 07:59:38 +00001117 // If the original function was part of a friend declaration,
1118 // inherit its namespace state.
Richard Smith22050f22013-07-17 23:53:16 +00001119 if (D->getFriendObjectKind())
1120 Record->setObjectOfFriendDecl();
John McCall02cace72009-08-28 07:59:38 +00001121
Douglas Gregor9901c572010-05-21 00:31:19 +00001122 // Make sure that anonymous structs and unions are recorded.
1123 if (D->isAnonymousStructOrUnion()) {
1124 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001125 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001126 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1127 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001128
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001129 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001130 return Record;
1131}
1132
Douglas Gregor71074fd2012-09-13 21:56:43 +00001133/// \brief Adjust the given function type for an instantiation of the
1134/// given declaration, to cope with modifications to the function's type that
1135/// aren't reflected in the type-source information.
1136///
1137/// \param D The declaration we're instantiating.
1138/// \param TInfo The already-instantiated type.
1139static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1140 FunctionDecl *D,
1141 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001142 const FunctionProtoType *OrigFunc
1143 = D->getType()->castAs<FunctionProtoType>();
1144 const FunctionProtoType *NewFunc
1145 = TInfo->getType()->castAs<FunctionProtoType>();
1146 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1147 return TInfo->getType();
1148
1149 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1150 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1151 return Context.getFunctionType(NewFunc->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00001152 NewFunc->getArgTypes(), NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001153}
1154
John McCall02cace72009-08-28 07:59:38 +00001155/// Normal class members are of more specific types and therefore
1156/// don't make it here. This function serves two purposes:
1157/// 1) instantiating function templates
1158/// 2) substituting friend declarations
1159/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001160Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001161 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001162 // Check whether there is already a function template specialization for
1163 // this declaration.
1164 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001165 if (FunctionTemplate && !TemplateParams) {
Richard Smithc95d4132013-05-03 23:46:09 +00001166 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001168 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001169 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001170 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001171 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Douglas Gregor127102b2009-06-29 20:59:39 +00001173 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001174 if (SpecFunc)
1175 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001176 }
Mike Stump1eb44332009-09-09 15:08:12 +00001177
John McCallb0cb0222010-03-27 05:57:59 +00001178 bool isFriend;
1179 if (FunctionTemplate)
1180 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1181 else
1182 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1183
Douglas Gregor79c22782010-01-16 20:21:20 +00001184 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001185 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001186 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001187 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001188 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Chris Lattner5f9e2722011-07-23 10:55:15 +00001190 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001191 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001192 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001193 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001194 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001195
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001196 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1197 if (QualifierLoc) {
1198 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1199 TemplateArgs);
1200 if (!QualifierLoc)
1201 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001202 }
1203
John McCall68b6b872010-02-06 01:50:47 +00001204 // If we're instantiating a local function declaration, put the result
Richard Smitha41c97a2013-09-20 01:15:31 +00001205 // in the enclosing namespace; otherwise we need to find the instantiated
1206 // context.
John McCall68b6b872010-02-06 01:50:47 +00001207 DeclContext *DC;
Richard Smitha41c97a2013-09-20 01:15:31 +00001208 if (D->isLocalExternDecl()) {
John McCall68b6b872010-02-06 01:50:47 +00001209 DC = Owner;
Richard Smitha41c97a2013-09-20 01:15:31 +00001210 SemaRef.adjustContextForLocalExternDecl(DC);
1211 } else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001212 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001213 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001214 DC = SemaRef.computeDeclContext(SS);
1215 if (!DC) return 0;
1216 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001217 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001218 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001219 }
John McCall68b6b872010-02-06 01:50:47 +00001220
John McCall02cace72009-08-28 07:59:38 +00001221 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001222 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001223 D->getNameInfo(), T, TInfo,
Rafael Espindola459ef032013-04-16 02:29:15 +00001224 D->getCanonicalDecl()->getStorageClass(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001225 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001226 D->isConstexpr());
Enea Zaffanellade9ed712013-07-19 18:02:36 +00001227 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCallb6217662010-03-15 10:12:16 +00001228
Richard Smithd4497dd2013-01-25 00:08:28 +00001229 if (D->isInlined())
1230 Function->setImplicitlyInline();
1231
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001232 if (QualifierLoc)
1233 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001234
Richard Smitha41c97a2013-09-20 01:15:31 +00001235 if (D->isLocalExternDecl())
1236 Function->setLocalExternDecl();
1237
John McCallb1a56e72010-03-26 23:10:15 +00001238 DeclContext *LexicalDC = Owner;
Richard Smitha41c97a2013-09-20 01:15:31 +00001239 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCallb1a56e72010-03-26 23:10:15 +00001240 assert(D->getDeclContext()->isFileContext());
1241 LexicalDC = D->getDeclContext();
1242 }
1243
1244 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Douglas Gregore53060f2009-06-25 22:08:12 +00001246 // Attach the parameters
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001247 for (unsigned P = 0; P < Params.size(); ++P)
1248 if (Params[P])
1249 Params[P]->setOwningFunction(Function);
David Blaikie4278c652011-09-21 18:16:56 +00001250 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001251
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001252 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001253 if (TemplateParams) {
1254 // Our resulting instantiation is actually a function template, since we
1255 // are substituting only the outer template parameters. For example, given
1256 //
1257 // template<typename T>
1258 // struct X {
1259 // template<typename U> friend void f(T, U);
1260 // };
1261 //
1262 // X<int> x;
1263 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001264 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001265 // which means substituting int for T, but leaving "f" as a friend function
1266 // template.
1267 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001268 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001269 Function->getLocation(),
1270 Function->getDeclName(),
1271 TemplateParams, Function);
1272 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001273
1274 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001275
1276 if (isFriend && D->isThisDeclarationADefinition()) {
1277 // TODO: should we remember this connection regardless of whether
1278 // the friend declaration provided a body?
1279 FunctionTemplate->setInstantiatedFromMemberTemplate(
1280 D->getDescribedFunctionTemplate());
1281 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001282 } else if (FunctionTemplate) {
1283 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001284 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001285 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001286 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001287 Innermost.begin(),
1288 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001289 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001290 } else if (isFriend) {
1291 // Note, we need this connection even if the friend doesn't have a body.
1292 // Its body may exist but not have been attached yet due to deferred
1293 // parsing.
1294 // FIXME: It might be cleaner to set this when attaching the body to the
1295 // friend function declaration, however that would require finding all the
1296 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001297 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001298 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001299
Douglas Gregore53060f2009-06-25 22:08:12 +00001300 if (InitFunctionInstantiation(Function, D))
1301 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001302
John McCallaf2094e2010-04-08 09:05:18 +00001303 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001304
Richard Smitha41c97a2013-09-20 01:15:31 +00001305 LookupResult Previous(
1306 SemaRef, Function->getDeclName(), SourceLocation(),
1307 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1308 : Sema::LookupOrdinaryName,
1309 Sema::ForRedeclaration);
John McCall68263142009-11-18 22:49:29 +00001310
John McCallaf2094e2010-04-08 09:05:18 +00001311 if (DependentFunctionTemplateSpecializationInfo *Info
1312 = D->getDependentSpecializationInfo()) {
1313 assert(isFriend && "non-friend has dependent specialization info?");
1314
1315 // This needs to be set now for future sanity.
Richard Smith22050f22013-07-17 23:53:16 +00001316 Function->setObjectOfFriendDecl();
John McCallaf2094e2010-04-08 09:05:18 +00001317
1318 // Instantiate the explicit template arguments.
1319 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1320 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001321 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1322 ExplicitArgs, TemplateArgs))
1323 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001324
1325 // Map the candidate templates to their instantiations.
1326 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1327 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1328 Info->getTemplate(I),
1329 TemplateArgs);
1330 if (!Temp) return 0;
1331
1332 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1333 }
1334
1335 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1336 &ExplicitArgs,
1337 Previous))
1338 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001339
John McCallaf2094e2010-04-08 09:05:18 +00001340 isExplicitSpecialization = true;
1341
1342 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001343 // Look only into the namespace where the friend would be declared to
1344 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001345 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001346 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001347
Douglas Gregora735b202009-10-13 14:39:41 +00001348 // In C++, the previous declaration we find might be a tag type
1349 // (class or enum). In this case, the new declaration will hide the
1350 // tag type. Note that this does does not apply if we're declaring a
1351 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001352 if (Previous.isSingleTagDecl())
1353 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001354 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001355
John McCall9f54ad42009-12-10 09:41:52 +00001356 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001357 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001358
John McCall76d32642010-04-24 01:30:58 +00001359 NamedDecl *PrincipalDecl = (TemplateParams
1360 ? cast<NamedDecl>(FunctionTemplate)
1361 : Function);
1362
Douglas Gregora735b202009-10-13 14:39:41 +00001363 // If the original function was part of a friend declaration,
1364 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001365 if (isFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00001366 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001367 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001368
Gabor Greif77535df2010-08-30 22:25:56 +00001369 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001370
Richard Smith53e53512011-10-19 00:54:10 +00001371 // C++98 [temp.friend]p5: When a function is defined in a friend function
1372 // declaration in a class template, the function is defined at each
1373 // instantiation of the class template. The function is defined even if it
1374 // is never used.
1375 // C++11 [temp.friend]p4: When a function is defined in a friend function
1376 // declaration in a class template, the function is instantiated when the
1377 // function is odr-used.
1378 //
1379 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1380 // redefinition, but don't instantiate the function.
Richard Smith80ad52f2013-01-02 11:42:31 +00001381 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smith53e53512011-10-19 00:54:10 +00001382 SemaRef.Diags.getDiagnosticLevel(
1383 diag::warn_cxx98_compat_friend_redefinition,
1384 Function->getLocation())
1385 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001386 D->isThisDeclarationADefinition()) {
1387 // Check for a function body.
1388 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001389 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001390 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001391 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001392 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001393 diag::warn_cxx98_compat_friend_redefinition :
1394 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001395 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001396 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001397 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001398 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001399 // Check for redefinitions due to other instantiations of this or
1400 // a similar friend function.
1401 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1402 REnd = Function->redecls_end();
1403 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001404 if (*R == Function)
1405 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001406 switch (R->getFriendObjectKind()) {
1407 case Decl::FOK_None:
Richard Smith80ad52f2013-01-02 11:42:31 +00001408 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith53e53512011-10-19 00:54:10 +00001409 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001410 if (MemberSpecializationInfo *MSInfo
1411 = Function->getMemberSpecializationInfo()) {
1412 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1413 SourceLocation Loc = R->getLocation(); // FIXME
1414 MSInfo->setPointOfInstantiation(Loc);
1415 SemaRef.PendingLocalImplicitInstantiations.push_back(
1416 std::make_pair(Function, Loc));
1417 queuedInstantiation = true;
1418 }
1419 }
1420 }
1421 break;
1422 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001423 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001424 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001425 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001426 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001427 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001428 diag::warn_cxx98_compat_friend_redefinition :
1429 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001430 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001431 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001432 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001433 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001434 break;
1435 }
1436 }
1437 }
1438 }
Douglas Gregora735b202009-10-13 14:39:41 +00001439 }
1440
Richard Smitha41c97a2013-09-20 01:15:31 +00001441 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1442 DC->makeDeclVisibleInContext(PrincipalDecl);
1443
John McCall76d32642010-04-24 01:30:58 +00001444 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1445 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1446 PrincipalDecl->setNonMemberOperator();
1447
Sean Hunteb88ae52011-05-23 21:07:59 +00001448 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001449 return Function;
1450}
1451
Douglas Gregord60e1052009-08-27 16:57:43 +00001452Decl *
1453TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001454 TemplateParameterList *TemplateParams,
1455 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001456 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregord60e1052009-08-27 16:57:43 +00001457 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001458 // We are creating a function template specialization from a function
1459 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001460 // specialization for this particular set of template arguments.
Richard Smithc95d4132013-05-03 23:46:09 +00001461 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001462
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001463 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001464 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001465 = FunctionTemplate->findSpecialization(Innermost.begin(),
1466 Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001467 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001468
Douglas Gregor6b906862009-08-21 00:16:32 +00001469 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001470 if (SpecFunc)
1471 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001472 }
1473
John McCallb0cb0222010-03-27 05:57:59 +00001474 bool isFriend;
1475 if (FunctionTemplate)
1476 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1477 else
1478 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1479
Douglas Gregor79c22782010-01-16 20:21:20 +00001480 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001481 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001482 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001483 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001484
John McCall4eab39f2010-10-19 02:26:41 +00001485 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001486 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001487 unsigned NumTempParamLists = 0;
1488 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1489 TempParamLists.set_size(NumTempParamLists);
1490 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1491 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1492 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1493 if (!InstParams)
1494 return NULL;
1495 TempParamLists[I] = InstParams;
1496 }
1497 }
1498
Chris Lattner5f9e2722011-07-23 10:55:15 +00001499 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramerdc370c12012-01-20 14:42:32 +00001500 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001501 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001502 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001503 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001504
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001505 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1506 if (QualifierLoc) {
1507 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001508 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001509 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001510 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001511 }
1512
1513 DeclContext *DC = Owner;
1514 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001515 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001516 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001517 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001518 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001519
1520 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1521 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001522 } else {
1523 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1524 D->getDeclContext(),
1525 TemplateArgs);
1526 }
1527 if (!DC) return 0;
1528 }
1529
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001530 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001531 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001532 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001533
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001534 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001535 DeclarationNameInfo NameInfo
1536 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001537 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001538 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001539 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001540 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001541 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001542 false, Constructor->isConstexpr());
Richard Smithb5eb3f52013-05-17 02:19:35 +00001543
Richard Smith4841ca52013-04-10 05:48:59 +00001544 // Claim that the instantiation of a constructor or constructor template
1545 // inherits the same constructor that the template does.
Richard Smithb5eb3f52013-05-17 02:19:35 +00001546 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1547 Constructor->getInheritedConstructor())) {
1548 // If we're instantiating a specialization of a function template, our
1549 // "inherited constructor" will actually itself be a function template.
1550 // Instantiate a declaration of it, too.
1551 if (FunctionTemplate) {
1552 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1553 !Inh->getParent()->isDependentContext() &&
1554 "inheriting constructor template in dependent context?");
1555 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1556 Inh);
Alp Tokerd69f37b2013-10-08 08:09:04 +00001557 if (Inst.isInvalid())
Richard Smithb5eb3f52013-05-17 02:19:35 +00001558 return 0;
1559 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1560 LocalInstantiationScope LocalScope(SemaRef);
1561
1562 // Use the same template arguments that we deduced for the inheriting
1563 // constructor. There's no way they could be deduced differently.
1564 MultiLevelTemplateArgumentList InheritedArgs;
1565 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1566 Inh = cast_or_null<CXXConstructorDecl>(
1567 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1568 if (!Inh)
1569 return 0;
1570 }
Richard Smith4841ca52013-04-10 05:48:59 +00001571 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smithb5eb3f52013-05-17 02:19:35 +00001572 }
Douglas Gregor17e32f32009-08-21 22:43:28 +00001573 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001574 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001575 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001576 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001577 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001578 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001579 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001580 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001581 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001582 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001583 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001584 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001585 } else {
Rafael Espindola72fdc892013-04-15 12:38:20 +00001586 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnara25777432010-08-11 22:01:17 +00001587 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001588 StartLoc, NameInfo, T, TInfo,
Rafael Espindola72fdc892013-04-15 12:38:20 +00001589 SC, D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001590 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001591 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001592
Richard Smithd4497dd2013-01-25 00:08:28 +00001593 if (D->isInlined())
1594 Method->setImplicitlyInline();
1595
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001596 if (QualifierLoc)
1597 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001598
Douglas Gregord60e1052009-08-27 16:57:43 +00001599 if (TemplateParams) {
1600 // Our resulting instantiation is actually a function template, since we
1601 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001602 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001603 // template<typename T>
1604 // struct X {
1605 // template<typename U> void f(T, U);
1606 // };
1607 //
1608 // X<int> x;
1609 //
1610 // We are instantiating the member template "f" within X<int>, which means
1611 // substituting int for T, but leaving "f" as a member function template.
1612 // Build the function template itself.
1613 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1614 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001615 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001616 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001617 if (isFriend) {
1618 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001619 FunctionTemplate->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001620 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001621 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001622 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001623 } else if (FunctionTemplate) {
1624 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001625 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001626 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001627 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001628 Innermost.begin(),
1629 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001630 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001631 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001632 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001633 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001634 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001635
Mike Stump1eb44332009-09-09 15:08:12 +00001636 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001637 // out-of-line, the instantiation will have the same lexical
1638 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001639 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001640 if (NumTempParamLists)
1641 Method->setTemplateParameterListsInfo(SemaRef.Context,
1642 NumTempParamLists,
1643 TempParamLists.data());
1644
John McCallb0cb0222010-03-27 05:57:59 +00001645 Method->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001646 Method->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001647 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001648 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001649
Douglas Gregor5545e162009-03-24 00:38:23 +00001650 // Attach the parameters
1651 for (unsigned P = 0; P < Params.size(); ++P)
1652 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001653 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001654
1655 if (InitMethodInstantiation(Method, D))
1656 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001657
Abramo Bagnara25777432010-08-11 22:01:17 +00001658 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1659 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001660
John McCallb0cb0222010-03-27 05:57:59 +00001661 if (!FunctionTemplate || TemplateParams || isFriend) {
1662 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001663
Douglas Gregordec06662009-08-21 18:42:58 +00001664 // In C++, the previous declaration we find might be a tag type
1665 // (class or enum). In this case, the new declaration will hide the
1666 // tag type. Note that this does does not apply if we're declaring a
1667 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001668 if (Previous.isSingleTagDecl())
1669 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001670 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001671
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001672 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001673 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001674
Douglas Gregor4ba31362009-12-01 17:24:26 +00001675 if (D->isPure())
1676 SemaRef.CheckPureMethod(Method, SourceRange());
1677
John McCall1f2e1a92012-08-10 03:15:35 +00001678 // Propagate access. For a non-friend declaration, the access is
1679 // whatever we're propagating from. For a friend, it should be the
1680 // previous declaration we just found.
1681 if (isFriend && Method->getPreviousDecl())
1682 Method->setAccess(Method->getPreviousDecl()->getAccess());
1683 else
1684 Method->setAccess(D->getAccess());
1685 if (FunctionTemplate)
1686 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001687
Anders Carlsson9eefa222011-01-20 06:52:44 +00001688 SemaRef.CheckOverrideControl(Method);
1689
Eli Friedman3bc45152011-11-15 22:39:08 +00001690 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithac713512012-12-08 02:53:02 +00001691 if (D->isExplicitlyDefaulted())
1692 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001693 if (D->isDeletedAsWritten())
Richard Smithac713512012-12-08 02:53:02 +00001694 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001695
John McCall1f2e1a92012-08-10 03:15:35 +00001696 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001697 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001698 // do nothing
1699
1700 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001701 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001702 // do nothing
1703
1704 // Otherwise, check access to friends and make them visible.
1705 } else if (isFriend) {
1706 // We only need to re-check access for methods which we didn't
1707 // manage to match during parsing.
1708 if (!D->getPreviousDecl())
1709 SemaRef.CheckFriendAccess(Method);
1710
1711 Record->makeDeclVisibleInContext(Method);
1712
1713 // Otherwise, add the declaration. We don't need to do this for
1714 // class-scope specializations because we'll have matched them with
1715 // the appropriate template.
1716 } else if (!IsClassScopeSpecialization) {
1717 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001718 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001719
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001720 return Method;
1721}
1722
Douglas Gregor615c5d42009-03-24 16:43:20 +00001723Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001724 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001725}
1726
Douglas Gregor03b2b072009-03-24 00:15:49 +00001727Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001728 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001729}
1730
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001731Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001732 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001733}
1734
Eli Friedmanded99792013-06-27 23:21:55 +00001735Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie66874fb2013-02-21 01:47:18 +00001736 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1737 /*ExpectParameterPack=*/ false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001738}
1739
John McCalle29ba202009-08-20 01:44:21 +00001740Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1741 TemplateTypeParmDecl *D) {
1742 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001743 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001744
John McCalle29ba202009-08-20 01:44:21 +00001745 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001746 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1747 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001748 D->getDepth() - TemplateArgs.getNumLevels(),
1749 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001750 D->wasDeclaredWithTypename(),
1751 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001752 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001753
David Majnemer9d57b8d2013-08-28 23:48:32 +00001754 if (D->hasDefaultArgument()) {
1755 TypeSourceInfo *InstantiatedDefaultArg =
1756 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1757 D->getDefaultArgumentLoc(), D->getDeclName());
1758 if (InstantiatedDefaultArg)
1759 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1760 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001761
1762 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001763 // scope.
1764 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001765
John McCalle29ba202009-08-20 01:44:21 +00001766 return Inst;
1767}
1768
Douglas Gregor33642df2009-10-23 23:25:44 +00001769Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1770 NonTypeTemplateParmDecl *D) {
1771 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001772 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001773 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1774 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001775 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001776 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001777 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001778 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001779
1780 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001781 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001782 // expansion of types. Substitute into each of the expanded types.
1783 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1784 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1785 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1786 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1787 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001788 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001789 D->getDeclName());
1790 if (!NewDI)
1791 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001792
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001793 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1794 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1795 D->getLocation());
1796 if (NewT.isNull())
1797 return 0;
1798 ExpandedParameterPackTypes.push_back(NewT);
1799 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001800
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001801 IsExpandedParameterPack = true;
1802 DI = D->getTypeSourceInfo();
1803 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001804 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001805 // The non-type template parameter pack's type is a pack expansion of types.
1806 // Determine whether we need to expand this parameter pack into separate
1807 // types.
David Blaikie39e6ab42013-02-18 22:06:02 +00001808 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001809 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001810 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001811 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001812
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001813 // Determine whether the set of unexpanded parameter packs can and should
1814 // be expanded.
1815 bool Expand = true;
1816 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001817 Optional<unsigned> OrigNumExpansions
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001818 = Expansion.getTypePtr()->getNumExpansions();
David Blaikiedc84cd52013-02-20 22:23:23 +00001819 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001820 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1821 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001822 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001823 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001824 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001825 NumExpansions))
1826 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001827
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001828 if (Expand) {
1829 for (unsigned I = 0; I != *NumExpansions; ++I) {
1830 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1831 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001832 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001833 D->getDeclName());
1834 if (!NewDI)
1835 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001836
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001837 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1838 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1839 NewDI->getType(),
1840 D->getLocation());
1841 if (NewT.isNull())
1842 return 0;
1843 ExpandedParameterPackTypes.push_back(NewT);
1844 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001845
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001846 // Note that we have an expanded parameter pack. The "type" of this
1847 // expanded parameter pack is the original expansion type, but callers
1848 // will end up using the expanded parameter pack types for type-checking.
1849 IsExpandedParameterPack = true;
1850 DI = D->getTypeSourceInfo();
1851 T = DI->getType();
1852 } else {
1853 // We cannot fully expand the pack expansion now, so substitute into the
1854 // pattern and create a new pack expansion type.
1855 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1856 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001857 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001858 D->getDeclName());
1859 if (!NewPattern)
1860 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001861
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001862 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1863 NumExpansions);
1864 if (!DI)
1865 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001866
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001867 T = DI->getType();
1868 }
1869 } else {
1870 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001871 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001872 D->getLocation(), D->getDeclName());
1873 if (!DI)
1874 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001875
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001876 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001877 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001878 D->getLocation());
1879 if (T.isNull()) {
1880 T = SemaRef.Context.IntTy;
1881 Invalid = true;
1882 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001883 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001884
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001885 NonTypeTemplateParmDecl *Param;
1886 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001887 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001888 D->getInnerLocStart(),
1889 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001890 D->getDepth() - TemplateArgs.getNumLevels(),
1891 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001892 D->getIdentifier(), T,
1893 DI,
1894 ExpandedParameterPackTypes.data(),
1895 ExpandedParameterPackTypes.size(),
1896 ExpandedParameterPackTypesAsWritten.data());
1897 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001898 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001899 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001900 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001901 D->getDepth() - TemplateArgs.getNumLevels(),
1902 D->getPosition(),
1903 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001904 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001905
Douglas Gregor9a299e02011-03-04 17:52:15 +00001906 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001907 if (Invalid)
1908 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001909
David Majnemer9d57b8d2013-08-28 23:48:32 +00001910 if (D->hasDefaultArgument()) {
1911 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1912 if (!Value.isInvalid())
1913 Param->setDefaultArgument(Value.get(), false);
1914 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001915
1916 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001917 // scope.
1918 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001919 return Param;
1920}
1921
Richard Smith6964b3f2012-09-07 02:06:42 +00001922static void collectUnexpandedParameterPacks(
1923 Sema &S,
1924 TemplateParameterList *Params,
1925 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1926 for (TemplateParameterList::const_iterator I = Params->begin(),
1927 E = Params->end(); I != E; ++I) {
1928 if ((*I)->isTemplateParameterPack())
1929 continue;
1930 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1931 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1932 Unexpanded);
1933 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1934 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1935 Unexpanded);
1936 }
1937}
1938
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001939Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001940TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1941 TemplateTemplateParmDecl *D) {
1942 // Instantiate the template parameter list of the template template parameter.
1943 TemplateParameterList *TempParams = D->getTemplateParameters();
1944 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001945 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1946
1947 bool IsExpandedParameterPack = false;
1948
1949 if (D->isExpandedParameterPack()) {
1950 // The template template parameter pack is an already-expanded pack
1951 // expansion of template parameters. Substitute into each of the expanded
1952 // parameters.
1953 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1954 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1955 I != N; ++I) {
1956 LocalInstantiationScope Scope(SemaRef);
1957 TemplateParameterList *Expansion =
1958 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1959 if (!Expansion)
1960 return 0;
1961 ExpandedParams.push_back(Expansion);
1962 }
1963
1964 IsExpandedParameterPack = true;
1965 InstParams = TempParams;
1966 } else if (D->isPackExpansion()) {
1967 // The template template parameter pack expands to a pack of template
1968 // template parameters. Determine whether we need to expand this parameter
1969 // pack into separate parameters.
1970 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1971 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1972 Unexpanded);
1973
1974 // Determine whether the set of unexpanded parameter packs can and should
1975 // be expanded.
1976 bool Expand = true;
1977 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001978 Optional<unsigned> NumExpansions;
Richard Smith6964b3f2012-09-07 02:06:42 +00001979 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1980 TempParams->getSourceRange(),
1981 Unexpanded,
1982 TemplateArgs,
1983 Expand, RetainExpansion,
1984 NumExpansions))
1985 return 0;
1986
1987 if (Expand) {
1988 for (unsigned I = 0; I != *NumExpansions; ++I) {
1989 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1990 LocalInstantiationScope Scope(SemaRef);
1991 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1992 if (!Expansion)
1993 return 0;
1994 ExpandedParams.push_back(Expansion);
1995 }
1996
1997 // Note that we have an expanded parameter pack. The "type" of this
1998 // expanded parameter pack is the original expansion type, but callers
1999 // will end up using the expanded parameter pack types for type-checking.
2000 IsExpandedParameterPack = true;
2001 InstParams = TempParams;
2002 } else {
2003 // We cannot fully expand the pack expansion now, so just substitute
2004 // into the pattern.
2005 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2006
2007 LocalInstantiationScope Scope(SemaRef);
2008 InstParams = SubstTemplateParams(TempParams);
2009 if (!InstParams)
2010 return 0;
2011 }
2012 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00002013 // Perform the actual substitution of template parameters within a new,
2014 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00002015 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00002016 InstParams = SubstTemplateParams(TempParams);
2017 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00002018 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002019 }
2020
Douglas Gregor9106ef72009-11-11 16:58:32 +00002021 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00002022 TemplateTemplateParmDecl *Param;
2023 if (IsExpandedParameterPack)
2024 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2025 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002026 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00002027 D->getPosition(),
2028 D->getIdentifier(), InstParams,
2029 ExpandedParams);
2030 else
2031 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2032 D->getLocation(),
2033 D->getDepth() - TemplateArgs.getNumLevels(),
2034 D->getPosition(),
2035 D->isParameterPack(),
2036 D->getIdentifier(), InstParams);
David Majnemer9d57b8d2013-08-28 23:48:32 +00002037 if (D->hasDefaultArgument()) {
2038 NestedNameSpecifierLoc QualifierLoc =
2039 D->getDefaultArgument().getTemplateQualifierLoc();
2040 QualifierLoc =
2041 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2042 TemplateName TName = SemaRef.SubstTemplateName(
2043 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2044 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2045 if (!TName.isNull())
2046 Param->setDefaultArgument(
2047 TemplateArgumentLoc(TemplateArgument(TName),
2048 D->getDefaultArgument().getTemplateQualifierLoc(),
2049 D->getDefaultArgument().getTemplateNameLoc()),
2050 false);
2051 }
Douglas Gregor9a299e02011-03-04 17:52:15 +00002052 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002053
2054 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00002055 // scope.
2056 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002057
Douglas Gregor9106ef72009-11-11 16:58:32 +00002058 return Param;
2059}
2060
Douglas Gregor48c32a72009-11-17 06:07:40 +00002061Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00002062 // Using directives are never dependent (and never contain any types or
2063 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002064
Douglas Gregor48c32a72009-11-17 06:07:40 +00002065 UsingDirectiveDecl *Inst
2066 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002067 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00002068 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002069 D->getIdentLocation(),
2070 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00002071 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00002072
2073 // Add the using directive to its declaration context
2074 // only if this is not a function or method.
2075 if (!Owner->isFunctionOrMethod())
2076 Owner->addDecl(Inst);
2077
Douglas Gregor48c32a72009-11-17 06:07:40 +00002078 return Inst;
2079}
2080
John McCalled976492009-12-04 22:46:56 +00002081Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00002082
2083 // The nested name specifier may be dependent, for example
2084 // template <typename T> struct t {
2085 // struct s1 { T f1(); };
2086 // struct s2 : s1 { using s1::f1; };
2087 // };
2088 // template struct t<int>;
2089 // Here, in using s1::f1, s1 refers to t<T>::s1;
2090 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00002091 NestedNameSpecifierLoc QualifierLoc
2092 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2093 TemplateArgs);
2094 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00002095 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00002096
2097 // The name info is non-dependent, so no transformation
2098 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002099 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00002100
John McCall9f54ad42009-12-10 09:41:52 +00002101 // We only need to do redeclaration lookups if we're in a class
2102 // scope (in fact, it's not really even possible in non-class
2103 // scopes).
2104 bool CheckRedeclaration = Owner->isRecord();
2105
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002106 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2107 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00002108
John McCalled976492009-12-04 22:46:56 +00002109 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002110 D->getUsingLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002111 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002112 NameInfo,
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002113 D->hasTypename());
John McCalled976492009-12-04 22:46:56 +00002114
Douglas Gregor5149f372011-02-25 15:54:31 +00002115 CXXScopeSpec SS;
2116 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00002117 if (CheckRedeclaration) {
2118 Prev.setHideTags(false);
2119 SemaRef.LookupQualifiedName(Prev, Owner);
2120
2121 // Check for invalid redeclarations.
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002122 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2123 D->hasTypename(), SS,
John McCall9f54ad42009-12-10 09:41:52 +00002124 D->getLocation(), Prev))
2125 NewUD->setInvalidDecl();
2126
2127 }
2128
2129 if (!NewUD->isInvalidDecl() &&
Enea Zaffanella8d030c72013-07-22 10:54:09 +00002130 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCalled976492009-12-04 22:46:56 +00002131 D->getLocation()))
2132 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002133
John McCalled976492009-12-04 22:46:56 +00002134 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2135 NewUD->setAccess(D->getAccess());
2136 Owner->addDecl(NewUD);
2137
John McCall9f54ad42009-12-10 09:41:52 +00002138 // Don't process the shadow decls for an invalid decl.
2139 if (NewUD->isInvalidDecl())
2140 return NewUD;
2141
Richard Smithc5a89a12012-04-02 01:30:27 +00002142 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2143 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2144 NewUD->setInvalidDecl();
2145 return NewUD;
2146 }
2147
John McCall323c3102009-12-22 22:26:37 +00002148 bool isFunctionScope = Owner->isFunctionOrMethod();
2149
John McCall9f54ad42009-12-10 09:41:52 +00002150 // Process the shadow decls.
2151 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2152 I != E; ++I) {
2153 UsingShadowDecl *Shadow = *I;
2154 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002155 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2156 Shadow->getLocation(),
2157 Shadow->getTargetDecl(),
2158 TemplateArgs));
2159 if (!InstTarget)
2160 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002161
2162 if (CheckRedeclaration &&
2163 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2164 continue;
2165
2166 UsingShadowDecl *InstShadow
2167 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2168 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002169
2170 if (isFunctionScope)
2171 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002172 }
John McCalled976492009-12-04 22:46:56 +00002173
2174 return NewUD;
2175}
2176
2177Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002178 // Ignore these; we handle them in bulk when processing the UsingDecl.
2179 return 0;
John McCalled976492009-12-04 22:46:56 +00002180}
2181
John McCall7ba107a2009-11-18 02:36:19 +00002182Decl * TemplateDeclInstantiator
2183 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002184 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002185 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002186 TemplateArgs);
2187 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002188 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002189
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002190 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002191 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002193 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002194 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002195 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002196 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002197 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002198 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002199 /*instantiation*/ true,
2200 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002201 if (UD)
John McCalled976492009-12-04 22:46:56 +00002202 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2203
John McCall7ba107a2009-11-18 02:36:19 +00002204 return UD;
2205}
2206
2207Decl * TemplateDeclInstantiator
2208 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002209 NestedNameSpecifierLoc QualifierLoc
2210 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2211 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002212 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002213
John McCall7ba107a2009-11-18 02:36:19 +00002214 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002215 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002216
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002217 DeclarationNameInfo NameInfo
2218 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2219
John McCall7ba107a2009-11-18 02:36:19 +00002220 NamedDecl *UD =
2221 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002222 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002223 /*instantiation*/ true,
2224 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002225 if (UD)
John McCalled976492009-12-04 22:46:56 +00002226 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2227
Anders Carlsson0d8df782009-08-29 19:37:28 +00002228 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002229}
2230
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002231
2232Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2233 ClassScopeFunctionSpecializationDecl *Decl) {
2234 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002235 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2236 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002237
2238 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2239 Sema::ForRedeclaration);
2240
Nico Weber6b020092012-06-25 17:21:05 +00002241 TemplateArgumentListInfo TemplateArgs;
2242 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2243 if (Decl->hasExplicitTemplateArgs()) {
2244 TemplateArgs = Decl->templateArgs();
2245 TemplateArgsPtr = &TemplateArgs;
2246 }
2247
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002248 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002249 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2250 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002251 NewFD->setInvalidDecl();
2252 return NewFD;
2253 }
2254
2255 // Associate the specialization with the pattern.
2256 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2257 assert(Specialization && "Class scope Specialization is null");
2258 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2259
2260 return NewFD;
2261}
2262
Alexey Bataevc6400582013-03-22 06:34:35 +00002263Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2264 OMPThreadPrivateDecl *D) {
Alexey Bataev6af701f2013-05-13 04:18:18 +00002265 SmallVector<Expr *, 5> Vars;
2266 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2267 E = D->varlist_end();
Alexey Bataevc6400582013-03-22 06:34:35 +00002268 I != E; ++I) {
2269 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2270 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6af701f2013-05-13 04:18:18 +00002271 Vars.push_back(Var);
Alexey Bataevc6400582013-03-22 06:34:35 +00002272 }
2273
2274 OMPThreadPrivateDecl *TD =
2275 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2276
2277 return TD;
2278}
2279
Eli Friedmanded99792013-06-27 23:21:55 +00002280Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2281 return VisitFunctionDecl(D, 0);
2282}
2283
2284Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2285 return VisitCXXMethodDecl(D, 0);
2286}
2287
2288Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2289 llvm_unreachable("There are only CXXRecordDecls in C++");
2290}
2291
2292Decl *
2293TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2294 ClassTemplateSpecializationDecl *D) {
2295 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2296 "inside templates");
2297}
2298
Larisse Voufoef4579c2013-08-06 01:03:05 +00002299Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2300 VarTemplateSpecializationDecl *D) {
2301
2302 TemplateArgumentListInfo VarTemplateArgsInfo;
2303 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2304 assert(VarTemplate &&
2305 "A template specialization without specialized template?");
2306
2307 // Substitute the current template arguments.
2308 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2309 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2310 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2311
2312 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2313 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2314 return 0;
2315
2316 // Check that the template argument list is well-formed for this template.
2317 SmallVector<TemplateArgument, 4> Converted;
2318 bool ExpansionIntoFixedList = false;
2319 if (SemaRef.CheckTemplateArgumentList(
2320 VarTemplate, VarTemplate->getLocStart(),
2321 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2322 Converted, &ExpansionIntoFixedList))
2323 return 0;
2324
2325 // Find the variable template specialization declaration that
2326 // corresponds to these arguments.
2327 void *InsertPos = 0;
2328 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2329 Converted.data(), Converted.size(), InsertPos))
2330 // If we already have a variable template specialization, return it.
2331 return VarSpec;
2332
2333 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2334 VarTemplateArgsInfo, Converted);
2335}
2336
2337Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2338 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2339 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smithd0629eb2013-09-27 20:14:12 +00002340 llvm::ArrayRef<TemplateArgument> Converted) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00002341
2342 // If this is the variable for an anonymous struct or union,
2343 // instantiate the anonymous struct/union type first.
2344 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2345 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2346 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2347 return 0;
2348
2349 // Do substitution on the type of the declaration
2350 TypeSourceInfo *DI =
2351 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2352 D->getTypeSpecStartLoc(), D->getDeclName());
2353 if (!DI)
2354 return 0;
2355
2356 if (DI->getType()->isFunctionType()) {
2357 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2358 << D->isStaticDataMember() << DI->getType();
2359 return 0;
2360 }
2361
2362 // Build the instantiated declaration
2363 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2364 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2365 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2366 Converted.size());
2367 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smithd0629eb2013-09-27 20:14:12 +00002368 if (InsertPos)
2369 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002370
2371 // Substitute the nested name specifier, if any.
2372 if (SubstQualifier(D, Var))
2373 return 0;
2374
2375 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smitha41c97a2013-09-20 01:15:31 +00002376 Owner, StartingScope);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002377
2378 return Var;
2379}
2380
Eli Friedmanded99792013-06-27 23:21:55 +00002381Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2382 llvm_unreachable("@defs is not supported in Objective-C++");
2383}
2384
2385Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2386 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2387 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2388 DiagnosticsEngine::Error,
2389 "cannot instantiate %0 yet");
2390 SemaRef.Diag(D->getLocation(), DiagID)
2391 << D->getDeclKindName();
2392
2393 return 0;
2394}
2395
2396Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2397 llvm_unreachable("Unexpected decl");
2398}
2399
John McCallce3ff2b2009-08-25 22:02:44 +00002400Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002401 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002402 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002403 if (D->isInvalidDecl())
2404 return 0;
2405
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002406 return Instantiator.Visit(D);
2407}
2408
John McCalle29ba202009-08-20 01:44:21 +00002409/// \brief Instantiates a nested template parameter list in the current
2410/// instantiation context.
2411///
2412/// \param L The parameter list to instantiate
2413///
2414/// \returns NULL if there was an error
2415TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002416TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002417 // Get errors for all the parameters before bailing out.
2418 bool Invalid = false;
2419
2420 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002421 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002422 ParamVector Params;
2423 Params.reserve(N);
2424 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2425 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002426 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002427 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002428 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002429 }
2430
2431 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002432 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002433 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002434
2435 TemplateParameterList *InstL
2436 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2437 L->getLAngleLoc(), &Params.front(), N,
2438 L->getRAngleLoc());
2439 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002440}
John McCalle29ba202009-08-20 01:44:21 +00002441
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002442/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002443/// specialization.
2444///
2445/// \param ClassTemplate the (instantiated) class template that is partially
2446// specialized by the instantiation of \p PartialSpec.
2447///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002448/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002449/// specialization that we are instantiating.
2450///
Douglas Gregord65587f2010-11-10 19:44:59 +00002451/// \returns The instantiated partial specialization, if successful; otherwise,
2452/// NULL to indicate an error.
2453ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002454TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2455 ClassTemplateDecl *ClassTemplate,
2456 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002457 // Create a local instantiation scope for this class template partial
2458 // specialization, which will contain the instantiations of the template
2459 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002460 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002461
Douglas Gregored9c0f92009-10-29 00:04:11 +00002462 // Substitute into the template parameters of the class template partial
2463 // specialization.
2464 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2465 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2466 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002467 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002468
Douglas Gregored9c0f92009-10-29 00:04:11 +00002469 // Substitute into the template arguments of the class template partial
2470 // specialization.
Enea Zaffanellac1cef082013-08-10 07:24:53 +00002471 const ASTTemplateArgumentListInfo *TemplArgInfo
2472 = PartialSpec->getTemplateArgsAsWritten();
2473 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2474 TemplArgInfo->RAngleLoc);
2475 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2476 TemplArgInfo->NumTemplateArgs,
Douglas Gregore02e2622010-12-22 21:19:48 +00002477 InstTemplateArgs, TemplateArgs))
2478 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002479
Douglas Gregored9c0f92009-10-29 00:04:11 +00002480 // Check that the template argument list is well-formed for this
2481 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002482 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002483 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002484 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002485 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002486 false,
2487 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002488 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002489
2490 // Figure out where to insert this class template partial specialization
2491 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002492 void *InsertPos = 0;
2493 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002494 = ClassTemplate->findPartialSpecialization(Converted.data(),
2495 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002496
Douglas Gregored9c0f92009-10-29 00:04:11 +00002497 // Build the canonical type that describes the converted template
2498 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002499 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002500 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002501 Converted.data(),
2502 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002503
2504 // Build the fully-sugared type for this class template
2505 // specialization as the user wrote in the specialization
2506 // itself. This means that we'll pretty-print the type retrieved
2507 // from the specialization's declaration the way that the user
2508 // actually wrote the specialization, rather than formatting the
2509 // name based on the "canonical" representation used to store the
2510 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002511 TypeSourceInfo *WrittenTy
2512 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2513 TemplateName(ClassTemplate),
2514 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002515 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002516 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002517
Douglas Gregored9c0f92009-10-29 00:04:11 +00002518 if (PrevDecl) {
2519 // We've already seen a partial specialization with the same template
2520 // parameters and template arguments. This can happen, for example, when
2521 // substituting the outer template arguments ends up causing two
2522 // class template partial specializations of a member class template
2523 // to have identical forms, e.g.,
2524 //
2525 // template<typename T, typename U>
2526 // struct Outer {
2527 // template<typename X, typename Y> struct Inner;
2528 // template<typename Y> struct Inner<T, Y>;
2529 // template<typename Y> struct Inner<U, Y>;
2530 // };
2531 //
2532 // Outer<int, int> outer; // error: the partial specializations of Inner
2533 // // have the same signature.
2534 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002535 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002536 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2537 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002538 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002539 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002540
2541
Douglas Gregored9c0f92009-10-29 00:04:11 +00002542 // Create the class template partial specialization declaration.
2543 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002544 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002545 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002546 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002547 PartialSpec->getLocStart(),
2548 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002549 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002550 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002551 Converted.data(),
2552 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002553 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002554 CanonType,
Richard Smith37fd27d2013-08-22 23:27:37 +00002555 0);
John McCallb6217662010-03-15 10:12:16 +00002556 // Substitute the nested name specifier, if any.
2557 if (SubstQualifier(PartialSpec, InstPartialSpec))
2558 return 0;
2559
Douglas Gregored9c0f92009-10-29 00:04:11 +00002560 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002561 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002562
Douglas Gregored9c0f92009-10-29 00:04:11 +00002563 // Add this partial specialization to the set of class template partial
2564 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002565 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002566 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002567}
2568
Larisse Voufoef4579c2013-08-06 01:03:05 +00002569/// \brief Instantiate the declaration of a variable template partial
2570/// specialization.
2571///
2572/// \param VarTemplate the (instantiated) variable template that is partially
2573/// specialized by the instantiation of \p PartialSpec.
2574///
2575/// \param PartialSpec the (uninstantiated) variable template partial
2576/// specialization that we are instantiating.
2577///
2578/// \returns The instantiated partial specialization, if successful; otherwise,
2579/// NULL to indicate an error.
2580VarTemplatePartialSpecializationDecl *
2581TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2582 VarTemplateDecl *VarTemplate,
2583 VarTemplatePartialSpecializationDecl *PartialSpec) {
2584 // Create a local instantiation scope for this variable template partial
2585 // specialization, which will contain the instantiations of the template
2586 // parameters.
2587 LocalInstantiationScope Scope(SemaRef);
2588
2589 // Substitute into the template parameters of the variable template partial
2590 // specialization.
2591 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2592 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2593 if (!InstParams)
2594 return 0;
2595
2596 // Substitute into the template arguments of the variable template partial
2597 // specialization.
Enea Zaffanellac1cef082013-08-10 07:24:53 +00002598 const ASTTemplateArgumentListInfo *TemplArgInfo
2599 = PartialSpec->getTemplateArgsAsWritten();
2600 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2601 TemplArgInfo->RAngleLoc);
2602 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2603 TemplArgInfo->NumTemplateArgs,
Larisse Voufoef4579c2013-08-06 01:03:05 +00002604 InstTemplateArgs, TemplateArgs))
2605 return 0;
2606
2607 // Check that the template argument list is well-formed for this
2608 // class template.
2609 SmallVector<TemplateArgument, 4> Converted;
2610 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2611 InstTemplateArgs, false, Converted))
2612 return 0;
2613
2614 // Figure out where to insert this variable template partial specialization
2615 // in the member template's set of variable template partial specializations.
2616 void *InsertPos = 0;
2617 VarTemplateSpecializationDecl *PrevDecl =
2618 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2619 InsertPos);
2620
2621 // Build the canonical type that describes the converted template
2622 // arguments of the variable template partial specialization.
2623 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2624 TemplateName(VarTemplate), Converted.data(), Converted.size());
2625
2626 // Build the fully-sugared type for this variable template
2627 // specialization as the user wrote in the specialization
2628 // itself. This means that we'll pretty-print the type retrieved
2629 // from the specialization's declaration the way that the user
2630 // actually wrote the specialization, rather than formatting the
2631 // name based on the "canonical" representation used to store the
2632 // template arguments in the specialization.
2633 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2634 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2635 CanonType);
2636
2637 if (PrevDecl) {
2638 // We've already seen a partial specialization with the same template
2639 // parameters and template arguments. This can happen, for example, when
2640 // substituting the outer template arguments ends up causing two
2641 // variable template partial specializations of a member variable template
2642 // to have identical forms, e.g.,
2643 //
2644 // template<typename T, typename U>
2645 // struct Outer {
2646 // template<typename X, typename Y> pair<X,Y> p;
2647 // template<typename Y> pair<T, Y> p;
2648 // template<typename Y> pair<U, Y> p;
2649 // };
2650 //
2651 // Outer<int, int> outer; // error: the partial specializations of Inner
2652 // // have the same signature.
2653 SemaRef.Diag(PartialSpec->getLocation(),
2654 diag::err_var_partial_spec_redeclared)
2655 << WrittenTy->getType();
2656 SemaRef.Diag(PrevDecl->getLocation(),
2657 diag::note_var_prev_partial_spec_here);
2658 return 0;
2659 }
2660
2661 // Do substitution on the type of the declaration
2662 TypeSourceInfo *DI = SemaRef.SubstType(
2663 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2664 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2665 if (!DI)
2666 return 0;
2667
2668 if (DI->getType()->isFunctionType()) {
2669 SemaRef.Diag(PartialSpec->getLocation(),
2670 diag::err_variable_instantiates_to_function)
2671 << PartialSpec->isStaticDataMember() << DI->getType();
2672 return 0;
2673 }
2674
2675 // Create the variable template partial specialization declaration.
2676 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2677 VarTemplatePartialSpecializationDecl::Create(
2678 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2679 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2680 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smith37fd27d2013-08-22 23:27:37 +00002681 Converted.size(), InstTemplateArgs);
Larisse Voufoef4579c2013-08-06 01:03:05 +00002682
2683 // Substitute the nested name specifier, if any.
2684 if (SubstQualifier(PartialSpec, InstPartialSpec))
2685 return 0;
2686
2687 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2688 InstPartialSpec->setTypeAsWritten(WrittenTy);
2689
Larisse Voufoef4579c2013-08-06 01:03:05 +00002690 // Add this partial specialization to the set of variable template partial
2691 // specializations. The instantiation of the initializer is not necessary.
2692 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Larisse Voufo04592e72013-08-22 00:28:27 +00002693
Larisse Voufo04592e72013-08-22 00:28:27 +00002694 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smitha41c97a2013-09-20 01:15:31 +00002695 LateAttrs, Owner, StartingScope);
Larisse Voufo04592e72013-08-22 00:28:27 +00002696
Larisse Voufoef4579c2013-08-06 01:03:05 +00002697 return InstPartialSpec;
2698}
2699
John McCall21ef0fa2010-03-11 09:03:00 +00002700TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002701TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002702 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002703 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2704 assert(OldTInfo && "substituting function without type source info");
2705 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002706
2707 CXXRecordDecl *ThisContext = 0;
2708 unsigned ThisTypeQuals = 0;
2709 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithcafeb942013-06-07 02:33:37 +00002710 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002711 ThisTypeQuals = Method->getTypeQualifiers();
2712 }
2713
John McCall6cd3b9f2010-04-09 17:38:44 +00002714 TypeSourceInfo *NewTInfo
2715 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2716 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002717 D->getDeclName(),
2718 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002719 if (!NewTInfo)
2720 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002721
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002722 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2723 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2724 if (NewTInfo != OldTInfo) {
2725 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002726 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002727 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith500d7292012-07-18 01:29:05 +00002728 unsigned NewIdx = 0;
David Blaikie39e6ab42013-02-18 22:06:02 +00002729 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregor12c9c002011-01-07 16:43:16 +00002730 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002731 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002732 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2733
David Blaikiedc84cd52013-02-20 22:23:23 +00002734 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith500d7292012-07-18 01:29:05 +00002735 if (OldParam->isParameterPack())
2736 NumArgumentsInExpansion =
2737 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2738 TemplateArgs);
2739 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002740 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002741 // instantiated to a (still-dependent) parameter pack.
David Blaikie39e6ab42013-02-18 22:06:02 +00002742 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002743 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002744 Scope->InstantiatedLocal(OldParam, NewParam);
2745 } else {
2746 // Parameter pack expansion: make the instantiation an argument pack.
2747 Scope->MakeInstantiatedLocalArgPack(OldParam);
2748 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002749 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith500d7292012-07-18 01:29:05 +00002750 Params.push_back(NewParam);
2751 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2752 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002753 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002754 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002755 } else {
2756 // The function type itself was not dependent and therefore no
2757 // substitution occurred. However, we still need to instantiate
2758 // the function parameters themselves.
2759 const FunctionProtoType *OldProto =
2760 cast<FunctionProtoType>(OldProtoLoc.getType());
David Blaikie39e6ab42013-02-18 22:06:02 +00002761 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002762 ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2763 if (!OldParam) {
2764 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2765 D, D->getLocation(), OldProto->getArgType(i)));
2766 continue;
2767 }
2768
Eli Friedmanded99792013-06-27 23:21:55 +00002769 ParmVarDecl *Parm =
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002770 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002771 if (!Parm)
2772 return 0;
2773 Params.push_back(Parm);
2774 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002775 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002776 } else {
2777 // If the type of this function, after ignoring parentheses, is not
2778 // *directly* a function type, then we're instantiating a function that
2779 // was declared via a typedef or with attributes, e.g.,
2780 //
2781 // typedef int functype(int, int);
2782 // functype func;
2783 // int __cdecl meth(int, int);
2784 //
2785 // In this case, we'll just go instantiate the ParmVarDecls that we
2786 // synthesized in the method declaration.
2787 SmallVector<QualType, 4> ParamTypes;
2788 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2789 D->getNumParams(), TemplateArgs, ParamTypes,
2790 &Params))
2791 return 0;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002792 }
Reid Klecknerc66e7e92013-07-31 21:00:18 +00002793
John McCall21ef0fa2010-03-11 09:03:00 +00002794 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002795}
2796
Richard Smithe6975e92012-04-17 00:58:00 +00002797/// Introduce the instantiated function parameters into the local
2798/// instantiation scope, and set the parameter names to those used
2799/// in the template.
2800static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2801 const FunctionDecl *PatternDecl,
2802 LocalInstantiationScope &Scope,
2803 const MultiLevelTemplateArgumentList &TemplateArgs) {
2804 unsigned FParamIdx = 0;
2805 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2806 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2807 if (!PatternParam->isParameterPack()) {
2808 // Simple case: not a parameter pack.
2809 assert(FParamIdx < Function->getNumParams());
2810 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2811 FunctionParam->setDeclName(PatternParam->getDeclName());
2812 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2813 ++FParamIdx;
2814 continue;
2815 }
2816
2817 // Expand the parameter pack.
2818 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikiedc84cd52013-02-20 22:23:23 +00002819 Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002820 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002821 assert(NumArgumentsInExpansion &&
2822 "should only be called when all template arguments are known");
2823 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002824 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2825 FunctionParam->setDeclName(PatternParam->getDeclName());
2826 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2827 ++FParamIdx;
2828 }
2829 }
2830}
2831
2832static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2833 const FunctionProtoType *Proto,
2834 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002835 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2836
Richard Smithe6975e92012-04-17 00:58:00 +00002837 // C++11 [expr.prim.general]p3:
2838 // If a declaration declares a member function or member function
2839 // template of a class X, the expression this is a prvalue of type
2840 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2841 // and the end of the function-definition, member-declarator, or
2842 // declarator.
2843 CXXRecordDecl *ThisContext = 0;
2844 unsigned ThisTypeQuals = 0;
2845 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2846 ThisContext = Method->getParent();
2847 ThisTypeQuals = Method->getTypeQualifiers();
2848 }
2849 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith80ad52f2013-01-02 11:42:31 +00002850 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithe6975e92012-04-17 00:58:00 +00002851
2852 // The function has an exception specification or a "noreturn"
2853 // attribute. Substitute into each of the exception types.
2854 SmallVector<QualType, 4> Exceptions;
2855 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2856 // FIXME: Poor location information!
2857 if (const PackExpansionType *PackExpansion
2858 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2859 // We have a pack expansion. Instantiate it.
2860 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2861 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2862 Unexpanded);
2863 assert(!Unexpanded.empty() &&
2864 "Pack expansion without parameter packs?");
2865
2866 bool Expand = false;
2867 bool RetainExpansion = false;
Richard Smithcafeb942013-06-07 02:33:37 +00002868 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithe6975e92012-04-17 00:58:00 +00002869 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2870 SourceRange(),
2871 Unexpanded,
2872 TemplateArgs,
2873 Expand,
2874 RetainExpansion,
2875 NumExpansions))
2876 break;
2877
2878 if (!Expand) {
2879 // We can't expand this pack expansion into separate arguments yet;
2880 // just substitute into the pattern and create a new pack expansion
2881 // type.
2882 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2883 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2884 TemplateArgs,
2885 New->getLocation(), New->getDeclName());
2886 if (T.isNull())
2887 break;
2888
2889 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2890 Exceptions.push_back(T);
2891 continue;
2892 }
2893
2894 // Substitute into the pack expansion pattern for each template
2895 bool Invalid = false;
2896 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2897 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2898
2899 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2900 TemplateArgs,
2901 New->getLocation(), New->getDeclName());
2902 if (T.isNull()) {
2903 Invalid = true;
2904 break;
2905 }
2906
2907 Exceptions.push_back(T);
2908 }
2909
2910 if (Invalid)
2911 break;
2912
2913 continue;
2914 }
2915
2916 QualType T
2917 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2918 New->getLocation(), New->getDeclName());
2919 if (T.isNull() ||
2920 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2921 continue;
2922
2923 Exceptions.push_back(T);
2924 }
2925 Expr *NoexceptExpr = 0;
2926 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2927 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2928 Sema::ConstantEvaluated);
2929 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2930 if (E.isUsable())
2931 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2932
2933 if (E.isUsable()) {
2934 NoexceptExpr = E.take();
2935 if (!NoexceptExpr->isTypeDependent() &&
2936 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002937 NoexceptExpr
2938 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2939 0, diag::err_noexcept_needs_constant_expression,
2940 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002941 }
2942 }
2943
2944 // Rebuild the function type
2945 const FunctionProtoType *NewProto
2946 = New->getType()->getAs<FunctionProtoType>();
2947 assert(NewProto && "Template instantiation without function prototype?");
2948
2949 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2950 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2951 EPI.NumExceptions = Exceptions.size();
2952 EPI.Exceptions = Exceptions.data();
2953 EPI.NoexceptExpr = NoexceptExpr;
2954
2955 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002956 NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002957}
2958
2959void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2960 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002961 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2962 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002963 return;
2964
2965 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2966 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd69f37b2013-10-08 08:09:04 +00002967 if (Inst.isInvalid()) {
Richard Smithb9d0b762012-07-27 04:22:15 +00002968 // We hit the instantiation depth limit. Clear the exception specification
2969 // so that our callers don't have to cope with EST_Uninstantiated.
2970 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2971 EPI.ExceptionSpecType = EST_None;
2972 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002973 Proto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002974 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002975 }
Richard Smithe6975e92012-04-17 00:58:00 +00002976
2977 // Enter the scope of this instantiation. We don't use
2978 // PushDeclContext because we don't have a scope.
2979 Sema::ContextRAII savedContext(*this, Decl);
2980 LocalInstantiationScope Scope(*this);
2981
2982 MultiLevelTemplateArgumentList TemplateArgs =
2983 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2984
Richard Smith13bffc52012-04-19 00:08:28 +00002985 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2986 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002987
Richard Smith13bffc52012-04-19 00:08:28 +00002988 ::InstantiateExceptionSpec(*this, Decl,
2989 Template->getType()->castAs<FunctionProtoType>(),
2990 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002991}
2992
Mike Stump1eb44332009-09-09 15:08:12 +00002993/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002994/// declaration (New) from the corresponding fields of its template (Tmpl).
2995///
2996/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002997bool
2998TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002999 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00003000 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00003001 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00003002
Douglas Gregorcca9e962009-07-01 22:01:06 +00003003 // If we are performing substituting explicitly-specified template arguments
3004 // or deduced template arguments into a function template and we reach this
3005 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00003006 // to keeping the new function template specialization. We therefore
3007 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00003008 // into a template instantiation for this specific function template
3009 // specialization, which is not a SFINAE context, so that we diagnose any
3010 // further errors in the declaration itself.
3011 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3012 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3013 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3014 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00003015 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00003016 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003017 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00003018 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00003019 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00003020 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00003021 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00003022 }
3023 }
Mike Stump1eb44332009-09-09 15:08:12 +00003024
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00003025 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3026 assert(Proto && "Function template without prototype?");
3027
Sebastian Redl60618fa2011-03-12 11:50:43 +00003028 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00003029 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00003030
Richard Smithe6975e92012-04-17 00:58:00 +00003031 // DR1330: In C++11, defer instantiation of a non-trivial
3032 // exception specification.
Richard Smith80ad52f2013-01-02 11:42:31 +00003033 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithe6975e92012-04-17 00:58:00 +00003034 EPI.ExceptionSpecType != EST_None &&
3035 EPI.ExceptionSpecType != EST_DynamicNone &&
3036 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00003037 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3038 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3039 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith4841ca52013-04-10 05:48:59 +00003040 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3041 if (EPI.ExceptionSpecType == EST_Unevaluated)
3042 NewEST = EST_Unevaluated;
Richard Smith13bffc52012-04-19 00:08:28 +00003043
Richard Smithe6975e92012-04-17 00:58:00 +00003044 // Mark the function has having an uninstantiated exception specification.
3045 const FunctionProtoType *NewProto
3046 = New->getType()->getAs<FunctionProtoType>();
3047 assert(NewProto && "Template instantiation without function prototype?");
3048 EPI = NewProto->getExtProtoInfo();
Richard Smith4841ca52013-04-10 05:48:59 +00003049 EPI.ExceptionSpecType = NewEST;
Richard Smithe6975e92012-04-17 00:58:00 +00003050 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00003051 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner0567a792013-06-10 20:51:09 +00003052 New->setType(SemaRef.Context.getFunctionType(
3053 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00003054 } else {
3055 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3056 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00003057 }
3058
Rafael Espindola19f74ac2011-07-06 15:46:09 +00003059 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00003060 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00003061 Tmpl->isDefined(Definition);
3062
DeLesley Hutchins23323e02012-01-20 22:50:54 +00003063 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3064 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00003065
Douglas Gregore53060f2009-06-25 22:08:12 +00003066 return false;
3067}
3068
Douglas Gregor5545e162009-03-24 00:38:23 +00003069/// \brief Initializes common fields of an instantiated method
3070/// declaration (New) from the corresponding fields of its template
3071/// (Tmpl).
3072///
3073/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00003074bool
3075TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00003076 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00003077 if (InitFunctionInstantiation(New, Tmpl))
3078 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00003079
Douglas Gregor5545e162009-03-24 00:38:23 +00003080 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00003081 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00003082 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00003083
Douglas Gregor5545e162009-03-24 00:38:23 +00003084 // FIXME: New needs a pointer to Tmpl
3085 return false;
3086}
Douglas Gregora58861f2009-05-13 20:28:22 +00003087
3088/// \brief Instantiate the definition of the given function from its
3089/// template.
3090///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003091/// \param PointOfInstantiation the point at which the instantiation was
3092/// required. Note that this is not precisely a "point of instantiation"
3093/// for the function, but it's close.
3094///
Douglas Gregora58861f2009-05-13 20:28:22 +00003095/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003096/// function template specialization or member function of a class template
3097/// specialization.
3098///
3099/// \param Recursive if true, recursively instantiates any functions that
3100/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003101///
3102/// \param DefinitionRequired if true, then we are performing an explicit
3103/// instantiation where the body of the function is required. Complain if
3104/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003105void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003106 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003107 bool Recursive,
3108 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00003109 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003110 return;
3111
Francois Pichetaf0f4d02011-08-14 03:52:19 +00003112 // Never instantiate an explicit specialization except if it is a class scope
3113 // explicit specialization.
3114 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3115 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003116 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00003117
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003118 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00003119 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00003120 assert(PatternDecl && "instantiating a non-template");
3121
3122 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3123 assert(PatternDecl && "template definition is not a template");
3124 if (!Pattern) {
3125 // Try to find a defaulted definition
3126 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00003127 }
Sean Huntf996e052011-05-27 20:00:14 +00003128 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003129
Francois Pichet8387e2a2011-04-22 22:18:13 +00003130 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00003131 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00003132 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00003133 PendingInstantiations.push_back(
3134 std::make_pair(Function, PointOfInstantiation));
3135 return;
3136 }
3137
David Majnemer360d23e2013-08-16 08:29:13 +00003138 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003139 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00003140 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00003141 LateTemplateParser) {
Richard Smithac32d902013-08-07 21:41:30 +00003142 // FIXME: Optimize to allow individual templates to be deserialized.
3143 if (PatternDecl->isFromASTFile())
3144 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3145
3146 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3147 assert(LPT && "missing LateParsedTemplate");
3148 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet8387e2a2011-04-22 22:18:13 +00003149 Pattern = PatternDecl->getBody(PatternDecl);
3150 }
3151
Sean Huntf996e052011-05-27 20:00:14 +00003152 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003153 if (DefinitionRequired) {
3154 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003155 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003156 diag::err_explicit_instantiation_undefined_func_template)
3157 << Function->getPrimaryTemplate();
3158 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003159 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003160 diag::err_explicit_instantiation_undefined_member)
3161 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003162
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003163 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003164 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003165 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00003166 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00003167 } else if (Function->getTemplateSpecializationKind()
3168 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003169 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003170 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003171 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00003172
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003173 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003174 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00003175
Richard Smith60e141e2013-05-04 07:00:32 +00003176 // C++1y [temp.explicit]p10:
3177 // Except for inline functions, declarations with types deduced from their
3178 // initializer or return value, and class template specializations, other
3179 // explicit instantiation declarations have the effect of suppressing the
3180 // implicit instantiation of the entity to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00003181 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003182 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith60e141e2013-05-04 07:00:32 +00003183 !PatternDecl->isInlined() &&
Richard Smith37e849a2013-08-14 20:16:31 +00003184 !PatternDecl->getResultType()->getContainedAutoType())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00003185 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003186
Richard Smithd4497dd2013-01-25 00:08:28 +00003187 if (PatternDecl->isInlined())
3188 Function->setImplicitlyInline();
3189
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00003190 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd69f37b2013-10-08 08:09:04 +00003191 if (Inst.isInvalid())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003192 return;
3193
Abramo Bagnarae9946242011-11-18 08:08:52 +00003194 // Copy the inner loc start from the pattern.
3195 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3196
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003197 // If we're performing recursive template instantiation, create our own
3198 // queue of pending implicit instantiations that we will instantiate later,
3199 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003200 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003201 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Faisal Vali86648b12013-06-26 02:34:24 +00003202 std::deque<PendingImplicitInstantiation>
3203 SavedPendingLocalImplicitInstantiations;
3204 SavedPendingLocalImplicitInstantiations.swap(
3205 PendingLocalImplicitInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003206 if (Recursive) {
3207 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003208 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003209 }
Mike Stump1eb44332009-09-09 15:08:12 +00003210
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003211 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00003212 Sema::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00003213
Douglas Gregor54dabfc2009-05-14 23:26:13 +00003214 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00003215 // recorded, unless we're actually a member function within a local
3216 // class, in which case we need to merge our results with the parent
3217 // scope (of the enclosing function).
3218 bool MergeWithParentScope = false;
3219 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3220 MergeWithParentScope = Rec->isLocalClass();
3221
3222 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00003223
Richard Smith1d28caf2012-12-11 01:14:52 +00003224 if (PatternDecl->isDefaulted())
Sean Huntcd10dec2011-05-23 23:14:04 +00003225 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smith1d28caf2012-12-11 01:14:52 +00003226 else {
3227 ActOnStartOfFunctionDef(0, Function);
3228
3229 // Enter the scope of this instantiation. We don't use
3230 // PushDeclContext because we don't have a scope.
3231 Sema::ContextRAII savedContext(*this, Function);
3232
3233 MultiLevelTemplateArgumentList TemplateArgs =
3234 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3235
3236 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3237 TemplateArgs);
3238
Sean Huntcd10dec2011-05-23 23:14:04 +00003239 // If this is a constructor, instantiate the member initializers.
3240 if (const CXXConstructorDecl *Ctor =
3241 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3242 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3243 TemplateArgs);
3244 }
3245
3246 // Instantiate the function body.
3247 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3248
3249 if (Body.isInvalid())
3250 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003251
Sean Huntcd10dec2011-05-23 23:14:04 +00003252 ActOnFinishFunctionBody(Function, Body.get(),
3253 /*IsInstantiation=*/true);
Richard Smith1d28caf2012-12-11 01:14:52 +00003254
3255 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3256
3257 savedContext.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00003258 }
3259
Douglas Gregoraba43bb2009-05-26 20:50:29 +00003260 DeclGroupRef DG(Function);
3261 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00003262
Douglas Gregor60406be2010-01-16 22:29:39 +00003263 // This class may have local implicit instantiations that need to be
3264 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003265 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00003266 Scope.Exit();
3267
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003268 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003269 // Define any pending vtables.
3270 DefineUsedVTables();
3271
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003272 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003273 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003274 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003275
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003276 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00003277 assert(VTableUses.empty() &&
3278 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003279 VTableUses.swap(SavedVTableUses);
3280
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003281 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003282 assert(PendingInstantiations.empty() &&
3283 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003284 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003285 }
Faisal Vali86648b12013-06-26 02:34:24 +00003286 SavedPendingLocalImplicitInstantiations.swap(
3287 PendingLocalImplicitInstantiations);
Douglas Gregora58861f2009-05-13 20:28:22 +00003288}
3289
Larisse Voufoef4579c2013-08-06 01:03:05 +00003290VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3291 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3292 const TemplateArgumentList &TemplateArgList,
3293 const TemplateArgumentListInfo &TemplateArgsInfo,
3294 SmallVectorImpl<TemplateArgument> &Converted,
3295 SourceLocation PointOfInstantiation, void *InsertPos,
3296 LateInstantiatedAttrVec *LateAttrs,
3297 LocalInstantiationScope *StartingScope) {
3298 if (FromVar->isInvalidDecl())
3299 return 0;
3300
3301 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd69f37b2013-10-08 08:09:04 +00003302 if (Inst.isInvalid())
Larisse Voufoef4579c2013-08-06 01:03:05 +00003303 return 0;
3304
3305 MultiLevelTemplateArgumentList TemplateArgLists;
3306 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3307
Richard Smithd0629eb2013-09-27 20:14:12 +00003308 // Instantiate the first declaration of the variable template: for a partial
3309 // specialization of a static data member template, the first declaration may
3310 // or may not be the declaration in the class; if it's in the class, we want
3311 // to instantiate a member in the class (a declaration), and if it's outside,
3312 // we want to instantiate a definition.
Rafael Espindolabc650912013-10-17 15:37:26 +00003313 FromVar = FromVar->getFirstDecl();
Richard Smithd0629eb2013-09-27 20:14:12 +00003314
Manuel Klimek2e563c22013-09-30 13:29:01 +00003315 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3316 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3317 MultiLevelList);
Larisse Voufoef4579c2013-08-06 01:03:05 +00003318
3319 // TODO: Set LateAttrs and StartingScope ...
3320
3321 return cast_or_null<VarTemplateSpecializationDecl>(
3322 Instantiator.VisitVarTemplateSpecializationDecl(
3323 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3324}
3325
3326/// \brief Instantiates a variable template specialization by completing it
3327/// with appropriate type information and initializer.
3328VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3329 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3330 const MultiLevelTemplateArgumentList &TemplateArgs) {
3331
3332 // Do substitution on the type of the declaration
3333 TypeSourceInfo *DI =
Richard Smithd0629eb2013-09-27 20:14:12 +00003334 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufoef4579c2013-08-06 01:03:05 +00003335 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3336 if (!DI)
3337 return 0;
3338
3339 // Update the type of this variable template specialization.
3340 VarSpec->setType(DI->getType());
3341
3342 // Instantiate the initializer.
3343 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3344
3345 return VarSpec;
3346}
3347
3348/// BuildVariableInstantiation - Used after a new variable has been created.
3349/// Sets basic variable data and decides whether to postpone the
3350/// variable instantiation.
3351void Sema::BuildVariableInstantiation(
3352 VarDecl *NewVar, VarDecl *OldVar,
3353 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smitha41c97a2013-09-20 01:15:31 +00003354 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3355 LocalInstantiationScope *StartingScope,
Larisse Voufo567f9172013-08-22 00:59:14 +00003356 bool InstantiatingVarTemplate) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003357
Richard Smitha41c97a2013-09-20 01:15:31 +00003358 // If we are instantiating a local extern declaration, the
3359 // instantiation belongs lexically to the containing function.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003360 // If we are instantiating a static data member defined
3361 // out-of-line, the instantiation will have the same lexical
3362 // context (which will be a namespace scope) as the template.
Richard Smitha41c97a2013-09-20 01:15:31 +00003363 if (OldVar->isLocalExternDecl()) {
3364 NewVar->setLocalExternDecl();
3365 NewVar->setLexicalDeclContext(Owner);
3366 } else if (OldVar->isOutOfLine())
Larisse Voufoef4579c2013-08-06 01:03:05 +00003367 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3368 NewVar->setTSCSpec(OldVar->getTSCSpec());
3369 NewVar->setInitStyle(OldVar->getInitStyle());
3370 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3371 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smith04fa7a32013-09-28 04:02:39 +00003372 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smithdd9459f2013-08-13 18:18:50 +00003373 NewVar->setPreviousDeclInSameBlockScope(
3374 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufoef4579c2013-08-06 01:03:05 +00003375 NewVar->setAccess(OldVar->getAccess());
3376
Richard Smith90618ff2013-09-23 23:12:22 +00003377 if (!OldVar->isStaticDataMember()) {
Eli Friedman86164e82013-09-05 00:02:25 +00003378 NewVar->setIsUsed(OldVar->isUsed(false));
Larisse Voufoef4579c2013-08-06 01:03:05 +00003379 NewVar->setReferenced(OldVar->isReferenced());
3380 }
3381
David Majnemeraa824612013-09-17 23:57:10 +00003382 // See if the old variable had a type-specifier that defined an anonymous tag.
3383 // If it did, mark the new variable as being the declarator for the new
3384 // anonymous tag.
3385 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3386 TagDecl *OldTag = OldTagType->getDecl();
3387 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3388 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3389 assert(!NewTag->hasNameForLinkage() &&
3390 !NewTag->hasDeclaratorForAnonDecl());
3391 NewTag->setDeclaratorForAnonDecl(NewVar);
3392 }
3393 }
3394
Larisse Voufoef4579c2013-08-06 01:03:05 +00003395 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3396
3397 if (NewVar->hasAttrs())
3398 CheckAlignasUnderalignment(NewVar);
3399
Richard Smitha41c97a2013-09-20 01:15:31 +00003400 LookupResult Previous(
3401 *this, NewVar->getDeclName(), NewVar->getLocation(),
3402 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3403 : Sema::LookupOrdinaryName,
3404 Sema::ForRedeclaration);
Larisse Voufoef4579c2013-08-06 01:03:05 +00003405
Richard Smitha41c97a2013-09-20 01:15:31 +00003406 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl()) {
Richard Smithdd9459f2013-08-13 18:18:50 +00003407 // We have a previous declaration. Use that one, so we merge with the
3408 // right type.
3409 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3410 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3411 Previous.addDecl(NewPrev);
3412 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3413 OldVar->hasLinkage())
Larisse Voufoef4579c2013-08-06 01:03:05 +00003414 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo567f9172013-08-22 00:59:14 +00003415 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufoef4579c2013-08-06 01:03:05 +00003416
Richard Smitha41c97a2013-09-20 01:15:31 +00003417 if (!InstantiatingVarTemplate) {
3418 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3419 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufoef4579c2013-08-06 01:03:05 +00003420 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smitha41c97a2013-09-20 01:15:31 +00003421 }
3422
3423 if (!OldVar->isOutOfLine()) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003424 if (NewVar->getDeclContext()->isFunctionOrMethod())
3425 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3426 }
3427
3428 // Link instantiations of static data members back to the template from
3429 // which they were instantiated.
Larisse Voufo567f9172013-08-22 00:59:14 +00003430 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufoef4579c2013-08-06 01:03:05 +00003431 NewVar->setInstantiationOfStaticDataMember(OldVar,
3432 TSK_ImplicitInstantiation);
3433
Richard Smithd0629eb2013-09-27 20:14:12 +00003434 // Delay instantiation of the initializer for variable templates until a
3435 // definition of the variable is needed.
3436 if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate)
Larisse Voufoef4579c2013-08-06 01:03:05 +00003437 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3438
3439 // Diagnose unused local variables with dependent types, where the diagnostic
3440 // will have been deferred.
3441 if (!NewVar->isInvalidDecl() &&
3442 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3443 OldVar->getType()->isDependentType())
3444 DiagnoseUnusedDecl(NewVar);
3445}
3446
3447/// \brief Instantiate the initializer of a variable.
3448void Sema::InstantiateVariableInitializer(
3449 VarDecl *Var, VarDecl *OldVar,
3450 const MultiLevelTemplateArgumentList &TemplateArgs) {
3451
3452 if (Var->getAnyInitializer())
3453 // We already have an initializer in the class.
3454 return;
3455
3456 if (OldVar->getInit()) {
3457 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3458 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3459 else
3460 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3461
3462 // Instantiate the initializer.
3463 ExprResult Init =
3464 SubstInitializer(OldVar->getInit(), TemplateArgs,
3465 OldVar->getInitStyle() == VarDecl::CallInit);
3466 if (!Init.isInvalid()) {
3467 bool TypeMayContainAuto = true;
3468 if (Init.get()) {
3469 bool DirectInit = OldVar->isDirectInit();
3470 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3471 } else
3472 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3473 } else {
3474 // FIXME: Not too happy about invalidating the declaration
3475 // because of a bogus initializer.
3476 Var->setInvalidDecl();
3477 }
3478
3479 PopExpressionEvaluationContext();
3480 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3481 !Var->isCXXForRangeDecl())
3482 ActOnUninitializedDecl(Var, false);
3483}
3484
Douglas Gregora58861f2009-05-13 20:28:22 +00003485/// \brief Instantiate the definition of the given variable from its
3486/// template.
3487///
Douglas Gregor7caa6822009-07-24 20:34:43 +00003488/// \param PointOfInstantiation the point at which the instantiation was
3489/// required. Note that this is not precisely a "point of instantiation"
3490/// for the function, but it's close.
3491///
3492/// \param Var the already-instantiated declaration of a static member
3493/// variable of a class template specialization.
3494///
3495/// \param Recursive if true, recursively instantiates any functions that
3496/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003497///
3498/// \param DefinitionRequired if true, then we are performing an explicit
3499/// instantiation where an out-of-line definition of the member variable
3500/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00003501void Sema::InstantiateStaticDataMemberDefinition(
3502 SourceLocation PointOfInstantiation,
3503 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003504 bool Recursive,
3505 bool DefinitionRequired) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003506 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3507 DefinitionRequired);
3508}
3509
3510void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3511 VarDecl *Var, bool Recursive,
3512 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00003513 if (Var->isInvalidDecl())
3514 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Larisse Voufoef4579c2013-08-06 01:03:05 +00003516 VarTemplateSpecializationDecl *VarSpec =
3517 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smithd0629eb2013-09-27 20:14:12 +00003518 VarDecl *PatternDecl = 0, *Def = 0;
3519 MultiLevelTemplateArgumentList TemplateArgs =
3520 getTemplateInstantiationArgs(Var);
Mike Stump1eb44332009-09-09 15:08:12 +00003521
Larisse Voufoef4579c2013-08-06 01:03:05 +00003522 if (VarSpec) {
Richard Smithd0629eb2013-09-27 20:14:12 +00003523 // If this is a variable template specialization, make sure that it is
3524 // non-dependent, then find its instantiation pattern.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003525 bool InstantiationDependent = false;
3526 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3527 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3528 "Only instantiate variable template specializations that are "
3529 "not type-dependent");
Larisse Voufo3151b7c2013-08-06 03:57:41 +00003530 (void)InstantiationDependent;
Larisse Voufoef4579c2013-08-06 01:03:05 +00003531
Richard Smithd0629eb2013-09-27 20:14:12 +00003532 // Find the variable initialization that we'll be substituting. If the
3533 // pattern was instantiated from a member template, look back further to
3534 // find the real pattern.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003535 assert(VarSpec->getSpecializedTemplate() &&
3536 "Specialization without specialized template?");
3537 llvm::PointerUnion<VarTemplateDecl *,
3538 VarTemplatePartialSpecializationDecl *> PatternPtr =
3539 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufo439d6652013-08-13 02:02:26 +00003540 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smithd0629eb2013-09-27 20:14:12 +00003541 VarTemplatePartialSpecializationDecl *Tmpl =
3542 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3543 while (VarTemplatePartialSpecializationDecl *From =
3544 Tmpl->getInstantiatedFromMember()) {
3545 if (Tmpl->isMemberSpecialization())
3546 break;
Larisse Voufo439d6652013-08-13 02:02:26 +00003547
Richard Smithd0629eb2013-09-27 20:14:12 +00003548 Tmpl = From;
3549 }
3550 PatternDecl = Tmpl;
Larisse Voufo439d6652013-08-13 02:02:26 +00003551 } else {
Richard Smithd0629eb2013-09-27 20:14:12 +00003552 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3553 while (VarTemplateDecl *From =
3554 Tmpl->getInstantiatedFromMemberTemplate()) {
3555 if (Tmpl->isMemberSpecialization())
3556 break;
Larisse Voufo439d6652013-08-13 02:02:26 +00003557
Richard Smithd0629eb2013-09-27 20:14:12 +00003558 Tmpl = From;
3559 }
3560 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufo439d6652013-08-13 02:02:26 +00003561 }
Richard Smithd0629eb2013-09-27 20:14:12 +00003562
3563 // If this is a static data member template, there might be an
3564 // uninstantiated initializer on the declaration. If so, instantiate
3565 // it now.
3566 if (PatternDecl->isStaticDataMember() &&
Rafael Espindolabc650912013-10-17 15:37:26 +00003567 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smithd0629eb2013-09-27 20:14:12 +00003568 !Var->hasInit()) {
3569 // FIXME: Factor out the duplicated instantiation context setup/tear down
3570 // code here.
3571 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd69f37b2013-10-08 08:09:04 +00003572 if (Inst.isInvalid())
Richard Smithd0629eb2013-09-27 20:14:12 +00003573 return;
3574
3575 // If we're performing recursive template instantiation, create our own
3576 // queue of pending implicit instantiations that we will instantiate
3577 // later, while we're still within our own instantiation context.
3578 SmallVector<VTableUse, 16> SavedVTableUses;
3579 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3580 if (Recursive) {
3581 VTableUses.swap(SavedVTableUses);
3582 PendingInstantiations.swap(SavedPendingInstantiations);
3583 }
3584
3585 LocalInstantiationScope Local(*this);
3586
3587 // Enter the scope of this instantiation. We don't use
3588 // PushDeclContext because we don't have a scope.
3589 ContextRAII PreviousContext(*this, Var->getDeclContext());
3590 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3591 PreviousContext.pop();
3592
3593 // FIXME: Need to inform the ASTConsumer that we instantiated the
3594 // initializer?
3595
3596 // This variable may have local implicit instantiations that need to be
3597 // instantiated within this scope.
3598 PerformPendingInstantiations(/*LocalOnly=*/true);
3599
3600 Local.Exit();
3601
3602 if (Recursive) {
3603 // Define any newly required vtables.
3604 DefineUsedVTables();
3605
3606 // Instantiate any pending implicit instantiations found during the
3607 // instantiation of this template.
3608 PerformPendingInstantiations();
3609
3610 // Restore the set of pending vtables.
3611 assert(VTableUses.empty() &&
3612 "VTableUses should be empty before it is discarded.");
3613 VTableUses.swap(SavedVTableUses);
3614
3615 // Restore the set of pending implicit instantiations.
3616 assert(PendingInstantiations.empty() &&
3617 "PendingInstantiations should be empty before it is discarded.");
3618 PendingInstantiations.swap(SavedPendingInstantiations);
3619 }
3620 }
3621
3622 // Find actual definition
3623 Def = PatternDecl->getDefinition(getASTContext());
3624 } else {
3625 // If this is a static data member, find its out-of-line definition.
3626 assert(Var->isStaticDataMember() && "not a static data member?");
3627 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3628
3629 assert(PatternDecl && "data member was not instantiated from a template?");
3630 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3631 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufoef4579c2013-08-06 01:03:05 +00003632 }
3633
Richard Smithd0629eb2013-09-27 20:14:12 +00003634 // If we don't have a definition of the variable template, we won't perform
3635 // any instantiation. Rather, we rely on the user to instantiate this
3636 // definition (or provide a specialization for it) in another translation
3637 // unit.
3638 if (!Def) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003639 if (DefinitionRequired) {
Richard Smithd0629eb2013-09-27 20:14:12 +00003640 if (VarSpec)
Larisse Voufoef4579c2013-08-06 01:03:05 +00003641 Diag(PointOfInstantiation,
Richard Smithd0629eb2013-09-27 20:14:12 +00003642 diag::err_explicit_instantiation_undefined_var_template) << Var;
3643 else
Larisse Voufoef4579c2013-08-06 01:03:05 +00003644 Diag(PointOfInstantiation,
3645 diag::err_explicit_instantiation_undefined_member)
Richard Smithd0629eb2013-09-27 20:14:12 +00003646 << 2 << Var->getDeclName() << Var->getDeclContext();
3647 Diag(PatternDecl->getLocation(),
3648 diag::note_explicit_instantiation_here);
Larisse Voufoef4579c2013-08-06 01:03:05 +00003649 if (VarSpec)
3650 Var->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00003651 } else if (Var->getTemplateSpecializationKind()
3652 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003653 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003654 std::make_pair(Var, PointOfInstantiation));
3655 }
3656
Douglas Gregor7caa6822009-07-24 20:34:43 +00003657 return;
3658 }
3659
Rafael Espindola234fe652012-03-05 10:54:55 +00003660 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3661
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003662 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00003663 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003664 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003665
Larisse Voufoef4579c2013-08-06 01:03:05 +00003666 // C++11 [temp.explicit]p10:
3667 // Except for inline functions, [...] explicit instantiation declarations
3668 // have the effect of suppressing the implicit instantiation of the entity
3669 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00003670 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003671 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003672
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003673 // Make sure to pass the instantiated variable to the consumer at the end.
3674 struct PassToConsumerRAII {
3675 ASTConsumer &Consumer;
3676 VarDecl *Var;
3677
3678 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3679 : Consumer(Consumer), Var(Var) { }
3680
3681 ~PassToConsumerRAII() {
Richard Smithd0629eb2013-09-27 20:14:12 +00003682 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003683 }
3684 } PassToConsumerRAII(Consumer, Var);
Rafael Espindola02503932012-03-08 15:51:03 +00003685
Richard Smithd0629eb2013-09-27 20:14:12 +00003686 // If we already have a definition, we're done.
3687 if (VarDecl *Def = Var->getDefinition()) {
3688 // We may be explicitly instantiating something we've already implicitly
3689 // instantiated.
3690 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3691 PointOfInstantiation);
3692 return;
Nick Lewycky95e38722012-04-04 02:38:36 +00003693 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003694
Douglas Gregor7caa6822009-07-24 20:34:43 +00003695 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd69f37b2013-10-08 08:09:04 +00003696 if (Inst.isInvalid())
Douglas Gregor7caa6822009-07-24 20:34:43 +00003697 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003698
Douglas Gregor7caa6822009-07-24 20:34:43 +00003699 // If we're performing recursive template instantiation, create our own
3700 // queue of pending implicit instantiations that we will instantiate later,
3701 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003702 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003703 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00003704 if (Recursive) {
3705 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003706 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00003707 }
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Douglas Gregor7caa6822009-07-24 20:34:43 +00003709 // Enter the scope of this instantiation. We don't use
3710 // PushDeclContext because we don't have a scope.
Larisse Voufoef4579c2013-08-06 01:03:05 +00003711 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003712 LocalInstantiationScope Local(*this);
John McCallf5ba7e02011-02-14 20:37:25 +00003713
Larisse Voufoef4579c2013-08-06 01:03:05 +00003714 VarDecl *OldVar = Var;
3715 if (!VarSpec)
3716 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smithd0629eb2013-09-27 20:14:12 +00003717 TemplateArgs));
3718 else if (Var->isStaticDataMember() &&
3719 Var->getLexicalDeclContext()->isRecord()) {
3720 // We need to instantiate the definition of a static data member template,
3721 // and all we have is the in-class declaration of it. Instantiate a separate
3722 // declaration of the definition.
3723 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3724 TemplateArgs);
3725 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3726 VarSpec->getSpecializedTemplate(), Def, 0,
3727 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3728 if (Var) {
3729 llvm::PointerUnion<VarTemplateDecl *,
3730 VarTemplatePartialSpecializationDecl *> PatternPtr =
3731 VarSpec->getSpecializedTemplateOrPartial();
3732 if (VarTemplatePartialSpecializationDecl *Partial =
3733 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3734 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3735 Partial, &VarSpec->getTemplateInstantiationArgs());
3736
3737 // Merge the definition with the declaration.
3738 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3739 LookupOrdinaryName, ForRedeclaration);
3740 R.addDecl(OldVar);
3741 MergeVarDecl(Var, R);
3742
3743 // Attach the initializer.
3744 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3745 }
3746 } else
3747 // Complete the existing variable's definition with an appropriately
3748 // substituted type and initializer.
3749 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufoef4579c2013-08-06 01:03:05 +00003750
3751 PreviousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003752
3753 if (Var) {
Larisse Voufoef4579c2013-08-06 01:03:05 +00003754 PassToConsumerRAII.Var = Var;
Richard Smithd0629eb2013-09-27 20:14:12 +00003755 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3756 OldVar->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00003757 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00003758
3759 // This variable may have local implicit instantiations that need to be
3760 // instantiated within this scope.
3761 PerformPendingInstantiations(/*LocalOnly=*/true);
3762
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003763 Local.Exit();
3764
Douglas Gregor7caa6822009-07-24 20:34:43 +00003765 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00003766 // Define any newly required vtables.
3767 DefineUsedVTables();
3768
Douglas Gregor7caa6822009-07-24 20:34:43 +00003769 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003770 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003771 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003772
Nick Lewycky81559102011-05-31 07:58:42 +00003773 // Restore the set of pending vtables.
3774 assert(VTableUses.empty() &&
Larisse Voufoef4579c2013-08-06 01:03:05 +00003775 "VTableUses should be empty before it is discarded.");
Nick Lewycky81559102011-05-31 07:58:42 +00003776 VTableUses.swap(SavedVTableUses);
3777
Douglas Gregor7caa6822009-07-24 20:34:43 +00003778 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003779 assert(PendingInstantiations.empty() &&
Larisse Voufoef4579c2013-08-06 01:03:05 +00003780 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003781 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00003782 }
Douglas Gregora58861f2009-05-13 20:28:22 +00003783}
Douglas Gregor815215d2009-05-27 05:35:12 +00003784
Anders Carlsson09025312009-08-29 05:16:22 +00003785void
3786Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3787 const CXXConstructorDecl *Tmpl,
3788 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003789
Richard Trieu90ab75b2011-09-09 03:18:59 +00003790 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003791 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003792
Anders Carlsson09025312009-08-29 05:16:22 +00003793 // Instantiate all the initializers.
3794 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003795 InitsEnd = Tmpl->init_end();
3796 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003797 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003798
Chandler Carruth030ef472010-09-03 21:54:20 +00003799 // Only instantiate written initializers, let Sema re-construct implicit
3800 // ones.
3801 if (!Init->isWritten())
3802 continue;
3803
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003804 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003805
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003806 if (Init->isPackExpansion()) {
3807 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003808 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky98a75582013-06-13 00:45:47 +00003809 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003810 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky98a75582013-06-13 00:45:47 +00003811 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003812 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003813 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00003814 Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003815 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003816 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003817 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003818 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003819 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003820 NumExpansions)) {
3821 AnyErrors = true;
3822 New->setInvalidDecl();
3823 continue;
3824 }
3825 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003826
3827 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003828 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003829 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3830
3831 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003832 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3833 /*CXXDirectInit=*/true);
3834 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003835 AnyErrors = true;
3836 break;
3837 }
3838
3839 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003840 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003841 TemplateArgs,
3842 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003843 New->getDeclName());
3844 if (!BaseTInfo) {
3845 AnyErrors = true;
3846 break;
3847 }
3848
3849 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003850 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003851 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003852 New->getParent(),
3853 SourceLocation());
3854 if (NewInit.isInvalid()) {
3855 AnyErrors = true;
3856 break;
3857 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003858
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003859 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003860 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003861
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003862 continue;
3863 }
3864
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003865 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003866 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3867 /*CXXDirectInit=*/true);
3868 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003869 AnyErrors = true;
3870 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003871 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003872
Anders Carlsson09025312009-08-29 05:16:22 +00003873 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003874 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3875 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3876 TemplateArgs,
3877 Init->getSourceLocation(),
3878 New->getDeclName());
3879 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003880 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003881 New->setInvalidDecl();
3882 continue;
3883 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003884
Douglas Gregor76852c22011-11-01 01:16:03 +00003885 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003886 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003887 New->getParent(), EllipsisLoc);
3888 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003889 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003890 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003891 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003892 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003893 Init->getMemberLocation(),
3894 Init->getMember(),
3895 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003896 if (!Member) {
3897 AnyErrors = true;
3898 New->setInvalidDecl();
3899 continue;
3900 }
Mike Stump1eb44332009-09-09 15:08:12 +00003901
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003902 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003903 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003904 } else if (Init->isIndirectMemberInitializer()) {
3905 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003906 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003907 Init->getMemberLocation(),
3908 Init->getIndirectMember(), TemplateArgs));
3909
Douglas Gregorb7107222011-03-04 19:46:35 +00003910 if (!IndirectMember) {
3911 AnyErrors = true;
3912 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003913 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003914 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003915
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003916 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003917 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003918 }
3919
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003920 if (NewInit.isInvalid()) {
3921 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003922 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003923 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003924 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003925 }
3926 }
Mike Stump1eb44332009-09-09 15:08:12 +00003927
Anders Carlsson09025312009-08-29 05:16:22 +00003928 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003929 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003930 /*FIXME: ColonLoc */
3931 SourceLocation(),
David Blaikie93c86172013-01-17 05:26:25 +00003932 NewInits,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003933 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003934}
3935
John McCall52a575a2009-08-29 08:11:13 +00003936// TODO: this could be templated if the various decl types used the
3937// same method name.
3938static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3939 ClassTemplateDecl *Instance) {
3940 Pattern = Pattern->getCanonicalDecl();
3941
3942 do {
3943 Instance = Instance->getCanonicalDecl();
3944 if (Pattern == Instance) return true;
3945 Instance = Instance->getInstantiatedFromMemberTemplate();
3946 } while (Instance);
3947
3948 return false;
3949}
3950
Douglas Gregor0d696532009-09-28 06:34:35 +00003951static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3952 FunctionTemplateDecl *Instance) {
3953 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003954
Douglas Gregor0d696532009-09-28 06:34:35 +00003955 do {
3956 Instance = Instance->getCanonicalDecl();
3957 if (Pattern == Instance) return true;
3958 Instance = Instance->getInstantiatedFromMemberTemplate();
3959 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003960
Douglas Gregor0d696532009-09-28 06:34:35 +00003961 return false;
3962}
3963
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003964static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003965isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3966 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003967 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003968 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3969 do {
3970 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3971 Instance->getCanonicalDecl());
3972 if (Pattern == Instance)
3973 return true;
3974 Instance = Instance->getInstantiatedFromMember();
3975 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003976
Douglas Gregored9c0f92009-10-29 00:04:11 +00003977 return false;
3978}
3979
John McCall52a575a2009-08-29 08:11:13 +00003980static bool isInstantiationOf(CXXRecordDecl *Pattern,
3981 CXXRecordDecl *Instance) {
3982 Pattern = Pattern->getCanonicalDecl();
3983
3984 do {
3985 Instance = Instance->getCanonicalDecl();
3986 if (Pattern == Instance) return true;
3987 Instance = Instance->getInstantiatedFromMemberClass();
3988 } while (Instance);
3989
3990 return false;
3991}
3992
3993static bool isInstantiationOf(FunctionDecl *Pattern,
3994 FunctionDecl *Instance) {
3995 Pattern = Pattern->getCanonicalDecl();
3996
3997 do {
3998 Instance = Instance->getCanonicalDecl();
3999 if (Pattern == Instance) return true;
4000 Instance = Instance->getInstantiatedFromMemberFunction();
4001 } while (Instance);
4002
4003 return false;
4004}
4005
4006static bool isInstantiationOf(EnumDecl *Pattern,
4007 EnumDecl *Instance) {
4008 Pattern = Pattern->getCanonicalDecl();
4009
4010 do {
4011 Instance = Instance->getCanonicalDecl();
4012 if (Pattern == Instance) return true;
4013 Instance = Instance->getInstantiatedFromMemberEnum();
4014 } while (Instance);
4015
4016 return false;
4017}
4018
John McCalled976492009-12-04 22:46:56 +00004019static bool isInstantiationOf(UsingShadowDecl *Pattern,
4020 UsingShadowDecl *Instance,
4021 ASTContext &C) {
4022 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4023}
4024
4025static bool isInstantiationOf(UsingDecl *Pattern,
4026 UsingDecl *Instance,
4027 ASTContext &C) {
4028 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4029}
4030
John McCall7ba107a2009-11-18 02:36:19 +00004031static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4032 UsingDecl *Instance,
4033 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00004034 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00004035}
4036
4037static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00004038 UsingDecl *Instance,
4039 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00004040 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00004041}
4042
John McCall52a575a2009-08-29 08:11:13 +00004043static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4044 VarDecl *Instance) {
4045 assert(Instance->isStaticDataMember());
4046
4047 Pattern = Pattern->getCanonicalDecl();
4048
4049 do {
4050 Instance = Instance->getCanonicalDecl();
4051 if (Pattern == Instance) return true;
4052 Instance = Instance->getInstantiatedFromStaticDataMember();
4053 } while (Instance);
4054
4055 return false;
4056}
4057
John McCalled976492009-12-04 22:46:56 +00004058// Other is the prospective instantiation
4059// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00004060static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00004061 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00004062 if (UnresolvedUsingTypenameDecl *UUD
4063 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4064 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4065 return isInstantiationOf(UUD, UD, Ctx);
4066 }
4067 }
4068
4069 if (UnresolvedUsingValueDecl *UUD
4070 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00004071 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4072 return isInstantiationOf(UUD, UD, Ctx);
4073 }
4074 }
Douglas Gregor815215d2009-05-27 05:35:12 +00004075
Anders Carlsson0d8df782009-08-29 19:37:28 +00004076 return false;
4077 }
Mike Stump1eb44332009-09-09 15:08:12 +00004078
John McCall52a575a2009-08-29 08:11:13 +00004079 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4080 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00004081
John McCall52a575a2009-08-29 08:11:13 +00004082 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4083 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00004084
John McCall52a575a2009-08-29 08:11:13 +00004085 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4086 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00004087
Douglas Gregor7caa6822009-07-24 20:34:43 +00004088 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00004089 if (Var->isStaticDataMember())
4090 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4091
4092 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4093 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00004094
Douglas Gregor0d696532009-09-28 06:34:35 +00004095 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4096 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4097
Douglas Gregored9c0f92009-10-29 00:04:11 +00004098 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4099 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4100 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4101 PartialSpec);
4102
Anders Carlssond8b285f2009-09-01 04:26:58 +00004103 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4104 if (!Field->getDeclName()) {
4105 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00004106 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00004107 cast<FieldDecl>(D);
4108 }
4109 }
Mike Stump1eb44332009-09-09 15:08:12 +00004110
John McCalled976492009-12-04 22:46:56 +00004111 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4112 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4113
4114 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4115 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4116
Douglas Gregor815215d2009-05-27 05:35:12 +00004117 return D->getDeclName() && isa<NamedDecl>(Other) &&
4118 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4119}
4120
4121template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00004122static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00004123 NamedDecl *D,
4124 ForwardIterator first,
4125 ForwardIterator last) {
4126 for (; first != last; ++first)
4127 if (isInstantiationOf(Ctx, D, *first))
4128 return cast<NamedDecl>(*first);
4129
4130 return 0;
4131}
4132
John McCall02cace72009-08-28 07:59:38 +00004133/// \brief Finds the instantiation of the given declaration context
4134/// within the current instantiation.
4135///
4136/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004137DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00004138 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00004139 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004140 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00004141 return cast_or_null<DeclContext>(ID);
4142 } else return DC;
4143}
4144
Douglas Gregored961e72009-05-27 17:54:46 +00004145/// \brief Find the instantiation of the given declaration within the
4146/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00004147///
4148/// This routine is intended to be used when \p D is a declaration
4149/// referenced from within a template, that needs to mapped into the
4150/// corresponding declaration within an instantiation. For example,
4151/// given:
4152///
4153/// \code
4154/// template<typename T>
4155/// struct X {
4156/// enum Kind {
4157/// KnownValue = sizeof(T)
4158/// };
4159///
4160/// bool getKind() const { return KnownValue; }
4161/// };
4162///
4163/// template struct X<int>;
4164/// \endcode
4165///
Serge Pavlov041d10c2013-07-10 04:59:14 +00004166/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4167/// \p EnumConstantDecl for \p KnownValue (which refers to
4168/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4169/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4170/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004171NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00004172 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00004173 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00004174 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00004175 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00004176 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4177 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00004178 // D is a local of some kind. Look into the map of local
4179 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00004180 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4181 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4182 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004183
Chris Lattner57ad3782011-02-17 20:34:02 +00004184 if (Found) {
4185 if (Decl *FD = Found->dyn_cast<Decl *>())
4186 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004187
Richard Smith9a4db032012-09-12 00:56:43 +00004188 int PackIdx = ArgumentPackSubstitutionIndex;
4189 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00004190 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4191 }
4192
Serge Pavlovdc49d522013-07-15 06:14:07 +00004193 // If we're performing a partial substitution during template argument
4194 // deduction, we may not have values for template parameters yet. They
4195 // just map to themselves.
4196 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4197 isa<TemplateTemplateParmDecl>(D))
4198 return D;
4199
Serge Pavlov29a46e62013-08-10 12:00:21 +00004200 if (D->isInvalidDecl())
4201 return 0;
4202
Chris Lattner57ad3782011-02-17 20:34:02 +00004203 // If we didn't find the decl, then we must have a label decl that hasn't
4204 // been found yet. Lazily instantiate it and return it now.
4205 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004206
Chris Lattner57ad3782011-02-17 20:34:02 +00004207 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4208 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004209
Chris Lattner57ad3782011-02-17 20:34:02 +00004210 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4211 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00004212 }
Douglas Gregor815215d2009-05-27 05:35:12 +00004213
Larisse Voufoef4579c2013-08-06 01:03:05 +00004214 // For variable template specializations, update those that are still
4215 // type-dependent.
4216 if (VarTemplateSpecializationDecl *VarSpec =
4217 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4218 bool InstantiationDependent = false;
4219 const TemplateArgumentListInfo &VarTemplateArgs =
4220 VarSpec->getTemplateArgsInfo();
4221 if (TemplateSpecializationType::anyDependentTemplateArguments(
4222 VarTemplateArgs, InstantiationDependent))
4223 D = cast<NamedDecl>(
4224 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4225 return D;
4226 }
4227
Douglas Gregore95b4092009-09-16 18:34:49 +00004228 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4229 if (!Record->isDependentContext())
4230 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004231
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004232 // Determine whether this record is the "templated" declaration describing
4233 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00004234 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004235 if (ClassTemplate)
4236 ClassTemplate = ClassTemplate->getCanonicalDecl();
4237 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4238 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4239 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufoef4579c2013-08-06 01:03:05 +00004240
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004241 // Walk the current context to find either the record or an instantiation of
4242 // it.
4243 DeclContext *DC = CurContext;
4244 while (!DC->isFileContext()) {
4245 // If we're performing substitution while we're inside the template
4246 // definition, we'll find our own context. We're done.
4247 if (DC->Equals(Record))
4248 return Record;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004249
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004250 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4251 // Check whether we're in the process of instantiating a class template
4252 // specialization of the template we're mapping.
4253 if (ClassTemplateSpecializationDecl *InstSpec
4254 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4255 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4256 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4257 return InstRecord;
4258 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004259
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004260 // Check whether we're in the process of instantiating a member class.
4261 if (isInstantiationOf(Record, InstRecord))
4262 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00004263 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004264
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004265 // Move to the outer template scope.
4266 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4267 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4268 DC = FD->getLexicalDeclContext();
4269 continue;
4270 }
John McCall52a575a2009-08-29 08:11:13 +00004271 }
Larisse Voufoef4579c2013-08-06 01:03:05 +00004272
Douglas Gregor2c1227c2011-11-07 17:43:18 +00004273 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00004274 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00004275
Douglas Gregore95b4092009-09-16 18:34:49 +00004276 // Fall through to deal with other dependent record types (e.g.,
4277 // anonymous unions in class templates).
4278 }
John McCall52a575a2009-08-29 08:11:13 +00004279
Douglas Gregore95b4092009-09-16 18:34:49 +00004280 if (!ParentDC->isDependentContext())
4281 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004282
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004283 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00004284 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00004285 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004286
Douglas Gregor815215d2009-05-27 05:35:12 +00004287 if (ParentDC != D->getDeclContext()) {
4288 // We performed some kind of instantiation in the parent context,
4289 // so now we need to look into the instantiated parent context to
4290 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004291
John McCall3cb0ebd2010-03-10 03:28:59 +00004292 // If our context used to be dependent, we may need to instantiate
4293 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004294 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00004295 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004296 if (!Spec->isDependentContext()) {
4297 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00004298 const RecordType *Tag = T->getAs<RecordType>();
4299 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004300 if (Tag->isBeingDefined())
4301 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00004302 if (!Tag->isBeingDefined() &&
4303 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4304 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00004305
4306 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00004307 }
4308 }
4309
Douglas Gregor815215d2009-05-27 05:35:12 +00004310 NamedDecl *Result = 0;
4311 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004312 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00004313 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor815215d2009-05-27 05:35:12 +00004314 } else {
4315 // Since we don't have a name for the entity we're looking for,
4316 // our only option is to walk through all of the declarations to
4317 // find that name. This will occur in a few cases:
4318 //
4319 // - anonymous struct/union within a template
4320 // - unnamed class/struct/union/enum within a template
4321 //
4322 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00004323 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004324 ParentDC->decls_begin(),
4325 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00004326 }
Mike Stump1eb44332009-09-09 15:08:12 +00004327
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004328 if (!Result) {
4329 if (isa<UsingShadowDecl>(D)) {
4330 // UsingShadowDecls can instantiate to nothing because of using hiding.
4331 } else if (Diags.hasErrorOccurred()) {
4332 // We've already complained about something, so most likely this
4333 // declaration failed to instantiate. There's no point in complaining
4334 // further, since this is normal in invalid code.
4335 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004336 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004337 // instantiated, and we haven't gotten around to instantiating this
4338 // member yet. This can happen when the code uses forward declarations
4339 // of member classes, and introduces ordering dependencies via
4340 // template instantiation.
4341 Diag(Loc, diag::err_member_not_yet_instantiated)
4342 << D->getDeclName()
4343 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4344 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00004345 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4346 // This enumeration constant was found when the template was defined,
4347 // but can't be found in the instantiation. This can happen if an
4348 // unscoped enumeration member is explicitly specialized.
4349 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4350 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4351 TemplateArgs));
4352 assert(Spec->getTemplateSpecializationKind() ==
4353 TSK_ExplicitSpecialization);
4354 Diag(Loc, diag::err_enumerator_does_not_exist)
4355 << D->getDeclName()
4356 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4357 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4358 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00004359 } else {
4360 // We should have found something, but didn't.
4361 llvm_unreachable("Unable to find instantiation of declaration!");
4362 }
4363 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004364
Douglas Gregor815215d2009-05-27 05:35:12 +00004365 D = Result;
4366 }
4367
Douglas Gregor815215d2009-05-27 05:35:12 +00004368 return D;
4369}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004370
Mike Stump1eb44332009-09-09 15:08:12 +00004371/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004372/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00004373void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00004374 // Load pending instantiations from the external source.
4375 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00004376 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00004377 ExternalSource->ReadPendingInstantiations(Pending);
4378 PendingInstantiations.insert(PendingInstantiations.begin(),
4379 Pending.begin(), Pending.end());
4380 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00004381
Douglas Gregor60406be2010-01-16 22:29:39 +00004382 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00004383 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00004384 PendingImplicitInstantiation Inst;
4385
4386 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00004387 Inst = PendingInstantiations.front();
4388 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00004389 } else {
4390 Inst = PendingLocalImplicitInstantiations.front();
4391 PendingLocalImplicitInstantiations.pop_front();
4392 }
Mike Stump1eb44332009-09-09 15:08:12 +00004393
Douglas Gregor7caa6822009-07-24 20:34:43 +00004394 // Instantiate function definitions
4395 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00004396 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4397 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00004398 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4399 TSK_ExplicitInstantiationDefinition;
4400 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4401 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00004402 continue;
4403 }
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Larisse Voufoef4579c2013-08-06 01:03:05 +00004405 // Instantiate variable definitions
Douglas Gregor7caa6822009-07-24 20:34:43 +00004406 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufoef4579c2013-08-06 01:03:05 +00004407
4408 assert((Var->isStaticDataMember() ||
4409 isa<VarTemplateSpecializationDecl>(Var)) &&
4410 "Not a static data member, nor a variable template"
4411 " specialization?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00004412
Chandler Carruth291b4412010-02-13 10:17:50 +00004413 // Don't try to instantiate declarations if the most recent redeclaration
4414 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004415 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00004416 continue;
4417
4418 // Check if the most recent declaration has changed the specialization kind
4419 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004420 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00004421 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00004422 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00004423 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00004424 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00004425 continue; // No longer need to instantiate this type.
4426 case TSK_ExplicitInstantiationDefinition:
4427 // We only need an instantiation if the pending instantiation *is* the
4428 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00004429 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00004430 case TSK_ImplicitInstantiation:
4431 break;
4432 }
4433
Larisse Voufoef4579c2013-08-06 01:03:05 +00004434 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4435 "instantiating variable definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00004436 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4437 TSK_ExplicitInstantiationDefinition;
Larisse Voufoef4579c2013-08-06 01:03:05 +00004438
4439 // Instantiate static data member definitions or variable template
4440 // specializations.
4441 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4442 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00004443 }
4444}
John McCall0c01d182010-03-24 05:22:00 +00004445
4446void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4447 const MultiLevelTemplateArgumentList &TemplateArgs) {
4448 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
4449 E = Pattern->ddiag_end(); I != E; ++I) {
4450 DependentDiagnostic *DD = *I;
4451
4452 switch (DD->getKind()) {
4453 case DependentDiagnostic::Access:
4454 HandleDependentAccessCheck(*DD, TemplateArgs);
4455 break;
4456 }
4457 }
4458}