blob: d780a3b71347be0317894c86dfdcb7c51307ac62 [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
John McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025
26using namespace clang;
27
John McCallb6217662010-03-15 10:12:16 +000028bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000030 if (!OldDecl->getQualifierLoc())
31 return false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000032
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000033 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000034 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000035 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000036
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000037 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000038 return true;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000039
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000040 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000041 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000046 if (!OldDecl->getQualifierLoc())
47 return false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000048
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000049 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000050 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000051 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000052
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000053 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000054 return true;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000055
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000056 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000057 return false;
58}
59
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +000060// Include attribute instantiation code.
61#include "clang/Sema/AttrTemplateInstantiate.inc"
62
Richard Smithf6565a92013-02-22 08:32:16 +000063static void instantiateDependentAlignedAttr(
64 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
65 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
66 if (Aligned->isAlignmentExpr()) {
67 // The alignment expression is a constant expression.
68 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
69 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
70 if (!Result.isInvalid())
71 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
72 Aligned->getSpellingListIndex(), IsPackExpansion);
73 } else {
74 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
75 TemplateArgs, Aligned->getLocation(),
76 DeclarationName());
77 if (Result)
78 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
79 Aligned->getSpellingListIndex(), IsPackExpansion);
80 }
81}
82
83static void instantiateDependentAlignedAttr(
84 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
85 const AlignedAttr *Aligned, Decl *New) {
86 if (!Aligned->isPackExpansion()) {
87 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
88 return;
89 }
90
91 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
92 if (Aligned->isAlignmentExpr())
93 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
94 Unexpanded);
95 else
96 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
97 Unexpanded);
98 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
99
100 // Determine whether we can expand this attribute pack yet.
101 bool Expand = true, RetainExpansion = false;
102 Optional<unsigned> NumExpansions;
103 // FIXME: Use the actual location of the ellipsis.
104 SourceLocation EllipsisLoc = Aligned->getLocation();
105 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
106 Unexpanded, TemplateArgs, Expand,
107 RetainExpansion, NumExpansions))
108 return;
109
110 if (!Expand) {
111 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
112 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
113 } else {
114 for (unsigned I = 0; I != *NumExpansions; ++I) {
115 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
116 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
117 }
118 }
119}
120
John McCall1d8d1cc2010-08-01 02:01:53 +0000121void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000122 const Decl *Tmpl, Decl *New,
123 LateInstantiatedAttrVec *LateAttrs,
124 LocalInstantiationScope *OuterMostScope) {
Sean Huntcf807c42010-08-18 23:23:40 +0000125 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
126 i != e; ++i) {
127 const Attr *TmplAttr = *i;
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000128
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000129 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smithf6565a92013-02-22 08:32:16 +0000130 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
131 if (Aligned && Aligned->isAlignmentDependent()) {
132 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
133 continue;
Chandler Carruth4ced79f2010-06-25 03:22:07 +0000134 }
135
Richard Smithf6565a92013-02-22 08:32:16 +0000136 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000137 if (TmplAttr->isLateParsed() && LateAttrs) {
138 // Late parsed attributes must be instantiated and attached after the
139 // enclosing class has been instantiated. See Sema::InstantiateClass.
140 LocalInstantiationScope *Saved = 0;
141 if (CurrentInstantiationScope)
142 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
143 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
144 } else {
Richard Smithcafeb942013-06-07 02:33:37 +0000145 // Allow 'this' within late-parsed attributes.
146 NamedDecl *ND = dyn_cast<NamedDecl>(New);
147 CXXRecordDecl *ThisContext =
148 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
149 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
150 ND && ND->isCXXInstanceMember());
151
Benjamin Kramer5bbc3852012-02-06 11:13:08 +0000152 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
153 *this, TemplateArgs);
Rafael Espindola31c195a2012-05-15 14:09:55 +0000154 if (NewAttr)
155 New->addAttr(NewAttr);
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000156 }
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000157 }
158}
159
Douglas Gregor4f722be2009-03-25 15:45:12 +0000160Decl *
161TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000162 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000163}
164
165Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000166TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
167 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
168 D->getIdentifier());
169 Owner->addDecl(Inst);
170 return Inst;
171}
172
173Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000174TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000175 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000176}
177
John McCall3dbd3d52010-02-16 06:53:13 +0000178Decl *
179TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
180 NamespaceAliasDecl *Inst
181 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
182 D->getNamespaceLoc(),
183 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000184 D->getIdentifier(),
185 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000186 D->getTargetNameLoc(),
187 D->getNamespace());
188 Owner->addDecl(Inst);
189 return Inst;
190}
191
Richard Smith3e4c6c42011-05-05 21:57:07 +0000192Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
193 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000194 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000195 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000196 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000197 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000198 DI = SemaRef.SubstType(DI, TemplateArgs,
199 D->getLocation(), D->getDeclName());
200 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000201 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000202 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000203 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000204 } else {
205 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000206 }
Mike Stump1eb44332009-09-09 15:08:12 +0000207
Richard Smithb5b37d12012-10-23 00:32:41 +0000208 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
209 // libstdc++ relies upon this bug in its implementation of common_type.
210 // If we happen to be processing that implementation, fake up the g++ ?:
211 // semantics. See LWG issue 2141 for more information on the bug.
212 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
213 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
214 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
215 DT->isReferenceType() &&
216 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
217 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
218 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
219 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
220 // Fold it to the (non-reference) type which g++ would have produced.
221 DI = SemaRef.Context.getTrivialTypeSourceInfo(
222 DI->getType().getNonReferenceType());
223
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000224 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000225 TypedefNameDecl *Typedef;
226 if (IsTypeAlias)
227 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
228 D->getLocation(), D->getIdentifier(), DI);
229 else
230 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
231 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000232 if (Invalid)
233 Typedef->setInvalidDecl();
234
John McCallcde5a402011-02-01 08:20:08 +0000235 // If the old typedef was the name for linkage purposes of an anonymous
236 // tag decl, re-establish that relationship for the new typedef.
237 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
238 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregorc61361b2013-03-08 22:15:15 +0000239 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCallcde5a402011-02-01 08:20:08 +0000240 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall83972f12013-03-09 00:54:27 +0000241 assert(!newTag->hasNameForLinkage());
Richard Smith162e1c12011-04-15 14:24:37 +0000242 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000243 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000244 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000245
Douglas Gregoref96ee02012-01-14 16:38:05 +0000246 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000247 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
248 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000249 if (!InstPrev)
250 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000251
Rafael Espindola5df37bd2011-12-26 22:42:47 +0000252 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
253
254 // If the typedef types are not identical, reject them.
255 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
256
257 Typedef->setPreviousDeclaration(InstPrevTypedef);
John McCall5126fd02009-12-30 00:31:22 +0000258 }
259
John McCall1d8d1cc2010-08-01 02:01:53 +0000260 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000261
John McCall46460a62010-01-20 21:53:11 +0000262 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000263
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000264 return Typedef;
265}
266
Richard Smith162e1c12011-04-15 14:24:37 +0000267Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000268 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
269 Owner->addDecl(Typedef);
270 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000271}
272
273Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000274 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
275 Owner->addDecl(Typedef);
276 return Typedef;
277}
278
279Decl *
280TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
281 // Create a local instantiation scope for this type alias template, which
282 // will contain the instantiations of the template parameters.
283 LocalInstantiationScope Scope(SemaRef);
284
285 TemplateParameterList *TempParams = D->getTemplateParameters();
286 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
287 if (!InstParams)
288 return 0;
289
290 TypeAliasDecl *Pattern = D->getTemplatedDecl();
291
292 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000293 if (Pattern->getPreviousDecl()) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000294 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000295 if (!Found.empty()) {
296 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3e4c6c42011-05-05 21:57:07 +0000297 }
298 }
299
300 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
301 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
302 if (!AliasInst)
303 return 0;
304
305 TypeAliasTemplateDecl *Inst
306 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
307 D->getDeclName(), InstParams, AliasInst);
308 if (PrevAliasTemplate)
309 Inst->setPreviousDeclaration(PrevAliasTemplate);
310
311 Inst->setAccess(D->getAccess());
312
313 if (!PrevAliasTemplate)
314 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000315
Richard Smith3e4c6c42011-05-05 21:57:07 +0000316 Owner->addDecl(Inst);
317
318 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000319}
320
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000321Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000322 // If this is the variable for an anonymous struct or union,
323 // instantiate the anonymous struct/union type first.
324 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
325 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
326 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
327 return 0;
328
John McCallce3ff2b2009-08-25 22:02:44 +0000329 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000330 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000331 TemplateArgs,
332 D->getTypeSpecStartLoc(),
333 D->getDeclName());
334 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000335 return 0;
336
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000337 if (DI->getType()->isFunctionType()) {
338 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
339 << D->isStaticDataMember() << DI->getType();
340 return 0;
341 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000342
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000343 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000344 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000345 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000346 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000347 DI->getType(), DI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000348 D->getStorageClass());
Enea Zaffanelladc173842013-05-04 08:27:07 +0000349 Var->setTSCSpec(D->getTSCSpec());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000350 Var->setInitStyle(D->getInitStyle());
Richard Smithad762fc2011-04-14 22:09:26 +0000351 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Richard Smith796c1a12012-01-19 22:46:17 +0000352 Var->setConstexpr(D->isConstexpr());
Mike Stump1eb44332009-09-09 15:08:12 +0000353
John McCallb6217662010-03-15 10:12:16 +0000354 // Substitute the nested name specifier, if any.
355 if (SubstQualifier(D, Var))
356 return 0;
357
Mike Stump1eb44332009-09-09 15:08:12 +0000358 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000359 // out-of-line, the instantiation will have the same lexical
360 // context (which will be a namespace scope) as the template.
361 if (D->isOutOfLine())
362 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000363
John McCall46460a62010-01-20 21:53:11 +0000364 Var->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000365
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000366 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000367 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000368 Var->setReferenced(D->isReferenced());
369 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000370
Richard Smith671b3212013-02-22 04:55:39 +0000371 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
372
373 if (Var->hasAttrs())
374 SemaRef.CheckAlignasUnderalignment(Var);
375
Mike Stump390b4cc2009-05-16 07:39:55 +0000376 // FIXME: In theory, we could have a previous declaration for variables that
377 // are not static data members.
John McCall68263142009-11-18 22:49:29 +0000378 // FIXME: having to fake up a LookupResult is dumb.
379 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000380 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000381 if (D->isStaticDataMember())
382 SemaRef.LookupQualifiedName(Previous, Owner, false);
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000383
384 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000385 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000386 SemaRef.inferObjCARCLifetime(Var))
387 Var->setInvalidDecl();
388
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +0000389 SemaRef.CheckVariableDeclaration(Var, Previous);
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Douglas Gregor7caa6822009-07-24 20:34:43 +0000391 if (D->isOutOfLine()) {
Richard Smith3e9ea0b2011-12-21 00:25:33 +0000392 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000393 Owner->makeDeclVisibleInContext(Var);
394 } else {
395 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000396 if (Owner->isFunctionOrMethod())
397 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000398 }
Richard Smithbe507b62013-02-01 08:12:08 +0000399
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000400 // Link instantiations of static data members back to the template from
401 // which they were instantiated.
402 if (Var->isStaticDataMember())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000403 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000404 TSK_ImplicitInstantiation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000405
Douglas Gregor60c93c92010-02-09 07:26:29 +0000406 if (Var->getAnyInitializer()) {
407 // We already have an initializer in the class.
408 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000409 if (Var->isStaticDataMember() && !D->isOutOfLine())
Richard Smithadb1d4c2012-07-22 23:45:10 +0000410 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000411 else
Richard Smithadb1d4c2012-07-22 23:45:10 +0000412 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000413
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000414 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000415 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
416 D->getInitStyle() == VarDecl::CallInit);
417 if (!Init.isInvalid()) {
Richard Smith34b41d92011-02-20 03:19:35 +0000418 bool TypeMayContainAuto = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000419 if (Init.get()) {
420 bool DirectInit = D->isDirectInit();
421 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
422 TypeMayContainAuto);
423 } else
Eli Friedman6aeaa602012-01-05 22:34:08 +0000424 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000425 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000426 // FIXME: Not too happy about invalidating the declaration
427 // because of a bogus initializer.
428 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000429 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000430
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000431 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000432 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
433 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000434 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000435
Richard Smithe3499ca2011-06-21 23:42:09 +0000436 // Diagnose unused local variables with dependent types, where the diagnostic
437 // will have been deferred.
438 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
439 D->getType()->isDependentType())
Douglas Gregor5764f612010-05-08 23:05:03 +0000440 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000441
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000442 return Var;
443}
444
Abramo Bagnara6206d532010-06-05 05:09:32 +0000445Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
446 AccessSpecDecl* AD
447 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
448 D->getAccessSpecifierLoc(), D->getColonLoc());
449 Owner->addHiddenDecl(AD);
450 return AD;
451}
452
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000453Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
454 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000455 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000456 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000457 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000458 DI = SemaRef.SubstType(DI, TemplateArgs,
459 D->getLocation(), D->getDeclName());
460 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000461 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000462 Invalid = true;
463 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000464 // C++ [temp.arg.type]p3:
465 // If a declaration acquires a function type through a type
466 // dependent on a template-parameter and this causes a
467 // declaration that does not use the syntactic form of a
468 // function declarator to have function type, the program is
469 // ill-formed.
470 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000471 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000472 Invalid = true;
473 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000474 } else {
475 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000476 }
477
478 Expr *BitWidth = D->getBitWidth();
479 if (Invalid)
480 BitWidth = 0;
481 else if (BitWidth) {
Richard Smithf6702a32011-12-20 02:08:33 +0000482 // The bit-width expression is a constant expression.
483 EnterExpressionEvaluationContext Unevaluated(SemaRef,
484 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000485
John McCall60d7b3a2010-08-24 06:29:42 +0000486 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000487 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000488 if (InstantiatedBitWidth.isInvalid()) {
489 Invalid = true;
490 BitWidth = 0;
491 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000492 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000493 }
494
John McCall07fb6be2009-10-22 23:33:21 +0000495 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
496 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000497 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000498 D->getLocation(),
499 D->isMutable(),
500 BitWidth,
Richard Smithca523302012-06-10 03:12:00 +0000501 D->getInClassInitStyle(),
Richard Smith703b6012012-05-23 04:22:22 +0000502 D->getInnerLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000503 D->getAccess(),
504 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000505 if (!Field) {
506 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000507 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000508 }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000510 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000511
Richard Smithbe507b62013-02-01 08:12:08 +0000512 if (Field->hasAttrs())
513 SemaRef.CheckAlignasUnderalignment(Field);
514
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000515 if (Invalid)
516 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000518 if (!Field->getDeclName()) {
519 // Keep track of where this decl came from.
520 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000521 }
Douglas Gregor9901c572010-05-21 00:31:19 +0000522 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
523 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000524 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000525 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000526 }
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000528 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000529 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000530 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000531
532 return Field;
533}
534
John McCall76da55d2013-04-16 07:28:30 +0000535Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
536 bool Invalid = false;
537 TypeSourceInfo *DI = D->getTypeSourceInfo();
538
539 if (DI->getType()->isVariablyModifiedType()) {
540 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
541 << D->getName();
542 Invalid = true;
543 } else if (DI->getType()->isInstantiationDependentType()) {
544 DI = SemaRef.SubstType(DI, TemplateArgs,
545 D->getLocation(), D->getDeclName());
546 if (!DI) {
547 DI = D->getTypeSourceInfo();
548 Invalid = true;
549 } else if (DI->getType()->isFunctionType()) {
550 // C++ [temp.arg.type]p3:
551 // If a declaration acquires a function type through a type
552 // dependent on a template-parameter and this causes a
553 // declaration that does not use the syntactic form of a
554 // function declarator to have function type, the program is
555 // ill-formed.
556 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
557 << DI->getType();
558 Invalid = true;
559 }
560 } else {
561 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
562 }
563
564 MSPropertyDecl *Property = new (SemaRef.Context)
565 MSPropertyDecl(Owner, D->getLocation(),
566 D->getDeclName(), DI->getType(), DI,
567 D->getLocStart(),
568 D->getGetterId(), D->getSetterId());
569
570 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
571 StartingScope);
572
573 if (Invalid)
574 Property->setInvalidDecl();
575
576 Property->setAccess(D->getAccess());
577 Owner->addDecl(Property);
578
579 return Property;
580}
581
Francois Pichet87c2e122010-11-21 06:08:52 +0000582Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
583 NamedDecl **NamedChain =
584 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
585
586 int i = 0;
587 for (IndirectFieldDecl::chain_iterator PI =
588 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000589 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000590 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000591 TemplateArgs);
592 if (!Next)
593 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000594
Douglas Gregorb7107222011-03-04 19:46:35 +0000595 NamedChain[i++] = Next;
596 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000597
Francois Pichet40e17752010-12-09 10:07:54 +0000598 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000599 IndirectFieldDecl* IndirectField
600 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000601 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000602 NamedChain, D->getChainingSize());
603
604
605 IndirectField->setImplicit(D->isImplicit());
606 IndirectField->setAccess(D->getAccess());
607 Owner->addDecl(IndirectField);
608 return IndirectField;
609}
610
John McCall02cace72009-08-28 07:59:38 +0000611Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000612 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000613 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000614 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000615 TypeSourceInfo *InstTy;
616 // If this is an unsupported friend, don't bother substituting template
617 // arguments into it. The actual type referred to won't be used by any
618 // parts of Clang, and may not be valid for instantiating. Just use the
619 // same info for the instantiated friend.
620 if (D->isUnsupportedFriend()) {
621 InstTy = Ty;
622 } else {
623 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
624 D->getLocation(), DeclarationName());
625 }
626 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000627 return 0;
John McCall02cace72009-08-28 07:59:38 +0000628
Richard Smithd6f80da2012-09-20 01:31:00 +0000629 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara0216df82011-10-29 20:52:52 +0000630 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000631 if (!FD)
632 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000633
Douglas Gregor06245bf2010-04-07 17:57:12 +0000634 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000635 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000636 Owner->addDecl(FD);
637 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000638 }
639
Douglas Gregor06245bf2010-04-07 17:57:12 +0000640 NamedDecl *ND = D->getFriendDecl();
641 assert(ND && "friend decl must be a decl or a type!");
642
John McCallaf2094e2010-04-08 09:05:18 +0000643 // All of the Visit implementations for the various potential friend
644 // declarations have to be carefully written to work for friend
645 // objects, with the most important detail being that the target
646 // decl should almost certainly not be placed in Owner.
647 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000648 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000649
John McCall02cace72009-08-28 07:59:38 +0000650 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000651 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000652 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000653 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000654 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000655 Owner->addDecl(FD);
656 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000657}
658
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000659Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
660 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Richard Smithf6702a32011-12-20 02:08:33 +0000662 // The expression in a static assertion is a constant expression.
663 EnterExpressionEvaluationContext Unevaluated(SemaRef,
664 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000665
John McCall60d7b3a2010-08-24 06:29:42 +0000666 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000667 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000668 if (InstantiatedAssertExpr.isInvalid())
669 return 0;
670
Richard Smithe3f470a2012-07-11 22:37:56 +0000671 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000672 InstantiatedAssertExpr.get(),
Richard Smithe3f470a2012-07-11 22:37:56 +0000673 D->getMessage(),
674 D->getRParenLoc(),
675 D->isFailed());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000676}
677
678Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith38f0df32012-03-26 04:58:10 +0000679 EnumDecl *PrevDecl = 0;
680 if (D->getPreviousDecl()) {
681 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
682 D->getPreviousDecl(),
683 TemplateArgs);
684 if (!Prev) return 0;
685 PrevDecl = cast<EnumDecl>(Prev);
686 }
687
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000688 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000689 D->getLocation(), D->getIdentifier(),
Richard Smith38f0df32012-03-26 04:58:10 +0000690 PrevDecl, D->isScoped(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000691 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000692 if (D->isFixed()) {
Richard Smithf1c66b42012-03-14 23:13:10 +0000693 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000694 // If we have type source information for the underlying type, it means it
695 // has been explicitly set by the user. Perform substitution on it before
696 // moving on.
697 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smithf1c66b42012-03-14 23:13:10 +0000698 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
699 DeclarationName());
700 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000701 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smithf1c66b42012-03-14 23:13:10 +0000702 else
703 Enum->setIntegerTypeSourceInfo(NewTI);
704 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000705 assert(!D->getIntegerType()->isDependentType()
706 && "Dependent type without type source info");
707 Enum->setIntegerType(D->getIntegerType());
708 }
709 }
710
John McCall5b629aa2010-10-22 23:36:17 +0000711 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
712
Richard Smithf1c66b42012-03-14 23:13:10 +0000713 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000714 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000715 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000716 Owner->addDecl(Enum);
Richard Smithf1c66b42012-03-14 23:13:10 +0000717
Richard Smith4ca93d92012-03-26 04:08:46 +0000718 EnumDecl *Def = D->getDefinition();
719 if (Def && Def != D) {
720 // If this is an out-of-line definition of an enum member template, check
721 // that the underlying types match in the instantiation of both
722 // declarations.
723 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
724 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
725 QualType DefnUnderlying =
726 SemaRef.SubstType(TI->getType(), TemplateArgs,
727 UnderlyingLoc, DeclarationName());
728 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
729 DefnUnderlying, Enum);
730 }
731 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000732
Douglas Gregor96084f12010-03-01 19:00:07 +0000733 if (D->getDeclContext()->isFunctionOrMethod())
734 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000735
Richard Smithf1c66b42012-03-14 23:13:10 +0000736 // C++11 [temp.inst]p1: The implicit instantiation of a class template
737 // specialization causes the implicit instantiation of the declarations, but
738 // not the definitions of scoped member enumerations.
739 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith38f0df32012-03-26 04:58:10 +0000740 // within a block scope, but we treat that much like a member template. Only
741 // instantiate the definition when visiting the definition in that case, since
742 // we will visit all redeclarations.
743 if (!Enum->isScoped() && Def &&
744 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith4ca93d92012-03-26 04:08:46 +0000745 InstantiateEnumDefinition(Enum, Def);
Richard Smithf1c66b42012-03-14 23:13:10 +0000746
747 return Enum;
748}
749
750void TemplateDeclInstantiator::InstantiateEnumDefinition(
751 EnumDecl *Enum, EnumDecl *Pattern) {
752 Enum->startDefinition();
753
Richard Smith1af83c42012-03-23 03:33:32 +0000754 // Update the location to refer to the definition.
755 Enum->setLocation(Pattern->getLocation());
756
Chris Lattner5f9e2722011-07-23 10:55:15 +0000757 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000758
759 EnumConstantDecl *LastEnumConst = 0;
Richard Smithf1c66b42012-03-14 23:13:10 +0000760 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
761 ECEnd = Pattern->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000762 EC != ECEnd; ++EC) {
763 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000764 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000765 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +0000766 // The enumerator's value expression is a constant expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000767 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smithf6702a32011-12-20 02:08:33 +0000768 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000769
John McCallce3ff2b2009-08-25 22:02:44 +0000770 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000771 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000772
773 // Drop the initial value and continue.
774 bool isInvalid = false;
775 if (Value.isInvalid()) {
776 Value = SemaRef.Owned((Expr *)0);
777 isInvalid = true;
778 }
779
Mike Stump1eb44332009-09-09 15:08:12 +0000780 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000781 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
782 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000783 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000784
785 if (isInvalid) {
786 if (EnumConst)
787 EnumConst->setInvalidDecl();
788 Enum->setInvalidDecl();
789 }
790
791 if (EnumConst) {
David Blaikie581deb32012-06-06 20:45:41 +0000792 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall5b629aa2010-10-22 23:36:17 +0000793
John McCall3b85ecf2010-01-23 22:37:59 +0000794 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000795 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000796 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000797 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000798
Richard Smithf1c66b42012-03-14 23:13:10 +0000799 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
800 !Enum->isScoped()) {
Douglas Gregor96084f12010-03-01 19:00:07 +0000801 // If the enumeration is within a function or method, record the enum
802 // constant as a local.
David Blaikie581deb32012-06-06 20:45:41 +0000803 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregor96084f12010-03-01 19:00:07 +0000804 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000805 }
806 }
Mike Stump1eb44332009-09-09 15:08:12 +0000807
Richard Smithf1c66b42012-03-14 23:13:10 +0000808 // FIXME: Fixup LBraceLoc
809 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
810 Enum->getRBraceLoc(), Enum,
Dmitri Gribenko9ff2b422013-04-27 20:23:52 +0000811 Enumerators,
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000812 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000813}
814
Douglas Gregor6477b692009-03-25 15:04:13 +0000815Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000816 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000817}
818
John McCalle29ba202009-08-20 01:44:21 +0000819Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000820 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
821
Douglas Gregor550d9b22009-10-31 17:21:17 +0000822 // Create a local instantiation scope for this class template, which
823 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000824 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000825 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000826 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000827 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000828 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000829
830 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000831
832 // Instantiate the qualifier. We have to do this first in case
833 // we're a friend declaration, because if we are then we need to put
834 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000835 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
836 if (QualifierLoc) {
837 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
838 TemplateArgs);
839 if (!QualifierLoc)
840 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000841 }
842
843 CXXRecordDecl *PrevDecl = 0;
844 ClassTemplateDecl *PrevClassTemplate = 0;
845
Douglas Gregoref96ee02012-01-14 16:38:05 +0000846 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky37574f52010-11-08 23:29:42 +0000847 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +0000848 if (!Found.empty()) {
849 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky37574f52010-11-08 23:29:42 +0000850 if (PrevClassTemplate)
851 PrevDecl = PrevClassTemplate->getTemplatedDecl();
852 }
853 }
854
John McCall93ba8572010-03-25 06:39:04 +0000855 // If this isn't a friend, then it's a member template, in which
856 // case we just want to build the instantiation in the
857 // specialization. If it is a friend, we want to build it in
858 // the appropriate context.
859 DeclContext *DC = Owner;
860 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000861 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000862 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000863 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000864 DC = SemaRef.computeDeclContext(SS);
865 if (!DC) return 0;
866 } else {
867 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
868 Pattern->getDeclContext(),
869 TemplateArgs);
870 }
871
872 // Look for a previous declaration of the template in the owning
873 // context.
874 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
875 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
876 SemaRef.LookupQualifiedName(R, DC);
877
878 if (R.isSingleResult()) {
879 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
880 if (PrevClassTemplate)
881 PrevDecl = PrevClassTemplate->getTemplatedDecl();
882 }
883
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000884 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000885 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000886 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000887 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000888 return 0;
889 }
890
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000891 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000892 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000893 bool Complain = true;
894
895 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
896 // template for struct std::tr1::__detail::_Map_base, where the
897 // template parameters of the friend declaration don't match the
898 // template parameters of the original declaration. In this one
899 // case, we don't complain about the ill-formed friend
900 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000901 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000902 Pattern->getIdentifier()->isStr("_Map_base") &&
903 DC->isNamespace() &&
904 cast<NamespaceDecl>(DC)->getIdentifier() &&
905 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
906 DeclContext *DCParent = DC->getParent();
907 if (DCParent->isNamespace() &&
908 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
909 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
910 DeclContext *DCParent2 = DCParent->getParent();
911 if (DCParent2->isNamespace() &&
912 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
913 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
914 DCParent2->getParent()->isTranslationUnit())
915 Complain = false;
916 }
917 }
918
John McCall93ba8572010-03-25 06:39:04 +0000919 TemplateParameterList *PrevParams
920 = PrevClassTemplate->getTemplateParameters();
921
922 // Make sure the parameter lists match.
923 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000924 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000925 Sema::TPL_TemplateMatch)) {
926 if (Complain)
927 return 0;
928
929 AdoptedPreviousTemplateParams = true;
930 InstParams = PrevParams;
931 }
John McCall93ba8572010-03-25 06:39:04 +0000932
933 // Do some additional validation, then merge default arguments
934 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000935 if (!AdoptedPreviousTemplateParams &&
936 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000937 Sema::TPC_ClassTemplate))
938 return 0;
939 }
940 }
941
John McCalle29ba202009-08-20 01:44:21 +0000942 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000943 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000944 Pattern->getLocStart(), Pattern->getLocation(),
945 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000946 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000947
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000948 if (QualifierLoc)
949 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000950
John McCalle29ba202009-08-20 01:44:21 +0000951 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000952 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
953 D->getIdentifier(), InstParams, RecordInst,
954 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000955 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000956
John McCall93ba8572010-03-25 06:39:04 +0000957 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000958 if (PrevClassTemplate)
959 Inst->setAccess(PrevClassTemplate->getAccess());
960 else
961 Inst->setAccess(D->getAccess());
962
Richard Smith22050f22013-07-17 23:53:16 +0000963 Inst->setObjectOfFriendDecl();
John McCall93ba8572010-03-25 06:39:04 +0000964 // TODO: do we want to track the instantiation progeny of this
965 // friend target decl?
966 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000967 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000968 if (!PrevClassTemplate)
969 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000970 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000971
Douglas Gregorf0510d42009-10-12 23:11:44 +0000972 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000973 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000974 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000975
Douglas Gregor259571e2009-10-30 22:42:42 +0000976 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000977 if (isFriend) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000978 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000979 Inst->setLexicalDeclContext(Owner);
980 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000981 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000982 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000983
Abramo Bagnara4c515482011-11-26 13:33:46 +0000984 if (D->isOutOfLine()) {
985 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
986 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
987 }
988
John McCalle29ba202009-08-20 01:44:21 +0000989 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000990
991 if (!PrevClassTemplate) {
992 // Queue up any out-of-line partial specializations of this member
993 // class template; the client will force their instantiation once
994 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000995 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000996 D->getPartialSpecializations(PartialSpecs);
997 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
998 if (PartialSpecs[I]->isOutOfLine())
999 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1000 }
1001
John McCalle29ba202009-08-20 01:44:21 +00001002 return Inst;
1003}
1004
Douglas Gregord60e1052009-08-27 16:57:43 +00001005Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +00001006TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1007 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00001008 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001009
Douglas Gregored9c0f92009-10-29 00:04:11 +00001010 // Lookup the already-instantiated declaration in the instantiation
1011 // of the class template and return that.
1012 DeclContext::lookup_result Found
1013 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00001014 if (Found.empty())
Douglas Gregored9c0f92009-10-29 00:04:11 +00001015 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001016
Douglas Gregored9c0f92009-10-29 00:04:11 +00001017 ClassTemplateDecl *InstClassTemplate
David Blaikie3bc93e32012-12-19 00:45:41 +00001018 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001019 if (!InstClassTemplate)
1020 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001021
Douglas Gregord65587f2010-11-10 19:44:59 +00001022 if (ClassTemplatePartialSpecializationDecl *Result
1023 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1024 return Result;
1025
1026 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +00001027}
1028
1029Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +00001030TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001031 // Create a local instantiation scope for this function template, which
1032 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001033 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +00001034 // itself.
John McCall2a7fb272010-08-25 05:32:35 +00001035 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +00001036
Douglas Gregord60e1052009-08-27 16:57:43 +00001037 TemplateParameterList *TempParams = D->getTemplateParameters();
1038 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +00001039 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +00001040 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001041
Douglas Gregora735b202009-10-13 14:39:41 +00001042 FunctionDecl *Instantiated = 0;
1043 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001044 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +00001045 InstParams));
1046 else
1047 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001048 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +00001049 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001050
Douglas Gregora735b202009-10-13 14:39:41 +00001051 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +00001052 return 0;
1053
Mike Stump1eb44332009-09-09 15:08:12 +00001054 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +00001055 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001056 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +00001057 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +00001058 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001059 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +00001060 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +00001061
John McCallb1a56e72010-03-26 23:10:15 +00001062 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1063
John McCalle976ffe2009-12-14 23:19:40 +00001064 // Link the instantiation back to the pattern *unless* this is a
1065 // non-definition friend declaration.
1066 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +00001067 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +00001068 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001069
John McCallb1a56e72010-03-26 23:10:15 +00001070 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +00001071 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001072 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +00001073 } else if (InstTemplate->getDeclContext()->isRecord() &&
1074 !D->getPreviousDecl()) {
1075 SemaRef.CheckFriendAccess(InstTemplate);
1076 }
John McCallb1a56e72010-03-26 23:10:15 +00001077
Douglas Gregord60e1052009-08-27 16:57:43 +00001078 return InstTemplate;
1079}
1080
Douglas Gregord475b8d2009-03-25 21:17:03 +00001081Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1082 CXXRecordDecl *PrevDecl = 0;
1083 if (D->isInjectedClassName())
1084 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +00001085 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001086 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +00001087 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +00001088 TemplateArgs);
1089 if (!Prev) return 0;
1090 PrevDecl = cast<CXXRecordDecl>(Prev);
1091 }
Douglas Gregord475b8d2009-03-25 21:17:03 +00001092
1093 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +00001094 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001095 D->getLocStart(), D->getLocation(),
1096 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +00001097
1098 // Substitute the nested name specifier, if any.
1099 if (SubstQualifier(D, Record))
1100 return 0;
1101
Douglas Gregord475b8d2009-03-25 21:17:03 +00001102 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001103 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1104 // the tag decls introduced by friend class declarations don't have an access
1105 // specifier. Remove once this area of the code gets sorted out.
1106 if (D->getAccess() != AS_none)
1107 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001108 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001109 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001110
John McCall02cace72009-08-28 07:59:38 +00001111 // If the original function was part of a friend declaration,
1112 // inherit its namespace state.
Richard Smith22050f22013-07-17 23:53:16 +00001113 if (D->getFriendObjectKind())
1114 Record->setObjectOfFriendDecl();
John McCall02cace72009-08-28 07:59:38 +00001115
Douglas Gregor9901c572010-05-21 00:31:19 +00001116 // Make sure that anonymous structs and unions are recorded.
1117 if (D->isAnonymousStructOrUnion()) {
1118 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001119 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001120 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1121 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001122
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001123 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001124 return Record;
1125}
1126
Douglas Gregor71074fd2012-09-13 21:56:43 +00001127/// \brief Adjust the given function type for an instantiation of the
1128/// given declaration, to cope with modifications to the function's type that
1129/// aren't reflected in the type-source information.
1130///
1131/// \param D The declaration we're instantiating.
1132/// \param TInfo The already-instantiated type.
1133static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1134 FunctionDecl *D,
1135 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001136 const FunctionProtoType *OrigFunc
1137 = D->getType()->castAs<FunctionProtoType>();
1138 const FunctionProtoType *NewFunc
1139 = TInfo->getType()->castAs<FunctionProtoType>();
1140 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1141 return TInfo->getType();
1142
1143 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1144 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1145 return Context.getFunctionType(NewFunc->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00001146 NewFunc->getArgTypes(), NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001147}
1148
John McCall02cace72009-08-28 07:59:38 +00001149/// Normal class members are of more specific types and therefore
1150/// don't make it here. This function serves two purposes:
1151/// 1) instantiating function templates
1152/// 2) substituting friend declarations
1153/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001154Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001155 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001156 // Check whether there is already a function template specialization for
1157 // this declaration.
1158 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001159 if (FunctionTemplate && !TemplateParams) {
Richard Smithc95d4132013-05-03 23:46:09 +00001160 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001161
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001162 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001163 FunctionDecl *SpecFunc
Richard Smithc95d4132013-05-03 23:46:09 +00001164 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001165 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Douglas Gregor127102b2009-06-29 20:59:39 +00001167 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001168 if (SpecFunc)
1169 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001170 }
Mike Stump1eb44332009-09-09 15:08:12 +00001171
John McCallb0cb0222010-03-27 05:57:59 +00001172 bool isFriend;
1173 if (FunctionTemplate)
1174 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1175 else
1176 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1177
Douglas Gregor79c22782010-01-16 20:21:20 +00001178 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001179 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001180 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001181 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001182 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Chris Lattner5f9e2722011-07-23 10:55:15 +00001184 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001185 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001186 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001187 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001188 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001189
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001190 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1191 if (QualifierLoc) {
1192 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1193 TemplateArgs);
1194 if (!QualifierLoc)
1195 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001196 }
1197
John McCall68b6b872010-02-06 01:50:47 +00001198 // If we're instantiating a local function declaration, put the result
1199 // in the owner; otherwise we need to find the instantiated context.
1200 DeclContext *DC;
1201 if (D->getDeclContext()->isFunctionOrMethod())
1202 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001203 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001204 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001205 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001206 DC = SemaRef.computeDeclContext(SS);
1207 if (!DC) return 0;
1208 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001209 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001210 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001211 }
John McCall68b6b872010-02-06 01:50:47 +00001212
John McCall02cace72009-08-28 07:59:38 +00001213 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001214 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001215 D->getNameInfo(), T, TInfo,
Rafael Espindola459ef032013-04-16 02:29:15 +00001216 D->getCanonicalDecl()->getStorageClass(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001217 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001218 D->isConstexpr());
Enea Zaffanellade9ed712013-07-19 18:02:36 +00001219 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCallb6217662010-03-15 10:12:16 +00001220
Richard Smithd4497dd2013-01-25 00:08:28 +00001221 if (D->isInlined())
1222 Function->setImplicitlyInline();
1223
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001224 if (QualifierLoc)
1225 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001226
John McCallb1a56e72010-03-26 23:10:15 +00001227 DeclContext *LexicalDC = Owner;
1228 if (!isFriend && D->isOutOfLine()) {
1229 assert(D->getDeclContext()->isFileContext());
1230 LexicalDC = D->getDeclContext();
1231 }
1232
1233 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Douglas Gregore53060f2009-06-25 22:08:12 +00001235 // Attach the parameters
Douglas Gregor5cbe1012011-07-05 18:30:26 +00001236 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
Douglas Gregor1d441ee2011-06-22 18:16:25 +00001237 // Adopt the already-instantiated parameters into our own context.
1238 for (unsigned P = 0; P < Params.size(); ++P)
1239 if (Params[P])
1240 Params[P]->setOwningFunction(Function);
1241 } else {
1242 // Since we were instantiated via a typedef of a function type, create
1243 // new parameters.
1244 const FunctionProtoType *Proto
1245 = Function->getType()->getAs<FunctionProtoType>();
1246 assert(Proto && "No function prototype in template instantiation?");
1247 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1248 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1249 ParmVarDecl *Param
1250 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1251 *AI);
1252 Param->setScopeInfo(0, Params.size());
1253 Params.push_back(Param);
1254 }
1255 }
David Blaikie4278c652011-09-21 18:16:56 +00001256 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001257
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001258 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001259 if (TemplateParams) {
1260 // Our resulting instantiation is actually a function template, since we
1261 // are substituting only the outer template parameters. For example, given
1262 //
1263 // template<typename T>
1264 // struct X {
1265 // template<typename U> friend void f(T, U);
1266 // };
1267 //
1268 // X<int> x;
1269 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001270 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001271 // which means substituting int for T, but leaving "f" as a friend function
1272 // template.
1273 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001274 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001275 Function->getLocation(),
1276 Function->getDeclName(),
1277 TemplateParams, Function);
1278 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001279
1280 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001281
1282 if (isFriend && D->isThisDeclarationADefinition()) {
1283 // TODO: should we remember this connection regardless of whether
1284 // the friend declaration provided a body?
1285 FunctionTemplate->setInstantiatedFromMemberTemplate(
1286 D->getDescribedFunctionTemplate());
1287 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001288 } else if (FunctionTemplate) {
1289 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001290 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001291 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001292 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001293 Innermost.begin(),
1294 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001295 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001296 } else if (isFriend) {
1297 // Note, we need this connection even if the friend doesn't have a body.
1298 // Its body may exist but not have been attached yet due to deferred
1299 // parsing.
1300 // FIXME: It might be cleaner to set this when attaching the body to the
1301 // friend function declaration, however that would require finding all the
1302 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001303 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001304 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001305
Douglas Gregore53060f2009-06-25 22:08:12 +00001306 if (InitFunctionInstantiation(Function, D))
1307 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001308
John McCallaf2094e2010-04-08 09:05:18 +00001309 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001310
John McCall68263142009-11-18 22:49:29 +00001311 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1312 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1313
John McCallaf2094e2010-04-08 09:05:18 +00001314 if (DependentFunctionTemplateSpecializationInfo *Info
1315 = D->getDependentSpecializationInfo()) {
1316 assert(isFriend && "non-friend has dependent specialization info?");
1317
1318 // This needs to be set now for future sanity.
Richard Smith22050f22013-07-17 23:53:16 +00001319 Function->setObjectOfFriendDecl();
John McCallaf2094e2010-04-08 09:05:18 +00001320
1321 // Instantiate the explicit template arguments.
1322 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1323 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001324 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1325 ExplicitArgs, TemplateArgs))
1326 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001327
1328 // Map the candidate templates to their instantiations.
1329 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1330 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1331 Info->getTemplate(I),
1332 TemplateArgs);
1333 if (!Temp) return 0;
1334
1335 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1336 }
1337
1338 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1339 &ExplicitArgs,
1340 Previous))
1341 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001342
John McCallaf2094e2010-04-08 09:05:18 +00001343 isExplicitSpecialization = true;
1344
1345 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001346 // Look only into the namespace where the friend would be declared to
1347 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001348 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001349 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001350
Douglas Gregora735b202009-10-13 14:39:41 +00001351 // In C++, the previous declaration we find might be a tag type
1352 // (class or enum). In this case, the new declaration will hide the
1353 // tag type. Note that this does does not apply if we're declaring a
1354 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001355 if (Previous.isSingleTagDecl())
1356 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001357 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001358
John McCall9f54ad42009-12-10 09:41:52 +00001359 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001360 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001361
John McCall76d32642010-04-24 01:30:58 +00001362 NamedDecl *PrincipalDecl = (TemplateParams
1363 ? cast<NamedDecl>(FunctionTemplate)
1364 : Function);
1365
Douglas Gregora735b202009-10-13 14:39:41 +00001366 // If the original function was part of a friend declaration,
1367 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001368 if (isFriend) {
Richard Smith22050f22013-07-17 23:53:16 +00001369 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001370 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001371
Gabor Greif77535df2010-08-30 22:25:56 +00001372 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001373
Richard Smith53e53512011-10-19 00:54:10 +00001374 // C++98 [temp.friend]p5: When a function is defined in a friend function
1375 // declaration in a class template, the function is defined at each
1376 // instantiation of the class template. The function is defined even if it
1377 // is never used.
1378 // C++11 [temp.friend]p4: When a function is defined in a friend function
1379 // declaration in a class template, the function is instantiated when the
1380 // function is odr-used.
1381 //
1382 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1383 // redefinition, but don't instantiate the function.
Richard Smith80ad52f2013-01-02 11:42:31 +00001384 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smith53e53512011-10-19 00:54:10 +00001385 SemaRef.Diags.getDiagnosticLevel(
1386 diag::warn_cxx98_compat_friend_redefinition,
1387 Function->getLocation())
1388 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001389 D->isThisDeclarationADefinition()) {
1390 // Check for a function body.
1391 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001392 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001393 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001394 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001395 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001396 diag::warn_cxx98_compat_friend_redefinition :
1397 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001398 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001399 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001400 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001401 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001402 // Check for redefinitions due to other instantiations of this or
1403 // a similar friend function.
1404 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1405 REnd = Function->redecls_end();
1406 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001407 if (*R == Function)
1408 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001409 switch (R->getFriendObjectKind()) {
1410 case Decl::FOK_None:
Richard Smith80ad52f2013-01-02 11:42:31 +00001411 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smith53e53512011-10-19 00:54:10 +00001412 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001413 if (MemberSpecializationInfo *MSInfo
1414 = Function->getMemberSpecializationInfo()) {
1415 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1416 SourceLocation Loc = R->getLocation(); // FIXME
1417 MSInfo->setPointOfInstantiation(Loc);
1418 SemaRef.PendingLocalImplicitInstantiations.push_back(
1419 std::make_pair(Function, Loc));
1420 queuedInstantiation = true;
1421 }
1422 }
1423 }
1424 break;
1425 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001426 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001427 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001428 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001429 SemaRef.Diag(Function->getLocation(),
Richard Smith80ad52f2013-01-02 11:42:31 +00001430 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smith53e53512011-10-19 00:54:10 +00001431 diag::warn_cxx98_compat_friend_redefinition :
1432 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001433 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001434 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith80ad52f2013-01-02 11:42:31 +00001435 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smith53e53512011-10-19 00:54:10 +00001436 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001437 break;
1438 }
1439 }
1440 }
1441 }
Douglas Gregora735b202009-10-13 14:39:41 +00001442 }
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
Abramo Bagnara723df242010-12-14 22:11:44 +00001505 // \brief If the type of this function, after ignoring parentheses,
1506 // is not *directly* a function type, then we're instantiating a function
1507 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001508 //
1509 // typedef int functype(int, int);
1510 // functype func;
1511 //
1512 // In this case, we'll just go instantiate the ParmVarDecls that we
1513 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001514 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001515 assert(!Params.size() && "Instantiating type could not yield parameters");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001516 SmallVector<QualType, 4> ParamTypes;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001517 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1518 D->getNumParams(), TemplateArgs, ParamTypes,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001519 &Params))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001520 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001521 }
1522
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001523 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1524 if (QualifierLoc) {
1525 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001526 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001527 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001528 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001529 }
1530
1531 DeclContext *DC = Owner;
1532 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001533 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001534 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001535 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001536 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001537
1538 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1539 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001540 } else {
1541 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1542 D->getDeclContext(),
1543 TemplateArgs);
1544 }
1545 if (!DC) return 0;
1546 }
1547
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001548 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001549 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001550 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001551
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001552 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001553 DeclarationNameInfo NameInfo
1554 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001555 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001556 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001557 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001558 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001559 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001560 false, Constructor->isConstexpr());
Richard Smithb5eb3f52013-05-17 02:19:35 +00001561
Richard Smith4841ca52013-04-10 05:48:59 +00001562 // Claim that the instantiation of a constructor or constructor template
1563 // inherits the same constructor that the template does.
Richard Smithb5eb3f52013-05-17 02:19:35 +00001564 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1565 Constructor->getInheritedConstructor())) {
1566 // If we're instantiating a specialization of a function template, our
1567 // "inherited constructor" will actually itself be a function template.
1568 // Instantiate a declaration of it, too.
1569 if (FunctionTemplate) {
1570 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1571 !Inh->getParent()->isDependentContext() &&
1572 "inheriting constructor template in dependent context?");
1573 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1574 Inh);
1575 if (Inst)
1576 return 0;
1577 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1578 LocalInstantiationScope LocalScope(SemaRef);
1579
1580 // Use the same template arguments that we deduced for the inheriting
1581 // constructor. There's no way they could be deduced differently.
1582 MultiLevelTemplateArgumentList InheritedArgs;
1583 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1584 Inh = cast_or_null<CXXConstructorDecl>(
1585 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1586 if (!Inh)
1587 return 0;
1588 }
Richard Smith4841ca52013-04-10 05:48:59 +00001589 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smithb5eb3f52013-05-17 02:19:35 +00001590 }
Douglas Gregor17e32f32009-08-21 22:43:28 +00001591 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001592 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001593 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001594 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001595 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001596 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001597 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001598 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001599 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001600 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001601 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001602 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001603 } else {
Rafael Espindola72fdc892013-04-15 12:38:20 +00001604 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnara25777432010-08-11 22:01:17 +00001605 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001606 StartLoc, NameInfo, T, TInfo,
Rafael Espindola72fdc892013-04-15 12:38:20 +00001607 SC, D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001608 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001609 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001610
Richard Smithd4497dd2013-01-25 00:08:28 +00001611 if (D->isInlined())
1612 Method->setImplicitlyInline();
1613
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001614 if (QualifierLoc)
1615 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001616
Douglas Gregord60e1052009-08-27 16:57:43 +00001617 if (TemplateParams) {
1618 // Our resulting instantiation is actually a function template, since we
1619 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001620 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001621 // template<typename T>
1622 // struct X {
1623 // template<typename U> void f(T, U);
1624 // };
1625 //
1626 // X<int> x;
1627 //
1628 // We are instantiating the member template "f" within X<int>, which means
1629 // substituting int for T, but leaving "f" as a member function template.
1630 // Build the function template itself.
1631 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1632 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001633 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001634 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001635 if (isFriend) {
1636 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001637 FunctionTemplate->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001638 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001639 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001640 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001641 } else if (FunctionTemplate) {
1642 // Record this function template specialization.
Richard Smithc95d4132013-05-03 23:46:09 +00001643 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001644 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001645 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smithc95d4132013-05-03 23:46:09 +00001646 Innermost.begin(),
1647 Innermost.size()),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001648 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001649 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001650 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001651 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001652 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001653
Mike Stump1eb44332009-09-09 15:08:12 +00001654 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001655 // out-of-line, the instantiation will have the same lexical
1656 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001657 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001658 if (NumTempParamLists)
1659 Method->setTemplateParameterListsInfo(SemaRef.Context,
1660 NumTempParamLists,
1661 TempParamLists.data());
1662
John McCallb0cb0222010-03-27 05:57:59 +00001663 Method->setLexicalDeclContext(Owner);
Richard Smith22050f22013-07-17 23:53:16 +00001664 Method->setObjectOfFriendDecl();
John McCallb0cb0222010-03-27 05:57:59 +00001665 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001666 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001667
Douglas Gregor5545e162009-03-24 00:38:23 +00001668 // Attach the parameters
1669 for (unsigned P = 0; P < Params.size(); ++P)
1670 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001671 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001672
1673 if (InitMethodInstantiation(Method, D))
1674 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001675
Abramo Bagnara25777432010-08-11 22:01:17 +00001676 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1677 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001678
John McCallb0cb0222010-03-27 05:57:59 +00001679 if (!FunctionTemplate || TemplateParams || isFriend) {
1680 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001681
Douglas Gregordec06662009-08-21 18:42:58 +00001682 // In C++, the previous declaration we find might be a tag type
1683 // (class or enum). In this case, the new declaration will hide the
1684 // tag type. Note that this does does not apply if we're declaring a
1685 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001686 if (Previous.isSingleTagDecl())
1687 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001688 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001689
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001690 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001691 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001692
Douglas Gregor4ba31362009-12-01 17:24:26 +00001693 if (D->isPure())
1694 SemaRef.CheckPureMethod(Method, SourceRange());
1695
John McCall1f2e1a92012-08-10 03:15:35 +00001696 // Propagate access. For a non-friend declaration, the access is
1697 // whatever we're propagating from. For a friend, it should be the
1698 // previous declaration we just found.
1699 if (isFriend && Method->getPreviousDecl())
1700 Method->setAccess(Method->getPreviousDecl()->getAccess());
1701 else
1702 Method->setAccess(D->getAccess());
1703 if (FunctionTemplate)
1704 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001705
Anders Carlsson9eefa222011-01-20 06:52:44 +00001706 SemaRef.CheckOverrideControl(Method);
1707
Eli Friedman3bc45152011-11-15 22:39:08 +00001708 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smithac713512012-12-08 02:53:02 +00001709 if (D->isExplicitlyDefaulted())
1710 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001711 if (D->isDeletedAsWritten())
Richard Smithac713512012-12-08 02:53:02 +00001712 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman3bc45152011-11-15 22:39:08 +00001713
John McCall1f2e1a92012-08-10 03:15:35 +00001714 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001715 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001716 // do nothing
1717
1718 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001719 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001720 // do nothing
1721
1722 // Otherwise, check access to friends and make them visible.
1723 } else if (isFriend) {
1724 // We only need to re-check access for methods which we didn't
1725 // manage to match during parsing.
1726 if (!D->getPreviousDecl())
1727 SemaRef.CheckFriendAccess(Method);
1728
1729 Record->makeDeclVisibleInContext(Method);
1730
1731 // Otherwise, add the declaration. We don't need to do this for
1732 // class-scope specializations because we'll have matched them with
1733 // the appropriate template.
1734 } else if (!IsClassScopeSpecialization) {
1735 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001736 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001737
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001738 return Method;
1739}
1740
Douglas Gregor615c5d42009-03-24 16:43:20 +00001741Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001742 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001743}
1744
Douglas Gregor03b2b072009-03-24 00:15:49 +00001745Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001746 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001747}
1748
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001749Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001750 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001751}
1752
Eli Friedmanded99792013-06-27 23:21:55 +00001753Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie66874fb2013-02-21 01:47:18 +00001754 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1755 /*ExpectParameterPack=*/ false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001756}
1757
John McCalle29ba202009-08-20 01:44:21 +00001758Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1759 TemplateTypeParmDecl *D) {
1760 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001761 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001762
John McCalle29ba202009-08-20 01:44:21 +00001763 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001764 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1765 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001766 D->getDepth() - TemplateArgs.getNumLevels(),
1767 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001768 D->wasDeclaredWithTypename(),
1769 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001770 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001771
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001772 if (D->hasDefaultArgument())
1773 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1774
1775 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001776 // scope.
1777 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001778
John McCalle29ba202009-08-20 01:44:21 +00001779 return Inst;
1780}
1781
Douglas Gregor33642df2009-10-23 23:25:44 +00001782Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1783 NonTypeTemplateParmDecl *D) {
1784 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001785 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001786 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1787 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001788 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001789 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001790 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001791 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001792
1793 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001794 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001795 // expansion of types. Substitute into each of the expanded types.
1796 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1797 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1798 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1799 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1800 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001801 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001802 D->getDeclName());
1803 if (!NewDI)
1804 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001805
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001806 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1807 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1808 D->getLocation());
1809 if (NewT.isNull())
1810 return 0;
1811 ExpandedParameterPackTypes.push_back(NewT);
1812 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001813
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001814 IsExpandedParameterPack = true;
1815 DI = D->getTypeSourceInfo();
1816 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001817 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001818 // The non-type template parameter pack's type is a pack expansion of types.
1819 // Determine whether we need to expand this parameter pack into separate
1820 // types.
David Blaikie39e6ab42013-02-18 22:06:02 +00001821 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001822 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001823 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001824 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001825
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001826 // Determine whether the set of unexpanded parameter packs can and should
1827 // be expanded.
1828 bool Expand = true;
1829 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001830 Optional<unsigned> OrigNumExpansions
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001831 = Expansion.getTypePtr()->getNumExpansions();
David Blaikiedc84cd52013-02-20 22:23:23 +00001832 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001833 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1834 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001835 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001836 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001837 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001838 NumExpansions))
1839 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001840
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001841 if (Expand) {
1842 for (unsigned I = 0; I != *NumExpansions; ++I) {
1843 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1844 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001845 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001846 D->getDeclName());
1847 if (!NewDI)
1848 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001849
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001850 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1851 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1852 NewDI->getType(),
1853 D->getLocation());
1854 if (NewT.isNull())
1855 return 0;
1856 ExpandedParameterPackTypes.push_back(NewT);
1857 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001858
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001859 // Note that we have an expanded parameter pack. The "type" of this
1860 // expanded parameter pack is the original expansion type, but callers
1861 // will end up using the expanded parameter pack types for type-checking.
1862 IsExpandedParameterPack = true;
1863 DI = D->getTypeSourceInfo();
1864 T = DI->getType();
1865 } else {
1866 // We cannot fully expand the pack expansion now, so substitute into the
1867 // pattern and create a new pack expansion type.
1868 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1869 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001870 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001871 D->getDeclName());
1872 if (!NewPattern)
1873 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001874
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001875 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1876 NumExpansions);
1877 if (!DI)
1878 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001879
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001880 T = DI->getType();
1881 }
1882 } else {
1883 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001884 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001885 D->getLocation(), D->getDeclName());
1886 if (!DI)
1887 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001888
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001889 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001890 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001891 D->getLocation());
1892 if (T.isNull()) {
1893 T = SemaRef.Context.IntTy;
1894 Invalid = true;
1895 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001896 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001897
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001898 NonTypeTemplateParmDecl *Param;
1899 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001900 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001901 D->getInnerLocStart(),
1902 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001903 D->getDepth() - TemplateArgs.getNumLevels(),
1904 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001905 D->getIdentifier(), T,
1906 DI,
1907 ExpandedParameterPackTypes.data(),
1908 ExpandedParameterPackTypes.size(),
1909 ExpandedParameterPackTypesAsWritten.data());
1910 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001911 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001912 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001913 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001914 D->getDepth() - TemplateArgs.getNumLevels(),
1915 D->getPosition(),
1916 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001917 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001918
Douglas Gregor9a299e02011-03-04 17:52:15 +00001919 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001920 if (Invalid)
1921 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001922
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001923 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001924
1925 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001926 // scope.
1927 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001928 return Param;
1929}
1930
Richard Smith6964b3f2012-09-07 02:06:42 +00001931static void collectUnexpandedParameterPacks(
1932 Sema &S,
1933 TemplateParameterList *Params,
1934 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1935 for (TemplateParameterList::const_iterator I = Params->begin(),
1936 E = Params->end(); I != E; ++I) {
1937 if ((*I)->isTemplateParameterPack())
1938 continue;
1939 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1940 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1941 Unexpanded);
1942 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1943 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1944 Unexpanded);
1945 }
1946}
1947
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001948Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001949TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1950 TemplateTemplateParmDecl *D) {
1951 // Instantiate the template parameter list of the template template parameter.
1952 TemplateParameterList *TempParams = D->getTemplateParameters();
1953 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001954 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1955
1956 bool IsExpandedParameterPack = false;
1957
1958 if (D->isExpandedParameterPack()) {
1959 // The template template parameter pack is an already-expanded pack
1960 // expansion of template parameters. Substitute into each of the expanded
1961 // parameters.
1962 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1963 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1964 I != N; ++I) {
1965 LocalInstantiationScope Scope(SemaRef);
1966 TemplateParameterList *Expansion =
1967 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1968 if (!Expansion)
1969 return 0;
1970 ExpandedParams.push_back(Expansion);
1971 }
1972
1973 IsExpandedParameterPack = true;
1974 InstParams = TempParams;
1975 } else if (D->isPackExpansion()) {
1976 // The template template parameter pack expands to a pack of template
1977 // template parameters. Determine whether we need to expand this parameter
1978 // pack into separate parameters.
1979 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1980 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1981 Unexpanded);
1982
1983 // Determine whether the set of unexpanded parameter packs can and should
1984 // be expanded.
1985 bool Expand = true;
1986 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001987 Optional<unsigned> NumExpansions;
Richard Smith6964b3f2012-09-07 02:06:42 +00001988 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1989 TempParams->getSourceRange(),
1990 Unexpanded,
1991 TemplateArgs,
1992 Expand, RetainExpansion,
1993 NumExpansions))
1994 return 0;
1995
1996 if (Expand) {
1997 for (unsigned I = 0; I != *NumExpansions; ++I) {
1998 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1999 LocalInstantiationScope Scope(SemaRef);
2000 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2001 if (!Expansion)
2002 return 0;
2003 ExpandedParams.push_back(Expansion);
2004 }
2005
2006 // Note that we have an expanded parameter pack. The "type" of this
2007 // expanded parameter pack is the original expansion type, but callers
2008 // will end up using the expanded parameter pack types for type-checking.
2009 IsExpandedParameterPack = true;
2010 InstParams = TempParams;
2011 } else {
2012 // We cannot fully expand the pack expansion now, so just substitute
2013 // into the pattern.
2014 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2015
2016 LocalInstantiationScope Scope(SemaRef);
2017 InstParams = SubstTemplateParams(TempParams);
2018 if (!InstParams)
2019 return 0;
2020 }
2021 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00002022 // Perform the actual substitution of template parameters within a new,
2023 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00002024 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00002025 InstParams = SubstTemplateParams(TempParams);
2026 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00002027 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002028 }
2029
Douglas Gregor9106ef72009-11-11 16:58:32 +00002030 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00002031 TemplateTemplateParmDecl *Param;
2032 if (IsExpandedParameterPack)
2033 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2034 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002035 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00002036 D->getPosition(),
2037 D->getIdentifier(), InstParams,
2038 ExpandedParams);
2039 else
2040 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2041 D->getLocation(),
2042 D->getDepth() - TemplateArgs.getNumLevels(),
2043 D->getPosition(),
2044 D->isParameterPack(),
2045 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00002046 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00002047 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002048
2049 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00002050 // scope.
2051 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002052
Douglas Gregor9106ef72009-11-11 16:58:32 +00002053 return Param;
2054}
2055
Douglas Gregor48c32a72009-11-17 06:07:40 +00002056Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00002057 // Using directives are never dependent (and never contain any types or
2058 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002059
Douglas Gregor48c32a72009-11-17 06:07:40 +00002060 UsingDirectiveDecl *Inst
2061 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002062 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00002063 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002064 D->getIdentLocation(),
2065 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00002066 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00002067
2068 // Add the using directive to its declaration context
2069 // only if this is not a function or method.
2070 if (!Owner->isFunctionOrMethod())
2071 Owner->addDecl(Inst);
2072
Douglas Gregor48c32a72009-11-17 06:07:40 +00002073 return Inst;
2074}
2075
John McCalled976492009-12-04 22:46:56 +00002076Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00002077
2078 // The nested name specifier may be dependent, for example
2079 // template <typename T> struct t {
2080 // struct s1 { T f1(); };
2081 // struct s2 : s1 { using s1::f1; };
2082 // };
2083 // template struct t<int>;
2084 // Here, in using s1::f1, s1 refers to t<T>::s1;
2085 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00002086 NestedNameSpecifierLoc QualifierLoc
2087 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2088 TemplateArgs);
2089 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00002090 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00002091
2092 // The name info is non-dependent, so no transformation
2093 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002094 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00002095
John McCall9f54ad42009-12-10 09:41:52 +00002096 // We only need to do redeclaration lookups if we're in a class
2097 // scope (in fact, it's not really even possible in non-class
2098 // scopes).
2099 bool CheckRedeclaration = Owner->isRecord();
2100
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002101 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2102 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00002103
John McCalled976492009-12-04 22:46:56 +00002104 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00002105 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002106 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002107 NameInfo,
John McCalled976492009-12-04 22:46:56 +00002108 D->isTypeName());
2109
Douglas Gregor5149f372011-02-25 15:54:31 +00002110 CXXScopeSpec SS;
2111 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00002112 if (CheckRedeclaration) {
2113 Prev.setHideTags(false);
2114 SemaRef.LookupQualifiedName(Prev, Owner);
2115
2116 // Check for invalid redeclarations.
2117 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
2118 D->isTypeName(), SS,
2119 D->getLocation(), Prev))
2120 NewUD->setInvalidDecl();
2121
2122 }
2123
2124 if (!NewUD->isInvalidDecl() &&
2125 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00002126 D->getLocation()))
2127 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002128
John McCalled976492009-12-04 22:46:56 +00002129 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2130 NewUD->setAccess(D->getAccess());
2131 Owner->addDecl(NewUD);
2132
John McCall9f54ad42009-12-10 09:41:52 +00002133 // Don't process the shadow decls for an invalid decl.
2134 if (NewUD->isInvalidDecl())
2135 return NewUD;
2136
Richard Smithc5a89a12012-04-02 01:30:27 +00002137 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2138 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2139 NewUD->setInvalidDecl();
2140 return NewUD;
2141 }
2142
John McCall323c3102009-12-22 22:26:37 +00002143 bool isFunctionScope = Owner->isFunctionOrMethod();
2144
John McCall9f54ad42009-12-10 09:41:52 +00002145 // Process the shadow decls.
2146 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2147 I != E; ++I) {
2148 UsingShadowDecl *Shadow = *I;
2149 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002150 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2151 Shadow->getLocation(),
2152 Shadow->getTargetDecl(),
2153 TemplateArgs));
2154 if (!InstTarget)
2155 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002156
2157 if (CheckRedeclaration &&
2158 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2159 continue;
2160
2161 UsingShadowDecl *InstShadow
2162 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2163 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002164
2165 if (isFunctionScope)
2166 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002167 }
John McCalled976492009-12-04 22:46:56 +00002168
2169 return NewUD;
2170}
2171
2172Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002173 // Ignore these; we handle them in bulk when processing the UsingDecl.
2174 return 0;
John McCalled976492009-12-04 22:46:56 +00002175}
2176
John McCall7ba107a2009-11-18 02:36:19 +00002177Decl * TemplateDeclInstantiator
2178 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002179 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002180 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002181 TemplateArgs);
2182 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002183 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002185 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002186 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002188 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002189 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002190 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002191 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002192 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002193 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002194 /*instantiation*/ true,
2195 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002196 if (UD)
John McCalled976492009-12-04 22:46:56 +00002197 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2198
John McCall7ba107a2009-11-18 02:36:19 +00002199 return UD;
2200}
2201
2202Decl * TemplateDeclInstantiator
2203 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002204 NestedNameSpecifierLoc QualifierLoc
2205 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2206 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002207 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002208
John McCall7ba107a2009-11-18 02:36:19 +00002209 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002210 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002211
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002212 DeclarationNameInfo NameInfo
2213 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2214
John McCall7ba107a2009-11-18 02:36:19 +00002215 NamedDecl *UD =
2216 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002217 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002218 /*instantiation*/ true,
2219 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002220 if (UD)
John McCalled976492009-12-04 22:46:56 +00002221 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2222
Anders Carlsson0d8df782009-08-29 19:37:28 +00002223 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002224}
2225
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002226
2227Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2228 ClassScopeFunctionSpecializationDecl *Decl) {
2229 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002230 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2231 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002232
2233 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2234 Sema::ForRedeclaration);
2235
Nico Weber6b020092012-06-25 17:21:05 +00002236 TemplateArgumentListInfo TemplateArgs;
2237 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2238 if (Decl->hasExplicitTemplateArgs()) {
2239 TemplateArgs = Decl->templateArgs();
2240 TemplateArgsPtr = &TemplateArgs;
2241 }
2242
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002243 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002244 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2245 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002246 NewFD->setInvalidDecl();
2247 return NewFD;
2248 }
2249
2250 // Associate the specialization with the pattern.
2251 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2252 assert(Specialization && "Class scope Specialization is null");
2253 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2254
2255 return NewFD;
2256}
2257
Alexey Bataevc6400582013-03-22 06:34:35 +00002258Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2259 OMPThreadPrivateDecl *D) {
Alexey Bataev6af701f2013-05-13 04:18:18 +00002260 SmallVector<Expr *, 5> Vars;
2261 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2262 E = D->varlist_end();
Alexey Bataevc6400582013-03-22 06:34:35 +00002263 I != E; ++I) {
2264 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2265 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6af701f2013-05-13 04:18:18 +00002266 Vars.push_back(Var);
Alexey Bataevc6400582013-03-22 06:34:35 +00002267 }
2268
2269 OMPThreadPrivateDecl *TD =
2270 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2271
2272 return TD;
2273}
2274
Eli Friedmanded99792013-06-27 23:21:55 +00002275Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2276 return VisitFunctionDecl(D, 0);
2277}
2278
2279Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2280 return VisitCXXMethodDecl(D, 0);
2281}
2282
2283Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2284 llvm_unreachable("There are only CXXRecordDecls in C++");
2285}
2286
2287Decl *
2288TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2289 ClassTemplateSpecializationDecl *D) {
2290 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2291 "inside templates");
2292}
2293
2294Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2295 llvm_unreachable("@defs is not supported in Objective-C++");
2296}
2297
2298Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2299 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2300 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2301 DiagnosticsEngine::Error,
2302 "cannot instantiate %0 yet");
2303 SemaRef.Diag(D->getLocation(), DiagID)
2304 << D->getDeclKindName();
2305
2306 return 0;
2307}
2308
2309Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2310 llvm_unreachable("Unexpected decl");
2311}
2312
John McCallce3ff2b2009-08-25 22:02:44 +00002313Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002314 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002315 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002316 if (D->isInvalidDecl())
2317 return 0;
2318
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002319 return Instantiator.Visit(D);
2320}
2321
John McCalle29ba202009-08-20 01:44:21 +00002322/// \brief Instantiates a nested template parameter list in the current
2323/// instantiation context.
2324///
2325/// \param L The parameter list to instantiate
2326///
2327/// \returns NULL if there was an error
2328TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002329TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002330 // Get errors for all the parameters before bailing out.
2331 bool Invalid = false;
2332
2333 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002334 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002335 ParamVector Params;
2336 Params.reserve(N);
2337 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2338 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002339 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002340 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002341 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002342 }
2343
2344 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002345 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002346 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002347
2348 TemplateParameterList *InstL
2349 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2350 L->getLAngleLoc(), &Params.front(), N,
2351 L->getRAngleLoc());
2352 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002353}
John McCalle29ba202009-08-20 01:44:21 +00002354
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002355/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002356/// specialization.
2357///
2358/// \param ClassTemplate the (instantiated) class template that is partially
2359// specialized by the instantiation of \p PartialSpec.
2360///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002361/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002362/// specialization that we are instantiating.
2363///
Douglas Gregord65587f2010-11-10 19:44:59 +00002364/// \returns The instantiated partial specialization, if successful; otherwise,
2365/// NULL to indicate an error.
2366ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002367TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2368 ClassTemplateDecl *ClassTemplate,
2369 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002370 // Create a local instantiation scope for this class template partial
2371 // specialization, which will contain the instantiations of the template
2372 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002373 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002374
Douglas Gregored9c0f92009-10-29 00:04:11 +00002375 // Substitute into the template parameters of the class template partial
2376 // specialization.
2377 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2378 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2379 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002380 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002381
Douglas Gregored9c0f92009-10-29 00:04:11 +00002382 // Substitute into the template arguments of the class template partial
2383 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00002384 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002385 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2386 PartialSpec->getNumTemplateArgsAsWritten(),
Douglas Gregore02e2622010-12-22 21:19:48 +00002387 InstTemplateArgs, TemplateArgs))
2388 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002389
Douglas Gregored9c0f92009-10-29 00:04:11 +00002390 // Check that the template argument list is well-formed for this
2391 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002392 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002393 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002394 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002395 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002396 false,
2397 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002398 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002399
2400 // Figure out where to insert this class template partial specialization
2401 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002402 void *InsertPos = 0;
2403 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002404 = ClassTemplate->findPartialSpecialization(Converted.data(),
2405 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002406
Douglas Gregored9c0f92009-10-29 00:04:11 +00002407 // Build the canonical type that describes the converted template
2408 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002409 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002410 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002411 Converted.data(),
2412 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002413
2414 // Build the fully-sugared type for this class template
2415 // specialization as the user wrote in the specialization
2416 // itself. This means that we'll pretty-print the type retrieved
2417 // from the specialization's declaration the way that the user
2418 // actually wrote the specialization, rather than formatting the
2419 // name based on the "canonical" representation used to store the
2420 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002421 TypeSourceInfo *WrittenTy
2422 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2423 TemplateName(ClassTemplate),
2424 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002425 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002426 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002427
Douglas Gregored9c0f92009-10-29 00:04:11 +00002428 if (PrevDecl) {
2429 // We've already seen a partial specialization with the same template
2430 // parameters and template arguments. This can happen, for example, when
2431 // substituting the outer template arguments ends up causing two
2432 // class template partial specializations of a member class template
2433 // to have identical forms, e.g.,
2434 //
2435 // template<typename T, typename U>
2436 // struct Outer {
2437 // template<typename X, typename Y> struct Inner;
2438 // template<typename Y> struct Inner<T, Y>;
2439 // template<typename Y> struct Inner<U, Y>;
2440 // };
2441 //
2442 // Outer<int, int> outer; // error: the partial specializations of Inner
2443 // // have the same signature.
2444 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002445 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002446 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2447 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002448 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002449 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002450
2451
Douglas Gregored9c0f92009-10-29 00:04:11 +00002452 // Create the class template partial specialization declaration.
2453 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002454 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002455 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002456 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002457 PartialSpec->getLocStart(),
2458 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002459 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002460 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002461 Converted.data(),
2462 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002463 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002464 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002465 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002466 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002467 // Substitute the nested name specifier, if any.
2468 if (SubstQualifier(PartialSpec, InstPartialSpec))
2469 return 0;
2470
Douglas Gregored9c0f92009-10-29 00:04:11 +00002471 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002472 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002473
Douglas Gregored9c0f92009-10-29 00:04:11 +00002474 // Add this partial specialization to the set of class template partial
2475 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002476 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002477 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002478}
2479
John McCall21ef0fa2010-03-11 09:03:00 +00002480TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002481TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002482 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002483 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2484 assert(OldTInfo && "substituting function without type source info");
2485 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002486
2487 CXXRecordDecl *ThisContext = 0;
2488 unsigned ThisTypeQuals = 0;
2489 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithcafeb942013-06-07 02:33:37 +00002490 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002491 ThisTypeQuals = Method->getTypeQualifiers();
2492 }
2493
John McCall6cd3b9f2010-04-09 17:38:44 +00002494 TypeSourceInfo *NewTInfo
2495 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2496 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002497 D->getDeclName(),
2498 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002499 if (!NewTInfo)
2500 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002501
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002502 if (NewTInfo != OldTInfo) {
2503 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002504 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002505 if (FunctionProtoTypeLoc OldProtoLoc =
2506 OldTL.getAs<FunctionProtoTypeLoc>()) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002507 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002508 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith500d7292012-07-18 01:29:05 +00002509 unsigned NewIdx = 0;
David Blaikie39e6ab42013-02-18 22:06:02 +00002510 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregor12c9c002011-01-07 16:43:16 +00002511 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002512 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002513 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2514
David Blaikiedc84cd52013-02-20 22:23:23 +00002515 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith500d7292012-07-18 01:29:05 +00002516 if (OldParam->isParameterPack())
2517 NumArgumentsInExpansion =
2518 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2519 TemplateArgs);
2520 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002521 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002522 // instantiated to a (still-dependent) parameter pack.
David Blaikie39e6ab42013-02-18 22:06:02 +00002523 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002524 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002525 Scope->InstantiatedLocal(OldParam, NewParam);
2526 } else {
2527 // Parameter pack expansion: make the instantiation an argument pack.
2528 Scope->MakeInstantiatedLocalArgPack(OldParam);
2529 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie39e6ab42013-02-18 22:06:02 +00002530 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith500d7292012-07-18 01:29:05 +00002531 Params.push_back(NewParam);
2532 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2533 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002534 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002535 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002536 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002537 } else {
2538 // The function type itself was not dependent and therefore no
2539 // substitution occurred. However, we still need to instantiate
2540 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002541 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00002542 if (FunctionProtoTypeLoc OldProtoLoc =
2543 OldTL.getAs<FunctionProtoTypeLoc>()) {
2544 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
Eli Friedmanded99792013-06-27 23:21:55 +00002545 ParmVarDecl *Parm =
2546 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldProtoLoc.getArg(i)));
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002547 if (!Parm)
2548 return 0;
2549 Params.push_back(Parm);
2550 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002551 }
2552 }
John McCall21ef0fa2010-03-11 09:03:00 +00002553 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002554}
2555
Richard Smithe6975e92012-04-17 00:58:00 +00002556/// Introduce the instantiated function parameters into the local
2557/// instantiation scope, and set the parameter names to those used
2558/// in the template.
2559static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2560 const FunctionDecl *PatternDecl,
2561 LocalInstantiationScope &Scope,
2562 const MultiLevelTemplateArgumentList &TemplateArgs) {
2563 unsigned FParamIdx = 0;
2564 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2565 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2566 if (!PatternParam->isParameterPack()) {
2567 // Simple case: not a parameter pack.
2568 assert(FParamIdx < Function->getNumParams());
2569 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2570 FunctionParam->setDeclName(PatternParam->getDeclName());
2571 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2572 ++FParamIdx;
2573 continue;
2574 }
2575
2576 // Expand the parameter pack.
2577 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikiedc84cd52013-02-20 22:23:23 +00002578 Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002579 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002580 assert(NumArgumentsInExpansion &&
2581 "should only be called when all template arguments are known");
2582 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002583 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2584 FunctionParam->setDeclName(PatternParam->getDeclName());
2585 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2586 ++FParamIdx;
2587 }
2588 }
2589}
2590
2591static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2592 const FunctionProtoType *Proto,
2593 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002594 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2595
Richard Smithe6975e92012-04-17 00:58:00 +00002596 // C++11 [expr.prim.general]p3:
2597 // If a declaration declares a member function or member function
2598 // template of a class X, the expression this is a prvalue of type
2599 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2600 // and the end of the function-definition, member-declarator, or
2601 // declarator.
2602 CXXRecordDecl *ThisContext = 0;
2603 unsigned ThisTypeQuals = 0;
2604 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2605 ThisContext = Method->getParent();
2606 ThisTypeQuals = Method->getTypeQualifiers();
2607 }
2608 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith80ad52f2013-01-02 11:42:31 +00002609 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithe6975e92012-04-17 00:58:00 +00002610
2611 // The function has an exception specification or a "noreturn"
2612 // attribute. Substitute into each of the exception types.
2613 SmallVector<QualType, 4> Exceptions;
2614 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2615 // FIXME: Poor location information!
2616 if (const PackExpansionType *PackExpansion
2617 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2618 // We have a pack expansion. Instantiate it.
2619 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2620 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2621 Unexpanded);
2622 assert(!Unexpanded.empty() &&
2623 "Pack expansion without parameter packs?");
2624
2625 bool Expand = false;
2626 bool RetainExpansion = false;
Richard Smithcafeb942013-06-07 02:33:37 +00002627 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithe6975e92012-04-17 00:58:00 +00002628 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2629 SourceRange(),
2630 Unexpanded,
2631 TemplateArgs,
2632 Expand,
2633 RetainExpansion,
2634 NumExpansions))
2635 break;
2636
2637 if (!Expand) {
2638 // We can't expand this pack expansion into separate arguments yet;
2639 // just substitute into the pattern and create a new pack expansion
2640 // type.
2641 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2642 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2643 TemplateArgs,
2644 New->getLocation(), New->getDeclName());
2645 if (T.isNull())
2646 break;
2647
2648 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2649 Exceptions.push_back(T);
2650 continue;
2651 }
2652
2653 // Substitute into the pack expansion pattern for each template
2654 bool Invalid = false;
2655 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2656 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2657
2658 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2659 TemplateArgs,
2660 New->getLocation(), New->getDeclName());
2661 if (T.isNull()) {
2662 Invalid = true;
2663 break;
2664 }
2665
2666 Exceptions.push_back(T);
2667 }
2668
2669 if (Invalid)
2670 break;
2671
2672 continue;
2673 }
2674
2675 QualType T
2676 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2677 New->getLocation(), New->getDeclName());
2678 if (T.isNull() ||
2679 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2680 continue;
2681
2682 Exceptions.push_back(T);
2683 }
2684 Expr *NoexceptExpr = 0;
2685 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2686 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2687 Sema::ConstantEvaluated);
2688 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2689 if (E.isUsable())
2690 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2691
2692 if (E.isUsable()) {
2693 NoexceptExpr = E.take();
2694 if (!NoexceptExpr->isTypeDependent() &&
2695 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002696 NoexceptExpr
2697 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2698 0, diag::err_noexcept_needs_constant_expression,
2699 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002700 }
2701 }
2702
2703 // Rebuild the function type
2704 const FunctionProtoType *NewProto
2705 = New->getType()->getAs<FunctionProtoType>();
2706 assert(NewProto && "Template instantiation without function prototype?");
2707
2708 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2709 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2710 EPI.NumExceptions = Exceptions.size();
2711 EPI.Exceptions = Exceptions.data();
2712 EPI.NoexceptExpr = NoexceptExpr;
2713
2714 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002715 NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002716}
2717
2718void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2719 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002720 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2721 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002722 return;
2723
2724 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2725 InstantiatingTemplate::ExceptionSpecification());
Richard Smithb9d0b762012-07-27 04:22:15 +00002726 if (Inst) {
2727 // We hit the instantiation depth limit. Clear the exception specification
2728 // so that our callers don't have to cope with EST_Uninstantiated.
2729 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2730 EPI.ExceptionSpecType = EST_None;
2731 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Reid Kleckner0567a792013-06-10 20:51:09 +00002732 Proto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002733 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002734 }
Richard Smithe6975e92012-04-17 00:58:00 +00002735
2736 // Enter the scope of this instantiation. We don't use
2737 // PushDeclContext because we don't have a scope.
2738 Sema::ContextRAII savedContext(*this, Decl);
2739 LocalInstantiationScope Scope(*this);
2740
2741 MultiLevelTemplateArgumentList TemplateArgs =
2742 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2743
Richard Smith13bffc52012-04-19 00:08:28 +00002744 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2745 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002746
Richard Smith13bffc52012-04-19 00:08:28 +00002747 ::InstantiateExceptionSpec(*this, Decl,
2748 Template->getType()->castAs<FunctionProtoType>(),
2749 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002750}
2751
Mike Stump1eb44332009-09-09 15:08:12 +00002752/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002753/// declaration (New) from the corresponding fields of its template (Tmpl).
2754///
2755/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002756bool
2757TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002758 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00002759 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00002760 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Douglas Gregorcca9e962009-07-01 22:01:06 +00002762 // If we are performing substituting explicitly-specified template arguments
2763 // or deduced template arguments into a function template and we reach this
2764 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002765 // to keeping the new function template specialization. We therefore
2766 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002767 // into a template instantiation for this specific function template
2768 // specialization, which is not a SFINAE context, so that we diagnose any
2769 // further errors in the declaration itself.
2770 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2771 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2772 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2773 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002774 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002775 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002776 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002777 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002778 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002779 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002780 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002781 }
2782 }
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002784 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2785 assert(Proto && "Function template without prototype?");
2786
Sebastian Redl60618fa2011-03-12 11:50:43 +00002787 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00002788 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00002789
Richard Smithe6975e92012-04-17 00:58:00 +00002790 // DR1330: In C++11, defer instantiation of a non-trivial
2791 // exception specification.
Richard Smith80ad52f2013-01-02 11:42:31 +00002792 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithe6975e92012-04-17 00:58:00 +00002793 EPI.ExceptionSpecType != EST_None &&
2794 EPI.ExceptionSpecType != EST_DynamicNone &&
2795 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00002796 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2797 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2798 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith4841ca52013-04-10 05:48:59 +00002799 ExceptionSpecificationType NewEST = EST_Uninstantiated;
2800 if (EPI.ExceptionSpecType == EST_Unevaluated)
2801 NewEST = EST_Unevaluated;
Richard Smith13bffc52012-04-19 00:08:28 +00002802
Richard Smithe6975e92012-04-17 00:58:00 +00002803 // Mark the function has having an uninstantiated exception specification.
2804 const FunctionProtoType *NewProto
2805 = New->getType()->getAs<FunctionProtoType>();
2806 assert(NewProto && "Template instantiation without function prototype?");
2807 EPI = NewProto->getExtProtoInfo();
Richard Smith4841ca52013-04-10 05:48:59 +00002808 EPI.ExceptionSpecType = NewEST;
Richard Smithe6975e92012-04-17 00:58:00 +00002809 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00002810 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner0567a792013-06-10 20:51:09 +00002811 New->setType(SemaRef.Context.getFunctionType(
2812 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002813 } else {
2814 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2815 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002816 }
2817
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002818 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00002819 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002820 Tmpl->isDefined(Definition);
2821
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002822 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2823 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002824
Douglas Gregore53060f2009-06-25 22:08:12 +00002825 return false;
2826}
2827
Douglas Gregor5545e162009-03-24 00:38:23 +00002828/// \brief Initializes common fields of an instantiated method
2829/// declaration (New) from the corresponding fields of its template
2830/// (Tmpl).
2831///
2832/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002833bool
2834TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002835 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002836 if (InitFunctionInstantiation(New, Tmpl))
2837 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002838
Douglas Gregor5545e162009-03-24 00:38:23 +00002839 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002840 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002841 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002842
Douglas Gregor5545e162009-03-24 00:38:23 +00002843 // FIXME: New needs a pointer to Tmpl
2844 return false;
2845}
Douglas Gregora58861f2009-05-13 20:28:22 +00002846
2847/// \brief Instantiate the definition of the given function from its
2848/// template.
2849///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002850/// \param PointOfInstantiation the point at which the instantiation was
2851/// required. Note that this is not precisely a "point of instantiation"
2852/// for the function, but it's close.
2853///
Douglas Gregora58861f2009-05-13 20:28:22 +00002854/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002855/// function template specialization or member function of a class template
2856/// specialization.
2857///
2858/// \param Recursive if true, recursively instantiates any functions that
2859/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002860///
2861/// \param DefinitionRequired if true, then we are performing an explicit
2862/// instantiation where the body of the function is required. Complain if
2863/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002864void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002865 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002866 bool Recursive,
2867 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002868 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002869 return;
2870
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002871 // Never instantiate an explicit specialization except if it is a class scope
2872 // explicit specialization.
2873 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2874 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002875 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002876
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002877 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002878 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00002879 assert(PatternDecl && "instantiating a non-template");
2880
2881 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2882 assert(PatternDecl && "template definition is not a template");
2883 if (!Pattern) {
2884 // Try to find a defaulted definition
2885 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00002886 }
Sean Huntf996e052011-05-27 20:00:14 +00002887 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002888
Francois Pichet8387e2a2011-04-22 22:18:13 +00002889 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00002890 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00002891 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00002892 PendingInstantiations.push_back(
2893 std::make_pair(Function, PointOfInstantiation));
2894 return;
2895 }
2896
2897 // Call the LateTemplateParser callback if there a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002898 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00002899 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00002900 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002901 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002902 Pattern = PatternDecl->getBody(PatternDecl);
2903 }
2904
Sean Huntf996e052011-05-27 20:00:14 +00002905 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002906 if (DefinitionRequired) {
2907 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002908 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002909 diag::err_explicit_instantiation_undefined_func_template)
2910 << Function->getPrimaryTemplate();
2911 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002912 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002913 diag::err_explicit_instantiation_undefined_member)
2914 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002915
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002916 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002917 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002918 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002919 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002920 } else if (Function->getTemplateSpecializationKind()
2921 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002922 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002923 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002924 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002925
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002926 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002927 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002928
Richard Smith60e141e2013-05-04 07:00:32 +00002929 // C++1y [temp.explicit]p10:
2930 // Except for inline functions, declarations with types deduced from their
2931 // initializer or return value, and class template specializations, other
2932 // explicit instantiation declarations have the effect of suppressing the
2933 // implicit instantiation of the entity to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002934 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002935 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith60e141e2013-05-04 07:00:32 +00002936 !PatternDecl->isInlined() &&
2937 !PatternDecl->getResultType()->isUndeducedType())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002938 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002939
Richard Smithd4497dd2013-01-25 00:08:28 +00002940 if (PatternDecl->isInlined())
2941 Function->setImplicitlyInline();
2942
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002943 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2944 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002945 return;
2946
Abramo Bagnarae9946242011-11-18 08:08:52 +00002947 // Copy the inner loc start from the pattern.
2948 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2949
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002950 // If we're performing recursive template instantiation, create our own
2951 // queue of pending implicit instantiations that we will instantiate later,
2952 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002953 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002954 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Faisal Vali86648b12013-06-26 02:34:24 +00002955 std::deque<PendingImplicitInstantiation>
2956 SavedPendingLocalImplicitInstantiations;
2957 SavedPendingLocalImplicitInstantiations.swap(
2958 PendingLocalImplicitInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002959 if (Recursive) {
2960 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002961 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002962 }
Mike Stump1eb44332009-09-09 15:08:12 +00002963
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002964 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002965 Sema::PotentiallyEvaluated);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002966
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002967 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002968 // recorded, unless we're actually a member function within a local
2969 // class, in which case we need to merge our results with the parent
2970 // scope (of the enclosing function).
2971 bool MergeWithParentScope = false;
2972 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2973 MergeWithParentScope = Rec->isLocalClass();
2974
2975 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Richard Smith1d28caf2012-12-11 01:14:52 +00002977 if (PatternDecl->isDefaulted())
Sean Huntcd10dec2011-05-23 23:14:04 +00002978 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smith1d28caf2012-12-11 01:14:52 +00002979 else {
2980 ActOnStartOfFunctionDef(0, Function);
2981
2982 // Enter the scope of this instantiation. We don't use
2983 // PushDeclContext because we don't have a scope.
2984 Sema::ContextRAII savedContext(*this, Function);
2985
2986 MultiLevelTemplateArgumentList TemplateArgs =
2987 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2988
2989 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2990 TemplateArgs);
2991
Sean Huntcd10dec2011-05-23 23:14:04 +00002992 // If this is a constructor, instantiate the member initializers.
2993 if (const CXXConstructorDecl *Ctor =
2994 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2995 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2996 TemplateArgs);
2997 }
2998
2999 // Instantiate the function body.
3000 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3001
3002 if (Body.isInvalid())
3003 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003004
Sean Huntcd10dec2011-05-23 23:14:04 +00003005 ActOnFinishFunctionBody(Function, Body.get(),
3006 /*IsInstantiation=*/true);
Richard Smith1d28caf2012-12-11 01:14:52 +00003007
3008 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3009
3010 savedContext.pop();
Mike Stump1eb44332009-09-09 15:08:12 +00003011 }
3012
Douglas Gregoraba43bb2009-05-26 20:50:29 +00003013 DeclGroupRef DG(Function);
3014 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00003015
Douglas Gregor60406be2010-01-16 22:29:39 +00003016 // This class may have local implicit instantiations that need to be
3017 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003018 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00003019 Scope.Exit();
3020
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003021 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003022 // Define any pending vtables.
3023 DefineUsedVTables();
3024
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003025 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003026 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003027 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003029 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00003030 assert(VTableUses.empty() &&
3031 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00003032 VTableUses.swap(SavedVTableUses);
3033
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003034 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003035 assert(PendingInstantiations.empty() &&
3036 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003037 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00003038 }
Faisal Vali86648b12013-06-26 02:34:24 +00003039 SavedPendingLocalImplicitInstantiations.swap(
3040 PendingLocalImplicitInstantiations);
Douglas Gregora58861f2009-05-13 20:28:22 +00003041}
3042
3043/// \brief Instantiate the definition of the given variable from its
3044/// template.
3045///
Douglas Gregor7caa6822009-07-24 20:34:43 +00003046/// \param PointOfInstantiation the point at which the instantiation was
3047/// required. Note that this is not precisely a "point of instantiation"
3048/// for the function, but it's close.
3049///
3050/// \param Var the already-instantiated declaration of a static member
3051/// variable of a class template specialization.
3052///
3053/// \param Recursive if true, recursively instantiates any functions that
3054/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003055///
3056/// \param DefinitionRequired if true, then we are performing an explicit
3057/// instantiation where an out-of-line definition of the member variable
3058/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00003059void Sema::InstantiateStaticDataMemberDefinition(
3060 SourceLocation PointOfInstantiation,
3061 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003062 bool Recursive,
3063 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00003064 if (Var->isInvalidDecl())
3065 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003066
Douglas Gregor7caa6822009-07-24 20:34:43 +00003067 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00003068 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003069 assert(Def && "This data member was not instantiated from a template?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003070 assert(Def->isStaticDataMember() && "Not a static data member?");
Douglas Gregor0d035142009-10-27 18:42:08 +00003071 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00003072
Douglas Gregor0d035142009-10-27 18:42:08 +00003073 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00003074 // We did not find an out-of-line definition of this static data member,
3075 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00003076 // instantiate this definition (or provide a specialization for it) in
3077 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003078 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00003079 Def = Var->getInstantiatedFromStaticDataMember();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003080 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00003081 diag::err_explicit_instantiation_undefined_member)
3082 << 2 << Var->getDeclName() << Var->getDeclContext();
3083 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00003084 } else if (Var->getTemplateSpecializationKind()
3085 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003086 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00003087 std::make_pair(Var, PointOfInstantiation));
3088 }
3089
Douglas Gregor7caa6822009-07-24 20:34:43 +00003090 return;
3091 }
3092
Rafael Espindola234fe652012-03-05 10:54:55 +00003093 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3094
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003095 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00003096 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003097 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003098
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003099 // C++0x [temp.explicit]p9:
3100 // Except for inline functions, other explicit instantiation declarations
3101 // have the effect of suppressing the implicit instantiation of the entity
3102 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00003103 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00003104 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003106 // Make sure to pass the instantiated variable to the consumer at the end.
3107 struct PassToConsumerRAII {
3108 ASTConsumer &Consumer;
3109 VarDecl *Var;
3110
3111 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3112 : Consumer(Consumer), Var(Var) { }
3113
3114 ~PassToConsumerRAII() {
3115 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3116 }
3117 } PassToConsumerRAII(Consumer, Var);
Rafael Espindola02503932012-03-08 15:51:03 +00003118
Douglas Gregorf15748a2011-06-03 03:35:07 +00003119 // If we already have a definition, we're done.
Nick Lewycky95e38722012-04-04 02:38:36 +00003120 if (VarDecl *Def = Var->getDefinition()) {
3121 // We may be explicitly instantiating something we've already implicitly
3122 // instantiated.
3123 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3124 PointOfInstantiation);
Douglas Gregorf15748a2011-06-03 03:35:07 +00003125 return;
Nick Lewycky95e38722012-04-04 02:38:36 +00003126 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00003127
Douglas Gregor7caa6822009-07-24 20:34:43 +00003128 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3129 if (Inst)
3130 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Douglas Gregor7caa6822009-07-24 20:34:43 +00003132 // If we're performing recursive template instantiation, create our own
3133 // queue of pending implicit instantiations that we will instantiate later,
3134 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003135 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00003136 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00003137 if (Recursive) {
3138 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00003139 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00003140 }
Mike Stump1eb44332009-09-09 15:08:12 +00003141
Douglas Gregor7caa6822009-07-24 20:34:43 +00003142 // Enter the scope of this instantiation. We don't use
3143 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00003144 ContextRAII previousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003145 LocalInstantiationScope Local(*this);
3146
Douglas Gregor1028c9f2009-10-14 21:29:40 +00003147 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00003148 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00003149 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00003150
3151 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00003152
3153 if (Var) {
Argyrios Kyrtzidisafda9052013-02-24 00:05:01 +00003154 PassToConsumerRAII.Var = Var;
Douglas Gregor583f33b2009-10-15 18:07:02 +00003155 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
3156 assert(MSInfo && "Missing member specialization information?");
3157 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
3158 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00003159 }
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003160 Local.Exit();
3161
Douglas Gregor7caa6822009-07-24 20:34:43 +00003162 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00003163 // Define any newly required vtables.
3164 DefineUsedVTables();
3165
Douglas Gregor7caa6822009-07-24 20:34:43 +00003166 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00003167 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003168 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Nick Lewycky81559102011-05-31 07:58:42 +00003170 // Restore the set of pending vtables.
3171 assert(VTableUses.empty() &&
3172 "VTableUses should be empty before it is discarded, "
3173 "while instantiating static data member.");
3174 VTableUses.swap(SavedVTableUses);
3175
Douglas Gregor7caa6822009-07-24 20:34:43 +00003176 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00003177 assert(PendingInstantiations.empty() &&
3178 "PendingInstantiations should be empty before it is discarded, "
3179 "while instantiating static data member.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00003180 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00003181 }
Douglas Gregora58861f2009-05-13 20:28:22 +00003182}
Douglas Gregor815215d2009-05-27 05:35:12 +00003183
Anders Carlsson09025312009-08-29 05:16:22 +00003184void
3185Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3186 const CXXConstructorDecl *Tmpl,
3187 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Richard Trieu90ab75b2011-09-09 03:18:59 +00003189 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003190 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003191
Anders Carlsson09025312009-08-29 05:16:22 +00003192 // Instantiate all the initializers.
3193 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003194 InitsEnd = Tmpl->init_end();
3195 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003196 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003197
Chandler Carruth030ef472010-09-03 21:54:20 +00003198 // Only instantiate written initializers, let Sema re-construct implicit
3199 // ones.
3200 if (!Init->isWritten())
3201 continue;
3202
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003203 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003204
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003205 if (Init->isPackExpansion()) {
3206 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003207 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky98a75582013-06-13 00:45:47 +00003208 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003209 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky98a75582013-06-13 00:45:47 +00003210 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003211 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003212 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00003213 Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003214 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003215 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003216 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003217 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003218 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003219 NumExpansions)) {
3220 AnyErrors = true;
3221 New->setInvalidDecl();
3222 continue;
3223 }
3224 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003225
3226 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003227 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003228 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3229
3230 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003231 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3232 /*CXXDirectInit=*/true);
3233 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003234 AnyErrors = true;
3235 break;
3236 }
3237
3238 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003239 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003240 TemplateArgs,
3241 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003242 New->getDeclName());
3243 if (!BaseTInfo) {
3244 AnyErrors = true;
3245 break;
3246 }
3247
3248 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003249 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003250 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003251 New->getParent(),
3252 SourceLocation());
3253 if (NewInit.isInvalid()) {
3254 AnyErrors = true;
3255 break;
3256 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003257
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003258 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003259 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003260
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003261 continue;
3262 }
3263
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003264 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003265 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3266 /*CXXDirectInit=*/true);
3267 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003268 AnyErrors = true;
3269 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003270 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003271
Anders Carlsson09025312009-08-29 05:16:22 +00003272 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003273 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3274 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3275 TemplateArgs,
3276 Init->getSourceLocation(),
3277 New->getDeclName());
3278 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003279 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003280 New->setInvalidDecl();
3281 continue;
3282 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003283
Douglas Gregor76852c22011-11-01 01:16:03 +00003284 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003285 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003286 New->getParent(), EllipsisLoc);
3287 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003288 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003289 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003290 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003291 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003292 Init->getMemberLocation(),
3293 Init->getMember(),
3294 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003295 if (!Member) {
3296 AnyErrors = true;
3297 New->setInvalidDecl();
3298 continue;
3299 }
Mike Stump1eb44332009-09-09 15:08:12 +00003300
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003301 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003302 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003303 } else if (Init->isIndirectMemberInitializer()) {
3304 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003305 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003306 Init->getMemberLocation(),
3307 Init->getIndirectMember(), TemplateArgs));
3308
Douglas Gregorb7107222011-03-04 19:46:35 +00003309 if (!IndirectMember) {
3310 AnyErrors = true;
3311 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003312 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003313 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003314
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003315 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003316 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003317 }
3318
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003319 if (NewInit.isInvalid()) {
3320 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003321 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003322 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003323 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003324 }
3325 }
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Anders Carlsson09025312009-08-29 05:16:22 +00003327 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003328 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003329 /*FIXME: ColonLoc */
3330 SourceLocation(),
David Blaikie93c86172013-01-17 05:26:25 +00003331 NewInits,
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003332 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003333}
3334
John McCall52a575a2009-08-29 08:11:13 +00003335// TODO: this could be templated if the various decl types used the
3336// same method name.
3337static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3338 ClassTemplateDecl *Instance) {
3339 Pattern = Pattern->getCanonicalDecl();
3340
3341 do {
3342 Instance = Instance->getCanonicalDecl();
3343 if (Pattern == Instance) return true;
3344 Instance = Instance->getInstantiatedFromMemberTemplate();
3345 } while (Instance);
3346
3347 return false;
3348}
3349
Douglas Gregor0d696532009-09-28 06:34:35 +00003350static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3351 FunctionTemplateDecl *Instance) {
3352 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003353
Douglas Gregor0d696532009-09-28 06:34:35 +00003354 do {
3355 Instance = Instance->getCanonicalDecl();
3356 if (Pattern == Instance) return true;
3357 Instance = Instance->getInstantiatedFromMemberTemplate();
3358 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003359
Douglas Gregor0d696532009-09-28 06:34:35 +00003360 return false;
3361}
3362
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003363static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003364isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3365 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003366 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003367 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3368 do {
3369 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3370 Instance->getCanonicalDecl());
3371 if (Pattern == Instance)
3372 return true;
3373 Instance = Instance->getInstantiatedFromMember();
3374 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003375
Douglas Gregored9c0f92009-10-29 00:04:11 +00003376 return false;
3377}
3378
John McCall52a575a2009-08-29 08:11:13 +00003379static bool isInstantiationOf(CXXRecordDecl *Pattern,
3380 CXXRecordDecl *Instance) {
3381 Pattern = Pattern->getCanonicalDecl();
3382
3383 do {
3384 Instance = Instance->getCanonicalDecl();
3385 if (Pattern == Instance) return true;
3386 Instance = Instance->getInstantiatedFromMemberClass();
3387 } while (Instance);
3388
3389 return false;
3390}
3391
3392static bool isInstantiationOf(FunctionDecl *Pattern,
3393 FunctionDecl *Instance) {
3394 Pattern = Pattern->getCanonicalDecl();
3395
3396 do {
3397 Instance = Instance->getCanonicalDecl();
3398 if (Pattern == Instance) return true;
3399 Instance = Instance->getInstantiatedFromMemberFunction();
3400 } while (Instance);
3401
3402 return false;
3403}
3404
3405static bool isInstantiationOf(EnumDecl *Pattern,
3406 EnumDecl *Instance) {
3407 Pattern = Pattern->getCanonicalDecl();
3408
3409 do {
3410 Instance = Instance->getCanonicalDecl();
3411 if (Pattern == Instance) return true;
3412 Instance = Instance->getInstantiatedFromMemberEnum();
3413 } while (Instance);
3414
3415 return false;
3416}
3417
John McCalled976492009-12-04 22:46:56 +00003418static bool isInstantiationOf(UsingShadowDecl *Pattern,
3419 UsingShadowDecl *Instance,
3420 ASTContext &C) {
3421 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3422}
3423
3424static bool isInstantiationOf(UsingDecl *Pattern,
3425 UsingDecl *Instance,
3426 ASTContext &C) {
3427 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3428}
3429
John McCall7ba107a2009-11-18 02:36:19 +00003430static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3431 UsingDecl *Instance,
3432 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003433 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003434}
3435
3436static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003437 UsingDecl *Instance,
3438 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003439 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003440}
3441
John McCall52a575a2009-08-29 08:11:13 +00003442static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3443 VarDecl *Instance) {
3444 assert(Instance->isStaticDataMember());
3445
3446 Pattern = Pattern->getCanonicalDecl();
3447
3448 do {
3449 Instance = Instance->getCanonicalDecl();
3450 if (Pattern == Instance) return true;
3451 Instance = Instance->getInstantiatedFromStaticDataMember();
3452 } while (Instance);
3453
3454 return false;
3455}
3456
John McCalled976492009-12-04 22:46:56 +00003457// Other is the prospective instantiation
3458// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003459static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003460 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003461 if (UnresolvedUsingTypenameDecl *UUD
3462 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3463 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3464 return isInstantiationOf(UUD, UD, Ctx);
3465 }
3466 }
3467
3468 if (UnresolvedUsingValueDecl *UUD
3469 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003470 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3471 return isInstantiationOf(UUD, UD, Ctx);
3472 }
3473 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003474
Anders Carlsson0d8df782009-08-29 19:37:28 +00003475 return false;
3476 }
Mike Stump1eb44332009-09-09 15:08:12 +00003477
John McCall52a575a2009-08-29 08:11:13 +00003478 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3479 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003480
John McCall52a575a2009-08-29 08:11:13 +00003481 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3482 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003483
John McCall52a575a2009-08-29 08:11:13 +00003484 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3485 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003486
Douglas Gregor7caa6822009-07-24 20:34:43 +00003487 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003488 if (Var->isStaticDataMember())
3489 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3490
3491 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3492 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003493
Douglas Gregor0d696532009-09-28 06:34:35 +00003494 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3495 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3496
Douglas Gregored9c0f92009-10-29 00:04:11 +00003497 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3498 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3499 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3500 PartialSpec);
3501
Anders Carlssond8b285f2009-09-01 04:26:58 +00003502 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3503 if (!Field->getDeclName()) {
3504 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00003505 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00003506 cast<FieldDecl>(D);
3507 }
3508 }
Mike Stump1eb44332009-09-09 15:08:12 +00003509
John McCalled976492009-12-04 22:46:56 +00003510 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3511 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3512
3513 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3514 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3515
Douglas Gregor815215d2009-05-27 05:35:12 +00003516 return D->getDeclName() && isa<NamedDecl>(Other) &&
3517 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3518}
3519
3520template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00003521static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00003522 NamedDecl *D,
3523 ForwardIterator first,
3524 ForwardIterator last) {
3525 for (; first != last; ++first)
3526 if (isInstantiationOf(Ctx, D, *first))
3527 return cast<NamedDecl>(*first);
3528
3529 return 0;
3530}
3531
John McCall02cace72009-08-28 07:59:38 +00003532/// \brief Finds the instantiation of the given declaration context
3533/// within the current instantiation.
3534///
3535/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003536DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00003537 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00003538 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003539 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00003540 return cast_or_null<DeclContext>(ID);
3541 } else return DC;
3542}
3543
Douglas Gregored961e72009-05-27 17:54:46 +00003544/// \brief Find the instantiation of the given declaration within the
3545/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00003546///
3547/// This routine is intended to be used when \p D is a declaration
3548/// referenced from within a template, that needs to mapped into the
3549/// corresponding declaration within an instantiation. For example,
3550/// given:
3551///
3552/// \code
3553/// template<typename T>
3554/// struct X {
3555/// enum Kind {
3556/// KnownValue = sizeof(T)
3557/// };
3558///
3559/// bool getKind() const { return KnownValue; }
3560/// };
3561///
3562/// template struct X<int>;
3563/// \endcode
3564///
Serge Pavlov041d10c2013-07-10 04:59:14 +00003565/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
3566/// \p EnumConstantDecl for \p KnownValue (which refers to
3567/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
3568/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
3569/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003570NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00003571 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00003572 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00003573 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00003574 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003575 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3576 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003577 // D is a local of some kind. Look into the map of local
3578 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00003579 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3580 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3581 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003582
Chris Lattner57ad3782011-02-17 20:34:02 +00003583 if (Found) {
3584 if (Decl *FD = Found->dyn_cast<Decl *>())
3585 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003586
Richard Smith9a4db032012-09-12 00:56:43 +00003587 int PackIdx = ArgumentPackSubstitutionIndex;
3588 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00003589 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3590 }
3591
Serge Pavlovdc49d522013-07-15 06:14:07 +00003592 // If we're performing a partial substitution during template argument
3593 // deduction, we may not have values for template parameters yet. They
3594 // just map to themselves.
3595 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3596 isa<TemplateTemplateParmDecl>(D))
3597 return D;
3598
Chris Lattner57ad3782011-02-17 20:34:02 +00003599 // If we didn't find the decl, then we must have a label decl that hasn't
3600 // been found yet. Lazily instantiate it and return it now.
3601 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003602
Chris Lattner57ad3782011-02-17 20:34:02 +00003603 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3604 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003605
Chris Lattner57ad3782011-02-17 20:34:02 +00003606 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3607 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003608 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003609
Douglas Gregore95b4092009-09-16 18:34:49 +00003610 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3611 if (!Record->isDependentContext())
3612 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003613
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003614 // Determine whether this record is the "templated" declaration describing
3615 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00003616 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003617 if (ClassTemplate)
3618 ClassTemplate = ClassTemplate->getCanonicalDecl();
3619 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3620 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3621 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3622
3623 // Walk the current context to find either the record or an instantiation of
3624 // it.
3625 DeclContext *DC = CurContext;
3626 while (!DC->isFileContext()) {
3627 // If we're performing substitution while we're inside the template
3628 // definition, we'll find our own context. We're done.
3629 if (DC->Equals(Record))
3630 return Record;
3631
3632 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3633 // Check whether we're in the process of instantiating a class template
3634 // specialization of the template we're mapping.
3635 if (ClassTemplateSpecializationDecl *InstSpec
3636 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3637 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3638 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3639 return InstRecord;
3640 }
3641
3642 // Check whether we're in the process of instantiating a member class.
3643 if (isInstantiationOf(Record, InstRecord))
3644 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00003645 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003646
3647
3648 // Move to the outer template scope.
3649 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3650 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3651 DC = FD->getLexicalDeclContext();
3652 continue;
3653 }
John McCall52a575a2009-08-29 08:11:13 +00003654 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003655
3656 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00003657 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003658
Douglas Gregore95b4092009-09-16 18:34:49 +00003659 // Fall through to deal with other dependent record types (e.g.,
3660 // anonymous unions in class templates).
3661 }
John McCall52a575a2009-08-29 08:11:13 +00003662
Douglas Gregore95b4092009-09-16 18:34:49 +00003663 if (!ParentDC->isDependentContext())
3664 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003665
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003666 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003667 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003668 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003669
Douglas Gregor815215d2009-05-27 05:35:12 +00003670 if (ParentDC != D->getDeclContext()) {
3671 // We performed some kind of instantiation in the parent context,
3672 // so now we need to look into the instantiated parent context to
3673 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003674
John McCall3cb0ebd2010-03-10 03:28:59 +00003675 // If our context used to be dependent, we may need to instantiate
3676 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003677 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003678 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003679 if (!Spec->isDependentContext()) {
3680 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003681 const RecordType *Tag = T->getAs<RecordType>();
3682 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003683 if (Tag->isBeingDefined())
3684 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003685 if (!Tag->isBeingDefined() &&
3686 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3687 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003688
3689 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003690 }
3691 }
3692
Douglas Gregor815215d2009-05-27 05:35:12 +00003693 NamedDecl *Result = 0;
3694 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003695 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikie3bc93e32012-12-19 00:45:41 +00003696 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003697 } else {
3698 // Since we don't have a name for the entity we're looking for,
3699 // our only option is to walk through all of the declarations to
3700 // find that name. This will occur in a few cases:
3701 //
3702 // - anonymous struct/union within a template
3703 // - unnamed class/struct/union/enum within a template
3704 //
3705 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003706 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003707 ParentDC->decls_begin(),
3708 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003709 }
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003711 if (!Result) {
3712 if (isa<UsingShadowDecl>(D)) {
3713 // UsingShadowDecls can instantiate to nothing because of using hiding.
3714 } else if (Diags.hasErrorOccurred()) {
3715 // We've already complained about something, so most likely this
3716 // declaration failed to instantiate. There's no point in complaining
3717 // further, since this is normal in invalid code.
3718 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003719 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003720 // instantiated, and we haven't gotten around to instantiating this
3721 // member yet. This can happen when the code uses forward declarations
3722 // of member classes, and introduces ordering dependencies via
3723 // template instantiation.
3724 Diag(Loc, diag::err_member_not_yet_instantiated)
3725 << D->getDeclName()
3726 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3727 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00003728 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3729 // This enumeration constant was found when the template was defined,
3730 // but can't be found in the instantiation. This can happen if an
3731 // unscoped enumeration member is explicitly specialized.
3732 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3733 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3734 TemplateArgs));
3735 assert(Spec->getTemplateSpecializationKind() ==
3736 TSK_ExplicitSpecialization);
3737 Diag(Loc, diag::err_enumerator_does_not_exist)
3738 << D->getDeclName()
3739 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3740 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3741 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003742 } else {
3743 // We should have found something, but didn't.
3744 llvm_unreachable("Unable to find instantiation of declaration!");
3745 }
3746 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003747
Douglas Gregor815215d2009-05-27 05:35:12 +00003748 D = Result;
3749 }
3750
Douglas Gregor815215d2009-05-27 05:35:12 +00003751 return D;
3752}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003753
Mike Stump1eb44332009-09-09 15:08:12 +00003754/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003755/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00003756void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003757 // Load pending instantiations from the external source.
3758 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00003759 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003760 ExternalSource->ReadPendingInstantiations(Pending);
3761 PendingInstantiations.insert(PendingInstantiations.begin(),
3762 Pending.begin(), Pending.end());
3763 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003764
Douglas Gregor60406be2010-01-16 22:29:39 +00003765 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003766 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003767 PendingImplicitInstantiation Inst;
3768
3769 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003770 Inst = PendingInstantiations.front();
3771 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003772 } else {
3773 Inst = PendingLocalImplicitInstantiations.front();
3774 PendingLocalImplicitInstantiations.pop_front();
3775 }
Mike Stump1eb44332009-09-09 15:08:12 +00003776
Douglas Gregor7caa6822009-07-24 20:34:43 +00003777 // Instantiate function definitions
3778 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003779 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3780 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003781 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3782 TSK_ExplicitInstantiationDefinition;
3783 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3784 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003785 continue;
3786 }
Mike Stump1eb44332009-09-09 15:08:12 +00003787
Douglas Gregor7caa6822009-07-24 20:34:43 +00003788 // Instantiate static data member definitions.
3789 VarDecl *Var = cast<VarDecl>(Inst.first);
3790 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003791
Chandler Carruth291b4412010-02-13 10:17:50 +00003792 // Don't try to instantiate declarations if the most recent redeclaration
3793 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003794 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00003795 continue;
3796
3797 // Check if the most recent declaration has changed the specialization kind
3798 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003799 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00003800 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00003801 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00003802 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003803 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003804 continue; // No longer need to instantiate this type.
3805 case TSK_ExplicitInstantiationDefinition:
3806 // We only need an instantiation if the pending instantiation *is* the
3807 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003808 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003809 case TSK_ImplicitInstantiation:
3810 break;
3811 }
3812
John McCallf312b1e2010-08-26 23:41:50 +00003813 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3814 "instantiating static data member "
3815 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Chandler Carruth58e390e2010-08-25 08:27:02 +00003817 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3818 TSK_ExplicitInstantiationDefinition;
3819 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3820 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003821 }
3822}
John McCall0c01d182010-03-24 05:22:00 +00003823
3824void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3825 const MultiLevelTemplateArgumentList &TemplateArgs) {
3826 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3827 E = Pattern->ddiag_end(); I != E; ++I) {
3828 DependentDiagnostic *DD = *I;
3829
3830 switch (DD->getKind()) {
3831 case DependentDiagnostic::Access:
3832 HandleDependentAccessCheck(*DD, TemplateArgs);
3833 break;
3834 }
3835 }
3836}