blob: 5ce43da9eb4ab152e644e1955c11241ac34c5b50 [file] [log] [blame]
Douglas Gregord7e7a512009-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 McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
John McCall58f10c32010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Douglas Gregor402250f2009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000025
26using namespace clang;
27
David Majnemer192d1792013-11-27 08:20:38 +000028static bool isDeclWithinFunction(const Decl *D) {
29 const DeclContext *DC = D->getDeclContext();
30 if (DC->isFunctionOrMethod())
31 return true;
32
33 if (DC->isRecord())
34 return cast<CXXRecordDecl>(DC)->isLocalClass();
35
36 return false;
37}
38
John McCall3e11ebe2010-03-15 10:12:16 +000039bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
40 DeclaratorDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000041 if (!OldDecl->getQualifierLoc())
42 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000043
Douglas Gregor14454802011-02-25 02:25:35 +000044 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000045 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000046 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000047
Douglas Gregor14454802011-02-25 02:25:35 +000048 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000049 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000050
Douglas Gregor14454802011-02-25 02:25:35 +000051 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000052 return false;
53}
54
55bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
56 TagDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000057 if (!OldDecl->getQualifierLoc())
58 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000059
Douglas Gregor14454802011-02-25 02:25:35 +000060 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000061 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000062 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000063
Douglas Gregor14454802011-02-25 02:25:35 +000064 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000065 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000066
Douglas Gregor14454802011-02-25 02:25:35 +000067 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000068 return false;
69}
70
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000071// Include attribute instantiation code.
72#include "clang/Sema/AttrTemplateInstantiate.inc"
73
Richard Smith44c247f2013-02-22 08:32:16 +000074static void instantiateDependentAlignedAttr(
75 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
76 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
77 if (Aligned->isAlignmentExpr()) {
78 // The alignment expression is a constant expression.
79 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
80 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
81 if (!Result.isInvalid())
82 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83 Aligned->getSpellingListIndex(), IsPackExpansion);
84 } else {
85 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
86 TemplateArgs, Aligned->getLocation(),
87 DeclarationName());
88 if (Result)
89 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
90 Aligned->getSpellingListIndex(), IsPackExpansion);
91 }
92}
93
94static void instantiateDependentAlignedAttr(
95 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
96 const AlignedAttr *Aligned, Decl *New) {
97 if (!Aligned->isPackExpansion()) {
98 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
99 return;
100 }
101
102 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
103 if (Aligned->isAlignmentExpr())
104 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
105 Unexpanded);
106 else
107 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
108 Unexpanded);
109 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
110
111 // Determine whether we can expand this attribute pack yet.
112 bool Expand = true, RetainExpansion = false;
113 Optional<unsigned> NumExpansions;
114 // FIXME: Use the actual location of the ellipsis.
115 SourceLocation EllipsisLoc = Aligned->getLocation();
116 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
117 Unexpanded, TemplateArgs, Expand,
118 RetainExpansion, NumExpansions))
119 return;
120
121 if (!Expand) {
122 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
123 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
124 } else {
125 for (unsigned I = 0; I != *NumExpansions; ++I) {
126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
128 }
129 }
130}
131
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000132static void instantiateDependentEnableIfAttr(
133 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
134 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
135 Expr *Cond = 0;
136 {
137 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
138 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
139 if (Result.isInvalid())
140 return;
141 Cond = Result.takeAs<Expr>();
142 }
143 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
144 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
145 if (Converted.isInvalid())
146 return;
147 Cond = Converted.take();
148 }
149
150 SmallVector<PartialDiagnosticAt, 8> Diags;
151 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
152 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
153 Diags)) {
154 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
155 for (int I = 0, N = Diags.size(); I != N; ++I)
156 S.Diag(Diags[I].first, Diags[I].second);
157 return;
158 }
159
Aaron Ballman36a53502014-01-16 13:03:14 +0000160 EnableIfAttr *EIA = new (S.getASTContext())
161 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
162 A->getMessage(),
163 A->getSpellingListIndex());
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000164 New->addAttr(EIA);
165}
166
John McCall6602bb12010-08-01 02:01:53 +0000167void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000168 const Decl *Tmpl, Decl *New,
169 LateInstantiatedAttrVec *LateAttrs,
170 LocalInstantiationScope *OuterMostScope) {
Aaron Ballman7dce1a82014-03-07 13:13:38 +0000171 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
172 i != e; ++i) {
173 const Attr *TmplAttr = *i;
174
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000175 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000176 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
177 if (Aligned && Aligned->isAlignmentDependent()) {
178 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
179 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000180 }
181
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000182 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
183 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
184 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
185 New);
186 continue;
187 }
188
Richard Smith44c247f2013-02-22 08:32:16 +0000189 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000190 if (TmplAttr->isLateParsed() && LateAttrs) {
191 // Late parsed attributes must be instantiated and attached after the
192 // enclosing class has been instantiated. See Sema::InstantiateClass.
193 LocalInstantiationScope *Saved = 0;
194 if (CurrentInstantiationScope)
195 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
196 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
197 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000198 // Allow 'this' within late-parsed attributes.
199 NamedDecl *ND = dyn_cast<NamedDecl>(New);
200 CXXRecordDecl *ThisContext =
201 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
202 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
203 ND && ND->isCXXInstanceMember());
204
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000205 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
206 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000207 if (NewAttr)
208 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000209 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000210 }
211}
212
Douglas Gregor8a655532009-03-25 15:45:12 +0000213Decl *
214TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000215 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000216}
217
218Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000219TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
220 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
221 D->getIdentifier());
222 Owner->addDecl(Inst);
223 return Inst;
224}
225
226Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000227TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000228 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000229}
230
John McCalld8d0d432010-02-16 06:53:13 +0000231Decl *
232TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
233 NamespaceAliasDecl *Inst
234 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
235 D->getNamespaceLoc(),
236 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000237 D->getIdentifier(),
238 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000239 D->getTargetNameLoc(),
240 D->getNamespace());
241 Owner->addDecl(Inst);
242 return Inst;
243}
244
Richard Smith3f1b5d02011-05-05 21:57:07 +0000245Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
246 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000247 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000248 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000249 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000250 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000251 DI = SemaRef.SubstType(DI, TemplateArgs,
252 D->getLocation(), D->getDeclName());
253 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000254 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000255 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000256 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000257 } else {
258 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000259 }
Mike Stump11289f42009-09-09 15:08:12 +0000260
Richard Smith2ddcbab2012-10-23 00:32:41 +0000261 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
262 // libstdc++ relies upon this bug in its implementation of common_type.
263 // If we happen to be processing that implementation, fake up the g++ ?:
264 // semantics. See LWG issue 2141 for more information on the bug.
265 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
266 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
267 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
268 DT->isReferenceType() &&
269 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
270 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
271 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
272 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
273 // Fold it to the (non-reference) type which g++ would have produced.
274 DI = SemaRef.Context.getTrivialTypeSourceInfo(
275 DI->getType().getNonReferenceType());
276
Douglas Gregord7e7a512009-03-17 21:15:40 +0000277 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000278 TypedefNameDecl *Typedef;
279 if (IsTypeAlias)
280 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
281 D->getLocation(), D->getIdentifier(), DI);
282 else
283 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
284 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000285 if (Invalid)
286 Typedef->setInvalidDecl();
287
John McCall04fcd0d2011-02-01 08:20:08 +0000288 // If the old typedef was the name for linkage purposes of an anonymous
289 // tag decl, re-establish that relationship for the new typedef.
290 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
291 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000292 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000293 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000294 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000295 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000296 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000297 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000298
Douglas Gregorec9fd132012-01-14 16:38:05 +0000299 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000300 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
301 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000302 if (!InstPrev)
303 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000304
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000305 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
306
307 // If the typedef types are not identical, reject them.
308 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
309
Rafael Espindola8db352d2013-10-17 15:37:26 +0000310 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000311 }
312
John McCall6602bb12010-08-01 02:01:53 +0000313 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000314
John McCall401982f2010-01-20 21:53:11 +0000315 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000316
Douglas Gregord7e7a512009-03-17 21:15:40 +0000317 return Typedef;
318}
319
Richard Smithdda56e42011-04-15 14:24:37 +0000320Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000321 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
322 Owner->addDecl(Typedef);
323 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000324}
325
326Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000327 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
328 Owner->addDecl(Typedef);
329 return Typedef;
330}
331
332Decl *
333TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
334 // Create a local instantiation scope for this type alias template, which
335 // will contain the instantiations of the template parameters.
336 LocalInstantiationScope Scope(SemaRef);
337
338 TemplateParameterList *TempParams = D->getTemplateParameters();
339 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
340 if (!InstParams)
341 return 0;
342
343 TypeAliasDecl *Pattern = D->getTemplatedDecl();
344
345 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000346 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000347 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000348 if (!Found.empty()) {
349 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000350 }
351 }
352
353 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
354 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
355 if (!AliasInst)
356 return 0;
357
358 TypeAliasTemplateDecl *Inst
359 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
360 D->getDeclName(), InstParams, AliasInst);
361 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000362 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000363
364 Inst->setAccess(D->getAccess());
365
366 if (!PrevAliasTemplate)
367 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000368
Richard Smith3f1b5d02011-05-05 21:57:07 +0000369 Owner->addDecl(Inst);
370
371 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000372}
373
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000374Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000375 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000376}
377
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000378Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
379 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000380
Douglas Gregor04163182010-05-21 00:31:19 +0000381 // If this is the variable for an anonymous struct or union,
382 // instantiate the anonymous struct/union type first.
383 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
384 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
385 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
386 return 0;
387
John McCall76d824f2009-08-25 22:02:44 +0000388 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000389 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000390 TemplateArgs,
391 D->getTypeSpecStartLoc(),
392 D->getDeclName());
393 if (!DI)
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000394 return 0;
395
Douglas Gregor61623342010-09-12 07:37:24 +0000396 if (DI->getType()->isFunctionType()) {
397 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
398 << D->isStaticDataMember() << DI->getType();
399 return 0;
400 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000401
Richard Smith541b38b2013-09-20 01:15:31 +0000402 DeclContext *DC = Owner;
403 if (D->isLocalExternDecl())
404 SemaRef.adjustContextForLocalExternDecl(DC);
405
Larisse Voufo39a1e502013-08-06 01:03:05 +0000406 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000407 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000408 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000409 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000410
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000411 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000412 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000413 SemaRef.inferObjCARCLifetime(Var))
414 Var->setInvalidDecl();
415
Larisse Voufo39a1e502013-08-06 01:03:05 +0000416 // Substitute the nested name specifier, if any.
417 if (SubstQualifier(D, Var))
418 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000419
Richard Smith541b38b2013-09-20 01:15:31 +0000420 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000421 StartingScope, InstantiatingVarTemplate);
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000422 return Var;
423}
424
Abramo Bagnarad7340582010-06-05 05:09:32 +0000425Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
426 AccessSpecDecl* AD
427 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
428 D->getAccessSpecifierLoc(), D->getColonLoc());
429 Owner->addHiddenDecl(AD);
430 return AD;
431}
432
Douglas Gregord7e7a512009-03-17 21:15:40 +0000433Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
434 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000435 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000436 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000437 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000438 DI = SemaRef.SubstType(DI, TemplateArgs,
439 D->getLocation(), D->getDeclName());
440 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000441 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000442 Invalid = true;
443 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000444 // C++ [temp.arg.type]p3:
445 // If a declaration acquires a function type through a type
446 // dependent on a template-parameter and this causes a
447 // declaration that does not use the syntactic form of a
448 // function declarator to have function type, the program is
449 // ill-formed.
450 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000451 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000452 Invalid = true;
453 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000454 } else {
455 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000456 }
457
458 Expr *BitWidth = D->getBitWidth();
459 if (Invalid)
460 BitWidth = 0;
461 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000462 // The bit-width expression is a constant expression.
463 EnterExpressionEvaluationContext Unevaluated(SemaRef,
464 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000465
John McCalldadc5752010-08-24 06:29:42 +0000466 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000467 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000468 if (InstantiatedBitWidth.isInvalid()) {
469 Invalid = true;
470 BitWidth = 0;
471 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000472 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000473 }
474
John McCall90459c52009-10-22 23:33:21 +0000475 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
476 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000477 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000478 D->getLocation(),
479 D->isMutable(),
480 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000481 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000482 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000483 D->getAccess(),
484 0);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000485 if (!Field) {
486 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000487 return 0;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000488 }
Mike Stump11289f42009-09-09 15:08:12 +0000489
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000490 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000491
Richard Smith848e1f12013-02-01 08:12:08 +0000492 if (Field->hasAttrs())
493 SemaRef.CheckAlignasUnderalignment(Field);
494
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000495 if (Invalid)
496 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000497
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000498 if (!Field->getDeclName()) {
499 // Keep track of where this decl came from.
500 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000501 }
Douglas Gregor04163182010-05-21 00:31:19 +0000502 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
503 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000504 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000505 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000506 }
Mike Stump11289f42009-09-09 15:08:12 +0000507
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000508 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000509 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000510 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000511
512 return Field;
513}
514
John McCall5e77d762013-04-16 07:28:30 +0000515Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
516 bool Invalid = false;
517 TypeSourceInfo *DI = D->getTypeSourceInfo();
518
519 if (DI->getType()->isVariablyModifiedType()) {
520 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000521 << D;
John McCall5e77d762013-04-16 07:28:30 +0000522 Invalid = true;
523 } else if (DI->getType()->isInstantiationDependentType()) {
524 DI = SemaRef.SubstType(DI, TemplateArgs,
525 D->getLocation(), D->getDeclName());
526 if (!DI) {
527 DI = D->getTypeSourceInfo();
528 Invalid = true;
529 } else if (DI->getType()->isFunctionType()) {
530 // C++ [temp.arg.type]p3:
531 // If a declaration acquires a function type through a type
532 // dependent on a template-parameter and this causes a
533 // declaration that does not use the syntactic form of a
534 // function declarator to have function type, the program is
535 // ill-formed.
536 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
537 << DI->getType();
538 Invalid = true;
539 }
540 } else {
541 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
542 }
543
Richard Smithf7981722013-11-22 09:01:48 +0000544 MSPropertyDecl *Property = MSPropertyDecl::Create(
545 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
546 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000547
548 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
549 StartingScope);
550
551 if (Invalid)
552 Property->setInvalidDecl();
553
554 Property->setAccess(D->getAccess());
555 Owner->addDecl(Property);
556
557 return Property;
558}
559
Francois Pichet783dd6e2010-11-21 06:08:52 +0000560Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
561 NamedDecl **NamedChain =
562 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
563
564 int i = 0;
565 for (IndirectFieldDecl::chain_iterator PI =
566 D->chain_begin(), PE = D->chain_end();
Douglas Gregor55e6b312011-03-04 19:46:35 +0000567 PI != PE; ++PI) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000568 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000569 TemplateArgs);
570 if (!Next)
571 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000572
Douglas Gregor55e6b312011-03-04 19:46:35 +0000573 NamedChain[i++] = Next;
574 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000575
Francois Pichetdbafc192010-12-09 10:07:54 +0000576 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000577 IndirectFieldDecl* IndirectField
578 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000579 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000580 NamedChain, D->getChainingSize());
581
582
583 IndirectField->setImplicit(D->isImplicit());
584 IndirectField->setAccess(D->getAccess());
585 Owner->addDecl(IndirectField);
586 return IndirectField;
587}
588
John McCallaa74a0c2009-08-28 07:59:38 +0000589Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000590 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000591 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000592 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000593 TypeSourceInfo *InstTy;
594 // If this is an unsupported friend, don't bother substituting template
595 // arguments into it. The actual type referred to won't be used by any
596 // parts of Clang, and may not be valid for instantiating. Just use the
597 // same info for the instantiated friend.
598 if (D->isUnsupportedFriend()) {
599 InstTy = Ty;
600 } else {
601 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
602 D->getLocation(), DeclarationName());
603 }
604 if (!InstTy)
Douglas Gregor33636e62009-12-24 20:56:24 +0000605 return 0;
John McCallaa74a0c2009-08-28 07:59:38 +0000606
Richard Smitha31a89a2012-09-20 01:31:00 +0000607 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000608 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000609 if (!FD)
610 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000611
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000612 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000613 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000614 Owner->addDecl(FD);
615 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000616 }
617
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000618 NamedDecl *ND = D->getFriendDecl();
619 assert(ND && "friend decl must be a decl or a type!");
620
John McCallb9c78482010-04-08 09:05:18 +0000621 // All of the Visit implementations for the various potential friend
622 // declarations have to be carefully written to work for friend
623 // objects, with the most important detail being that the target
624 // decl should almost certainly not be placed in Owner.
625 Decl *NewND = Visit(ND);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000626 if (!NewND) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000627
John McCallaa74a0c2009-08-28 07:59:38 +0000628 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000629 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000630 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000631 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000632 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000633 Owner->addDecl(FD);
634 return FD;
John McCall58de3582009-08-14 02:03:10 +0000635}
636
Douglas Gregord7e7a512009-03-17 21:15:40 +0000637Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
638 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000639
Richard Smith764d2fe2011-12-20 02:08:33 +0000640 // The expression in a static assertion is a constant expression.
641 EnterExpressionEvaluationContext Unevaluated(SemaRef,
642 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000643
John McCalldadc5752010-08-24 06:29:42 +0000644 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000645 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000646 if (InstantiatedAssertExpr.isInvalid())
647 return 0;
648
Richard Smithded9c2e2012-07-11 22:37:56 +0000649 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000650 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000651 D->getMessage(),
652 D->getRParenLoc(),
653 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000654}
655
656Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith2e6610a2012-03-26 04:58:10 +0000657 EnumDecl *PrevDecl = 0;
658 if (D->getPreviousDecl()) {
659 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
660 D->getPreviousDecl(),
661 TemplateArgs);
662 if (!Prev) return 0;
663 PrevDecl = cast<EnumDecl>(Prev);
664 }
665
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000666 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000667 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000668 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000669 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000670 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000671 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000672 // If we have type source information for the underlying type, it means it
673 // has been explicitly set by the user. Perform substitution on it before
674 // moving on.
675 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000676 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
677 DeclarationName());
678 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000679 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000680 else
681 Enum->setIntegerTypeSourceInfo(NewTI);
682 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000683 assert(!D->getIntegerType()->isDependentType()
684 && "Dependent type without type source info");
685 Enum->setIntegerType(D->getIntegerType());
686 }
687 }
688
John McCall811a0f52010-10-22 23:36:17 +0000689 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
690
Richard Smith4b38ded2012-03-14 23:13:10 +0000691 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000692 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +0000693 // Forward the mangling number from the template to the instantiated decl.
694 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
John McCall3e11ebe2010-03-15 10:12:16 +0000695 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000696 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000697
Richard Smith258a7442012-03-26 04:08:46 +0000698 EnumDecl *Def = D->getDefinition();
699 if (Def && Def != D) {
700 // If this is an out-of-line definition of an enum member template, check
701 // that the underlying types match in the instantiation of both
702 // declarations.
703 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
704 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
705 QualType DefnUnderlying =
706 SemaRef.SubstType(TI->getType(), TemplateArgs,
707 UnderlyingLoc, DeclarationName());
708 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
709 DefnUnderlying, Enum);
710 }
711 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000712
Richard Smith4b38ded2012-03-14 23:13:10 +0000713 // C++11 [temp.inst]p1: The implicit instantiation of a class template
714 // specialization causes the implicit instantiation of the declarations, but
715 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000716 //
717 // DR1484 clarifies that enumeration definitions inside of a template
718 // declaration aren't considered entities that can be separately instantiated
719 // from the rest of the entity they are declared inside of.
720 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
721 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000722 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000723 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000724
725 return Enum;
726}
727
728void TemplateDeclInstantiator::InstantiateEnumDefinition(
729 EnumDecl *Enum, EnumDecl *Pattern) {
730 Enum->startDefinition();
731
Richard Smith7d137e32012-03-23 03:33:32 +0000732 // Update the location to refer to the definition.
733 Enum->setLocation(Pattern->getLocation());
734
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000735 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000736
737 EnumConstantDecl *LastEnumConst = 0;
Richard Smith4b38ded2012-03-14 23:13:10 +0000738 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
739 ECEnd = Pattern->enumerator_end();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000740 EC != ECEnd; ++EC) {
741 // The specified value for the enumerator.
John McCalldadc5752010-08-24 06:29:42 +0000742 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000743 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000744 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000745 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000746 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000747
John McCall76d824f2009-08-25 22:02:44 +0000748 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000749 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000750
751 // Drop the initial value and continue.
752 bool isInvalid = false;
753 if (Value.isInvalid()) {
754 Value = SemaRef.Owned((Expr *)0);
755 isInvalid = true;
756 }
757
Mike Stump11289f42009-09-09 15:08:12 +0000758 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000759 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
760 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000761 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000762
763 if (isInvalid) {
764 if (EnumConst)
765 EnumConst->setInvalidDecl();
766 Enum->setInvalidDecl();
767 }
768
769 if (EnumConst) {
David Blaikie40ed2972012-06-06 20:45:41 +0000770 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000771
John McCallf9b528c2010-01-23 22:37:59 +0000772 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000773 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000774 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000775 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000776
Richard Smith4b38ded2012-03-14 23:13:10 +0000777 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
778 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000779 // If the enumeration is within a function or method, record the enum
780 // constant as a local.
David Blaikie40ed2972012-06-06 20:45:41 +0000781 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000782 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000783 }
784 }
Mike Stump11289f42009-09-09 15:08:12 +0000785
Richard Smith4b38ded2012-03-14 23:13:10 +0000786 // FIXME: Fixup LBraceLoc
787 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
788 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000789 Enumerators,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +0000790 0, 0);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000791}
792
Douglas Gregor9106b822009-03-25 15:04:13 +0000793Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000794 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000795}
796
John McCall87a44eb2009-08-20 01:44:21 +0000797Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000798 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
799
Douglas Gregor954de172009-10-31 17:21:17 +0000800 // Create a local instantiation scope for this class template, which
801 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000802 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000803 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000804 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000805 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000806 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +0000807
808 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000809
810 // Instantiate the qualifier. We have to do this first in case
811 // we're a friend declaration, because if we are then we need to put
812 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000813 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
814 if (QualifierLoc) {
815 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
816 TemplateArgs);
817 if (!QualifierLoc)
818 return 0;
John McCall598b4402010-03-25 06:39:04 +0000819 }
820
821 CXXRecordDecl *PrevDecl = 0;
822 ClassTemplateDecl *PrevClassTemplate = 0;
823
Douglas Gregorec9fd132012-01-14 16:38:05 +0000824 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000825 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000826 if (!Found.empty()) {
827 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000828 if (PrevClassTemplate)
829 PrevDecl = PrevClassTemplate->getTemplatedDecl();
830 }
831 }
832
John McCall598b4402010-03-25 06:39:04 +0000833 // If this isn't a friend, then it's a member template, in which
834 // case we just want to build the instantiation in the
835 // specialization. If it is a friend, we want to build it in
836 // the appropriate context.
837 DeclContext *DC = Owner;
838 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000839 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000840 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000841 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000842 DC = SemaRef.computeDeclContext(SS);
843 if (!DC) return 0;
844 } else {
845 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
846 Pattern->getDeclContext(),
847 TemplateArgs);
848 }
849
850 // Look for a previous declaration of the template in the owning
851 // context.
852 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
853 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
854 SemaRef.LookupQualifiedName(R, DC);
855
856 if (R.isSingleResult()) {
857 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
858 if (PrevClassTemplate)
859 PrevDecl = PrevClassTemplate->getTemplatedDecl();
860 }
861
Douglas Gregor14454802011-02-25 02:25:35 +0000862 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000863 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000864 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000865 << QualifierLoc.getSourceRange();
John McCall598b4402010-03-25 06:39:04 +0000866 return 0;
867 }
868
Douglas Gregor01e09d92010-04-08 18:16:15 +0000869 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000870 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000871 bool Complain = true;
872
873 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
874 // template for struct std::tr1::__detail::_Map_base, where the
875 // template parameters of the friend declaration don't match the
876 // template parameters of the original declaration. In this one
877 // case, we don't complain about the ill-formed friend
878 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000879 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000880 Pattern->getIdentifier()->isStr("_Map_base") &&
881 DC->isNamespace() &&
882 cast<NamespaceDecl>(DC)->getIdentifier() &&
883 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
884 DeclContext *DCParent = DC->getParent();
885 if (DCParent->isNamespace() &&
886 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
887 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
888 DeclContext *DCParent2 = DCParent->getParent();
889 if (DCParent2->isNamespace() &&
890 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
891 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
892 DCParent2->getParent()->isTranslationUnit())
893 Complain = false;
894 }
895 }
896
John McCall598b4402010-03-25 06:39:04 +0000897 TemplateParameterList *PrevParams
898 = PrevClassTemplate->getTemplateParameters();
899
900 // Make sure the parameter lists match.
901 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000902 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000903 Sema::TPL_TemplateMatch)) {
904 if (Complain)
905 return 0;
906
907 AdoptedPreviousTemplateParams = true;
908 InstParams = PrevParams;
909 }
John McCall598b4402010-03-25 06:39:04 +0000910
911 // Do some additional validation, then merge default arguments
912 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000913 if (!AdoptedPreviousTemplateParams &&
914 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000915 Sema::TPC_ClassTemplate))
916 return 0;
917 }
918 }
919
John McCall87a44eb2009-08-20 01:44:21 +0000920 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000921 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000922 Pattern->getLocStart(), Pattern->getLocation(),
923 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000924 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000925
Douglas Gregor14454802011-02-25 02:25:35 +0000926 if (QualifierLoc)
927 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000928
John McCall87a44eb2009-08-20 01:44:21 +0000929 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000930 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
931 D->getIdentifier(), InstParams, RecordInst,
932 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000933 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000934
John McCall598b4402010-03-25 06:39:04 +0000935 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000936 if (PrevClassTemplate)
937 Inst->setAccess(PrevClassTemplate->getAccess());
938 else
939 Inst->setAccess(D->getAccess());
940
Richard Smith64017682013-07-17 23:53:16 +0000941 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000942 // TODO: do we want to track the instantiation progeny of this
943 // friend target decl?
944 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000945 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000946 if (!PrevClassTemplate)
947 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000948 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000949
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000950 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000951 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000952 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000953
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000954 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000955 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000956 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000957 Inst->setLexicalDeclContext(Owner);
958 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000959 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000960 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000961
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000962 if (D->isOutOfLine()) {
963 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
964 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
965 }
966
John McCall87a44eb2009-08-20 01:44:21 +0000967 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000968
969 if (!PrevClassTemplate) {
970 // Queue up any out-of-line partial specializations of this member
971 // class template; the client will force their instantiation once
972 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000973 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000974 D->getPartialSpecializations(PartialSpecs);
975 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000976 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +0000977 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
978 }
979
John McCall87a44eb2009-08-20 01:44:21 +0000980 return Inst;
981}
982
Douglas Gregore704c9d2009-08-27 16:57:43 +0000983Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000984TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
985 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000986 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000987
Douglas Gregor21610382009-10-29 00:04:11 +0000988 // Lookup the already-instantiated declaration in the instantiation
989 // of the class template and return that.
990 DeclContext::lookup_result Found
991 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000992 if (Found.empty())
Douglas Gregor21610382009-10-29 00:04:11 +0000993 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000994
Douglas Gregor21610382009-10-29 00:04:11 +0000995 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +0000996 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +0000997 if (!InstClassTemplate)
998 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000999
Douglas Gregor869853e2010-11-10 19:44:59 +00001000 if (ClassTemplatePartialSpecializationDecl *Result
1001 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1002 return Result;
1003
1004 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001005}
1006
Larisse Voufo39a1e502013-08-06 01:03:05 +00001007Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1008 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1009 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001010
1011 // Create a local instantiation scope for this variable template, which
1012 // will contain the instantiations of the template parameters.
1013 LocalInstantiationScope Scope(SemaRef);
1014 TemplateParameterList *TempParams = D->getTemplateParameters();
1015 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1016 if (!InstParams)
1017 return NULL;
1018
1019 VarDecl *Pattern = D->getTemplatedDecl();
1020 VarTemplateDecl *PrevVarTemplate = 0;
1021
1022 if (Pattern->getPreviousDecl()) {
1023 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1024 if (!Found.empty())
1025 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1026 }
1027
Richard Smith1c34fb72013-08-13 18:18:50 +00001028 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001029 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1030 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +00001031
1032 DeclContext *DC = Owner;
1033
Larisse Voufo39a1e502013-08-06 01:03:05 +00001034 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1035 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001036 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001037 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001038 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001039
1040 Inst->setAccess(D->getAccess());
1041 if (!PrevVarTemplate)
1042 Inst->setInstantiatedFromMemberTemplate(D);
1043
1044 if (D->isOutOfLine()) {
1045 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1046 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1047 }
1048
1049 Owner->addDecl(Inst);
1050
1051 if (!PrevVarTemplate) {
1052 // Queue up any out-of-line partial specializations of this member
1053 // variable template; the client will force their instantiation once
1054 // the enclosing class has been instantiated.
1055 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1056 D->getPartialSpecializations(PartialSpecs);
1057 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001058 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001059 OutOfLineVarPartialSpecs.push_back(
1060 std::make_pair(Inst, PartialSpecs[I]));
1061 }
1062
1063 return Inst;
1064}
1065
1066Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1067 VarTemplatePartialSpecializationDecl *D) {
1068 assert(D->isStaticDataMember() &&
1069 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001070
1071 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1072
1073 // Lookup the already-instantiated declaration and return that.
1074 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1075 assert(!Found.empty() && "Instantiation found nothing?");
1076
1077 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1078 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1079
1080 if (VarTemplatePartialSpecializationDecl *Result =
1081 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1082 return Result;
1083
1084 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1085}
1086
Douglas Gregore4b05162009-10-07 17:21:34 +00001087Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001088TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001089 // Create a local instantiation scope for this function template, which
1090 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001091 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001092 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001093 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001094
Douglas Gregore704c9d2009-08-27 16:57:43 +00001095 TemplateParameterList *TempParams = D->getTemplateParameters();
1096 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001097 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001098 return NULL;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001099
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001100 FunctionDecl *Instantiated = 0;
1101 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001102 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001103 InstParams));
1104 else
1105 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001106 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001107 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001108
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001109 if (!Instantiated)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001110 return 0;
1111
Mike Stump11289f42009-09-09 15:08:12 +00001112 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001113 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001114 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001115 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001116 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001117 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001118 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001119
John McCall30837102010-03-26 23:10:15 +00001120 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1121
John McCall2079d0b2009-12-14 23:19:40 +00001122 // Link the instantiation back to the pattern *unless* this is a
1123 // non-definition friend declaration.
1124 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001125 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001126 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001127
John McCall30837102010-03-26 23:10:15 +00001128 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001129 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001130 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001131 } else if (InstTemplate->getDeclContext()->isRecord() &&
1132 !D->getPreviousDecl()) {
1133 SemaRef.CheckFriendAccess(InstTemplate);
1134 }
John McCall30837102010-03-26 23:10:15 +00001135
Douglas Gregore704c9d2009-08-27 16:57:43 +00001136 return InstTemplate;
1137}
1138
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001139Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1140 CXXRecordDecl *PrevDecl = 0;
1141 if (D->isInjectedClassName())
1142 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001143 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001144 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001145 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001146 TemplateArgs);
1147 if (!Prev) return 0;
1148 PrevDecl = cast<CXXRecordDecl>(Prev);
1149 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001150
1151 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001152 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001153 D->getLocStart(), D->getLocation(),
1154 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001155
1156 // Substitute the nested name specifier, if any.
1157 if (SubstQualifier(D, Record))
1158 return 0;
1159
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001160 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001161 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1162 // the tag decls introduced by friend class declarations don't have an access
1163 // specifier. Remove once this area of the code gets sorted out.
1164 if (D->getAccess() != AS_none)
1165 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001166 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001167 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001168
John McCallaa74a0c2009-08-28 07:59:38 +00001169 // If the original function was part of a friend declaration,
1170 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001171 if (D->getFriendObjectKind())
1172 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001173
Douglas Gregor04163182010-05-21 00:31:19 +00001174 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001175 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001176 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001177
1178 if (D->isLocalClass())
1179 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001180
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001181 // Forward the mangling number from the template to the instantiated decl.
1182 SemaRef.Context.setManglingNumber(Record,
1183 SemaRef.Context.getManglingNumber(D));
1184
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001185 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001186
1187 // DR1484 clarifies that the members of a local class are instantiated as part
1188 // of the instantiation of their enclosing entity.
1189 if (D->isCompleteDefinition() && D->isLocalClass()) {
David Majnemera64cb5a2014-02-22 00:17:46 +00001190 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1191 TSK_ImplicitInstantiation,
1192 /*Complain=*/true);
1193 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1194 TSK_ImplicitInstantiation);
David Majnemer192d1792013-11-27 08:20:38 +00001195 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001196 return Record;
1197}
1198
Douglas Gregor89f593a2012-09-13 21:56:43 +00001199/// \brief Adjust the given function type for an instantiation of the
1200/// given declaration, to cope with modifications to the function's type that
1201/// aren't reflected in the type-source information.
1202///
1203/// \param D The declaration we're instantiating.
1204/// \param TInfo The already-instantiated type.
1205static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1206 FunctionDecl *D,
1207 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001208 const FunctionProtoType *OrigFunc
1209 = D->getType()->castAs<FunctionProtoType>();
1210 const FunctionProtoType *NewFunc
1211 = TInfo->getType()->castAs<FunctionProtoType>();
1212 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1213 return TInfo->getType();
1214
1215 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1216 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001217 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001218 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001219}
1220
John McCallaa74a0c2009-08-28 07:59:38 +00001221/// Normal class members are of more specific types and therefore
1222/// don't make it here. This function serves two purposes:
1223/// 1) instantiating function templates
1224/// 2) substituting friend declarations
Douglas Gregor33636e62009-12-24 20:56:24 +00001225Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001226 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001227 // Check whether there is already a function template specialization for
1228 // this declaration.
1229 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001230 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001231 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001232
Douglas Gregorce9978f2012-03-28 14:34:23 +00001233 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001234 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001235 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001236 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001237
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001238 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001239 if (SpecFunc)
1240 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001241 }
Mike Stump11289f42009-09-09 15:08:12 +00001242
John McCall2f88d7d2010-03-27 05:57:59 +00001243 bool isFriend;
1244 if (FunctionTemplate)
1245 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1246 else
1247 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1248
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001249 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001250 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001251 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001252 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001253 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001254
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001255 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001256 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001257 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001258 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001259 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001260
Douglas Gregor14454802011-02-25 02:25:35 +00001261 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1262 if (QualifierLoc) {
1263 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1264 TemplateArgs);
1265 if (!QualifierLoc)
1266 return 0;
John McCalle0b2ddb2010-03-26 04:53:08 +00001267 }
1268
John McCallce410662010-02-06 01:50:47 +00001269 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001270 // in the enclosing namespace; otherwise we need to find the instantiated
1271 // context.
John McCallce410662010-02-06 01:50:47 +00001272 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001273 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001274 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001275 SemaRef.adjustContextForLocalExternDecl(DC);
1276 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001277 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001278 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001279 DC = SemaRef.computeDeclContext(SS);
1280 if (!DC) return 0;
1281 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001282 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001283 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001284 }
John McCallce410662010-02-06 01:50:47 +00001285
John McCallaa74a0c2009-08-28 07:59:38 +00001286 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001287 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001288 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001289 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001290 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001291 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001292 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001293
Richard Smithf3814ad2013-01-25 00:08:28 +00001294 if (D->isInlined())
1295 Function->setImplicitlyInline();
1296
Douglas Gregor14454802011-02-25 02:25:35 +00001297 if (QualifierLoc)
1298 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001299
Richard Smith541b38b2013-09-20 01:15:31 +00001300 if (D->isLocalExternDecl())
1301 Function->setLocalExternDecl();
1302
John McCall30837102010-03-26 23:10:15 +00001303 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001304 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001305 assert(D->getDeclContext()->isFileContext());
1306 LexicalDC = D->getDeclContext();
1307 }
1308
1309 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001310
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001311 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001312 for (unsigned P = 0; P < Params.size(); ++P)
1313 if (Params[P])
1314 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001315 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001316
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001317 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001318 if (TemplateParams) {
1319 // Our resulting instantiation is actually a function template, since we
1320 // are substituting only the outer template parameters. For example, given
1321 //
1322 // template<typename T>
1323 // struct X {
1324 // template<typename U> friend void f(T, U);
1325 // };
1326 //
1327 // X<int> x;
1328 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001329 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001330 // which means substituting int for T, but leaving "f" as a friend function
1331 // template.
1332 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001333 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001334 Function->getLocation(),
1335 Function->getDeclName(),
1336 TemplateParams, Function);
1337 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001338
1339 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001340
1341 if (isFriend && D->isThisDeclarationADefinition()) {
1342 // TODO: should we remember this connection regardless of whether
1343 // the friend declaration provided a body?
1344 FunctionTemplate->setInstantiatedFromMemberTemplate(
1345 D->getDescribedFunctionTemplate());
1346 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001347 } else if (FunctionTemplate) {
1348 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001349 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001350 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001351 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001352 Innermost.begin(),
1353 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001354 /*InsertPos=*/0);
Chandler Carruth48b28312011-08-18 09:09:59 +00001355 } else if (isFriend) {
1356 // Note, we need this connection even if the friend doesn't have a body.
1357 // Its body may exist but not have been attached yet due to deferred
1358 // parsing.
1359 // FIXME: It might be cleaner to set this when attaching the body to the
1360 // friend function declaration, however that would require finding all the
1361 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001362 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001363 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001364
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001365 if (InitFunctionInstantiation(Function, D))
1366 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001367
John McCallb9c78482010-04-08 09:05:18 +00001368 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001369
Richard Smith541b38b2013-09-20 01:15:31 +00001370 LookupResult Previous(
1371 SemaRef, Function->getDeclName(), SourceLocation(),
1372 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1373 : Sema::LookupOrdinaryName,
1374 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001375
John McCallb9c78482010-04-08 09:05:18 +00001376 if (DependentFunctionTemplateSpecializationInfo *Info
1377 = D->getDependentSpecializationInfo()) {
1378 assert(isFriend && "non-friend has dependent specialization info?");
1379
1380 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001381 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001382
1383 // Instantiate the explicit template arguments.
1384 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1385 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001386 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1387 ExplicitArgs, TemplateArgs))
1388 return 0;
John McCallb9c78482010-04-08 09:05:18 +00001389
1390 // Map the candidate templates to their instantiations.
1391 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1392 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1393 Info->getTemplate(I),
1394 TemplateArgs);
1395 if (!Temp) return 0;
1396
1397 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1398 }
1399
1400 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1401 &ExplicitArgs,
1402 Previous))
1403 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001404
John McCallb9c78482010-04-08 09:05:18 +00001405 isExplicitSpecialization = true;
1406
1407 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001408 // Look only into the namespace where the friend would be declared to
1409 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001410 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001411 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001412
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001413 // In C++, the previous declaration we find might be a tag type
1414 // (class or enum). In this case, the new declaration will hide the
1415 // tag type. Note that this does does not apply if we're declaring a
1416 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001417 if (Previous.isSingleTagDecl())
1418 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001419 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001420
John McCall84d87672009-12-10 09:41:52 +00001421 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001422 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001423
John McCallb9467b62010-04-24 01:30:58 +00001424 NamedDecl *PrincipalDecl = (TemplateParams
1425 ? cast<NamedDecl>(FunctionTemplate)
1426 : Function);
1427
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001428 // If the original function was part of a friend declaration,
1429 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001430 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001431 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001432 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001433
Richard Smith91dfaac2014-02-03 02:37:59 +00001434 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001435
Richard Smith91dfaac2014-02-03 02:37:59 +00001436 // C++11 [temp.friend]p4 (DR329):
1437 // When a function is defined in a friend function declaration in a class
1438 // template, the function is instantiated when the function is odr-used.
1439 // The same restrictions on multiple declarations and definitions that
1440 // apply to non-template function declarations and definitions also apply
1441 // to these implicit definitions.
1442 if (D->isThisDeclarationADefinition()) {
Douglas Gregorb92ea592010-05-18 05:45:02 +00001443 // Check for a function body.
1444 const FunctionDecl *Definition = 0;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001445 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001446 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001447 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1448 << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001449 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001450 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001451 // Check for redefinitions due to other instantiations of this or
1452 // a similar friend function.
Aaron Ballman86c93902014-03-06 23:45:36 +00001453 else for (auto R : Function->redecls()) {
1454 if (R == Function)
Gabor Greif122f1eb2010-08-28 15:42:30 +00001455 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001456
1457 // If some prior declaration of this function has been used, we need
1458 // to instantiate its definition.
1459 if (!QueuedInstantiation && R->isUsed(false)) {
1460 if (MemberSpecializationInfo *MSInfo =
1461 Function->getMemberSpecializationInfo()) {
1462 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1463 SourceLocation Loc = R->getLocation(); // FIXME
1464 MSInfo->setPointOfInstantiation(Loc);
1465 SemaRef.PendingLocalImplicitInstantiations.push_back(
1466 std::make_pair(Function, Loc));
1467 QueuedInstantiation = true;
Gabor Greif718d5152010-08-30 21:10:05 +00001468 }
1469 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001470 }
1471
1472 // If some prior declaration of this function was a friend with an
1473 // uninstantiated definition, reject it.
1474 if (R->getFriendObjectKind()) {
1475 if (const FunctionDecl *RPattern =
1476 R->getTemplateInstantiationPattern()) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001477 if (RPattern->isDefined(RPattern)) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001478 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001479 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001480 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregorb92ea592010-05-18 05:45:02 +00001481 break;
1482 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001483 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001484 }
1485 }
1486 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001487 }
1488
Richard Smith541b38b2013-09-20 01:15:31 +00001489 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1490 DC->makeDeclVisibleInContext(PrincipalDecl);
1491
John McCallb9467b62010-04-24 01:30:58 +00001492 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1493 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1494 PrincipalDecl->setNonMemberOperator();
1495
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001496 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001497 return Function;
1498}
1499
Douglas Gregore704c9d2009-08-27 16:57:43 +00001500Decl *
1501TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001502 TemplateParameterList *TemplateParams,
1503 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001504 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001505 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001506 // We are creating a function template specialization from a function
1507 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001508 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001509 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001510
Douglas Gregorce9978f2012-03-28 14:34:23 +00001511 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001512 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001513 = FunctionTemplate->findSpecialization(Innermost.begin(),
1514 Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001515 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001516
Douglas Gregor97628d62009-08-21 00:16:32 +00001517 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001518 if (SpecFunc)
1519 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001520 }
1521
John McCall2f88d7d2010-03-27 05:57:59 +00001522 bool isFriend;
1523 if (FunctionTemplate)
1524 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1525 else
1526 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1527
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001528 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001529 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001530 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001531 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001532
John McCalld0e23ec2010-10-19 02:26:41 +00001533 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001534 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001535 unsigned NumTempParamLists = 0;
1536 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1537 TempParamLists.set_size(NumTempParamLists);
1538 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1539 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1540 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1541 if (!InstParams)
1542 return NULL;
1543 TempParamLists[I] = InstParams;
1544 }
1545 }
1546
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001547 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001548 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001549 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001550 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001551 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001552
Douglas Gregor14454802011-02-25 02:25:35 +00001553 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1554 if (QualifierLoc) {
1555 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001556 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001557 if (!QualifierLoc)
Douglas Gregor14454802011-02-25 02:25:35 +00001558 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001559 }
1560
1561 DeclContext *DC = Owner;
1562 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001563 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001564 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001565 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001566 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001567
1568 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1569 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001570 } else {
1571 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1572 D->getDeclContext(),
1573 TemplateArgs);
1574 }
1575 if (!DC) return 0;
1576 }
1577
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001578 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001579 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001580 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001581
Abramo Bagnaradff19302011-03-08 08:55:46 +00001582 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001583 DeclarationNameInfo NameInfo
1584 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001585 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001586 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001587 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001588 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001589 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001590 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001591
Richard Smith185be182013-04-10 05:48:59 +00001592 // Claim that the instantiation of a constructor or constructor template
1593 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001594 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1595 Constructor->getInheritedConstructor())) {
1596 // If we're instantiating a specialization of a function template, our
1597 // "inherited constructor" will actually itself be a function template.
1598 // Instantiate a declaration of it, too.
1599 if (FunctionTemplate) {
1600 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1601 !Inh->getParent()->isDependentContext() &&
1602 "inheriting constructor template in dependent context?");
1603 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1604 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001605 if (Inst.isInvalid())
Richard Smith4c163a02013-05-17 02:19:35 +00001606 return 0;
1607 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1608 LocalInstantiationScope LocalScope(SemaRef);
1609
1610 // Use the same template arguments that we deduced for the inheriting
1611 // constructor. There's no way they could be deduced differently.
1612 MultiLevelTemplateArgumentList InheritedArgs;
1613 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1614 Inh = cast_or_null<CXXConstructorDecl>(
1615 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1616 if (!Inh)
1617 return 0;
1618 }
Richard Smith185be182013-04-10 05:48:59 +00001619 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001620 }
Douglas Gregore8394862009-08-21 22:43:28 +00001621 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001622 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001623 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001624 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001625 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001626 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001627 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001628 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001629 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001630 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001631 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001632 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001633 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001634 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001635 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001636 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001637 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001638 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001639 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001640
Richard Smithf3814ad2013-01-25 00:08:28 +00001641 if (D->isInlined())
1642 Method->setImplicitlyInline();
1643
Douglas Gregor14454802011-02-25 02:25:35 +00001644 if (QualifierLoc)
1645 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001646
Douglas Gregore704c9d2009-08-27 16:57:43 +00001647 if (TemplateParams) {
1648 // Our resulting instantiation is actually a function template, since we
1649 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001650 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001651 // template<typename T>
1652 // struct X {
1653 // template<typename U> void f(T, U);
1654 // };
1655 //
1656 // X<int> x;
1657 //
1658 // We are instantiating the member template "f" within X<int>, which means
1659 // substituting int for T, but leaving "f" as a member function template.
1660 // Build the function template itself.
1661 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1662 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001663 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001664 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001665 if (isFriend) {
1666 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001667 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001668 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001669 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001670 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001671 } else if (FunctionTemplate) {
1672 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001673 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001674 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001675 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001676 Innermost.begin(),
1677 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001678 /*InsertPos=*/0);
John McCall2f88d7d2010-03-27 05:57:59 +00001679 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001680 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001681 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001682 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001683
Mike Stump11289f42009-09-09 15:08:12 +00001684 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001685 // out-of-line, the instantiation will have the same lexical
1686 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001687 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001688 if (NumTempParamLists)
1689 Method->setTemplateParameterListsInfo(SemaRef.Context,
1690 NumTempParamLists,
1691 TempParamLists.data());
1692
John McCall2f88d7d2010-03-27 05:57:59 +00001693 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001694 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001695 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001696 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001697
Douglas Gregor21342092009-03-24 00:38:23 +00001698 // Attach the parameters
1699 for (unsigned P = 0; P < Params.size(); ++P)
1700 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001701 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001702
1703 if (InitMethodInstantiation(Method, D))
1704 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001705
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001706 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1707 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001708
John McCall2f88d7d2010-03-27 05:57:59 +00001709 if (!FunctionTemplate || TemplateParams || isFriend) {
1710 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001711
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001712 // In C++, the previous declaration we find might be a tag type
1713 // (class or enum). In this case, the new declaration will hide the
1714 // tag type. Note that this does does not apply if we're declaring a
1715 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001716 if (Previous.isSingleTagDecl())
1717 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001718 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001719
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001720 if (!IsClassScopeSpecialization)
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001721 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001722
Douglas Gregor21920e372009-12-01 17:24:26 +00001723 if (D->isPure())
1724 SemaRef.CheckPureMethod(Method, SourceRange());
1725
John McCalla0a96892012-08-10 03:15:35 +00001726 // Propagate access. For a non-friend declaration, the access is
1727 // whatever we're propagating from. For a friend, it should be the
1728 // previous declaration we just found.
1729 if (isFriend && Method->getPreviousDecl())
1730 Method->setAccess(Method->getPreviousDecl()->getAccess());
1731 else
1732 Method->setAccess(D->getAccess());
1733 if (FunctionTemplate)
1734 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001735
Anders Carlsson7c812f52011-01-20 06:52:44 +00001736 SemaRef.CheckOverrideControl(Method);
1737
Eli Friedman41340732011-11-15 22:39:08 +00001738 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001739 if (D->isExplicitlyDefaulted())
1740 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001741 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001742 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001743
John McCalla0a96892012-08-10 03:15:35 +00001744 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001745 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001746 // do nothing
1747
1748 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001749 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001750 // do nothing
1751
1752 // Otherwise, check access to friends and make them visible.
1753 } else if (isFriend) {
1754 // We only need to re-check access for methods which we didn't
1755 // manage to match during parsing.
1756 if (!D->getPreviousDecl())
1757 SemaRef.CheckFriendAccess(Method);
1758
1759 Record->makeDeclVisibleInContext(Method);
1760
1761 // Otherwise, add the declaration. We don't need to do this for
1762 // class-scope specializations because we'll have matched them with
1763 // the appropriate template.
1764 } else if (!IsClassScopeSpecialization) {
1765 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001766 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001767
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001768 return Method;
1769}
1770
Douglas Gregor4044d992009-03-24 16:43:20 +00001771Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001772 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001773}
1774
Douglas Gregor654b07e2009-03-24 00:15:49 +00001775Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001776 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001777}
1778
Douglas Gregor1880ba52009-03-25 00:34:44 +00001779Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001780 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001781}
1782
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001783Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001784 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1785 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001786}
1787
John McCall87a44eb2009-08-20 01:44:21 +00001788Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1789 TemplateTypeParmDecl *D) {
1790 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001791 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001792
John McCall87a44eb2009-08-20 01:44:21 +00001793 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001794 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1795 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001796 D->getDepth() - TemplateArgs.getNumLevels(),
1797 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001798 D->wasDeclaredWithTypename(),
1799 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001800 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001801
David Majnemer89189202013-08-28 23:48:32 +00001802 if (D->hasDefaultArgument()) {
1803 TypeSourceInfo *InstantiatedDefaultArg =
1804 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1805 D->getDefaultArgumentLoc(), D->getDeclName());
1806 if (InstantiatedDefaultArg)
1807 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1808 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001809
1810 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001811 // scope.
1812 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001813
John McCall87a44eb2009-08-20 01:44:21 +00001814 return Inst;
1815}
1816
Douglas Gregor6b815c82009-10-23 23:25:44 +00001817Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1818 NonTypeTemplateParmDecl *D) {
1819 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001820 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001821 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1822 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001823 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001824 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001825 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001826 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001827
1828 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001829 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001830 // expansion of types. Substitute into each of the expanded types.
1831 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1832 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1833 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1834 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1835 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001836 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001837 D->getDeclName());
1838 if (!NewDI)
1839 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001840
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001841 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1842 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1843 D->getLocation());
1844 if (NewT.isNull())
1845 return 0;
1846 ExpandedParameterPackTypes.push_back(NewT);
1847 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001848
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001849 IsExpandedParameterPack = true;
1850 DI = D->getTypeSourceInfo();
1851 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001852 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001853 // The non-type template parameter pack's type is a pack expansion of types.
1854 // Determine whether we need to expand this parameter pack into separate
1855 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001856 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001857 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001858 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001859 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001860
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001861 // Determine whether the set of unexpanded parameter packs can and should
1862 // be expanded.
1863 bool Expand = true;
1864 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001865 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001866 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001867 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001868 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1869 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001870 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001871 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001872 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001873 NumExpansions))
1874 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001875
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001876 if (Expand) {
1877 for (unsigned I = 0; I != *NumExpansions; ++I) {
1878 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1879 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001880 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001881 D->getDeclName());
1882 if (!NewDI)
1883 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001884
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001885 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1886 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1887 NewDI->getType(),
1888 D->getLocation());
1889 if (NewT.isNull())
1890 return 0;
1891 ExpandedParameterPackTypes.push_back(NewT);
1892 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001893
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001894 // Note that we have an expanded parameter pack. The "type" of this
1895 // expanded parameter pack is the original expansion type, but callers
1896 // will end up using the expanded parameter pack types for type-checking.
1897 IsExpandedParameterPack = true;
1898 DI = D->getTypeSourceInfo();
1899 T = DI->getType();
1900 } else {
1901 // We cannot fully expand the pack expansion now, so substitute into the
1902 // pattern and create a new pack expansion type.
1903 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1904 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001905 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001906 D->getDeclName());
1907 if (!NewPattern)
1908 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001909
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001910 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1911 NumExpansions);
1912 if (!DI)
1913 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001914
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001915 T = DI->getType();
1916 }
1917 } else {
1918 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001919 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001920 D->getLocation(), D->getDeclName());
1921 if (!DI)
1922 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001923
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001924 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001925 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001926 D->getLocation());
1927 if (T.isNull()) {
1928 T = SemaRef.Context.IntTy;
1929 Invalid = true;
1930 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001931 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001932
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001933 NonTypeTemplateParmDecl *Param;
1934 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001935 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001936 D->getInnerLocStart(),
1937 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001938 D->getDepth() - TemplateArgs.getNumLevels(),
1939 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001940 D->getIdentifier(), T,
1941 DI,
1942 ExpandedParameterPackTypes.data(),
1943 ExpandedParameterPackTypes.size(),
1944 ExpandedParameterPackTypesAsWritten.data());
1945 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001946 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001947 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001948 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001949 D->getDepth() - TemplateArgs.getNumLevels(),
1950 D->getPosition(),
1951 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001952 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001953
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001954 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001955 if (Invalid)
1956 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001957
David Majnemer89189202013-08-28 23:48:32 +00001958 if (D->hasDefaultArgument()) {
1959 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1960 if (!Value.isInvalid())
1961 Param->setDefaultArgument(Value.get(), false);
1962 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001963
1964 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001965 // scope.
1966 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001967 return Param;
1968}
1969
Richard Smith1fde8ec2012-09-07 02:06:42 +00001970static void collectUnexpandedParameterPacks(
1971 Sema &S,
1972 TemplateParameterList *Params,
1973 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1974 for (TemplateParameterList::const_iterator I = Params->begin(),
1975 E = Params->end(); I != E; ++I) {
1976 if ((*I)->isTemplateParameterPack())
1977 continue;
1978 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1979 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1980 Unexpanded);
1981 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1982 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1983 Unexpanded);
1984 }
1985}
1986
Anders Carlsson4bd78752009-08-28 15:18:15 +00001987Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001988TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1989 TemplateTemplateParmDecl *D) {
1990 // Instantiate the template parameter list of the template template parameter.
1991 TemplateParameterList *TempParams = D->getTemplateParameters();
1992 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001993 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1994
1995 bool IsExpandedParameterPack = false;
1996
1997 if (D->isExpandedParameterPack()) {
1998 // The template template parameter pack is an already-expanded pack
1999 // expansion of template parameters. Substitute into each of the expanded
2000 // parameters.
2001 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2002 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2003 I != N; ++I) {
2004 LocalInstantiationScope Scope(SemaRef);
2005 TemplateParameterList *Expansion =
2006 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2007 if (!Expansion)
2008 return 0;
2009 ExpandedParams.push_back(Expansion);
2010 }
2011
2012 IsExpandedParameterPack = true;
2013 InstParams = TempParams;
2014 } else if (D->isPackExpansion()) {
2015 // The template template parameter pack expands to a pack of template
2016 // template parameters. Determine whether we need to expand this parameter
2017 // pack into separate parameters.
2018 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2019 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2020 Unexpanded);
2021
2022 // Determine whether the set of unexpanded parameter packs can and should
2023 // be expanded.
2024 bool Expand = true;
2025 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002026 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002027 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2028 TempParams->getSourceRange(),
2029 Unexpanded,
2030 TemplateArgs,
2031 Expand, RetainExpansion,
2032 NumExpansions))
2033 return 0;
2034
2035 if (Expand) {
2036 for (unsigned I = 0; I != *NumExpansions; ++I) {
2037 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2038 LocalInstantiationScope Scope(SemaRef);
2039 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2040 if (!Expansion)
2041 return 0;
2042 ExpandedParams.push_back(Expansion);
2043 }
2044
2045 // Note that we have an expanded parameter pack. The "type" of this
2046 // expanded parameter pack is the original expansion type, but callers
2047 // will end up using the expanded parameter pack types for type-checking.
2048 IsExpandedParameterPack = true;
2049 InstParams = TempParams;
2050 } else {
2051 // We cannot fully expand the pack expansion now, so just substitute
2052 // into the pattern.
2053 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2054
2055 LocalInstantiationScope Scope(SemaRef);
2056 InstParams = SubstTemplateParams(TempParams);
2057 if (!InstParams)
2058 return 0;
2059 }
2060 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002061 // Perform the actual substitution of template parameters within a new,
2062 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002063 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002064 InstParams = SubstTemplateParams(TempParams);
2065 if (!InstParams)
Richard Smith1fde8ec2012-09-07 02:06:42 +00002066 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002067 }
2068
Douglas Gregor38fee962009-11-11 16:58:32 +00002069 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002070 TemplateTemplateParmDecl *Param;
2071 if (IsExpandedParameterPack)
2072 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2073 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002074 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002075 D->getPosition(),
2076 D->getIdentifier(), InstParams,
2077 ExpandedParams);
2078 else
2079 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2080 D->getLocation(),
2081 D->getDepth() - TemplateArgs.getNumLevels(),
2082 D->getPosition(),
2083 D->isParameterPack(),
2084 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002085 if (D->hasDefaultArgument()) {
2086 NestedNameSpecifierLoc QualifierLoc =
2087 D->getDefaultArgument().getTemplateQualifierLoc();
2088 QualifierLoc =
2089 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2090 TemplateName TName = SemaRef.SubstTemplateName(
2091 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2092 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2093 if (!TName.isNull())
2094 Param->setDefaultArgument(
2095 TemplateArgumentLoc(TemplateArgument(TName),
2096 D->getDefaultArgument().getTemplateQualifierLoc(),
2097 D->getDefaultArgument().getTemplateNameLoc()),
2098 false);
2099 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002100 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002101
2102 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002103 // scope.
2104 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002105
Douglas Gregor38fee962009-11-11 16:58:32 +00002106 return Param;
2107}
2108
Douglas Gregore0b28662009-11-17 06:07:40 +00002109Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002110 // Using directives are never dependent (and never contain any types or
2111 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002112
Douglas Gregore0b28662009-11-17 06:07:40 +00002113 UsingDirectiveDecl *Inst
2114 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002115 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002116 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002117 D->getIdentLocation(),
2118 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002119 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002120
2121 // Add the using directive to its declaration context
2122 // only if this is not a function or method.
2123 if (!Owner->isFunctionOrMethod())
2124 Owner->addDecl(Inst);
2125
Douglas Gregore0b28662009-11-17 06:07:40 +00002126 return Inst;
2127}
2128
John McCallb96ec562009-12-04 22:46:56 +00002129Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002130
2131 // The nested name specifier may be dependent, for example
2132 // template <typename T> struct t {
2133 // struct s1 { T f1(); };
2134 // struct s2 : s1 { using s1::f1; };
2135 // };
2136 // template struct t<int>;
2137 // Here, in using s1::f1, s1 refers to t<T>::s1;
2138 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002139 NestedNameSpecifierLoc QualifierLoc
2140 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2141 TemplateArgs);
2142 if (!QualifierLoc)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00002143 return 0;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002144
2145 // The name info is non-dependent, so no transformation
2146 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002147 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002148
John McCall84d87672009-12-10 09:41:52 +00002149 // We only need to do redeclaration lookups if we're in a class
2150 // scope (in fact, it's not really even possible in non-class
2151 // scopes).
2152 bool CheckRedeclaration = Owner->isRecord();
2153
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002154 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2155 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002156
John McCallb96ec562009-12-04 22:46:56 +00002157 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002158 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002159 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002160 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002161 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002162
Douglas Gregor0499ab62011-02-25 15:54:31 +00002163 CXXScopeSpec SS;
2164 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002165 if (CheckRedeclaration) {
2166 Prev.setHideTags(false);
2167 SemaRef.LookupQualifiedName(Prev, Owner);
2168
2169 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002170 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2171 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002172 D->getLocation(), Prev))
2173 NewUD->setInvalidDecl();
2174
2175 }
2176
2177 if (!NewUD->isInvalidDecl() &&
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002178 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCallb96ec562009-12-04 22:46:56 +00002179 D->getLocation()))
2180 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002181
John McCallb96ec562009-12-04 22:46:56 +00002182 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2183 NewUD->setAccess(D->getAccess());
2184 Owner->addDecl(NewUD);
2185
John McCall84d87672009-12-10 09:41:52 +00002186 // Don't process the shadow decls for an invalid decl.
2187 if (NewUD->isInvalidDecl())
2188 return NewUD;
2189
Richard Smith23d55872012-04-02 01:30:27 +00002190 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2191 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2192 NewUD->setInvalidDecl();
2193 return NewUD;
2194 }
2195
John McCalla1d85502009-12-22 22:26:37 +00002196 bool isFunctionScope = Owner->isFunctionOrMethod();
2197
John McCall84d87672009-12-10 09:41:52 +00002198 // Process the shadow decls.
2199 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2200 I != E; ++I) {
2201 UsingShadowDecl *Shadow = *I;
2202 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002203 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2204 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002205 if (!InstTarget)
2206 return 0;
John McCall84d87672009-12-10 09:41:52 +00002207
Richard Smithfd8634a2013-10-23 02:17:46 +00002208 UsingShadowDecl *PrevDecl = 0;
2209 if (CheckRedeclaration) {
2210 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2211 continue;
2212 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2213 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2214 Shadow->getLocation(), OldPrev, TemplateArgs));
2215 }
John McCall84d87672009-12-10 09:41:52 +00002216
Richard Smithfd8634a2013-10-23 02:17:46 +00002217 UsingShadowDecl *InstShadow =
2218 SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002219 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002220
2221 if (isFunctionScope)
2222 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002223 }
John McCallb96ec562009-12-04 22:46:56 +00002224
2225 return NewUD;
2226}
2227
2228Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002229 // Ignore these; we handle them in bulk when processing the UsingDecl.
2230 return 0;
John McCallb96ec562009-12-04 22:46:56 +00002231}
2232
John McCalle61f2ba2009-11-18 02:36:19 +00002233Decl * TemplateDeclInstantiator
2234 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002235 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002236 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002237 TemplateArgs);
2238 if (!QualifierLoc)
Anders Carlsson4bd78752009-08-28 15:18:15 +00002239 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002240
Anders Carlsson4bd78752009-08-28 15:18:15 +00002241 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002242 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002243
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002244 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002245 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002246 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002247 NamedDecl *UD =
John McCall3f746822009-11-17 05:59:44 +00002248 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002249 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002250 /*instantiation*/ true,
2251 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002252 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002253 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2254
John McCalle61f2ba2009-11-18 02:36:19 +00002255 return UD;
2256}
2257
2258Decl * TemplateDeclInstantiator
2259 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002260 NestedNameSpecifierLoc QualifierLoc
2261 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2262 if (!QualifierLoc)
John McCalle61f2ba2009-11-18 02:36:19 +00002263 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002264
John McCalle61f2ba2009-11-18 02:36:19 +00002265 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002266 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002267
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002268 DeclarationNameInfo NameInfo
2269 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2270
John McCalle61f2ba2009-11-18 02:36:19 +00002271 NamedDecl *UD =
2272 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002273 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002274 /*instantiation*/ true,
2275 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002276 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002277 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2278
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002279 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002280}
2281
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002282
2283Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2284 ClassScopeFunctionSpecializationDecl *Decl) {
2285 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002286 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2287 0, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002288
2289 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2290 Sema::ForRedeclaration);
2291
Nico Weber7b5a7162012-06-25 17:21:05 +00002292 TemplateArgumentListInfo TemplateArgs;
2293 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2294 if (Decl->hasExplicitTemplateArgs()) {
2295 TemplateArgs = Decl->templateArgs();
2296 TemplateArgsPtr = &TemplateArgs;
2297 }
2298
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002299 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002300 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2301 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002302 NewFD->setInvalidDecl();
2303 return NewFD;
2304 }
2305
2306 // Associate the specialization with the pattern.
2307 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2308 assert(Specialization && "Class scope Specialization is null");
2309 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2310
2311 return NewFD;
2312}
2313
Alexey Bataeva769e072013-03-22 06:34:35 +00002314Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2315 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002316 SmallVector<Expr *, 5> Vars;
2317 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2318 E = D->varlist_end();
Alexey Bataeva769e072013-03-22 06:34:35 +00002319 I != E; ++I) {
2320 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2321 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002322 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002323 }
2324
2325 OMPThreadPrivateDecl *TD =
2326 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2327
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002328 TD->setAccess(AS_public);
2329 Owner->addDecl(TD);
2330
Alexey Bataeva769e072013-03-22 06:34:35 +00002331 return TD;
2332}
2333
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002334Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2335 return VisitFunctionDecl(D, 0);
2336}
2337
2338Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2339 return VisitCXXMethodDecl(D, 0);
2340}
2341
2342Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2343 llvm_unreachable("There are only CXXRecordDecls in C++");
2344}
2345
2346Decl *
2347TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2348 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002349 // As a MS extension, we permit class-scope explicit specialization
2350 // of member class templates.
2351 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2352 assert(ClassTemplate->getDeclContext()->isRecord() &&
2353 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2354 "can only instantiate an explicit specialization "
2355 "for a member class template");
2356
2357 // Lookup the already-instantiated declaration in the instantiation
2358 // of the class template. FIXME: Diagnose or assert if this fails?
2359 DeclContext::lookup_result Found
2360 = Owner->lookup(ClassTemplate->getDeclName());
2361 if (Found.empty())
2362 return 0;
2363 ClassTemplateDecl *InstClassTemplate
2364 = dyn_cast<ClassTemplateDecl>(Found.front());
2365 if (!InstClassTemplate)
2366 return 0;
2367
2368 // Substitute into the template arguments of the class template explicit
2369 // specialization.
2370 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2371 castAs<TemplateSpecializationTypeLoc>();
2372 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2373 Loc.getRAngleLoc());
2374 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2375 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2376 ArgLocs.push_back(Loc.getArgLoc(I));
2377 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2378 InstTemplateArgs, TemplateArgs))
2379 return 0;
2380
2381 // Check that the template argument list is well-formed for this
2382 // class template.
2383 SmallVector<TemplateArgument, 4> Converted;
2384 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2385 D->getLocation(),
2386 InstTemplateArgs,
2387 false,
2388 Converted))
2389 return 0;
2390
2391 // Figure out where to insert this class template explicit specialization
2392 // in the member template's set of class template explicit specializations.
2393 void *InsertPos = 0;
2394 ClassTemplateSpecializationDecl *PrevDecl =
2395 InstClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2396 InsertPos);
2397
2398 // Check whether we've already seen a conflicting instantiation of this
2399 // declaration (for instance, if there was a prior implicit instantiation).
2400 bool Ignored;
2401 if (PrevDecl &&
2402 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2403 D->getSpecializationKind(),
2404 PrevDecl,
2405 PrevDecl->getSpecializationKind(),
2406 PrevDecl->getPointOfInstantiation(),
2407 Ignored))
2408 return 0;
2409
2410 // If PrevDecl was a definition and D is also a definition, diagnose.
2411 // This happens in cases like:
2412 //
2413 // template<typename T, typename U>
2414 // struct Outer {
2415 // template<typename X> struct Inner;
2416 // template<> struct Inner<T> {};
2417 // template<> struct Inner<U> {};
2418 // };
2419 //
2420 // Outer<int, int> outer; // error: the explicit specializations of Inner
2421 // // have the same signature.
2422 if (PrevDecl && PrevDecl->getDefinition() &&
2423 D->isThisDeclarationADefinition()) {
2424 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2425 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2426 diag::note_previous_definition);
2427 return 0;
2428 }
2429
2430 // Create the class template partial specialization declaration.
2431 ClassTemplateSpecializationDecl *InstD
2432 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2433 D->getTagKind(),
2434 Owner,
2435 D->getLocStart(),
2436 D->getLocation(),
2437 InstClassTemplate,
2438 Converted.data(),
2439 Converted.size(),
2440 PrevDecl);
2441
2442 // Add this partial specialization to the set of class template partial
2443 // specializations.
2444 if (!PrevDecl)
2445 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2446
2447 // Substitute the nested name specifier, if any.
2448 if (SubstQualifier(D, InstD))
2449 return 0;
2450
2451 // Build the canonical type that describes the converted template
2452 // arguments of the class template explicit specialization.
2453 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2454 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2455 SemaRef.Context.getRecordType(InstD));
2456
2457 // Build the fully-sugared type for this class template
2458 // specialization as the user wrote in the specialization
2459 // itself. This means that we'll pretty-print the type retrieved
2460 // from the specialization's declaration the way that the user
2461 // actually wrote the specialization, rather than formatting the
2462 // name based on the "canonical" representation used to store the
2463 // template arguments in the specialization.
2464 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2465 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2466 CanonType);
2467
2468 InstD->setAccess(D->getAccess());
2469 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2470 InstD->setSpecializationKind(D->getSpecializationKind());
2471 InstD->setTypeAsWritten(WrittenTy);
2472 InstD->setExternLoc(D->getExternLoc());
2473 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2474
2475 Owner->addDecl(InstD);
2476
2477 // Instantiate the members of the class-scope explicit specialization eagerly.
2478 // We don't have support for lazy instantiation of an explicit specialization
2479 // yet, and MSVC eagerly instantiates in this case.
2480 if (D->isThisDeclarationADefinition() &&
2481 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2482 TSK_ImplicitInstantiation,
2483 /*Complain=*/true))
2484 return 0;
2485
2486 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002487}
2488
Larisse Voufo39a1e502013-08-06 01:03:05 +00002489Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2490 VarTemplateSpecializationDecl *D) {
2491
2492 TemplateArgumentListInfo VarTemplateArgsInfo;
2493 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2494 assert(VarTemplate &&
2495 "A template specialization without specialized template?");
2496
2497 // Substitute the current template arguments.
2498 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2499 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2500 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2501
2502 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2503 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2504 return 0;
2505
2506 // Check that the template argument list is well-formed for this template.
2507 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002508 if (SemaRef.CheckTemplateArgumentList(
2509 VarTemplate, VarTemplate->getLocStart(),
2510 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002511 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002512 return 0;
2513
2514 // Find the variable template specialization declaration that
2515 // corresponds to these arguments.
2516 void *InsertPos = 0;
2517 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2518 Converted.data(), Converted.size(), InsertPos))
2519 // If we already have a variable template specialization, return it.
2520 return VarSpec;
2521
2522 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2523 VarTemplateArgsInfo, Converted);
2524}
2525
2526Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2527 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2528 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smith8809a0c2013-09-27 20:14:12 +00002529 llvm::ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002530
2531 // If this is the variable for an anonymous struct or union,
2532 // instantiate the anonymous struct/union type first.
2533 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2534 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2535 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2536 return 0;
2537
2538 // Do substitution on the type of the declaration
2539 TypeSourceInfo *DI =
2540 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2541 D->getTypeSpecStartLoc(), D->getDeclName());
2542 if (!DI)
2543 return 0;
2544
2545 if (DI->getType()->isFunctionType()) {
2546 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2547 << D->isStaticDataMember() << DI->getType();
2548 return 0;
2549 }
2550
2551 // Build the instantiated declaration
2552 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2553 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2554 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2555 Converted.size());
2556 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002557 if (InsertPos)
2558 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002559
2560 // Substitute the nested name specifier, if any.
2561 if (SubstQualifier(D, Var))
2562 return 0;
2563
2564 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002565 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002566
2567 return Var;
2568}
2569
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002570Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2571 llvm_unreachable("@defs is not supported in Objective-C++");
2572}
2573
2574Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2575 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2576 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2577 DiagnosticsEngine::Error,
2578 "cannot instantiate %0 yet");
2579 SemaRef.Diag(D->getLocation(), DiagID)
2580 << D->getDeclKindName();
2581
2582 return 0;
2583}
2584
2585Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2586 llvm_unreachable("Unexpected decl");
2587}
2588
John McCall76d824f2009-08-25 22:02:44 +00002589Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002590 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002591 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002592 if (D->isInvalidDecl())
2593 return 0;
2594
Douglas Gregord7e7a512009-03-17 21:15:40 +00002595 return Instantiator.Visit(D);
2596}
2597
John McCall87a44eb2009-08-20 01:44:21 +00002598/// \brief Instantiates a nested template parameter list in the current
2599/// instantiation context.
2600///
2601/// \param L The parameter list to instantiate
2602///
2603/// \returns NULL if there was an error
2604TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002605TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002606 // Get errors for all the parameters before bailing out.
2607 bool Invalid = false;
2608
2609 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002610 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002611 ParamVector Params;
2612 Params.reserve(N);
2613 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2614 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002615 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002616 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002617 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002618 }
2619
2620 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002621 if (Invalid)
John McCall87a44eb2009-08-20 01:44:21 +00002622 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +00002623
2624 TemplateParameterList *InstL
2625 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2626 L->getLAngleLoc(), &Params.front(), N,
2627 L->getRAngleLoc());
2628 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002629}
John McCall87a44eb2009-08-20 01:44:21 +00002630
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002631/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002632/// specialization.
2633///
2634/// \param ClassTemplate the (instantiated) class template that is partially
2635// specialized by the instantiation of \p PartialSpec.
2636///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002637/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002638/// specialization that we are instantiating.
2639///
Douglas Gregor869853e2010-11-10 19:44:59 +00002640/// \returns The instantiated partial specialization, if successful; otherwise,
2641/// NULL to indicate an error.
2642ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002643TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2644 ClassTemplateDecl *ClassTemplate,
2645 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002646 // Create a local instantiation scope for this class template partial
2647 // specialization, which will contain the instantiations of the template
2648 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002649 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002650
Douglas Gregor21610382009-10-29 00:04:11 +00002651 // Substitute into the template parameters of the class template partial
2652 // specialization.
2653 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2654 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2655 if (!InstParams)
Douglas Gregor869853e2010-11-10 19:44:59 +00002656 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002657
Douglas Gregor21610382009-10-29 00:04:11 +00002658 // Substitute into the template arguments of the class template partial
2659 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002660 const ASTTemplateArgumentListInfo *TemplArgInfo
2661 = PartialSpec->getTemplateArgsAsWritten();
2662 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2663 TemplArgInfo->RAngleLoc);
2664 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2665 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002666 InstTemplateArgs, TemplateArgs))
2667 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002668
Douglas Gregor21610382009-10-29 00:04:11 +00002669 // Check that the template argument list is well-formed for this
2670 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002671 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002672 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002673 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002674 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002675 false,
2676 Converted))
Douglas Gregor869853e2010-11-10 19:44:59 +00002677 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002678
2679 // Figure out where to insert this class template partial specialization
2680 // in the member template's set of class template partial specializations.
Douglas Gregor21610382009-10-29 00:04:11 +00002681 void *InsertPos = 0;
2682 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002683 = ClassTemplate->findPartialSpecialization(Converted.data(),
2684 Converted.size(), InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002685
Douglas Gregor21610382009-10-29 00:04:11 +00002686 // Build the canonical type that describes the converted template
2687 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002688 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002689 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002690 Converted.data(),
2691 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002692
2693 // Build the fully-sugared type for this class template
2694 // specialization as the user wrote in the specialization
2695 // itself. This means that we'll pretty-print the type retrieved
2696 // from the specialization's declaration the way that the user
2697 // actually wrote the specialization, rather than formatting the
2698 // name based on the "canonical" representation used to store the
2699 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002700 TypeSourceInfo *WrittenTy
2701 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2702 TemplateName(ClassTemplate),
2703 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002704 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002705 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002706
Douglas Gregor21610382009-10-29 00:04:11 +00002707 if (PrevDecl) {
2708 // We've already seen a partial specialization with the same template
2709 // parameters and template arguments. This can happen, for example, when
2710 // substituting the outer template arguments ends up causing two
2711 // class template partial specializations of a member class template
2712 // to have identical forms, e.g.,
2713 //
2714 // template<typename T, typename U>
2715 // struct Outer {
2716 // template<typename X, typename Y> struct Inner;
2717 // template<typename Y> struct Inner<T, Y>;
2718 // template<typename Y> struct Inner<U, Y>;
2719 // };
2720 //
2721 // Outer<int, int> outer; // error: the partial specializations of Inner
2722 // // have the same signature.
2723 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002724 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002725 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2726 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregor869853e2010-11-10 19:44:59 +00002727 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002728 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002729
2730
Douglas Gregor21610382009-10-29 00:04:11 +00002731 // Create the class template partial specialization declaration.
2732 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002733 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002734 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002735 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002736 PartialSpec->getLocStart(),
2737 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002738 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002739 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002740 Converted.data(),
2741 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002742 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002743 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00002744 0);
John McCall3e11ebe2010-03-15 10:12:16 +00002745 // Substitute the nested name specifier, if any.
2746 if (SubstQualifier(PartialSpec, InstPartialSpec))
2747 return 0;
2748
Douglas Gregor21610382009-10-29 00:04:11 +00002749 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002750 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002751
Douglas Gregor21610382009-10-29 00:04:11 +00002752 // Add this partial specialization to the set of class template partial
2753 // specializations.
Douglas Gregorce9978f2012-03-28 14:34:23 +00002754 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregor869853e2010-11-10 19:44:59 +00002755 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002756}
2757
Larisse Voufo39a1e502013-08-06 01:03:05 +00002758/// \brief Instantiate the declaration of a variable template partial
2759/// specialization.
2760///
2761/// \param VarTemplate the (instantiated) variable template that is partially
2762/// specialized by the instantiation of \p PartialSpec.
2763///
2764/// \param PartialSpec the (uninstantiated) variable template partial
2765/// specialization that we are instantiating.
2766///
2767/// \returns The instantiated partial specialization, if successful; otherwise,
2768/// NULL to indicate an error.
2769VarTemplatePartialSpecializationDecl *
2770TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2771 VarTemplateDecl *VarTemplate,
2772 VarTemplatePartialSpecializationDecl *PartialSpec) {
2773 // Create a local instantiation scope for this variable template partial
2774 // specialization, which will contain the instantiations of the template
2775 // parameters.
2776 LocalInstantiationScope Scope(SemaRef);
2777
2778 // Substitute into the template parameters of the variable template partial
2779 // specialization.
2780 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2781 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2782 if (!InstParams)
2783 return 0;
2784
2785 // Substitute into the template arguments of the variable template partial
2786 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002787 const ASTTemplateArgumentListInfo *TemplArgInfo
2788 = PartialSpec->getTemplateArgsAsWritten();
2789 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2790 TemplArgInfo->RAngleLoc);
2791 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2792 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002793 InstTemplateArgs, TemplateArgs))
2794 return 0;
2795
2796 // Check that the template argument list is well-formed for this
2797 // class template.
2798 SmallVector<TemplateArgument, 4> Converted;
2799 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2800 InstTemplateArgs, false, Converted))
2801 return 0;
2802
2803 // Figure out where to insert this variable template partial specialization
2804 // in the member template's set of variable template partial specializations.
2805 void *InsertPos = 0;
2806 VarTemplateSpecializationDecl *PrevDecl =
2807 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2808 InsertPos);
2809
2810 // Build the canonical type that describes the converted template
2811 // arguments of the variable template partial specialization.
2812 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2813 TemplateName(VarTemplate), Converted.data(), Converted.size());
2814
2815 // Build the fully-sugared type for this variable template
2816 // specialization as the user wrote in the specialization
2817 // itself. This means that we'll pretty-print the type retrieved
2818 // from the specialization's declaration the way that the user
2819 // actually wrote the specialization, rather than formatting the
2820 // name based on the "canonical" representation used to store the
2821 // template arguments in the specialization.
2822 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2823 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2824 CanonType);
2825
2826 if (PrevDecl) {
2827 // We've already seen a partial specialization with the same template
2828 // parameters and template arguments. This can happen, for example, when
2829 // substituting the outer template arguments ends up causing two
2830 // variable template partial specializations of a member variable template
2831 // to have identical forms, e.g.,
2832 //
2833 // template<typename T, typename U>
2834 // struct Outer {
2835 // template<typename X, typename Y> pair<X,Y> p;
2836 // template<typename Y> pair<T, Y> p;
2837 // template<typename Y> pair<U, Y> p;
2838 // };
2839 //
2840 // Outer<int, int> outer; // error: the partial specializations of Inner
2841 // // have the same signature.
2842 SemaRef.Diag(PartialSpec->getLocation(),
2843 diag::err_var_partial_spec_redeclared)
2844 << WrittenTy->getType();
2845 SemaRef.Diag(PrevDecl->getLocation(),
2846 diag::note_var_prev_partial_spec_here);
2847 return 0;
2848 }
2849
2850 // Do substitution on the type of the declaration
2851 TypeSourceInfo *DI = SemaRef.SubstType(
2852 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2853 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2854 if (!DI)
2855 return 0;
2856
2857 if (DI->getType()->isFunctionType()) {
2858 SemaRef.Diag(PartialSpec->getLocation(),
2859 diag::err_variable_instantiates_to_function)
2860 << PartialSpec->isStaticDataMember() << DI->getType();
2861 return 0;
2862 }
2863
2864 // Create the variable template partial specialization declaration.
2865 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2866 VarTemplatePartialSpecializationDecl::Create(
2867 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2868 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2869 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002870 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002871
2872 // Substitute the nested name specifier, if any.
2873 if (SubstQualifier(PartialSpec, InstPartialSpec))
2874 return 0;
2875
2876 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2877 InstPartialSpec->setTypeAsWritten(WrittenTy);
2878
Larisse Voufo39a1e502013-08-06 01:03:05 +00002879 // Add this partial specialization to the set of variable template partial
2880 // specializations. The instantiation of the initializer is not necessary.
2881 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002882
Larisse Voufo4cda4612013-08-22 00:28:27 +00002883 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002884 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002885
Larisse Voufo39a1e502013-08-06 01:03:05 +00002886 return InstPartialSpec;
2887}
2888
John McCall58f10c32010-03-11 09:03:00 +00002889TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002890TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002891 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002892 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2893 assert(OldTInfo && "substituting function without type source info");
2894 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregor3024f072012-04-16 07:05:22 +00002895
2896 CXXRecordDecl *ThisContext = 0;
2897 unsigned ThisTypeQuals = 0;
2898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002899 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002900 ThisTypeQuals = Method->getTypeQualifiers();
2901 }
2902
John McCallb29f78f2010-04-09 17:38:44 +00002903 TypeSourceInfo *NewTInfo
2904 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2905 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002906 D->getDeclName(),
2907 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002908 if (!NewTInfo)
2909 return 0;
Douglas Gregor21342092009-03-24 00:38:23 +00002910
Reid Klecknera09e44c2013-07-31 21:00:18 +00002911 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2912 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2913 if (NewTInfo != OldTInfo) {
2914 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002915 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002916 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002917 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002918 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00002919 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002920 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002921 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2922
David Blaikie05785d12013-02-20 22:23:23 +00002923 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002924 if (OldParam->isParameterPack())
2925 NumArgumentsInExpansion =
2926 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2927 TemplateArgs);
2928 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002929 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002930 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002931 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002932 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002933 Scope->InstantiatedLocal(OldParam, NewParam);
2934 } else {
2935 // Parameter pack expansion: make the instantiation an argument pack.
2936 Scope->MakeInstantiatedLocalArgPack(OldParam);
2937 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002938 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002939 Params.push_back(NewParam);
2940 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2941 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002942 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002943 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002944 } else {
2945 // The function type itself was not dependent and therefore no
2946 // substitution occurred. However, we still need to instantiate
2947 // the function parameters themselves.
2948 const FunctionProtoType *OldProto =
2949 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002950 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
2951 ++i) {
2952 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00002953 if (!OldParam) {
2954 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00002955 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00002956 continue;
2957 }
2958
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002959 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002960 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002961 if (!Parm)
2962 return 0;
2963 Params.push_back(Parm);
2964 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002965 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002966 } else {
2967 // If the type of this function, after ignoring parentheses, is not
2968 // *directly* a function type, then we're instantiating a function that
2969 // was declared via a typedef or with attributes, e.g.,
2970 //
2971 // typedef int functype(int, int);
2972 // functype func;
2973 // int __cdecl meth(int, int);
2974 //
2975 // In this case, we'll just go instantiate the ParmVarDecls that we
2976 // synthesized in the method declaration.
2977 SmallVector<QualType, 4> ParamTypes;
2978 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2979 D->getNumParams(), TemplateArgs, ParamTypes,
2980 &Params))
2981 return 0;
Douglas Gregor940bca72010-04-12 07:48:19 +00002982 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002983
John McCall58f10c32010-03-11 09:03:00 +00002984 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002985}
2986
Richard Smithf623c962012-04-17 00:58:00 +00002987/// Introduce the instantiated function parameters into the local
2988/// instantiation scope, and set the parameter names to those used
2989/// in the template.
2990static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2991 const FunctionDecl *PatternDecl,
2992 LocalInstantiationScope &Scope,
2993 const MultiLevelTemplateArgumentList &TemplateArgs) {
2994 unsigned FParamIdx = 0;
2995 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2996 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2997 if (!PatternParam->isParameterPack()) {
2998 // Simple case: not a parameter pack.
2999 assert(FParamIdx < Function->getNumParams());
3000 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3001 FunctionParam->setDeclName(PatternParam->getDeclName());
3002 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3003 ++FParamIdx;
3004 continue;
3005 }
3006
3007 // Expand the parameter pack.
3008 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003009 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003010 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003011 assert(NumArgumentsInExpansion &&
3012 "should only be called when all template arguments are known");
3013 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003014 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
3015 FunctionParam->setDeclName(PatternParam->getDeclName());
3016 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3017 ++FParamIdx;
3018 }
3019 }
3020}
3021
3022static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
3023 const FunctionProtoType *Proto,
3024 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00003025 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
3026
Richard Smithf623c962012-04-17 00:58:00 +00003027 // C++11 [expr.prim.general]p3:
3028 // If a declaration declares a member function or member function
3029 // template of a class X, the expression this is a prvalue of type
3030 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3031 // and the end of the function-definition, member-declarator, or
3032 // declarator.
3033 CXXRecordDecl *ThisContext = 0;
3034 unsigned ThisTypeQuals = 0;
3035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3036 ThisContext = Method->getParent();
3037 ThisTypeQuals = Method->getTypeQualifiers();
3038 }
3039 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003040 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00003041
3042 // The function has an exception specification or a "noreturn"
3043 // attribute. Substitute into each of the exception types.
3044 SmallVector<QualType, 4> Exceptions;
3045 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3046 // FIXME: Poor location information!
3047 if (const PackExpansionType *PackExpansion
3048 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3049 // We have a pack expansion. Instantiate it.
3050 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3051 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3052 Unexpanded);
3053 assert(!Unexpanded.empty() &&
3054 "Pack expansion without parameter packs?");
3055
3056 bool Expand = false;
3057 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003058 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00003059 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3060 SourceRange(),
3061 Unexpanded,
3062 TemplateArgs,
3063 Expand,
3064 RetainExpansion,
3065 NumExpansions))
3066 break;
3067
3068 if (!Expand) {
3069 // We can't expand this pack expansion into separate arguments yet;
3070 // just substitute into the pattern and create a new pack expansion
3071 // type.
3072 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3073 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3074 TemplateArgs,
3075 New->getLocation(), New->getDeclName());
3076 if (T.isNull())
3077 break;
3078
3079 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3080 Exceptions.push_back(T);
3081 continue;
3082 }
3083
3084 // Substitute into the pack expansion pattern for each template
3085 bool Invalid = false;
3086 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3087 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3088
3089 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3090 TemplateArgs,
3091 New->getLocation(), New->getDeclName());
3092 if (T.isNull()) {
3093 Invalid = true;
3094 break;
3095 }
3096
3097 Exceptions.push_back(T);
3098 }
3099
3100 if (Invalid)
3101 break;
3102
3103 continue;
3104 }
3105
3106 QualType T
3107 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3108 New->getLocation(), New->getDeclName());
3109 if (T.isNull() ||
3110 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3111 continue;
3112
3113 Exceptions.push_back(T);
3114 }
3115 Expr *NoexceptExpr = 0;
3116 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3117 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3118 Sema::ConstantEvaluated);
3119 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3120 if (E.isUsable())
3121 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3122
3123 if (E.isUsable()) {
3124 NoexceptExpr = E.take();
3125 if (!NoexceptExpr->isTypeDependent() &&
3126 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00003127 NoexceptExpr
3128 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
3129 0, diag::err_noexcept_needs_constant_expression,
3130 /*AllowFold*/ false).take();
Richard Smithf623c962012-04-17 00:58:00 +00003131 }
3132 }
3133
3134 // Rebuild the function type
3135 const FunctionProtoType *NewProto
3136 = New->getType()->getAs<FunctionProtoType>();
3137 assert(NewProto && "Template instantiation without function prototype?");
3138
3139 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
3140 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
3141 EPI.NumExceptions = Exceptions.size();
3142 EPI.Exceptions = Exceptions.data();
3143 EPI.NoexceptExpr = NoexceptExpr;
3144
Alp Toker314cc812014-01-25 16:55:45 +00003145 New->setType(SemaRef.Context.getFunctionType(NewProto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00003146 NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003147}
3148
3149void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3150 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003151 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3152 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003153 return;
3154
3155 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3156 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003157 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003158 // We hit the instantiation depth limit. Clear the exception specification
3159 // so that our callers don't have to cope with EST_Uninstantiated.
3160 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3161 EPI.ExceptionSpecType = EST_None;
Alp Toker314cc812014-01-25 16:55:45 +00003162 Decl->setType(Context.getFunctionType(Proto->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00003163 Proto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003164 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003165 }
Richard Smithf623c962012-04-17 00:58:00 +00003166
3167 // Enter the scope of this instantiation. We don't use
3168 // PushDeclContext because we don't have a scope.
3169 Sema::ContextRAII savedContext(*this, Decl);
3170 LocalInstantiationScope Scope(*this);
3171
3172 MultiLevelTemplateArgumentList TemplateArgs =
3173 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
3174
Richard Smithd3729422012-04-19 00:08:28 +00003175 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3176 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003177
Richard Smithd3729422012-04-19 00:08:28 +00003178 ::InstantiateExceptionSpec(*this, Decl,
3179 Template->getType()->castAs<FunctionProtoType>(),
3180 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003181}
3182
Mike Stump11289f42009-09-09 15:08:12 +00003183/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003184/// declaration (New) from the corresponding fields of its template (Tmpl).
3185///
3186/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003187bool
3188TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003189 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003190 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003191 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003192
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003193 // Forward the mangling number from the template to the instantiated decl.
3194 SemaRef.Context.setManglingNumber(New,
3195 SemaRef.Context.getManglingNumber(Tmpl));
3196
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003197 // If we are performing substituting explicitly-specified template arguments
3198 // or deduced template arguments into a function template and we reach this
3199 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003200 // to keeping the new function template specialization. We therefore
3201 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003202 // into a template instantiation for this specific function template
3203 // specialization, which is not a SFINAE context, so that we diagnose any
3204 // further errors in the declaration itself.
3205 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3206 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3207 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3208 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003209 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003210 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003211 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003212 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003213 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003214 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003215 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003216 }
3217 }
Mike Stump11289f42009-09-09 15:08:12 +00003218
Douglas Gregor049bdca2009-12-08 17:45:32 +00003219 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3220 assert(Proto && "Function template without prototype?");
3221
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003222 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003223 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003224
Richard Smithf623c962012-04-17 00:58:00 +00003225 // DR1330: In C++11, defer instantiation of a non-trivial
3226 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003227 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithf623c962012-04-17 00:58:00 +00003228 EPI.ExceptionSpecType != EST_None &&
3229 EPI.ExceptionSpecType != EST_DynamicNone &&
3230 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003231 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3232 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3233 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003234 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3235 if (EPI.ExceptionSpecType == EST_Unevaluated)
3236 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003237
Richard Smithf623c962012-04-17 00:58:00 +00003238 // Mark the function has having an uninstantiated exception specification.
3239 const FunctionProtoType *NewProto
3240 = New->getType()->getAs<FunctionProtoType>();
3241 assert(NewProto && "Template instantiation without function prototype?");
3242 EPI = NewProto->getExtProtoInfo();
Richard Smith185be182013-04-10 05:48:59 +00003243 EPI.ExceptionSpecType = NewEST;
Richard Smithf623c962012-04-17 00:58:00 +00003244 EPI.ExceptionSpecDecl = New;
Richard Smithd3729422012-04-19 00:08:28 +00003245 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003246 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003247 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003248 } else {
3249 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3250 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003251 }
3252
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003253 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003254 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003255 Tmpl->isDefined(Definition);
3256
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003257 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3258 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003259
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003260 return false;
3261}
3262
Douglas Gregor21342092009-03-24 00:38:23 +00003263/// \brief Initializes common fields of an instantiated method
3264/// declaration (New) from the corresponding fields of its template
3265/// (Tmpl).
3266///
3267/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003268bool
3269TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003270 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003271 if (InitFunctionInstantiation(New, Tmpl))
3272 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003273
Douglas Gregor21342092009-03-24 00:38:23 +00003274 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003275 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003276 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003277
Douglas Gregor21342092009-03-24 00:38:23 +00003278 // FIXME: New needs a pointer to Tmpl
3279 return false;
3280}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003281
3282/// \brief Instantiate the definition of the given function from its
3283/// template.
3284///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003285/// \param PointOfInstantiation the point at which the instantiation was
3286/// required. Note that this is not precisely a "point of instantiation"
3287/// for the function, but it's close.
3288///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003289/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003290/// function template specialization or member function of a class template
3291/// specialization.
3292///
3293/// \param Recursive if true, recursively instantiates any functions that
3294/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003295///
3296/// \param DefinitionRequired if true, then we are performing an explicit
3297/// instantiation where the body of the function is required. Complain if
3298/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003299void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003300 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003301 bool Recursive,
3302 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003303 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003304 return;
3305
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003306 // Never instantiate an explicit specialization except if it is a class scope
3307 // explicit specialization.
3308 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3309 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003310 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003311
Douglas Gregor24c332b2009-05-14 21:06:31 +00003312 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003313 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003314 assert(PatternDecl && "instantiating a non-template");
3315
3316 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3317 assert(PatternDecl && "template definition is not a template");
3318 if (!Pattern) {
3319 // Try to find a defaulted definition
3320 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003321 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003322 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003323
Francois Pichet1c229c02011-04-22 22:18:13 +00003324 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003325 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003326 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003327 PendingInstantiations.push_back(
3328 std::make_pair(Function, PointOfInstantiation));
3329 return;
3330 }
3331
David Majnemerf0a84f22013-08-16 08:29:13 +00003332 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003333 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003334 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003335 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003336 // FIXME: Optimize to allow individual templates to be deserialized.
3337 if (PatternDecl->isFromASTFile())
3338 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3339
3340 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3341 assert(LPT && "missing LateParsedTemplate");
3342 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003343 Pattern = PatternDecl->getBody(PatternDecl);
3344 }
3345
Alexis Hunt23f6b832011-05-27 20:00:14 +00003346 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003347 if (DefinitionRequired) {
3348 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003349 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003350 diag::err_explicit_instantiation_undefined_func_template)
3351 << Function->getPrimaryTemplate();
3352 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003353 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003354 diag::err_explicit_instantiation_undefined_member)
3355 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003356
Douglas Gregora8b89d22009-10-15 14:05:49 +00003357 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003358 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003359 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003360 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003361 } else if (Function->getTemplateSpecializationKind()
3362 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003363 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003364 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003365 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003366
Douglas Gregor24c332b2009-05-14 21:06:31 +00003367 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003368 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003369
Richard Smith2a7d4812013-05-04 07:00:32 +00003370 // C++1y [temp.explicit]p10:
3371 // Except for inline functions, declarations with types deduced from their
3372 // initializer or return value, and class template specializations, other
3373 // explicit instantiation declarations have the effect of suppressing the
3374 // implicit instantiation of the entity to which they refer.
Alp Toker314cc812014-01-25 16:55:45 +00003375 if (Function->getTemplateSpecializationKind() ==
3376 TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003377 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003378 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003379 return;
Mike Stump11289f42009-09-09 15:08:12 +00003380
Richard Smithf3814ad2013-01-25 00:08:28 +00003381 if (PatternDecl->isInlined())
3382 Function->setImplicitlyInline();
3383
Douglas Gregor85673582009-05-18 17:01:57 +00003384 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003385 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003386 return;
3387
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003388 // Copy the inner loc start from the pattern.
3389 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3390
Douglas Gregordda7ced2009-06-30 17:20:14 +00003391 // If we're performing recursive template instantiation, create our own
3392 // queue of pending implicit instantiations that we will instantiate later,
3393 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003394 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003395 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003396 SavePendingLocalImplicitInstantiationsRAII
3397 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003398 if (Recursive) {
3399 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003400 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003403 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003404 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003405
Douglas Gregorb4850462009-05-14 23:26:13 +00003406 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003407 // recorded, unless we're actually a member function within a local
3408 // class, in which case we need to merge our results with the parent
3409 // scope (of the enclosing function).
3410 bool MergeWithParentScope = false;
3411 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3412 MergeWithParentScope = Rec->isLocalClass();
3413
3414 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003415
Richard Smithbd305122012-12-11 01:14:52 +00003416 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003417 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003418 else {
3419 ActOnStartOfFunctionDef(0, Function);
3420
3421 // Enter the scope of this instantiation. We don't use
3422 // PushDeclContext because we don't have a scope.
3423 Sema::ContextRAII savedContext(*this, Function);
3424
3425 MultiLevelTemplateArgumentList TemplateArgs =
3426 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3427
3428 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3429 TemplateArgs);
3430
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003431 // If this is a constructor, instantiate the member initializers.
3432 if (const CXXConstructorDecl *Ctor =
3433 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3434 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3435 TemplateArgs);
3436 }
3437
3438 // Instantiate the function body.
3439 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3440
3441 if (Body.isInvalid())
3442 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003443
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003444 ActOnFinishFunctionBody(Function, Body.get(),
3445 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003446
3447 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3448
3449 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003450 }
3451
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003452 DeclGroupRef DG(Function);
3453 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003454
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003455 // This class may have local implicit instantiations that need to be
3456 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003457 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003458 Scope.Exit();
3459
Douglas Gregordda7ced2009-06-30 17:20:14 +00003460 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003461 // Define any pending vtables.
3462 DefineUsedVTables();
3463
Douglas Gregordda7ced2009-06-30 17:20:14 +00003464 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003465 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003466 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003467
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003468 // Restore the set of pending vtables.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003469 assert(VTableUses.empty() &&
3470 "VTableUses should be empty before it is discarded.");
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003471 VTableUses.swap(SavedVTableUses);
3472
Douglas Gregordda7ced2009-06-30 17:20:14 +00003473 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003474 assert(PendingInstantiations.empty() &&
3475 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003476 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregordda7ced2009-06-30 17:20:14 +00003477 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003478}
3479
Larisse Voufo39a1e502013-08-06 01:03:05 +00003480VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3481 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3482 const TemplateArgumentList &TemplateArgList,
3483 const TemplateArgumentListInfo &TemplateArgsInfo,
3484 SmallVectorImpl<TemplateArgument> &Converted,
3485 SourceLocation PointOfInstantiation, void *InsertPos,
3486 LateInstantiatedAttrVec *LateAttrs,
3487 LocalInstantiationScope *StartingScope) {
3488 if (FromVar->isInvalidDecl())
3489 return 0;
3490
3491 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003492 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003493 return 0;
3494
3495 MultiLevelTemplateArgumentList TemplateArgLists;
3496 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3497
Richard Smith8809a0c2013-09-27 20:14:12 +00003498 // Instantiate the first declaration of the variable template: for a partial
3499 // specialization of a static data member template, the first declaration may
3500 // or may not be the declaration in the class; if it's in the class, we want
3501 // to instantiate a member in the class (a declaration), and if it's outside,
3502 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00003503 //
3504 // If we're instantiating an explicitly-specialized member template or member
3505 // partial specialization, don't do this. The member specialization completely
3506 // replaces the original declaration in this case.
3507 bool IsMemberSpec = false;
3508 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3509 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3510 IsMemberSpec = PartialSpec->isMemberSpecialization();
3511 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3512 IsMemberSpec = FromTemplate->isMemberSpecialization();
3513 if (!IsMemberSpec)
3514 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003515
Manuel Klimek5843add2013-09-30 13:29:01 +00003516 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3517 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3518 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003519
3520 // TODO: Set LateAttrs and StartingScope ...
3521
3522 return cast_or_null<VarTemplateSpecializationDecl>(
3523 Instantiator.VisitVarTemplateSpecializationDecl(
3524 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3525}
3526
3527/// \brief Instantiates a variable template specialization by completing it
3528/// with appropriate type information and initializer.
3529VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3530 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3531 const MultiLevelTemplateArgumentList &TemplateArgs) {
3532
3533 // Do substitution on the type of the declaration
3534 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003535 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003536 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3537 if (!DI)
3538 return 0;
3539
3540 // Update the type of this variable template specialization.
3541 VarSpec->setType(DI->getType());
3542
3543 // Instantiate the initializer.
3544 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3545
3546 return VarSpec;
3547}
3548
3549/// BuildVariableInstantiation - Used after a new variable has been created.
3550/// Sets basic variable data and decides whether to postpone the
3551/// variable instantiation.
3552void Sema::BuildVariableInstantiation(
3553 VarDecl *NewVar, VarDecl *OldVar,
3554 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003555 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3556 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003557 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003558
Richard Smith541b38b2013-09-20 01:15:31 +00003559 // If we are instantiating a local extern declaration, the
3560 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003561 // If we are instantiating a static data member defined
3562 // out-of-line, the instantiation will have the same lexical
3563 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00003564 if (OldVar->isLocalExternDecl()) {
3565 NewVar->setLocalExternDecl();
3566 NewVar->setLexicalDeclContext(Owner);
3567 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003568 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3569 NewVar->setTSCSpec(OldVar->getTSCSpec());
3570 NewVar->setInitStyle(OldVar->getInitStyle());
3571 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3572 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00003573 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00003574 NewVar->setPreviousDeclInSameBlockScope(
3575 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003576 NewVar->setAccess(OldVar->getAccess());
3577
Richard Smith0b551192013-09-23 23:12:22 +00003578 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00003579 if (OldVar->isUsed(false))
3580 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003581 NewVar->setReferenced(OldVar->isReferenced());
3582 }
3583
David Majnemer50ce8352013-09-17 23:57:10 +00003584 // See if the old variable had a type-specifier that defined an anonymous tag.
3585 // If it did, mark the new variable as being the declarator for the new
3586 // anonymous tag.
3587 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3588 TagDecl *OldTag = OldTagType->getDecl();
3589 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3590 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3591 assert(!NewTag->hasNameForLinkage() &&
3592 !NewTag->hasDeclaratorForAnonDecl());
3593 NewTag->setDeclaratorForAnonDecl(NewVar);
3594 }
3595 }
3596
Larisse Voufo39a1e502013-08-06 01:03:05 +00003597 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3598
3599 if (NewVar->hasAttrs())
3600 CheckAlignasUnderalignment(NewVar);
3601
Richard Smith541b38b2013-09-20 01:15:31 +00003602 LookupResult Previous(
3603 *this, NewVar->getDeclName(), NewVar->getLocation(),
3604 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3605 : Sema::LookupOrdinaryName,
3606 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003607
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00003608 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3609 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3610 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003611 // We have a previous declaration. Use that one, so we merge with the
3612 // right type.
3613 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3614 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3615 Previous.addDecl(NewPrev);
3616 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3617 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003618 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003619 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003620
Richard Smith541b38b2013-09-20 01:15:31 +00003621 if (!InstantiatingVarTemplate) {
3622 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3623 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003624 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00003625 }
3626
3627 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003628 if (NewVar->getDeclContext()->isFunctionOrMethod())
3629 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3630 }
3631
3632 // Link instantiations of static data members back to the template from
3633 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003634 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003635 NewVar->setInstantiationOfStaticDataMember(OldVar,
3636 TSK_ImplicitInstantiation);
3637
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003638 // Forward the mangling number from the template to the instantiated decl.
3639 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00003640 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003641
Richard Smith8809a0c2013-09-27 20:14:12 +00003642 // Delay instantiation of the initializer for variable templates until a
3643 // definition of the variable is needed.
3644 if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003645 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3646
3647 // Diagnose unused local variables with dependent types, where the diagnostic
3648 // will have been deferred.
3649 if (!NewVar->isInvalidDecl() &&
3650 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3651 OldVar->getType()->isDependentType())
3652 DiagnoseUnusedDecl(NewVar);
3653}
3654
3655/// \brief Instantiate the initializer of a variable.
3656void Sema::InstantiateVariableInitializer(
3657 VarDecl *Var, VarDecl *OldVar,
3658 const MultiLevelTemplateArgumentList &TemplateArgs) {
3659
3660 if (Var->getAnyInitializer())
3661 // We already have an initializer in the class.
3662 return;
3663
3664 if (OldVar->getInit()) {
3665 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3666 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3667 else
3668 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3669
3670 // Instantiate the initializer.
3671 ExprResult Init =
3672 SubstInitializer(OldVar->getInit(), TemplateArgs,
3673 OldVar->getInitStyle() == VarDecl::CallInit);
3674 if (!Init.isInvalid()) {
3675 bool TypeMayContainAuto = true;
3676 if (Init.get()) {
3677 bool DirectInit = OldVar->isDirectInit();
3678 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3679 } else
3680 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3681 } else {
3682 // FIXME: Not too happy about invalidating the declaration
3683 // because of a bogus initializer.
3684 Var->setInvalidDecl();
3685 }
3686
3687 PopExpressionEvaluationContext();
3688 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3689 !Var->isCXXForRangeDecl())
3690 ActOnUninitializedDecl(Var, false);
3691}
3692
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003693/// \brief Instantiate the definition of the given variable from its
3694/// template.
3695///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003696/// \param PointOfInstantiation the point at which the instantiation was
3697/// required. Note that this is not precisely a "point of instantiation"
3698/// for the function, but it's close.
3699///
3700/// \param Var the already-instantiated declaration of a static member
3701/// variable of a class template specialization.
3702///
3703/// \param Recursive if true, recursively instantiates any functions that
3704/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003705///
3706/// \param DefinitionRequired if true, then we are performing an explicit
3707/// instantiation where an out-of-line definition of the member variable
3708/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003709void Sema::InstantiateStaticDataMemberDefinition(
3710 SourceLocation PointOfInstantiation,
3711 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003712 bool Recursive,
3713 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003714 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3715 DefinitionRequired);
3716}
3717
3718void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3719 VarDecl *Var, bool Recursive,
3720 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003721 if (Var->isInvalidDecl())
3722 return;
Mike Stump11289f42009-09-09 15:08:12 +00003723
Larisse Voufo39a1e502013-08-06 01:03:05 +00003724 VarTemplateSpecializationDecl *VarSpec =
3725 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smith8809a0c2013-09-27 20:14:12 +00003726 VarDecl *PatternDecl = 0, *Def = 0;
3727 MultiLevelTemplateArgumentList TemplateArgs =
3728 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003729
Larisse Voufo39a1e502013-08-06 01:03:05 +00003730 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003731 // If this is a variable template specialization, make sure that it is
3732 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003733 bool InstantiationDependent = false;
3734 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3735 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3736 "Only instantiate variable template specializations that are "
3737 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003738 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003739
Richard Smith8809a0c2013-09-27 20:14:12 +00003740 // Find the variable initialization that we'll be substituting. If the
3741 // pattern was instantiated from a member template, look back further to
3742 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003743 assert(VarSpec->getSpecializedTemplate() &&
3744 "Specialization without specialized template?");
3745 llvm::PointerUnion<VarTemplateDecl *,
3746 VarTemplatePartialSpecializationDecl *> PatternPtr =
3747 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003748 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003749 VarTemplatePartialSpecializationDecl *Tmpl =
3750 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3751 while (VarTemplatePartialSpecializationDecl *From =
3752 Tmpl->getInstantiatedFromMember()) {
3753 if (Tmpl->isMemberSpecialization())
3754 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003755
Richard Smith8809a0c2013-09-27 20:14:12 +00003756 Tmpl = From;
3757 }
3758 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003759 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003760 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3761 while (VarTemplateDecl *From =
3762 Tmpl->getInstantiatedFromMemberTemplate()) {
3763 if (Tmpl->isMemberSpecialization())
3764 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003765
Richard Smith8809a0c2013-09-27 20:14:12 +00003766 Tmpl = From;
3767 }
3768 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003769 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003770
3771 // If this is a static data member template, there might be an
3772 // uninstantiated initializer on the declaration. If so, instantiate
3773 // it now.
3774 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003775 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003776 !Var->hasInit()) {
3777 // FIXME: Factor out the duplicated instantiation context setup/tear down
3778 // code here.
3779 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003780 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003781 return;
3782
3783 // If we're performing recursive template instantiation, create our own
3784 // queue of pending implicit instantiations that we will instantiate
3785 // later, while we're still within our own instantiation context.
3786 SmallVector<VTableUse, 16> SavedVTableUses;
3787 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3788 if (Recursive) {
3789 VTableUses.swap(SavedVTableUses);
3790 PendingInstantiations.swap(SavedPendingInstantiations);
3791 }
3792
3793 LocalInstantiationScope Local(*this);
3794
3795 // Enter the scope of this instantiation. We don't use
3796 // PushDeclContext because we don't have a scope.
3797 ContextRAII PreviousContext(*this, Var->getDeclContext());
3798 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3799 PreviousContext.pop();
3800
3801 // FIXME: Need to inform the ASTConsumer that we instantiated the
3802 // initializer?
3803
3804 // This variable may have local implicit instantiations that need to be
3805 // instantiated within this scope.
3806 PerformPendingInstantiations(/*LocalOnly=*/true);
3807
3808 Local.Exit();
3809
3810 if (Recursive) {
3811 // Define any newly required vtables.
3812 DefineUsedVTables();
3813
3814 // Instantiate any pending implicit instantiations found during the
3815 // instantiation of this template.
3816 PerformPendingInstantiations();
3817
3818 // Restore the set of pending vtables.
3819 assert(VTableUses.empty() &&
3820 "VTableUses should be empty before it is discarded.");
3821 VTableUses.swap(SavedVTableUses);
3822
3823 // Restore the set of pending implicit instantiations.
3824 assert(PendingInstantiations.empty() &&
3825 "PendingInstantiations should be empty before it is discarded.");
3826 PendingInstantiations.swap(SavedPendingInstantiations);
3827 }
3828 }
3829
3830 // Find actual definition
3831 Def = PatternDecl->getDefinition(getASTContext());
3832 } else {
3833 // If this is a static data member, find its out-of-line definition.
3834 assert(Var->isStaticDataMember() && "not a static data member?");
3835 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3836
3837 assert(PatternDecl && "data member was not instantiated from a template?");
3838 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3839 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003840 }
3841
Richard Smith8809a0c2013-09-27 20:14:12 +00003842 // If we don't have a definition of the variable template, we won't perform
3843 // any instantiation. Rather, we rely on the user to instantiate this
3844 // definition (or provide a specialization for it) in another translation
3845 // unit.
3846 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003847 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003848 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003849 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003850 diag::err_explicit_instantiation_undefined_var_template) << Var;
3851 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003852 Diag(PointOfInstantiation,
3853 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003854 << 2 << Var->getDeclName() << Var->getDeclContext();
3855 Diag(PatternDecl->getLocation(),
3856 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003857 if (VarSpec)
3858 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003859 } else if (Var->getTemplateSpecializationKind()
3860 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003861 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003862 std::make_pair(Var, PointOfInstantiation));
3863 }
3864
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003865 return;
3866 }
3867
Rafael Espindola189fa742012-03-05 10:54:55 +00003868 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3869
Douglas Gregor86d142a2009-10-08 07:24:58 +00003870 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003871 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003872 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003873
Larisse Voufo39a1e502013-08-06 01:03:05 +00003874 // C++11 [temp.explicit]p10:
3875 // Except for inline functions, [...] explicit instantiation declarations
3876 // have the effect of suppressing the implicit instantiation of the entity
3877 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003878 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003879 return;
Mike Stump11289f42009-09-09 15:08:12 +00003880
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003881 // Make sure to pass the instantiated variable to the consumer at the end.
3882 struct PassToConsumerRAII {
3883 ASTConsumer &Consumer;
3884 VarDecl *Var;
3885
3886 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3887 : Consumer(Consumer), Var(Var) { }
3888
3889 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003890 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003891 }
3892 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003893
Richard Smith8809a0c2013-09-27 20:14:12 +00003894 // If we already have a definition, we're done.
3895 if (VarDecl *Def = Var->getDefinition()) {
3896 // We may be explicitly instantiating something we've already implicitly
3897 // instantiated.
3898 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3899 PointOfInstantiation);
3900 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003901 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003902
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003903 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003904 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003905 return;
Mike Stump11289f42009-09-09 15:08:12 +00003906
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003907 // If we're performing recursive template instantiation, create our own
3908 // queue of pending implicit instantiations that we will instantiate later,
3909 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003910 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003911 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003912 SavePendingLocalImplicitInstantiationsRAII
3913 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003914 if (Recursive) {
3915 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003916 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003917 }
Mike Stump11289f42009-09-09 15:08:12 +00003918
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003919 // Enter the scope of this instantiation. We don't use
3920 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003921 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003922 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003923
Larisse Voufo39a1e502013-08-06 01:03:05 +00003924 VarDecl *OldVar = Var;
3925 if (!VarSpec)
3926 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003927 TemplateArgs));
3928 else if (Var->isStaticDataMember() &&
3929 Var->getLexicalDeclContext()->isRecord()) {
3930 // We need to instantiate the definition of a static data member template,
3931 // and all we have is the in-class declaration of it. Instantiate a separate
3932 // declaration of the definition.
3933 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3934 TemplateArgs);
3935 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3936 VarSpec->getSpecializedTemplate(), Def, 0,
3937 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3938 if (Var) {
3939 llvm::PointerUnion<VarTemplateDecl *,
3940 VarTemplatePartialSpecializationDecl *> PatternPtr =
3941 VarSpec->getSpecializedTemplateOrPartial();
3942 if (VarTemplatePartialSpecializationDecl *Partial =
3943 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3944 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3945 Partial, &VarSpec->getTemplateInstantiationArgs());
3946
3947 // Merge the definition with the declaration.
3948 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3949 LookupOrdinaryName, ForRedeclaration);
3950 R.addDecl(OldVar);
3951 MergeVarDecl(Var, R);
3952
3953 // Attach the initializer.
3954 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3955 }
3956 } else
3957 // Complete the existing variable's definition with an appropriately
3958 // substituted type and initializer.
3959 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003960
3961 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003962
3963 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003964 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003965 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3966 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003967 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003968
3969 // This variable may have local implicit instantiations that need to be
3970 // instantiated within this scope.
3971 PerformPendingInstantiations(/*LocalOnly=*/true);
3972
Douglas Gregora86bc002012-02-16 21:36:18 +00003973 Local.Exit();
3974
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003975 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003976 // Define any newly required vtables.
3977 DefineUsedVTables();
3978
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003979 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003980 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003981 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003982
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003983 // Restore the set of pending vtables.
3984 assert(VTableUses.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003985 "VTableUses should be empty before it is discarded.");
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003986 VTableUses.swap(SavedVTableUses);
3987
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003988 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003989 assert(PendingInstantiations.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003990 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003991 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00003992 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003993}
Douglas Gregor51783312009-05-27 05:35:12 +00003994
Anders Carlsson70553942009-08-29 05:16:22 +00003995void
3996Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3997 const CXXConstructorDecl *Tmpl,
3998 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003999
Richard Trieu9becef62011-09-09 03:18:59 +00004000 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004001 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004002
Anders Carlsson70553942009-08-29 05:16:22 +00004003 // Instantiate all the initializers.
4004 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregora3a3f6f2009-09-01 21:04:42 +00004005 InitsEnd = Tmpl->init_end();
4006 Inits != InitsEnd; ++Inits) {
Alexis Hunt1d792652011-01-08 20:30:50 +00004007 CXXCtorInitializer *Init = *Inits;
Anders Carlsson70553942009-08-29 05:16:22 +00004008
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004009 // Only instantiate written initializers, let Sema re-construct implicit
4010 // ones.
4011 if (!Init->isWritten())
4012 continue;
4013
Douglas Gregor44e7df62011-01-04 00:32:56 +00004014 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004015
Douglas Gregor44e7df62011-01-04 00:32:56 +00004016 if (Init->isPackExpansion()) {
4017 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004018 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004019 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004020 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004021 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004022 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004023 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004024 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004025 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004026 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004027 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004028 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004029 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004030 NumExpansions)) {
4031 AnyErrors = true;
4032 New->setInvalidDecl();
4033 continue;
4034 }
4035 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004036
4037 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004038 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004039 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4040
4041 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004042 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4043 /*CXXDirectInit=*/true);
4044 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004045 AnyErrors = true;
4046 break;
4047 }
4048
4049 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004050 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004051 TemplateArgs,
4052 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004053 New->getDeclName());
4054 if (!BaseTInfo) {
4055 AnyErrors = true;
4056 break;
4057 }
4058
4059 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004060 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redla9351792012-02-11 23:51:47 +00004061 BaseTInfo, TempInit.take(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004062 New->getParent(),
4063 SourceLocation());
4064 if (NewInit.isInvalid()) {
4065 AnyErrors = true;
4066 break;
4067 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004068
Douglas Gregor44e7df62011-01-04 00:32:56 +00004069 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004070 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004071
Douglas Gregor44e7df62011-01-04 00:32:56 +00004072 continue;
4073 }
4074
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004075 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004076 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4077 /*CXXDirectInit=*/true);
4078 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004079 AnyErrors = true;
4080 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004081 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004082
Anders Carlsson70553942009-08-29 05:16:22 +00004083 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004084 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4085 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4086 TemplateArgs,
4087 Init->getSourceLocation(),
4088 New->getDeclName());
4089 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004090 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004091 New->setInvalidDecl();
4092 continue;
4093 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004094
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004095 if (Init->isBaseInitializer())
Sebastian Redla9351792012-02-11 23:51:47 +00004096 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004097 New->getParent(), EllipsisLoc);
4098 else
Sebastian Redla9351792012-02-11 23:51:47 +00004099 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004100 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004101 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004102 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004103 Init->getMemberLocation(),
4104 Init->getMember(),
4105 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004106 if (!Member) {
4107 AnyErrors = true;
4108 New->setInvalidDecl();
4109 continue;
4110 }
Mike Stump11289f42009-09-09 15:08:12 +00004111
Sebastian Redla9351792012-02-11 23:51:47 +00004112 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004113 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004114 } else if (Init->isIndirectMemberInitializer()) {
4115 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004116 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004117 Init->getMemberLocation(),
4118 Init->getIndirectMember(), TemplateArgs));
4119
Douglas Gregor55e6b312011-03-04 19:46:35 +00004120 if (!IndirectMember) {
4121 AnyErrors = true;
4122 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004123 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004124 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004125
Sebastian Redla9351792012-02-11 23:51:47 +00004126 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004127 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004128 }
4129
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004130 if (NewInit.isInvalid()) {
4131 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004132 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004133 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004134 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004135 }
4136 }
Mike Stump11289f42009-09-09 15:08:12 +00004137
Anders Carlsson70553942009-08-29 05:16:22 +00004138 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004139 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004140 /*FIXME: ColonLoc */
4141 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004142 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004143 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004144}
4145
John McCall59660882009-08-29 08:11:13 +00004146// TODO: this could be templated if the various decl types used the
4147// same method name.
4148static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4149 ClassTemplateDecl *Instance) {
4150 Pattern = Pattern->getCanonicalDecl();
4151
4152 do {
4153 Instance = Instance->getCanonicalDecl();
4154 if (Pattern == Instance) return true;
4155 Instance = Instance->getInstantiatedFromMemberTemplate();
4156 } while (Instance);
4157
4158 return false;
4159}
4160
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004161static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4162 FunctionTemplateDecl *Instance) {
4163 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004164
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004165 do {
4166 Instance = Instance->getCanonicalDecl();
4167 if (Pattern == Instance) return true;
4168 Instance = Instance->getInstantiatedFromMemberTemplate();
4169 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004170
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004171 return false;
4172}
4173
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004174static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004175isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4176 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004177 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004178 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4179 do {
4180 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4181 Instance->getCanonicalDecl());
4182 if (Pattern == Instance)
4183 return true;
4184 Instance = Instance->getInstantiatedFromMember();
4185 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004186
Douglas Gregor21610382009-10-29 00:04:11 +00004187 return false;
4188}
4189
John McCall59660882009-08-29 08:11:13 +00004190static bool isInstantiationOf(CXXRecordDecl *Pattern,
4191 CXXRecordDecl *Instance) {
4192 Pattern = Pattern->getCanonicalDecl();
4193
4194 do {
4195 Instance = Instance->getCanonicalDecl();
4196 if (Pattern == Instance) return true;
4197 Instance = Instance->getInstantiatedFromMemberClass();
4198 } while (Instance);
4199
4200 return false;
4201}
4202
4203static bool isInstantiationOf(FunctionDecl *Pattern,
4204 FunctionDecl *Instance) {
4205 Pattern = Pattern->getCanonicalDecl();
4206
4207 do {
4208 Instance = Instance->getCanonicalDecl();
4209 if (Pattern == Instance) return true;
4210 Instance = Instance->getInstantiatedFromMemberFunction();
4211 } while (Instance);
4212
4213 return false;
4214}
4215
4216static bool isInstantiationOf(EnumDecl *Pattern,
4217 EnumDecl *Instance) {
4218 Pattern = Pattern->getCanonicalDecl();
4219
4220 do {
4221 Instance = Instance->getCanonicalDecl();
4222 if (Pattern == Instance) return true;
4223 Instance = Instance->getInstantiatedFromMemberEnum();
4224 } while (Instance);
4225
4226 return false;
4227}
4228
John McCallb96ec562009-12-04 22:46:56 +00004229static bool isInstantiationOf(UsingShadowDecl *Pattern,
4230 UsingShadowDecl *Instance,
4231 ASTContext &C) {
4232 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4233}
4234
4235static bool isInstantiationOf(UsingDecl *Pattern,
4236 UsingDecl *Instance,
4237 ASTContext &C) {
4238 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4239}
4240
John McCalle61f2ba2009-11-18 02:36:19 +00004241static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4242 UsingDecl *Instance,
4243 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004244 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00004245}
4246
4247static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004248 UsingDecl *Instance,
4249 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004250 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004251}
4252
John McCall59660882009-08-29 08:11:13 +00004253static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4254 VarDecl *Instance) {
4255 assert(Instance->isStaticDataMember());
4256
4257 Pattern = Pattern->getCanonicalDecl();
4258
4259 do {
4260 Instance = Instance->getCanonicalDecl();
4261 if (Pattern == Instance) return true;
4262 Instance = Instance->getInstantiatedFromStaticDataMember();
4263 } while (Instance);
4264
4265 return false;
4266}
4267
John McCallb96ec562009-12-04 22:46:56 +00004268// Other is the prospective instantiation
4269// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004270static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004271 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004272 if (UnresolvedUsingTypenameDecl *UUD
4273 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4274 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4275 return isInstantiationOf(UUD, UD, Ctx);
4276 }
4277 }
4278
4279 if (UnresolvedUsingValueDecl *UUD
4280 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004281 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4282 return isInstantiationOf(UUD, UD, Ctx);
4283 }
4284 }
Douglas Gregor51783312009-05-27 05:35:12 +00004285
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004286 return false;
4287 }
Mike Stump11289f42009-09-09 15:08:12 +00004288
John McCall59660882009-08-29 08:11:13 +00004289 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4290 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004291
John McCall59660882009-08-29 08:11:13 +00004292 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4293 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004294
John McCall59660882009-08-29 08:11:13 +00004295 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4296 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004297
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004298 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004299 if (Var->isStaticDataMember())
4300 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4301
4302 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4303 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004304
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004305 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4306 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4307
Douglas Gregor21610382009-10-29 00:04:11 +00004308 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4309 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4310 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4311 PartialSpec);
4312
Anders Carlsson5da84842009-09-01 04:26:58 +00004313 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4314 if (!Field->getDeclName()) {
4315 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00004316 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00004317 cast<FieldDecl>(D);
4318 }
4319 }
Mike Stump11289f42009-09-09 15:08:12 +00004320
John McCallb96ec562009-12-04 22:46:56 +00004321 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4322 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4323
4324 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4325 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4326
Douglas Gregor51783312009-05-27 05:35:12 +00004327 return D->getDeclName() && isa<NamedDecl>(Other) &&
4328 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4329}
4330
4331template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004332static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004333 NamedDecl *D,
4334 ForwardIterator first,
4335 ForwardIterator last) {
4336 for (; first != last; ++first)
4337 if (isInstantiationOf(Ctx, D, *first))
4338 return cast<NamedDecl>(*first);
4339
4340 return 0;
4341}
4342
John McCallaa74a0c2009-08-28 07:59:38 +00004343/// \brief Finds the instantiation of the given declaration context
4344/// within the current instantiation.
4345///
4346/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004347DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004348 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004349 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004350 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004351 return cast_or_null<DeclContext>(ID);
4352 } else return DC;
4353}
4354
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004355/// \brief Find the instantiation of the given declaration within the
4356/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004357///
4358/// This routine is intended to be used when \p D is a declaration
4359/// referenced from within a template, that needs to mapped into the
4360/// corresponding declaration within an instantiation. For example,
4361/// given:
4362///
4363/// \code
4364/// template<typename T>
4365/// struct X {
4366/// enum Kind {
4367/// KnownValue = sizeof(T)
4368/// };
4369///
4370/// bool getKind() const { return KnownValue; }
4371/// };
4372///
4373/// template struct X<int>;
4374/// \endcode
4375///
Serge Pavloved5fe902013-07-10 04:59:14 +00004376/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4377/// \p EnumConstantDecl for \p KnownValue (which refers to
4378/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4379/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4380/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004381NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004382 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004383 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004384 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4385 // parameters (p below) can have their ParentDC set to the translation-unit
4386 // - thus we can not consistently check if the ParentDC of such a parameter
4387 // is Dependent or/and a FunctionOrMethod.
4388 // For e.g. this code, during Template argument deduction tries to
4389 // find an instantiated decl for (T y) when the ParentDC for y is
4390 // the translation unit.
4391 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004392 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004393 // Foo(baz);
4394 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4395 // it gets here, always has a FunctionOrMethod as its ParentDC??
4396 // For now:
4397 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4398 // whose type is not instantiation dependent, do nothing to the decl
4399 // - otherwise find its instantiated decl.
4400 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4401 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4402 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004403 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004404 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004405 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4406 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004407 // D is a local of some kind. Look into the map of local
4408 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00004409 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4410 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4411 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004412
Chris Lattnercab02a62011-02-17 20:34:02 +00004413 if (Found) {
4414 if (Decl *FD = Found->dyn_cast<Decl *>())
4415 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004416
Richard Smithb15fe3a2012-09-12 00:56:43 +00004417 int PackIdx = ArgumentPackSubstitutionIndex;
4418 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00004419 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4420 }
4421
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004422 // If we're performing a partial substitution during template argument
4423 // deduction, we may not have values for template parameters yet. They
4424 // just map to themselves.
4425 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4426 isa<TemplateTemplateParmDecl>(D))
4427 return D;
4428
Serge Pavlov074a5182013-08-10 12:00:21 +00004429 if (D->isInvalidDecl())
4430 return 0;
4431
Chris Lattnercab02a62011-02-17 20:34:02 +00004432 // If we didn't find the decl, then we must have a label decl that hasn't
4433 // been found yet. Lazily instantiate it and return it now.
4434 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004435
Chris Lattnercab02a62011-02-17 20:34:02 +00004436 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4437 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004438
Chris Lattnercab02a62011-02-17 20:34:02 +00004439 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4440 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004441 }
Douglas Gregor51783312009-05-27 05:35:12 +00004442
Larisse Voufo39a1e502013-08-06 01:03:05 +00004443 // For variable template specializations, update those that are still
4444 // type-dependent.
4445 if (VarTemplateSpecializationDecl *VarSpec =
4446 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4447 bool InstantiationDependent = false;
4448 const TemplateArgumentListInfo &VarTemplateArgs =
4449 VarSpec->getTemplateArgsInfo();
4450 if (TemplateSpecializationType::anyDependentTemplateArguments(
4451 VarTemplateArgs, InstantiationDependent))
4452 D = cast<NamedDecl>(
4453 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4454 return D;
4455 }
4456
Douglas Gregor64621e62009-09-16 18:34:49 +00004457 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4458 if (!Record->isDependentContext())
4459 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004460
Douglas Gregor4109afa2011-11-07 17:43:18 +00004461 // Determine whether this record is the "templated" declaration describing
4462 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004463 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004464 if (ClassTemplate)
4465 ClassTemplate = ClassTemplate->getCanonicalDecl();
4466 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4467 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4468 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004469
Douglas Gregor4109afa2011-11-07 17:43:18 +00004470 // Walk the current context to find either the record or an instantiation of
4471 // it.
4472 DeclContext *DC = CurContext;
4473 while (!DC->isFileContext()) {
4474 // If we're performing substitution while we're inside the template
4475 // definition, we'll find our own context. We're done.
4476 if (DC->Equals(Record))
4477 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004478
Douglas Gregor4109afa2011-11-07 17:43:18 +00004479 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4480 // Check whether we're in the process of instantiating a class template
4481 // specialization of the template we're mapping.
4482 if (ClassTemplateSpecializationDecl *InstSpec
4483 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4484 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4485 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4486 return InstRecord;
4487 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004488
Douglas Gregor4109afa2011-11-07 17:43:18 +00004489 // Check whether we're in the process of instantiating a member class.
4490 if (isInstantiationOf(Record, InstRecord))
4491 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004492 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004493
Douglas Gregor4109afa2011-11-07 17:43:18 +00004494 // Move to the outer template scope.
4495 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4496 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4497 DC = FD->getLexicalDeclContext();
4498 continue;
4499 }
John McCall59660882009-08-29 08:11:13 +00004500 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004501
Douglas Gregor4109afa2011-11-07 17:43:18 +00004502 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004503 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004504
Douglas Gregor64621e62009-09-16 18:34:49 +00004505 // Fall through to deal with other dependent record types (e.g.,
4506 // anonymous unions in class templates).
4507 }
John McCall59660882009-08-29 08:11:13 +00004508
Douglas Gregor64621e62009-09-16 18:34:49 +00004509 if (!ParentDC->isDependentContext())
4510 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004511
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004512 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004513 if (!ParentDC)
Douglas Gregor2ffd9652009-09-01 17:53:10 +00004514 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004515
Douglas Gregor51783312009-05-27 05:35:12 +00004516 if (ParentDC != D->getDeclContext()) {
4517 // We performed some kind of instantiation in the parent context,
4518 // so now we need to look into the instantiated parent context to
4519 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004520
John McCalle78aac42010-03-10 03:28:59 +00004521 // If our context used to be dependent, we may need to instantiate
4522 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004523 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004524 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004525 if (!Spec->isDependentContext()) {
4526 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004527 const RecordType *Tag = T->getAs<RecordType>();
4528 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004529 if (Tag->isBeingDefined())
4530 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004531 if (!Tag->isBeingDefined() &&
4532 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4533 return 0;
Douglas Gregor25edf432010-11-05 23:22:45 +00004534
4535 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004536 }
4537 }
4538
Douglas Gregor51783312009-05-27 05:35:12 +00004539 NamedDecl *Result = 0;
4540 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004541 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004542 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004543 } else {
4544 // Since we don't have a name for the entity we're looking for,
4545 // our only option is to walk through all of the declarations to
4546 // find that name. This will occur in a few cases:
4547 //
4548 // - anonymous struct/union within a template
4549 // - unnamed class/struct/union/enum within a template
4550 //
4551 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004552 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004553 ParentDC->decls_begin(),
4554 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556
Douglas Gregor528ad932011-03-06 20:12:45 +00004557 if (!Result) {
4558 if (isa<UsingShadowDecl>(D)) {
4559 // UsingShadowDecls can instantiate to nothing because of using hiding.
4560 } else if (Diags.hasErrorOccurred()) {
4561 // We've already complained about something, so most likely this
4562 // declaration failed to instantiate. There's no point in complaining
4563 // further, since this is normal in invalid code.
4564 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004565 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004566 // instantiated, and we haven't gotten around to instantiating this
4567 // member yet. This can happen when the code uses forward declarations
4568 // of member classes, and introduces ordering dependencies via
4569 // template instantiation.
4570 Diag(Loc, diag::err_member_not_yet_instantiated)
4571 << D->getDeclName()
4572 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4573 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004574 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4575 // This enumeration constant was found when the template was defined,
4576 // but can't be found in the instantiation. This can happen if an
4577 // unscoped enumeration member is explicitly specialized.
4578 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4579 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4580 TemplateArgs));
4581 assert(Spec->getTemplateSpecializationKind() ==
4582 TSK_ExplicitSpecialization);
4583 Diag(Loc, diag::err_enumerator_does_not_exist)
4584 << D->getDeclName()
4585 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4586 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4587 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004588 } else {
4589 // We should have found something, but didn't.
4590 llvm_unreachable("Unable to find instantiation of declaration!");
4591 }
4592 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004593
Douglas Gregor51783312009-05-27 05:35:12 +00004594 D = Result;
4595 }
4596
Douglas Gregor51783312009-05-27 05:35:12 +00004597 return D;
4598}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004599
Mike Stump11289f42009-09-09 15:08:12 +00004600/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004601/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004602void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregore39f97c2011-07-28 19:49:54 +00004603 // Load pending instantiations from the external source.
4604 if (!LocalOnly && ExternalSource) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00004605 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregore39f97c2011-07-28 19:49:54 +00004606 ExternalSource->ReadPendingInstantiations(Pending);
4607 PendingInstantiations.insert(PendingInstantiations.begin(),
4608 Pending.begin(), Pending.end());
4609 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004610
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004611 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004612 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004613 PendingImplicitInstantiation Inst;
4614
4615 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004616 Inst = PendingInstantiations.front();
4617 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004618 } else {
4619 Inst = PendingLocalImplicitInstantiations.front();
4620 PendingLocalImplicitInstantiations.pop_front();
4621 }
Mike Stump11289f42009-09-09 15:08:12 +00004622
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004623 // Instantiate function definitions
4624 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004625 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4626 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004627 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4628 TSK_ExplicitInstantiationDefinition;
4629 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4630 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004631 continue;
4632 }
Mike Stump11289f42009-09-09 15:08:12 +00004633
Larisse Voufo39a1e502013-08-06 01:03:05 +00004634 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004635 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004636
4637 assert((Var->isStaticDataMember() ||
4638 isa<VarTemplateSpecializationDecl>(Var)) &&
4639 "Not a static data member, nor a variable template"
4640 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004641
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004642 // Don't try to instantiate declarations if the most recent redeclaration
4643 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004644 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004645 continue;
4646
4647 // Check if the most recent declaration has changed the specialization kind
4648 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004649 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004650 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004651 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004652 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004653 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004654 continue; // No longer need to instantiate this type.
4655 case TSK_ExplicitInstantiationDefinition:
4656 // We only need an instantiation if the pending instantiation *is* the
4657 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004658 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004659 case TSK_ImplicitInstantiation:
4660 break;
4661 }
4662
Larisse Voufo39a1e502013-08-06 01:03:05 +00004663 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4664 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004665 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4666 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004667
4668 // Instantiate static data member definitions or variable template
4669 // specializations.
4670 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4671 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004672 }
4673}
John McCallc62bb642010-03-24 05:22:00 +00004674
4675void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4676 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00004677 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00004678 switch (DD->getKind()) {
4679 case DependentDiagnostic::Access:
4680 HandleDependentAccessCheck(*DD, TemplateArgs);
4681 break;
4682 }
4683 }
4684}