blob: be2db41efd872754dcd929ff5abf3a87ba76f586 [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"
Richard Smithd28ac5b2014-03-22 23:33:22 +000015#include "clang/AST/ASTMutationListener.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000016#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall58f10c32010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.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) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000135 Expr *Cond = nullptr;
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000136 {
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 Ballmanb97112e2014-03-08 22:19:01 +0000171 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000172 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000173 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
174 if (Aligned && Aligned->isAlignmentDependent()) {
175 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
176 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000177 }
178
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000179 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
180 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
181 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
182 New);
183 continue;
184 }
185
Richard Smith44c247f2013-02-22 08:32:16 +0000186 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000187 if (TmplAttr->isLateParsed() && LateAttrs) {
188 // Late parsed attributes must be instantiated and attached after the
189 // enclosing class has been instantiated. See Sema::InstantiateClass.
Craig Topperc3ec1492014-05-26 06:22:03 +0000190 LocalInstantiationScope *Saved = nullptr;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000191 if (CurrentInstantiationScope)
192 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
193 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
194 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000195 // Allow 'this' within late-parsed attributes.
196 NamedDecl *ND = dyn_cast<NamedDecl>(New);
197 CXXRecordDecl *ThisContext =
198 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
199 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
200 ND && ND->isCXXInstanceMember());
201
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000202 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
203 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000204 if (NewAttr)
205 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000206 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000207 }
208}
209
Douglas Gregor8a655532009-03-25 15:45:12 +0000210Decl *
211TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000212 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000213}
214
215Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000216TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
217 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
218 D->getIdentifier());
219 Owner->addDecl(Inst);
220 return Inst;
221}
222
223Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000224TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000225 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000226}
227
John McCalld8d0d432010-02-16 06:53:13 +0000228Decl *
229TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
230 NamespaceAliasDecl *Inst
231 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
232 D->getNamespaceLoc(),
233 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000234 D->getIdentifier(),
235 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000236 D->getTargetNameLoc(),
237 D->getNamespace());
238 Owner->addDecl(Inst);
239 return Inst;
240}
241
Richard Smith3f1b5d02011-05-05 21:57:07 +0000242Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
243 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000244 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000245 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000246 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000247 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000248 DI = SemaRef.SubstType(DI, TemplateArgs,
249 D->getLocation(), D->getDeclName());
250 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000251 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000252 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000253 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000254 } else {
255 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000256 }
Mike Stump11289f42009-09-09 15:08:12 +0000257
Richard Smith2ddcbab2012-10-23 00:32:41 +0000258 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
259 // libstdc++ relies upon this bug in its implementation of common_type.
260 // If we happen to be processing that implementation, fake up the g++ ?:
261 // semantics. See LWG issue 2141 for more information on the bug.
262 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
263 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
264 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
265 DT->isReferenceType() &&
266 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
267 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
268 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
269 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
270 // Fold it to the (non-reference) type which g++ would have produced.
271 DI = SemaRef.Context.getTrivialTypeSourceInfo(
272 DI->getType().getNonReferenceType());
273
Douglas Gregord7e7a512009-03-17 21:15:40 +0000274 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000275 TypedefNameDecl *Typedef;
276 if (IsTypeAlias)
277 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
278 D->getLocation(), D->getIdentifier(), DI);
279 else
280 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
281 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000282 if (Invalid)
283 Typedef->setInvalidDecl();
284
John McCall04fcd0d2011-02-01 08:20:08 +0000285 // If the old typedef was the name for linkage purposes of an anonymous
286 // tag decl, re-establish that relationship for the new typedef.
287 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
288 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000289 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000290 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000291 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000292 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000293 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000294 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000295
Douglas Gregorec9fd132012-01-14 16:38:05 +0000296 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000297 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
298 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000299 if (!InstPrev)
Craig Topperc3ec1492014-05-26 06:22:03 +0000300 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000301
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000302 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
303
304 // If the typedef types are not identical, reject them.
305 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
306
Rafael Espindola8db352d2013-10-17 15:37:26 +0000307 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000308 }
309
John McCall6602bb12010-08-01 02:01:53 +0000310 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000311
John McCall401982f2010-01-20 21:53:11 +0000312 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000313
Douglas Gregord7e7a512009-03-17 21:15:40 +0000314 return Typedef;
315}
316
Richard Smithdda56e42011-04-15 14:24:37 +0000317Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000318 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
319 Owner->addDecl(Typedef);
320 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000321}
322
323Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000324 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
325 Owner->addDecl(Typedef);
326 return Typedef;
327}
328
329Decl *
330TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
331 // Create a local instantiation scope for this type alias template, which
332 // will contain the instantiations of the template parameters.
333 LocalInstantiationScope Scope(SemaRef);
334
335 TemplateParameterList *TempParams = D->getTemplateParameters();
336 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
337 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000338 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000339
340 TypeAliasDecl *Pattern = D->getTemplatedDecl();
341
Craig Topperc3ec1492014-05-26 06:22:03 +0000342 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000343 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000344 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000345 if (!Found.empty()) {
346 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000347 }
348 }
349
350 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
351 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
352 if (!AliasInst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000353 return nullptr;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000354
355 TypeAliasTemplateDecl *Inst
356 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
357 D->getDeclName(), InstParams, AliasInst);
358 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000359 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000360
361 Inst->setAccess(D->getAccess());
362
363 if (!PrevAliasTemplate)
364 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000365
Richard Smith3f1b5d02011-05-05 21:57:07 +0000366 Owner->addDecl(Inst);
367
368 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000369}
370
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000371Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000372 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000373}
374
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000375Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
376 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000377
Douglas Gregor04163182010-05-21 00:31:19 +0000378 // If this is the variable for an anonymous struct or union,
379 // instantiate the anonymous struct/union type first.
380 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
381 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
382 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +0000383 return nullptr;
Douglas Gregor04163182010-05-21 00:31:19 +0000384
John McCall76d824f2009-08-25 22:02:44 +0000385 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000386 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000387 TemplateArgs,
388 D->getTypeSpecStartLoc(),
389 D->getDeclName());
390 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +0000391 return nullptr;
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000392
Douglas Gregor61623342010-09-12 07:37:24 +0000393 if (DI->getType()->isFunctionType()) {
394 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
395 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +0000396 return nullptr;
Douglas Gregor61623342010-09-12 07:37:24 +0000397 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000398
Richard Smith541b38b2013-09-20 01:15:31 +0000399 DeclContext *DC = Owner;
400 if (D->isLocalExternDecl())
401 SemaRef.adjustContextForLocalExternDecl(DC);
402
Larisse Voufo39a1e502013-08-06 01:03:05 +0000403 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000404 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000405 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000406 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000407
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000408 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000409 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000410 SemaRef.inferObjCARCLifetime(Var))
411 Var->setInvalidDecl();
412
Larisse Voufo39a1e502013-08-06 01:03:05 +0000413 // Substitute the nested name specifier, if any.
414 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +0000415 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000416
Richard Smith541b38b2013-09-20 01:15:31 +0000417 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000418 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000419
420 if (D->isNRVOVariable()) {
421 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
422 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
423 Var->setNRVOVariable(true);
424 }
425
Alexander Kornienko83a4e182014-05-27 21:29:22 +0000426 Var->setImplicit(D->isImplicit());
427
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000428 return Var;
429}
430
Abramo Bagnarad7340582010-06-05 05:09:32 +0000431Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
432 AccessSpecDecl* AD
433 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
434 D->getAccessSpecifierLoc(), D->getColonLoc());
435 Owner->addHiddenDecl(AD);
436 return AD;
437}
438
Douglas Gregord7e7a512009-03-17 21:15:40 +0000439Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
440 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000441 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000442 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000443 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000444 DI = SemaRef.SubstType(DI, TemplateArgs,
445 D->getLocation(), D->getDeclName());
446 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000447 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000448 Invalid = true;
449 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000450 // C++ [temp.arg.type]p3:
451 // If a declaration acquires a function type through a type
452 // dependent on a template-parameter and this causes a
453 // declaration that does not use the syntactic form of a
454 // function declarator to have function type, the program is
455 // ill-formed.
456 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000457 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000458 Invalid = true;
459 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000460 } else {
461 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000462 }
463
464 Expr *BitWidth = D->getBitWidth();
465 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +0000466 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000467 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000468 // The bit-width expression is a constant expression.
469 EnterExpressionEvaluationContext Unevaluated(SemaRef,
470 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000471
John McCalldadc5752010-08-24 06:29:42 +0000472 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000473 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000474 if (InstantiatedBitWidth.isInvalid()) {
475 Invalid = true;
Craig Topperc3ec1492014-05-26 06:22:03 +0000476 BitWidth = nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000477 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000478 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000479 }
480
John McCall90459c52009-10-22 23:33:21 +0000481 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
482 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000483 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000484 D->getLocation(),
485 D->isMutable(),
486 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000487 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000488 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000489 D->getAccess(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000490 nullptr);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000491 if (!Field) {
492 cast<Decl>(Owner)->setInvalidDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +0000493 return nullptr;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000496 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000497
Richard Smith848e1f12013-02-01 08:12:08 +0000498 if (Field->hasAttrs())
499 SemaRef.CheckAlignasUnderalignment(Field);
500
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000501 if (Invalid)
502 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000503
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000504 if (!Field->getDeclName()) {
505 // Keep track of where this decl came from.
506 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000507 }
Douglas Gregor04163182010-05-21 00:31:19 +0000508 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
509 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000510 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000511 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000512 }
Mike Stump11289f42009-09-09 15:08:12 +0000513
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000514 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000515 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000516 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000517
518 return Field;
519}
520
John McCall5e77d762013-04-16 07:28:30 +0000521Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
522 bool Invalid = false;
523 TypeSourceInfo *DI = D->getTypeSourceInfo();
524
525 if (DI->getType()->isVariablyModifiedType()) {
526 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000527 << D;
John McCall5e77d762013-04-16 07:28:30 +0000528 Invalid = true;
529 } else if (DI->getType()->isInstantiationDependentType()) {
530 DI = SemaRef.SubstType(DI, TemplateArgs,
531 D->getLocation(), D->getDeclName());
532 if (!DI) {
533 DI = D->getTypeSourceInfo();
534 Invalid = true;
535 } else if (DI->getType()->isFunctionType()) {
536 // C++ [temp.arg.type]p3:
537 // If a declaration acquires a function type through a type
538 // dependent on a template-parameter and this causes a
539 // declaration that does not use the syntactic form of a
540 // function declarator to have function type, the program is
541 // ill-formed.
542 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
543 << DI->getType();
544 Invalid = true;
545 }
546 } else {
547 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
548 }
549
Richard Smithf7981722013-11-22 09:01:48 +0000550 MSPropertyDecl *Property = MSPropertyDecl::Create(
551 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
552 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000553
554 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
555 StartingScope);
556
557 if (Invalid)
558 Property->setInvalidDecl();
559
560 Property->setAccess(D->getAccess());
561 Owner->addDecl(Property);
562
563 return Property;
564}
565
Francois Pichet783dd6e2010-11-21 06:08:52 +0000566Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
567 NamedDecl **NamedChain =
568 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
569
570 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +0000571 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +0000572 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000573 TemplateArgs);
574 if (!Next)
Craig Topperc3ec1492014-05-26 06:22:03 +0000575 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000576
Douglas Gregor55e6b312011-03-04 19:46:35 +0000577 NamedChain[i++] = Next;
578 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000579
Francois Pichetdbafc192010-12-09 10:07:54 +0000580 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000581 IndirectFieldDecl* IndirectField
582 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000583 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000584 NamedChain, D->getChainingSize());
585
586
587 IndirectField->setImplicit(D->isImplicit());
588 IndirectField->setAccess(D->getAccess());
589 Owner->addDecl(IndirectField);
590 return IndirectField;
591}
592
John McCallaa74a0c2009-08-28 07:59:38 +0000593Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000594 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000595 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000596 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000597 TypeSourceInfo *InstTy;
598 // If this is an unsupported friend, don't bother substituting template
599 // arguments into it. The actual type referred to won't be used by any
600 // parts of Clang, and may not be valid for instantiating. Just use the
601 // same info for the instantiated friend.
602 if (D->isUnsupportedFriend()) {
603 InstTy = Ty;
604 } else {
605 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
606 D->getLocation(), DeclarationName());
607 }
608 if (!InstTy)
Craig Topperc3ec1492014-05-26 06:22:03 +0000609 return nullptr;
John McCallaa74a0c2009-08-28 07:59:38 +0000610
Richard Smitha31a89a2012-09-20 01:31:00 +0000611 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000612 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000613 if (!FD)
Craig Topperc3ec1492014-05-26 06:22:03 +0000614 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000615
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000616 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000617 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000618 Owner->addDecl(FD);
619 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000620 }
621
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000622 NamedDecl *ND = D->getFriendDecl();
623 assert(ND && "friend decl must be a decl or a type!");
624
John McCallb9c78482010-04-08 09:05:18 +0000625 // All of the Visit implementations for the various potential friend
626 // declarations have to be carefully written to work for friend
627 // objects, with the most important detail being that the target
628 // decl should almost certainly not be placed in Owner.
629 Decl *NewND = Visit(ND);
Craig Topperc3ec1492014-05-26 06:22:03 +0000630 if (!NewND) return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000631
John McCallaa74a0c2009-08-28 07:59:38 +0000632 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000633 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000634 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000635 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000636 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000637 Owner->addDecl(FD);
638 return FD;
John McCall58de3582009-08-14 02:03:10 +0000639}
640
Douglas Gregord7e7a512009-03-17 21:15:40 +0000641Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
642 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000643
Richard Smith764d2fe2011-12-20 02:08:33 +0000644 // The expression in a static assertion is a constant expression.
645 EnterExpressionEvaluationContext Unevaluated(SemaRef,
646 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000647
John McCalldadc5752010-08-24 06:29:42 +0000648 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000649 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000650 if (InstantiatedAssertExpr.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +0000651 return nullptr;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000652
Richard Smithded9c2e2012-07-11 22:37:56 +0000653 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000654 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000655 D->getMessage(),
656 D->getRParenLoc(),
657 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000658}
659
660Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000661 EnumDecl *PrevDecl = nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +0000662 if (D->getPreviousDecl()) {
663 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
664 D->getPreviousDecl(),
665 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +0000666 if (!Prev) return nullptr;
Richard Smith2e6610a2012-03-26 04:58:10 +0000667 PrevDecl = cast<EnumDecl>(Prev);
668 }
669
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000670 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000671 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000672 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000673 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000674 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000675 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000676 // If we have type source information for the underlying type, it means it
677 // has been explicitly set by the user. Perform substitution on it before
678 // moving on.
679 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000680 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
681 DeclarationName());
682 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000683 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000684 else
685 Enum->setIntegerTypeSourceInfo(NewTI);
686 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000687 assert(!D->getIntegerType()->isDependentType()
688 && "Dependent type without type source info");
689 Enum->setIntegerType(D->getIntegerType());
690 }
691 }
692
John McCall811a0f52010-10-22 23:36:17 +0000693 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
694
Richard Smith4b38ded2012-03-14 23:13:10 +0000695 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000696 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +0000697 // Forward the mangling number from the template to the instantiated decl.
698 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
Craig Topperc3ec1492014-05-26 06:22:03 +0000699 if (SubstQualifier(D, Enum)) return nullptr;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000700 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000701
Richard Smith258a7442012-03-26 04:08:46 +0000702 EnumDecl *Def = D->getDefinition();
703 if (Def && Def != D) {
704 // If this is an out-of-line definition of an enum member template, check
705 // that the underlying types match in the instantiation of both
706 // declarations.
707 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
708 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
709 QualType DefnUnderlying =
710 SemaRef.SubstType(TI->getType(), TemplateArgs,
711 UnderlyingLoc, DeclarationName());
712 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
713 DefnUnderlying, Enum);
714 }
715 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000716
Richard Smith4b38ded2012-03-14 23:13:10 +0000717 // C++11 [temp.inst]p1: The implicit instantiation of a class template
718 // specialization causes the implicit instantiation of the declarations, but
719 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000720 //
721 // DR1484 clarifies that enumeration definitions inside of a template
722 // declaration aren't considered entities that can be separately instantiated
723 // from the rest of the entity they are declared inside of.
724 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
725 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000726 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000727 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000728
729 return Enum;
730}
731
732void TemplateDeclInstantiator::InstantiateEnumDefinition(
733 EnumDecl *Enum, EnumDecl *Pattern) {
734 Enum->startDefinition();
735
Richard Smith7d137e32012-03-23 03:33:32 +0000736 // Update the location to refer to the definition.
737 Enum->setLocation(Pattern->getLocation());
738
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000739 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000740
Craig Topperc3ec1492014-05-26 06:22:03 +0000741 EnumConstantDecl *LastEnumConst = nullptr;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000742 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000743 // The specified value for the enumerator.
Craig Topperc3ec1492014-05-26 06:22:03 +0000744 ExprResult Value = SemaRef.Owned((Expr *)nullptr);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000745 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000746 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000747 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000748 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000749
John McCall76d824f2009-08-25 22:02:44 +0000750 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000751 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000752
753 // Drop the initial value and continue.
754 bool isInvalid = false;
755 if (Value.isInvalid()) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000756 Value = SemaRef.Owned((Expr *)nullptr);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000757 isInvalid = true;
758 }
759
Mike Stump11289f42009-09-09 15:08:12 +0000760 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000761 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
762 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000763 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000764
765 if (isInvalid) {
766 if (EnumConst)
767 EnumConst->setInvalidDecl();
768 Enum->setInvalidDecl();
769 }
770
771 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000772 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000773
John McCallf9b528c2010-01-23 22:37:59 +0000774 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000775 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000776 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000777 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000778
Richard Smith4b38ded2012-03-14 23:13:10 +0000779 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
780 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000781 // If the enumeration is within a function or method, record the enum
782 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000783 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000784 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000785 }
786 }
Mike Stump11289f42009-09-09 15:08:12 +0000787
Richard Smith4b38ded2012-03-14 23:13:10 +0000788 // FIXME: Fixup LBraceLoc
789 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
790 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000791 Enumerators,
Craig Topperc3ec1492014-05-26 06:22:03 +0000792 nullptr, nullptr);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000793}
794
Douglas Gregor9106b822009-03-25 15:04:13 +0000795Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000796 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000797}
798
John McCall87a44eb2009-08-20 01:44:21 +0000799Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000800 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
801
Douglas Gregor954de172009-10-31 17:21:17 +0000802 // Create a local instantiation scope for this class template, which
803 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000804 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000805 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000806 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000807 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +0000808 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +0000809
810 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000811
812 // Instantiate the qualifier. We have to do this first in case
813 // we're a friend declaration, because if we are then we need to put
814 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000815 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
816 if (QualifierLoc) {
817 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
818 TemplateArgs);
819 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +0000820 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000821 }
822
Craig Topperc3ec1492014-05-26 06:22:03 +0000823 CXXRecordDecl *PrevDecl = nullptr;
824 ClassTemplateDecl *PrevClassTemplate = nullptr;
John McCall598b4402010-03-25 06:39:04 +0000825
Douglas Gregorec9fd132012-01-14 16:38:05 +0000826 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000827 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000828 if (!Found.empty()) {
829 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000830 if (PrevClassTemplate)
831 PrevDecl = PrevClassTemplate->getTemplatedDecl();
832 }
833 }
834
John McCall598b4402010-03-25 06:39:04 +0000835 // If this isn't a friend, then it's a member template, in which
836 // case we just want to build the instantiation in the
837 // specialization. If it is a friend, we want to build it in
838 // the appropriate context.
839 DeclContext *DC = Owner;
840 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000841 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000842 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000843 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000844 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +0000845 if (!DC) return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000846 } else {
847 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
848 Pattern->getDeclContext(),
849 TemplateArgs);
850 }
851
852 // Look for a previous declaration of the template in the owning
853 // context.
854 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
855 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
856 SemaRef.LookupQualifiedName(R, DC);
857
858 if (R.isSingleResult()) {
859 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
860 if (PrevClassTemplate)
861 PrevDecl = PrevClassTemplate->getTemplatedDecl();
862 }
863
Douglas Gregor14454802011-02-25 02:25:35 +0000864 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000865 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000866 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000867 << QualifierLoc.getSourceRange();
Craig Topperc3ec1492014-05-26 06:22:03 +0000868 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000869 }
870
Douglas Gregor01e09d92010-04-08 18:16:15 +0000871 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000872 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000873 bool Complain = true;
874
875 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
876 // template for struct std::tr1::__detail::_Map_base, where the
877 // template parameters of the friend declaration don't match the
878 // template parameters of the original declaration. In this one
879 // case, we don't complain about the ill-formed friend
880 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000881 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000882 Pattern->getIdentifier()->isStr("_Map_base") &&
883 DC->isNamespace() &&
884 cast<NamespaceDecl>(DC)->getIdentifier() &&
885 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
886 DeclContext *DCParent = DC->getParent();
887 if (DCParent->isNamespace() &&
888 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
889 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
Richard Trieuc771d5d2014-05-28 02:16:01 +0000890 if (cast<Decl>(DCParent)->isInStdNamespace())
Douglas Gregor01e09d92010-04-08 18:16:15 +0000891 Complain = false;
892 }
893 }
894
John McCall598b4402010-03-25 06:39:04 +0000895 TemplateParameterList *PrevParams
896 = PrevClassTemplate->getTemplateParameters();
897
898 // Make sure the parameter lists match.
899 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000900 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000901 Sema::TPL_TemplateMatch)) {
902 if (Complain)
Craig Topperc3ec1492014-05-26 06:22:03 +0000903 return nullptr;
Douglas Gregor01e09d92010-04-08 18:16:15 +0000904
905 AdoptedPreviousTemplateParams = true;
906 InstParams = PrevParams;
907 }
John McCall598b4402010-03-25 06:39:04 +0000908
909 // Do some additional validation, then merge default arguments
910 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000911 if (!AdoptedPreviousTemplateParams &&
912 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000913 Sema::TPC_ClassTemplate))
Craig Topperc3ec1492014-05-26 06:22:03 +0000914 return nullptr;
John McCall598b4402010-03-25 06:39:04 +0000915 }
916 }
917
John McCall87a44eb2009-08-20 01:44:21 +0000918 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000919 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000920 Pattern->getLocStart(), Pattern->getLocation(),
921 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000922 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000923
Douglas Gregor14454802011-02-25 02:25:35 +0000924 if (QualifierLoc)
925 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000926
John McCall87a44eb2009-08-20 01:44:21 +0000927 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000928 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
929 D->getIdentifier(), InstParams, RecordInst,
930 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000931 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000932
John McCall598b4402010-03-25 06:39:04 +0000933 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000934 if (PrevClassTemplate)
935 Inst->setAccess(PrevClassTemplate->getAccess());
936 else
937 Inst->setAccess(D->getAccess());
938
Richard Smith64017682013-07-17 23:53:16 +0000939 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000940 // TODO: do we want to track the instantiation progeny of this
941 // friend target decl?
942 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000943 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000944 if (!PrevClassTemplate)
945 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000946 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000947
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000948 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000949 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000950 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000951
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000952 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000953 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000954 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000955 Inst->setLexicalDeclContext(Owner);
956 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000957 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000958 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000959
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000960 if (D->isOutOfLine()) {
961 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
962 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
963 }
964
John McCall87a44eb2009-08-20 01:44:21 +0000965 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000966
967 if (!PrevClassTemplate) {
968 // Queue up any out-of-line partial specializations of this member
969 // class template; the client will force their instantiation once
970 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000971 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000972 D->getPartialSpecializations(PartialSpecs);
973 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000974 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +0000975 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
976 }
977
John McCall87a44eb2009-08-20 01:44:21 +0000978 return Inst;
979}
980
Douglas Gregore704c9d2009-08-27 16:57:43 +0000981Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000982TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
983 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000984 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000985
Douglas Gregor21610382009-10-29 00:04:11 +0000986 // Lookup the already-instantiated declaration in the instantiation
987 // of the class template and return that.
988 DeclContext::lookup_result Found
989 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000990 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +0000991 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000992
Douglas Gregor21610382009-10-29 00:04:11 +0000993 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +0000994 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +0000995 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +0000996 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000997
Douglas Gregor869853e2010-11-10 19:44:59 +0000998 if (ClassTemplatePartialSpecializationDecl *Result
999 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1000 return Result;
1001
1002 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001003}
1004
Larisse Voufo39a1e502013-08-06 01:03:05 +00001005Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1006 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1007 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001008
1009 // Create a local instantiation scope for this variable template, which
1010 // will contain the instantiations of the template parameters.
1011 LocalInstantiationScope Scope(SemaRef);
1012 TemplateParameterList *TempParams = D->getTemplateParameters();
1013 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1014 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001015 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001016
1017 VarDecl *Pattern = D->getTemplatedDecl();
Craig Topperc3ec1492014-05-26 06:22:03 +00001018 VarTemplateDecl *PrevVarTemplate = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00001019
1020 if (Pattern->getPreviousDecl()) {
1021 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1022 if (!Found.empty())
1023 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1024 }
1025
Richard Smith1c34fb72013-08-13 18:18:50 +00001026 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001027 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1028 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +00001029
1030 DeclContext *DC = Owner;
1031
Larisse Voufo39a1e502013-08-06 01:03:05 +00001032 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1033 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001034 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001035 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001036 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001037
1038 Inst->setAccess(D->getAccess());
1039 if (!PrevVarTemplate)
1040 Inst->setInstantiatedFromMemberTemplate(D);
1041
1042 if (D->isOutOfLine()) {
1043 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1044 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1045 }
1046
1047 Owner->addDecl(Inst);
1048
1049 if (!PrevVarTemplate) {
1050 // Queue up any out-of-line partial specializations of this member
1051 // variable template; the client will force their instantiation once
1052 // the enclosing class has been instantiated.
1053 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1054 D->getPartialSpecializations(PartialSpecs);
1055 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001056 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001057 OutOfLineVarPartialSpecs.push_back(
1058 std::make_pair(Inst, PartialSpecs[I]));
1059 }
1060
1061 return Inst;
1062}
1063
1064Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1065 VarTemplatePartialSpecializationDecl *D) {
1066 assert(D->isStaticDataMember() &&
1067 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001068
1069 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1070
1071 // Lookup the already-instantiated declaration and return that.
1072 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1073 assert(!Found.empty() && "Instantiation found nothing?");
1074
1075 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1076 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1077
1078 if (VarTemplatePartialSpecializationDecl *Result =
1079 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1080 return Result;
1081
1082 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1083}
1084
Douglas Gregore4b05162009-10-07 17:21:34 +00001085Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001086TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001087 // Create a local instantiation scope for this function template, which
1088 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001089 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001090 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001091 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001092
Douglas Gregore704c9d2009-08-27 16:57:43 +00001093 TemplateParameterList *TempParams = D->getTemplateParameters();
1094 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001095 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001096 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001097
Craig Topperc3ec1492014-05-26 06:22:03 +00001098 FunctionDecl *Instantiated = nullptr;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001099 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001100 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001101 InstParams));
1102 else
1103 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001104 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001105 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001106
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001107 if (!Instantiated)
Craig Topperc3ec1492014-05-26 06:22:03 +00001108 return nullptr;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001109
Mike Stump11289f42009-09-09 15:08:12 +00001110 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001111 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001112 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001113 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001114 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001115 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001116 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001117
John McCall30837102010-03-26 23:10:15 +00001118 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1119
John McCall2079d0b2009-12-14 23:19:40 +00001120 // Link the instantiation back to the pattern *unless* this is a
1121 // non-definition friend declaration.
1122 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001123 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001124 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001125
John McCall30837102010-03-26 23:10:15 +00001126 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001127 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001128 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001129 } else if (InstTemplate->getDeclContext()->isRecord() &&
1130 !D->getPreviousDecl()) {
1131 SemaRef.CheckFriendAccess(InstTemplate);
1132 }
John McCall30837102010-03-26 23:10:15 +00001133
Douglas Gregore704c9d2009-08-27 16:57:43 +00001134 return InstTemplate;
1135}
1136
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001137Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001138 CXXRecordDecl *PrevDecl = nullptr;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001139 if (D->isInjectedClassName())
1140 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001141 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001142 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001143 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001144 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001145 if (!Prev) return nullptr;
John McCalle9f92a02009-12-15 22:29:06 +00001146 PrevDecl = cast<CXXRecordDecl>(Prev);
1147 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001148
1149 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001150 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001151 D->getLocStart(), D->getLocation(),
1152 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001153
1154 // Substitute the nested name specifier, if any.
1155 if (SubstQualifier(D, Record))
Craig Topperc3ec1492014-05-26 06:22:03 +00001156 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00001157
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001158 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001159 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1160 // the tag decls introduced by friend class declarations don't have an access
1161 // specifier. Remove once this area of the code gets sorted out.
1162 if (D->getAccess() != AS_none)
1163 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001164 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001165 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001166
John McCallaa74a0c2009-08-28 07:59:38 +00001167 // If the original function was part of a friend declaration,
1168 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001169 if (D->getFriendObjectKind())
1170 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001171
Douglas Gregor04163182010-05-21 00:31:19 +00001172 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001173 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001174 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001175
1176 if (D->isLocalClass())
1177 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001178
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001179 // Forward the mangling number from the template to the instantiated decl.
1180 SemaRef.Context.setManglingNumber(Record,
1181 SemaRef.Context.getManglingNumber(D));
1182
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001183 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001184
1185 // DR1484 clarifies that the members of a local class are instantiated as part
1186 // of the instantiation of their enclosing entity.
1187 if (D->isCompleteDefinition() && D->isLocalClass()) {
David Majnemera64cb5a2014-02-22 00:17:46 +00001188 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1189 TSK_ImplicitInstantiation,
1190 /*Complain=*/true);
1191 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1192 TSK_ImplicitInstantiation);
David Majnemer192d1792013-11-27 08:20:38 +00001193 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001194 return Record;
1195}
1196
Douglas Gregor89f593a2012-09-13 21:56:43 +00001197/// \brief Adjust the given function type for an instantiation of the
1198/// given declaration, to cope with modifications to the function's type that
1199/// aren't reflected in the type-source information.
1200///
1201/// \param D The declaration we're instantiating.
1202/// \param TInfo The already-instantiated type.
1203static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1204 FunctionDecl *D,
1205 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001206 const FunctionProtoType *OrigFunc
1207 = D->getType()->castAs<FunctionProtoType>();
1208 const FunctionProtoType *NewFunc
1209 = TInfo->getType()->castAs<FunctionProtoType>();
1210 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1211 return TInfo->getType();
1212
1213 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1214 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001215 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001216 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001217}
1218
John McCallaa74a0c2009-08-28 07:59:38 +00001219/// Normal class members are of more specific types and therefore
1220/// don't make it here. This function serves two purposes:
1221/// 1) instantiating function templates
1222/// 2) substituting friend declarations
Douglas Gregor33636e62009-12-24 20:56:24 +00001223Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001224 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001225 // Check whether there is already a function template specialization for
1226 // this declaration.
1227 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001228 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001229 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001230
Craig Topperc3ec1492014-05-26 06:22:03 +00001231 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001232 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001233 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001234 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001235
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001236 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001237 if (SpecFunc)
1238 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001239 }
Mike Stump11289f42009-09-09 15:08:12 +00001240
John McCall2f88d7d2010-03-27 05:57:59 +00001241 bool isFriend;
1242 if (FunctionTemplate)
1243 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1244 else
1245 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1246
Craig Topperc3ec1492014-05-26 06:22:03 +00001247 bool MergeWithParentScope = (TemplateParams != nullptr) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001248 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001249 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001250 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001251 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001252
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001253 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001254 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001255 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001256 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001257 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001258
Douglas Gregor14454802011-02-25 02:25:35 +00001259 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1260 if (QualifierLoc) {
1261 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1262 TemplateArgs);
1263 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001264 return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001265 }
1266
John McCallce410662010-02-06 01:50:47 +00001267 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001268 // in the enclosing namespace; otherwise we need to find the instantiated
1269 // context.
John McCallce410662010-02-06 01:50:47 +00001270 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001271 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001272 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001273 SemaRef.adjustContextForLocalExternDecl(DC);
1274 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001275 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001276 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001277 DC = SemaRef.computeDeclContext(SS);
Craig Topperc3ec1492014-05-26 06:22:03 +00001278 if (!DC) return nullptr;
John McCalle0b2ddb2010-03-26 04:53:08 +00001279 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001280 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001281 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001282 }
John McCallce410662010-02-06 01:50:47 +00001283
John McCallaa74a0c2009-08-28 07:59:38 +00001284 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001285 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001286 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001287 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001288 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001289 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001290 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001291
Richard Smithf3814ad2013-01-25 00:08:28 +00001292 if (D->isInlined())
1293 Function->setImplicitlyInline();
1294
Douglas Gregor14454802011-02-25 02:25:35 +00001295 if (QualifierLoc)
1296 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001297
Richard Smith541b38b2013-09-20 01:15:31 +00001298 if (D->isLocalExternDecl())
1299 Function->setLocalExternDecl();
1300
John McCall30837102010-03-26 23:10:15 +00001301 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001302 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001303 assert(D->getDeclContext()->isFileContext());
1304 LexicalDC = D->getDeclContext();
1305 }
1306
1307 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001308
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001309 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001310 for (unsigned P = 0; P < Params.size(); ++P)
1311 if (Params[P])
1312 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001313 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001314
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001315 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001316 if (TemplateParams) {
1317 // Our resulting instantiation is actually a function template, since we
1318 // are substituting only the outer template parameters. For example, given
1319 //
1320 // template<typename T>
1321 // struct X {
1322 // template<typename U> friend void f(T, U);
1323 // };
1324 //
1325 // X<int> x;
1326 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001327 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001328 // which means substituting int for T, but leaving "f" as a friend function
1329 // template.
1330 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001331 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001332 Function->getLocation(),
1333 Function->getDeclName(),
1334 TemplateParams, Function);
1335 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001336
1337 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001338
1339 if (isFriend && D->isThisDeclarationADefinition()) {
1340 // TODO: should we remember this connection regardless of whether
1341 // the friend declaration provided a body?
1342 FunctionTemplate->setInstantiatedFromMemberTemplate(
1343 D->getDescribedFunctionTemplate());
1344 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001345 } else if (FunctionTemplate) {
1346 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001347 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001348 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001349 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001350 Innermost.begin(),
1351 Innermost.size()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001352 /*InsertPos=*/nullptr);
Chandler Carruth48b28312011-08-18 09:09:59 +00001353 } else if (isFriend) {
1354 // Note, we need this connection even if the friend doesn't have a body.
1355 // Its body may exist but not have been attached yet due to deferred
1356 // parsing.
1357 // FIXME: It might be cleaner to set this when attaching the body to the
1358 // friend function declaration, however that would require finding all the
1359 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001360 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001361 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001362
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001363 if (InitFunctionInstantiation(Function, D))
1364 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001365
John McCallb9c78482010-04-08 09:05:18 +00001366 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001367
Richard Smith541b38b2013-09-20 01:15:31 +00001368 LookupResult Previous(
1369 SemaRef, Function->getDeclName(), SourceLocation(),
1370 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1371 : Sema::LookupOrdinaryName,
1372 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001373
John McCallb9c78482010-04-08 09:05:18 +00001374 if (DependentFunctionTemplateSpecializationInfo *Info
1375 = D->getDependentSpecializationInfo()) {
1376 assert(isFriend && "non-friend has dependent specialization info?");
1377
1378 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001379 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001380
1381 // Instantiate the explicit template arguments.
1382 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1383 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001384 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1385 ExplicitArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00001386 return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001387
1388 // Map the candidate templates to their instantiations.
1389 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1390 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1391 Info->getTemplate(I),
1392 TemplateArgs);
Craig Topperc3ec1492014-05-26 06:22:03 +00001393 if (!Temp) return nullptr;
John McCallb9c78482010-04-08 09:05:18 +00001394
1395 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1396 }
1397
1398 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1399 &ExplicitArgs,
1400 Previous))
1401 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001402
John McCallb9c78482010-04-08 09:05:18 +00001403 isExplicitSpecialization = true;
1404
1405 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001406 // Look only into the namespace where the friend would be declared to
1407 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001408 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001409 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001410
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001411 // In C++, the previous declaration we find might be a tag type
1412 // (class or enum). In this case, the new declaration will hide the
1413 // tag type. Note that this does does not apply if we're declaring a
1414 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001415 if (Previous.isSingleTagDecl())
1416 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001417 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001418
Craig Topperc3ec1492014-05-26 06:22:03 +00001419 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001420 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001421
John McCallb9467b62010-04-24 01:30:58 +00001422 NamedDecl *PrincipalDecl = (TemplateParams
1423 ? cast<NamedDecl>(FunctionTemplate)
1424 : Function);
1425
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001426 // If the original function was part of a friend declaration,
1427 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001428 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001429 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001430 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001431
Richard Smith91dfaac2014-02-03 02:37:59 +00001432 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001433
Richard Smith91dfaac2014-02-03 02:37:59 +00001434 // C++11 [temp.friend]p4 (DR329):
1435 // When a function is defined in a friend function declaration in a class
1436 // template, the function is instantiated when the function is odr-used.
1437 // The same restrictions on multiple declarations and definitions that
1438 // apply to non-template function declarations and definitions also apply
1439 // to these implicit definitions.
1440 if (D->isThisDeclarationADefinition()) {
Douglas Gregorb92ea592010-05-18 05:45:02 +00001441 // Check for a function body.
Craig Topperc3ec1492014-05-26 06:22:03 +00001442 const FunctionDecl *Definition = nullptr;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001443 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001444 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001445 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1446 << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001447 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001448 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001449 // Check for redefinitions due to other instantiations of this or
1450 // a similar friend function.
Aaron Ballman86c93902014-03-06 23:45:36 +00001451 else for (auto R : Function->redecls()) {
1452 if (R == Function)
Gabor Greif122f1eb2010-08-28 15:42:30 +00001453 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001454
1455 // If some prior declaration of this function has been used, we need
1456 // to instantiate its definition.
1457 if (!QueuedInstantiation && R->isUsed(false)) {
1458 if (MemberSpecializationInfo *MSInfo =
1459 Function->getMemberSpecializationInfo()) {
1460 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1461 SourceLocation Loc = R->getLocation(); // FIXME
1462 MSInfo->setPointOfInstantiation(Loc);
1463 SemaRef.PendingLocalImplicitInstantiations.push_back(
1464 std::make_pair(Function, Loc));
1465 QueuedInstantiation = true;
Gabor Greif718d5152010-08-30 21:10:05 +00001466 }
1467 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001468 }
1469
1470 // If some prior declaration of this function was a friend with an
1471 // uninstantiated definition, reject it.
1472 if (R->getFriendObjectKind()) {
1473 if (const FunctionDecl *RPattern =
1474 R->getTemplateInstantiationPattern()) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001475 if (RPattern->isDefined(RPattern)) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001476 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001477 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001478 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregorb92ea592010-05-18 05:45:02 +00001479 break;
1480 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001481 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001482 }
1483 }
1484 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001485 }
1486
Richard Smith541b38b2013-09-20 01:15:31 +00001487 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1488 DC->makeDeclVisibleInContext(PrincipalDecl);
1489
John McCallb9467b62010-04-24 01:30:58 +00001490 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1491 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1492 PrincipalDecl->setNonMemberOperator();
1493
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001494 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001495 return Function;
1496}
1497
Douglas Gregore704c9d2009-08-27 16:57:43 +00001498Decl *
1499TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001500 TemplateParameterList *TemplateParams,
1501 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001502 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001503 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001504 // We are creating a function template specialization from a function
1505 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001506 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001507 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001508
Craig Topperc3ec1492014-05-26 06:22:03 +00001509 void *InsertPos = nullptr;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001510 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001511 = FunctionTemplate->findSpecialization(Innermost.begin(),
1512 Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001513 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001514
Douglas Gregor97628d62009-08-21 00:16:32 +00001515 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001516 if (SpecFunc)
1517 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001518 }
1519
John McCall2f88d7d2010-03-27 05:57:59 +00001520 bool isFriend;
1521 if (FunctionTemplate)
1522 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1523 else
1524 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1525
Craig Topperc3ec1492014-05-26 06:22:03 +00001526 bool MergeWithParentScope = (TemplateParams != nullptr) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001527 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001528 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001529 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001530
John McCalld0e23ec2010-10-19 02:26:41 +00001531 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001532 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001533 unsigned NumTempParamLists = 0;
1534 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1535 TempParamLists.set_size(NumTempParamLists);
1536 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1537 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1538 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1539 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00001540 return nullptr;
John McCalld0e23ec2010-10-19 02:26:41 +00001541 TempParamLists[I] = InstParams;
1542 }
1543 }
1544
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001545 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001546 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001547 if (!TInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00001548 return nullptr;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001549 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001550
Douglas Gregor14454802011-02-25 02:25:35 +00001551 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1552 if (QualifierLoc) {
1553 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001554 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001555 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00001556 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001557 }
1558
1559 DeclContext *DC = Owner;
1560 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001561 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001562 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001563 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001564 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001565
1566 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
Craig Topperc3ec1492014-05-26 06:22:03 +00001567 return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001568 } else {
1569 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1570 D->getDeclContext(),
1571 TemplateArgs);
1572 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001573 if (!DC) return nullptr;
John McCall2f88d7d2010-03-27 05:57:59 +00001574 }
1575
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001576 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001577 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Craig Topperc3ec1492014-05-26 06:22:03 +00001578 CXXMethodDecl *Method = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001579
Abramo Bagnaradff19302011-03-08 08:55:46 +00001580 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001581 DeclarationNameInfo NameInfo
1582 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001583 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001584 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001585 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001586 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001587 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001588 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001589
Richard Smith185be182013-04-10 05:48:59 +00001590 // Claim that the instantiation of a constructor or constructor template
1591 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001592 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1593 Constructor->getInheritedConstructor())) {
1594 // If we're instantiating a specialization of a function template, our
1595 // "inherited constructor" will actually itself be a function template.
1596 // Instantiate a declaration of it, too.
1597 if (FunctionTemplate) {
1598 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1599 !Inh->getParent()->isDependentContext() &&
1600 "inheriting constructor template in dependent context?");
1601 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1602 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001603 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00001604 return nullptr;
Richard Smith4c163a02013-05-17 02:19:35 +00001605 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1606 LocalInstantiationScope LocalScope(SemaRef);
1607
1608 // Use the same template arguments that we deduced for the inheriting
1609 // constructor. There's no way they could be deduced differently.
1610 MultiLevelTemplateArgumentList InheritedArgs;
1611 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1612 Inh = cast_or_null<CXXConstructorDecl>(
1613 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1614 if (!Inh)
Craig Topperc3ec1492014-05-26 06:22:03 +00001615 return nullptr;
Richard Smith4c163a02013-05-17 02:19:35 +00001616 }
Richard Smith185be182013-04-10 05:48:59 +00001617 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001618 }
Douglas Gregore8394862009-08-21 22:43:28 +00001619 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001620 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001621 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001622 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001623 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001624 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001625 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001626 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001627 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001628 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001629 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001630 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001631 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001632 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001633 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001634 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001635 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001636 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001637 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001638
Richard Smithf3814ad2013-01-25 00:08:28 +00001639 if (D->isInlined())
1640 Method->setImplicitlyInline();
1641
Douglas Gregor14454802011-02-25 02:25:35 +00001642 if (QualifierLoc)
1643 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001644
Douglas Gregore704c9d2009-08-27 16:57:43 +00001645 if (TemplateParams) {
1646 // Our resulting instantiation is actually a function template, since we
1647 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001648 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001649 // template<typename T>
1650 // struct X {
1651 // template<typename U> void f(T, U);
1652 // };
1653 //
1654 // X<int> x;
1655 //
1656 // We are instantiating the member template "f" within X<int>, which means
1657 // substituting int for T, but leaving "f" as a member function template.
1658 // Build the function template itself.
1659 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1660 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001661 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001662 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001663 if (isFriend) {
1664 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001665 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001666 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001667 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001668 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001669 } else if (FunctionTemplate) {
1670 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001671 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001672 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001673 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001674 Innermost.begin(),
1675 Innermost.size()),
Craig Topperc3ec1492014-05-26 06:22:03 +00001676 /*InsertPos=*/nullptr);
John McCall2f88d7d2010-03-27 05:57:59 +00001677 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001678 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001679 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001680 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001681
Mike Stump11289f42009-09-09 15:08:12 +00001682 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001683 // out-of-line, the instantiation will have the same lexical
1684 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001685 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001686 if (NumTempParamLists)
1687 Method->setTemplateParameterListsInfo(SemaRef.Context,
1688 NumTempParamLists,
1689 TempParamLists.data());
1690
John McCall2f88d7d2010-03-27 05:57:59 +00001691 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001692 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001693 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001694 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001695
Douglas Gregor21342092009-03-24 00:38:23 +00001696 // Attach the parameters
1697 for (unsigned P = 0; P < Params.size(); ++P)
1698 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001699 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001700
1701 if (InitMethodInstantiation(Method, D))
1702 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001703
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001704 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1705 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCall2f88d7d2010-03-27 05:57:59 +00001707 if (!FunctionTemplate || TemplateParams || isFriend) {
1708 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001709
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001710 // In C++, the previous declaration we find might be a tag type
1711 // (class or enum). In this case, the new declaration will hide the
1712 // tag type. Note that this does does not apply if we're declaring a
1713 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001714 if (Previous.isSingleTagDecl())
1715 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001716 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001717
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001718 if (!IsClassScopeSpecialization)
Craig Topperc3ec1492014-05-26 06:22:03 +00001719 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001720
Douglas Gregor21920e372009-12-01 17:24:26 +00001721 if (D->isPure())
1722 SemaRef.CheckPureMethod(Method, SourceRange());
1723
John McCalla0a96892012-08-10 03:15:35 +00001724 // Propagate access. For a non-friend declaration, the access is
1725 // whatever we're propagating from. For a friend, it should be the
1726 // previous declaration we just found.
1727 if (isFriend && Method->getPreviousDecl())
1728 Method->setAccess(Method->getPreviousDecl()->getAccess());
1729 else
1730 Method->setAccess(D->getAccess());
1731 if (FunctionTemplate)
1732 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001733
Anders Carlsson7c812f52011-01-20 06:52:44 +00001734 SemaRef.CheckOverrideControl(Method);
1735
Eli Friedman41340732011-11-15 22:39:08 +00001736 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001737 if (D->isExplicitlyDefaulted())
1738 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001739 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001740 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001741
John McCalla0a96892012-08-10 03:15:35 +00001742 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001743 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001744 // do nothing
1745
1746 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001747 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001748 // do nothing
1749
1750 // Otherwise, check access to friends and make them visible.
1751 } else if (isFriend) {
1752 // We only need to re-check access for methods which we didn't
1753 // manage to match during parsing.
1754 if (!D->getPreviousDecl())
1755 SemaRef.CheckFriendAccess(Method);
1756
1757 Record->makeDeclVisibleInContext(Method);
1758
1759 // Otherwise, add the declaration. We don't need to do this for
1760 // class-scope specializations because we'll have matched them with
1761 // the appropriate template.
1762 } else if (!IsClassScopeSpecialization) {
1763 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001764 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001765
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001766 return Method;
1767}
1768
Douglas Gregor4044d992009-03-24 16:43:20 +00001769Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001770 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001771}
1772
Douglas Gregor654b07e2009-03-24 00:15:49 +00001773Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001774 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001775}
1776
Douglas Gregor1880ba52009-03-25 00:34:44 +00001777Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001778 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001779}
1780
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001781Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001782 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1783 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001784}
1785
John McCall87a44eb2009-08-20 01:44:21 +00001786Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1787 TemplateTypeParmDecl *D) {
1788 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001789 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001790
John McCall87a44eb2009-08-20 01:44:21 +00001791 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001792 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1793 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001794 D->getDepth() - TemplateArgs.getNumLevels(),
1795 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001796 D->wasDeclaredWithTypename(),
1797 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001798 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001799
David Majnemer89189202013-08-28 23:48:32 +00001800 if (D->hasDefaultArgument()) {
1801 TypeSourceInfo *InstantiatedDefaultArg =
1802 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1803 D->getDefaultArgumentLoc(), D->getDeclName());
1804 if (InstantiatedDefaultArg)
1805 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1806 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001807
1808 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001809 // scope.
1810 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001811
John McCall87a44eb2009-08-20 01:44:21 +00001812 return Inst;
1813}
1814
Douglas Gregor6b815c82009-10-23 23:25:44 +00001815Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1816 NonTypeTemplateParmDecl *D) {
1817 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001818 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001819 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1820 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001821 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001822 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001823 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001824 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001825
1826 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001827 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001828 // expansion of types. Substitute into each of the expanded types.
1829 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1830 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1831 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1832 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1833 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001834 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001835 D->getDeclName());
1836 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001837 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001838
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001839 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1840 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1841 D->getLocation());
1842 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001843 return nullptr;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001844 ExpandedParameterPackTypes.push_back(NewT);
1845 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001846
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001847 IsExpandedParameterPack = true;
1848 DI = D->getTypeSourceInfo();
1849 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001850 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001851 // The non-type template parameter pack's type is a pack expansion of types.
1852 // Determine whether we need to expand this parameter pack into separate
1853 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001854 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001855 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001856 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001857 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001858
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001859 // Determine whether the set of unexpanded parameter packs can and should
1860 // be expanded.
1861 bool Expand = true;
1862 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001863 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001864 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001865 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001866 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1867 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001868 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001869 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001870 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001871 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00001872 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001873
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001874 if (Expand) {
1875 for (unsigned I = 0; I != *NumExpansions; ++I) {
1876 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1877 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001878 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001879 D->getDeclName());
1880 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001881 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001882
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001883 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1884 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1885 NewDI->getType(),
1886 D->getLocation());
1887 if (NewT.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001888 return nullptr;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001889 ExpandedParameterPackTypes.push_back(NewT);
1890 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001891
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001892 // Note that we have an expanded parameter pack. The "type" of this
1893 // expanded parameter pack is the original expansion type, but callers
1894 // will end up using the expanded parameter pack types for type-checking.
1895 IsExpandedParameterPack = true;
1896 DI = D->getTypeSourceInfo();
1897 T = DI->getType();
1898 } else {
1899 // We cannot fully expand the pack expansion now, so substitute into the
1900 // pattern and create a new pack expansion type.
1901 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1902 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001903 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001904 D->getDeclName());
1905 if (!NewPattern)
Craig Topperc3ec1492014-05-26 06:22:03 +00001906 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001907
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001908 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1909 NumExpansions);
1910 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001911 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001912
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001913 T = DI->getType();
1914 }
1915 } else {
1916 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001917 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001918 D->getLocation(), D->getDeclName());
1919 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001920 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001921
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001922 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001923 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001924 D->getLocation());
1925 if (T.isNull()) {
1926 T = SemaRef.Context.IntTy;
1927 Invalid = true;
1928 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001929 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001930
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001931 NonTypeTemplateParmDecl *Param;
1932 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001933 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001934 D->getInnerLocStart(),
1935 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001936 D->getDepth() - TemplateArgs.getNumLevels(),
1937 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001938 D->getIdentifier(), T,
1939 DI,
1940 ExpandedParameterPackTypes.data(),
1941 ExpandedParameterPackTypes.size(),
1942 ExpandedParameterPackTypesAsWritten.data());
1943 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001944 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001945 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001946 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001947 D->getDepth() - TemplateArgs.getNumLevels(),
1948 D->getPosition(),
1949 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001950 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001951
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001952 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001953 if (Invalid)
1954 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001955
David Majnemer89189202013-08-28 23:48:32 +00001956 if (D->hasDefaultArgument()) {
1957 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1958 if (!Value.isInvalid())
1959 Param->setDefaultArgument(Value.get(), false);
1960 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001961
1962 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001963 // scope.
1964 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001965 return Param;
1966}
1967
Richard Smith1fde8ec2012-09-07 02:06:42 +00001968static void collectUnexpandedParameterPacks(
1969 Sema &S,
1970 TemplateParameterList *Params,
1971 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1972 for (TemplateParameterList::const_iterator I = Params->begin(),
1973 E = Params->end(); I != E; ++I) {
1974 if ((*I)->isTemplateParameterPack())
1975 continue;
1976 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1977 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1978 Unexpanded);
1979 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1980 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1981 Unexpanded);
1982 }
1983}
1984
Anders Carlsson4bd78752009-08-28 15:18:15 +00001985Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001986TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1987 TemplateTemplateParmDecl *D) {
1988 // Instantiate the template parameter list of the template template parameter.
1989 TemplateParameterList *TempParams = D->getTemplateParameters();
1990 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001991 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1992
1993 bool IsExpandedParameterPack = false;
1994
1995 if (D->isExpandedParameterPack()) {
1996 // The template template parameter pack is an already-expanded pack
1997 // expansion of template parameters. Substitute into each of the expanded
1998 // parameters.
1999 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2000 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2001 I != N; ++I) {
2002 LocalInstantiationScope Scope(SemaRef);
2003 TemplateParameterList *Expansion =
2004 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2005 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002006 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002007 ExpandedParams.push_back(Expansion);
2008 }
2009
2010 IsExpandedParameterPack = true;
2011 InstParams = TempParams;
2012 } else if (D->isPackExpansion()) {
2013 // The template template parameter pack expands to a pack of template
2014 // template parameters. Determine whether we need to expand this parameter
2015 // pack into separate parameters.
2016 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2017 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2018 Unexpanded);
2019
2020 // Determine whether the set of unexpanded parameter packs can and should
2021 // be expanded.
2022 bool Expand = true;
2023 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002024 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002025 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2026 TempParams->getSourceRange(),
2027 Unexpanded,
2028 TemplateArgs,
2029 Expand, RetainExpansion,
2030 NumExpansions))
Craig Topperc3ec1492014-05-26 06:22:03 +00002031 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002032
2033 if (Expand) {
2034 for (unsigned I = 0; I != *NumExpansions; ++I) {
2035 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2036 LocalInstantiationScope Scope(SemaRef);
2037 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2038 if (!Expansion)
Craig Topperc3ec1492014-05-26 06:22:03 +00002039 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002040 ExpandedParams.push_back(Expansion);
2041 }
2042
2043 // Note that we have an expanded parameter pack. The "type" of this
2044 // expanded parameter pack is the original expansion type, but callers
2045 // will end up using the expanded parameter pack types for type-checking.
2046 IsExpandedParameterPack = true;
2047 InstParams = TempParams;
2048 } else {
2049 // We cannot fully expand the pack expansion now, so just substitute
2050 // into the pattern.
2051 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2052
2053 LocalInstantiationScope Scope(SemaRef);
2054 InstParams = SubstTemplateParams(TempParams);
2055 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002056 return nullptr;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002057 }
2058 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002059 // Perform the actual substitution of template parameters within a new,
2060 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002061 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002062 InstParams = SubstTemplateParams(TempParams);
2063 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002064 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002065 }
2066
Douglas Gregor38fee962009-11-11 16:58:32 +00002067 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002068 TemplateTemplateParmDecl *Param;
2069 if (IsExpandedParameterPack)
2070 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2071 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002072 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002073 D->getPosition(),
2074 D->getIdentifier(), InstParams,
2075 ExpandedParams);
2076 else
2077 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2078 D->getLocation(),
2079 D->getDepth() - TemplateArgs.getNumLevels(),
2080 D->getPosition(),
2081 D->isParameterPack(),
2082 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002083 if (D->hasDefaultArgument()) {
2084 NestedNameSpecifierLoc QualifierLoc =
2085 D->getDefaultArgument().getTemplateQualifierLoc();
2086 QualifierLoc =
2087 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2088 TemplateName TName = SemaRef.SubstTemplateName(
2089 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2090 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2091 if (!TName.isNull())
2092 Param->setDefaultArgument(
2093 TemplateArgumentLoc(TemplateArgument(TName),
2094 D->getDefaultArgument().getTemplateQualifierLoc(),
2095 D->getDefaultArgument().getTemplateNameLoc()),
2096 false);
2097 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002098 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002099
2100 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002101 // scope.
2102 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002103
Douglas Gregor38fee962009-11-11 16:58:32 +00002104 return Param;
2105}
2106
Douglas Gregore0b28662009-11-17 06:07:40 +00002107Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002108 // Using directives are never dependent (and never contain any types or
2109 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002110
Douglas Gregore0b28662009-11-17 06:07:40 +00002111 UsingDirectiveDecl *Inst
2112 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002113 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002114 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002115 D->getIdentLocation(),
2116 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002117 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002118
2119 // Add the using directive to its declaration context
2120 // only if this is not a function or method.
2121 if (!Owner->isFunctionOrMethod())
2122 Owner->addDecl(Inst);
2123
Douglas Gregore0b28662009-11-17 06:07:40 +00002124 return Inst;
2125}
2126
John McCallb96ec562009-12-04 22:46:56 +00002127Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002128
2129 // The nested name specifier may be dependent, for example
2130 // template <typename T> struct t {
2131 // struct s1 { T f1(); };
2132 // struct s2 : s1 { using s1::f1; };
2133 // };
2134 // template struct t<int>;
2135 // Here, in using s1::f1, s1 refers to t<T>::s1;
2136 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002137 NestedNameSpecifierLoc QualifierLoc
2138 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2139 TemplateArgs);
2140 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002141 return nullptr;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002142
2143 // The name info is non-dependent, so no transformation
2144 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002145 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002146
John McCall84d87672009-12-10 09:41:52 +00002147 // We only need to do redeclaration lookups if we're in a class
2148 // scope (in fact, it's not really even possible in non-class
2149 // scopes).
2150 bool CheckRedeclaration = Owner->isRecord();
2151
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002152 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2153 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002154
John McCallb96ec562009-12-04 22:46:56 +00002155 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002156 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002157 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002158 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002159 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002160
Douglas Gregor0499ab62011-02-25 15:54:31 +00002161 CXXScopeSpec SS;
2162 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002163 if (CheckRedeclaration) {
2164 Prev.setHideTags(false);
2165 SemaRef.LookupQualifiedName(Prev, Owner);
2166
2167 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002168 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2169 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002170 D->getLocation(), Prev))
2171 NewUD->setInvalidDecl();
2172
2173 }
2174
2175 if (!NewUD->isInvalidDecl() &&
Richard Smith7ad0b882014-04-02 21:44:35 +00002176 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00002177 D->getLocation()))
2178 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002179
John McCallb96ec562009-12-04 22:46:56 +00002180 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2181 NewUD->setAccess(D->getAccess());
2182 Owner->addDecl(NewUD);
2183
John McCall84d87672009-12-10 09:41:52 +00002184 // Don't process the shadow decls for an invalid decl.
2185 if (NewUD->isInvalidDecl())
2186 return NewUD;
2187
Richard Smith23d55872012-04-02 01:30:27 +00002188 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00002189 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002190 return NewUD;
2191 }
2192
John McCalla1d85502009-12-22 22:26:37 +00002193 bool isFunctionScope = Owner->isFunctionOrMethod();
2194
John McCall84d87672009-12-10 09:41:52 +00002195 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002196 for (auto *Shadow : D->shadows()) {
John McCall84d87672009-12-10 09:41:52 +00002197 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002198 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2199 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002200 if (!InstTarget)
Craig Topperc3ec1492014-05-26 06:22:03 +00002201 return nullptr;
John McCall84d87672009-12-10 09:41:52 +00002202
Craig Topperc3ec1492014-05-26 06:22:03 +00002203 UsingShadowDecl *PrevDecl = nullptr;
Richard Smithfd8634a2013-10-23 02:17:46 +00002204 if (CheckRedeclaration) {
2205 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2206 continue;
2207 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2208 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2209 Shadow->getLocation(), OldPrev, TemplateArgs));
2210 }
John McCall84d87672009-12-10 09:41:52 +00002211
Richard Smithfd8634a2013-10-23 02:17:46 +00002212 UsingShadowDecl *InstShadow =
Craig Topperc3ec1492014-05-26 06:22:03 +00002213 SemaRef.BuildUsingShadowDecl(/*Scope*/nullptr, NewUD, InstTarget,
2214 PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002215 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002216
2217 if (isFunctionScope)
2218 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002219 }
John McCallb96ec562009-12-04 22:46:56 +00002220
2221 return NewUD;
2222}
2223
2224Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002225 // Ignore these; we handle them in bulk when processing the UsingDecl.
Craig Topperc3ec1492014-05-26 06:22:03 +00002226 return nullptr;
John McCallb96ec562009-12-04 22:46:56 +00002227}
2228
John McCalle61f2ba2009-11-18 02:36:19 +00002229Decl * TemplateDeclInstantiator
2230 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002231 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002232 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002233 TemplateArgs);
2234 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002235 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00002236
Anders Carlsson4bd78752009-08-28 15:18:15 +00002237 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002238 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002239
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002240 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002241 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002242 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002243 NamedDecl *UD =
Craig Topperc3ec1492014-05-26 06:22:03 +00002244 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2245 D->getUsingLoc(), SS, NameInfo, nullptr,
John McCalle61f2ba2009-11-18 02:36:19 +00002246 /*instantiation*/ true,
2247 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002248 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002249 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2250
John McCalle61f2ba2009-11-18 02:36:19 +00002251 return UD;
2252}
2253
2254Decl * TemplateDeclInstantiator
2255 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002256 NestedNameSpecifierLoc QualifierLoc
2257 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2258 if (!QualifierLoc)
Craig Topperc3ec1492014-05-26 06:22:03 +00002259 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002260
John McCalle61f2ba2009-11-18 02:36:19 +00002261 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002262 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002263
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002264 DeclarationNameInfo NameInfo
2265 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2266
John McCalle61f2ba2009-11-18 02:36:19 +00002267 NamedDecl *UD =
Craig Topperc3ec1492014-05-26 06:22:03 +00002268 SemaRef.BuildUsingDeclaration(/*Scope*/ nullptr, D->getAccess(),
2269 D->getUsingLoc(), SS, NameInfo, nullptr,
John McCalle61f2ba2009-11-18 02:36:19 +00002270 /*instantiation*/ true,
2271 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002272 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002273 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2274
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002275 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002276}
2277
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002278
2279Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2280 ClassScopeFunctionSpecializationDecl *Decl) {
2281 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002282 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
Craig Topperc3ec1492014-05-26 06:22:03 +00002283 nullptr, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002284
2285 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2286 Sema::ForRedeclaration);
2287
Nico Weber7b5a7162012-06-25 17:21:05 +00002288 TemplateArgumentListInfo TemplateArgs;
Craig Topperc3ec1492014-05-26 06:22:03 +00002289 TemplateArgumentListInfo *TemplateArgsPtr = nullptr;
Nico Weber7b5a7162012-06-25 17:21:05 +00002290 if (Decl->hasExplicitTemplateArgs()) {
2291 TemplateArgs = Decl->templateArgs();
2292 TemplateArgsPtr = &TemplateArgs;
2293 }
2294
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002295 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002296 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2297 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002298 NewFD->setInvalidDecl();
2299 return NewFD;
2300 }
2301
2302 // Associate the specialization with the pattern.
2303 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2304 assert(Specialization && "Class scope Specialization is null");
2305 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2306
2307 return NewFD;
2308}
2309
Alexey Bataeva769e072013-03-22 06:34:35 +00002310Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2311 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002312 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002313 for (auto *I : D->varlists()) {
2314 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).take();
Alexey Bataeva769e072013-03-22 06:34:35 +00002315 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002316 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002317 }
2318
2319 OMPThreadPrivateDecl *TD =
2320 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2321
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002322 TD->setAccess(AS_public);
2323 Owner->addDecl(TD);
2324
Alexey Bataeva769e072013-03-22 06:34:35 +00002325 return TD;
2326}
2327
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002328Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002329 return VisitFunctionDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002330}
2331
2332Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002333 return VisitCXXMethodDecl(D, nullptr);
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002334}
2335
2336Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2337 llvm_unreachable("There are only CXXRecordDecls in C++");
2338}
2339
2340Decl *
2341TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2342 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002343 // As a MS extension, we permit class-scope explicit specialization
2344 // of member class templates.
2345 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2346 assert(ClassTemplate->getDeclContext()->isRecord() &&
2347 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2348 "can only instantiate an explicit specialization "
2349 "for a member class template");
2350
2351 // Lookup the already-instantiated declaration in the instantiation
2352 // of the class template. FIXME: Diagnose or assert if this fails?
2353 DeclContext::lookup_result Found
2354 = Owner->lookup(ClassTemplate->getDeclName());
2355 if (Found.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00002356 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002357 ClassTemplateDecl *InstClassTemplate
2358 = dyn_cast<ClassTemplateDecl>(Found.front());
2359 if (!InstClassTemplate)
Craig Topperc3ec1492014-05-26 06:22:03 +00002360 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002361
2362 // Substitute into the template arguments of the class template explicit
2363 // specialization.
2364 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2365 castAs<TemplateSpecializationTypeLoc>();
2366 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2367 Loc.getRAngleLoc());
2368 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2369 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2370 ArgLocs.push_back(Loc.getArgLoc(I));
2371 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2372 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002373 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002374
2375 // Check that the template argument list is well-formed for this
2376 // class template.
2377 SmallVector<TemplateArgument, 4> Converted;
2378 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2379 D->getLocation(),
2380 InstTemplateArgs,
2381 false,
2382 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002383 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002384
2385 // Figure out where to insert this class template explicit specialization
2386 // in the member template's set of class template explicit specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002387 void *InsertPos = nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002388 ClassTemplateSpecializationDecl *PrevDecl =
2389 InstClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2390 InsertPos);
2391
2392 // Check whether we've already seen a conflicting instantiation of this
2393 // declaration (for instance, if there was a prior implicit instantiation).
2394 bool Ignored;
2395 if (PrevDecl &&
2396 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2397 D->getSpecializationKind(),
2398 PrevDecl,
2399 PrevDecl->getSpecializationKind(),
2400 PrevDecl->getPointOfInstantiation(),
2401 Ignored))
Craig Topperc3ec1492014-05-26 06:22:03 +00002402 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002403
2404 // If PrevDecl was a definition and D is also a definition, diagnose.
2405 // This happens in cases like:
2406 //
2407 // template<typename T, typename U>
2408 // struct Outer {
2409 // template<typename X> struct Inner;
2410 // template<> struct Inner<T> {};
2411 // template<> struct Inner<U> {};
2412 // };
2413 //
2414 // Outer<int, int> outer; // error: the explicit specializations of Inner
2415 // // have the same signature.
2416 if (PrevDecl && PrevDecl->getDefinition() &&
2417 D->isThisDeclarationADefinition()) {
2418 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2419 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2420 diag::note_previous_definition);
Craig Topperc3ec1492014-05-26 06:22:03 +00002421 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002422 }
2423
2424 // Create the class template partial specialization declaration.
2425 ClassTemplateSpecializationDecl *InstD
2426 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2427 D->getTagKind(),
2428 Owner,
2429 D->getLocStart(),
2430 D->getLocation(),
2431 InstClassTemplate,
2432 Converted.data(),
2433 Converted.size(),
2434 PrevDecl);
2435
2436 // Add this partial specialization to the set of class template partial
2437 // specializations.
2438 if (!PrevDecl)
2439 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2440
2441 // Substitute the nested name specifier, if any.
2442 if (SubstQualifier(D, InstD))
Craig Topperc3ec1492014-05-26 06:22:03 +00002443 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002444
2445 // Build the canonical type that describes the converted template
2446 // arguments of the class template explicit specialization.
2447 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2448 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2449 SemaRef.Context.getRecordType(InstD));
2450
2451 // Build the fully-sugared type for this class template
2452 // specialization as the user wrote in the specialization
2453 // itself. This means that we'll pretty-print the type retrieved
2454 // from the specialization's declaration the way that the user
2455 // actually wrote the specialization, rather than formatting the
2456 // name based on the "canonical" representation used to store the
2457 // template arguments in the specialization.
2458 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2459 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2460 CanonType);
2461
2462 InstD->setAccess(D->getAccess());
2463 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2464 InstD->setSpecializationKind(D->getSpecializationKind());
2465 InstD->setTypeAsWritten(WrittenTy);
2466 InstD->setExternLoc(D->getExternLoc());
2467 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2468
2469 Owner->addDecl(InstD);
2470
2471 // Instantiate the members of the class-scope explicit specialization eagerly.
2472 // We don't have support for lazy instantiation of an explicit specialization
2473 // yet, and MSVC eagerly instantiates in this case.
2474 if (D->isThisDeclarationADefinition() &&
2475 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2476 TSK_ImplicitInstantiation,
2477 /*Complain=*/true))
Craig Topperc3ec1492014-05-26 06:22:03 +00002478 return nullptr;
Richard Smith8a0dde72013-12-14 01:04:22 +00002479
2480 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002481}
2482
Larisse Voufo39a1e502013-08-06 01:03:05 +00002483Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2484 VarTemplateSpecializationDecl *D) {
2485
2486 TemplateArgumentListInfo VarTemplateArgsInfo;
2487 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2488 assert(VarTemplate &&
2489 "A template specialization without specialized template?");
2490
2491 // Substitute the current template arguments.
2492 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2493 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2494 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2495
2496 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2497 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002498 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002499
2500 // Check that the template argument list is well-formed for this template.
2501 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002502 if (SemaRef.CheckTemplateArgumentList(
2503 VarTemplate, VarTemplate->getLocStart(),
2504 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002505 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002506 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002507
2508 // Find the variable template specialization declaration that
2509 // corresponds to these arguments.
Craig Topperc3ec1492014-05-26 06:22:03 +00002510 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002511 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2512 Converted.data(), Converted.size(), InsertPos))
2513 // If we already have a variable template specialization, return it.
2514 return VarSpec;
2515
2516 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2517 VarTemplateArgsInfo, Converted);
2518}
2519
2520Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2521 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2522 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smith8809a0c2013-09-27 20:14:12 +00002523 llvm::ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002524
2525 // If this is the variable for an anonymous struct or union,
2526 // instantiate the anonymous struct/union type first.
2527 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2528 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2529 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
Craig Topperc3ec1492014-05-26 06:22:03 +00002530 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002531
2532 // Do substitution on the type of the declaration
2533 TypeSourceInfo *DI =
2534 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2535 D->getTypeSpecStartLoc(), D->getDeclName());
2536 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002537 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002538
2539 if (DI->getType()->isFunctionType()) {
2540 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2541 << D->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00002542 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002543 }
2544
2545 // Build the instantiated declaration
2546 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2547 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2548 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2549 Converted.size());
2550 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002551 if (InsertPos)
2552 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002553
2554 // Substitute the nested name specifier, if any.
2555 if (SubstQualifier(D, Var))
Craig Topperc3ec1492014-05-26 06:22:03 +00002556 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002557
2558 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002559 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002560
2561 return Var;
2562}
2563
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002564Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2565 llvm_unreachable("@defs is not supported in Objective-C++");
2566}
2567
2568Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2569 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2570 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2571 DiagnosticsEngine::Error,
2572 "cannot instantiate %0 yet");
2573 SemaRef.Diag(D->getLocation(), DiagID)
2574 << D->getDeclKindName();
2575
Craig Topperc3ec1492014-05-26 06:22:03 +00002576 return nullptr;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002577}
2578
2579Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2580 llvm_unreachable("Unexpected decl");
2581}
2582
John McCall76d824f2009-08-25 22:02:44 +00002583Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002584 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002585 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002586 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00002587 return nullptr;
Douglas Gregor71ad4772010-02-16 19:28:15 +00002588
Douglas Gregord7e7a512009-03-17 21:15:40 +00002589 return Instantiator.Visit(D);
2590}
2591
John McCall87a44eb2009-08-20 01:44:21 +00002592/// \brief Instantiates a nested template parameter list in the current
2593/// instantiation context.
2594///
2595/// \param L The parameter list to instantiate
2596///
2597/// \returns NULL if there was an error
2598TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002599TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002600 // Get errors for all the parameters before bailing out.
2601 bool Invalid = false;
2602
2603 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002604 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002605 ParamVector Params;
2606 Params.reserve(N);
2607 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2608 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002609 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002610 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002611 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002612 }
2613
2614 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002615 if (Invalid)
Craig Topperc3ec1492014-05-26 06:22:03 +00002616 return nullptr;
John McCall87a44eb2009-08-20 01:44:21 +00002617
2618 TemplateParameterList *InstL
2619 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2620 L->getLAngleLoc(), &Params.front(), N,
2621 L->getRAngleLoc());
2622 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002623}
John McCall87a44eb2009-08-20 01:44:21 +00002624
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002625/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002626/// specialization.
2627///
2628/// \param ClassTemplate the (instantiated) class template that is partially
2629// specialized by the instantiation of \p PartialSpec.
2630///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002631/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002632/// specialization that we are instantiating.
2633///
Douglas Gregor869853e2010-11-10 19:44:59 +00002634/// \returns The instantiated partial specialization, if successful; otherwise,
2635/// NULL to indicate an error.
2636ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002637TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2638 ClassTemplateDecl *ClassTemplate,
2639 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002640 // Create a local instantiation scope for this class template partial
2641 // specialization, which will contain the instantiations of the template
2642 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002643 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002644
Douglas Gregor21610382009-10-29 00:04:11 +00002645 // Substitute into the template parameters of the class template partial
2646 // specialization.
2647 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2648 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2649 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002650 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002651
Douglas Gregor21610382009-10-29 00:04:11 +00002652 // Substitute into the template arguments of the class template partial
2653 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002654 const ASTTemplateArgumentListInfo *TemplArgInfo
2655 = PartialSpec->getTemplateArgsAsWritten();
2656 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2657 TemplArgInfo->RAngleLoc);
2658 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2659 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002660 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002661 return nullptr;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002662
Douglas Gregor21610382009-10-29 00:04:11 +00002663 // Check that the template argument list is well-formed for this
2664 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002665 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002666 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002667 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002668 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002669 false,
2670 Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002671 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002672
2673 // Figure out where to insert this class template partial specialization
2674 // in the member template's set of class template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002675 void *InsertPos = nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002676 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002677 = ClassTemplate->findPartialSpecialization(Converted.data(),
2678 Converted.size(), InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002679
Douglas Gregor21610382009-10-29 00:04:11 +00002680 // Build the canonical type that describes the converted template
2681 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002682 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002683 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002684 Converted.data(),
2685 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002686
2687 // Build the fully-sugared type for this class template
2688 // specialization as the user wrote in the specialization
2689 // itself. This means that we'll pretty-print the type retrieved
2690 // from the specialization's declaration the way that the user
2691 // actually wrote the specialization, rather than formatting the
2692 // name based on the "canonical" representation used to store the
2693 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002694 TypeSourceInfo *WrittenTy
2695 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2696 TemplateName(ClassTemplate),
2697 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002698 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002699 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002700
Douglas Gregor21610382009-10-29 00:04:11 +00002701 if (PrevDecl) {
2702 // We've already seen a partial specialization with the same template
2703 // parameters and template arguments. This can happen, for example, when
2704 // substituting the outer template arguments ends up causing two
2705 // class template partial specializations of a member class template
2706 // to have identical forms, e.g.,
2707 //
2708 // template<typename T, typename U>
2709 // struct Outer {
2710 // template<typename X, typename Y> struct Inner;
2711 // template<typename Y> struct Inner<T, Y>;
2712 // template<typename Y> struct Inner<U, Y>;
2713 // };
2714 //
2715 // Outer<int, int> outer; // error: the partial specializations of Inner
2716 // // have the same signature.
2717 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002718 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002719 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2720 << SemaRef.Context.getTypeDeclType(PrevDecl);
Craig Topperc3ec1492014-05-26 06:22:03 +00002721 return nullptr;
Douglas Gregor21610382009-10-29 00:04:11 +00002722 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002723
2724
Douglas Gregor21610382009-10-29 00:04:11 +00002725 // Create the class template partial specialization declaration.
2726 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002727 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002728 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002729 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002730 PartialSpec->getLocStart(),
2731 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002732 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002733 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002734 Converted.data(),
2735 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002736 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002737 CanonType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002738 nullptr);
John McCall3e11ebe2010-03-15 10:12:16 +00002739 // Substitute the nested name specifier, if any.
2740 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00002741 return nullptr;
John McCall3e11ebe2010-03-15 10:12:16 +00002742
Douglas Gregor21610382009-10-29 00:04:11 +00002743 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002744 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002745
Douglas Gregor21610382009-10-29 00:04:11 +00002746 // Add this partial specialization to the set of class template partial
2747 // specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002748 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
2749 /*InsertPos=*/nullptr);
Douglas Gregor869853e2010-11-10 19:44:59 +00002750 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002751}
2752
Larisse Voufo39a1e502013-08-06 01:03:05 +00002753/// \brief Instantiate the declaration of a variable template partial
2754/// specialization.
2755///
2756/// \param VarTemplate the (instantiated) variable template that is partially
2757/// specialized by the instantiation of \p PartialSpec.
2758///
2759/// \param PartialSpec the (uninstantiated) variable template partial
2760/// specialization that we are instantiating.
2761///
2762/// \returns The instantiated partial specialization, if successful; otherwise,
2763/// NULL to indicate an error.
2764VarTemplatePartialSpecializationDecl *
2765TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2766 VarTemplateDecl *VarTemplate,
2767 VarTemplatePartialSpecializationDecl *PartialSpec) {
2768 // Create a local instantiation scope for this variable template partial
2769 // specialization, which will contain the instantiations of the template
2770 // parameters.
2771 LocalInstantiationScope Scope(SemaRef);
2772
2773 // Substitute into the template parameters of the variable template partial
2774 // specialization.
2775 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2776 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2777 if (!InstParams)
Craig Topperc3ec1492014-05-26 06:22:03 +00002778 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002779
2780 // Substitute into the template arguments of the variable template partial
2781 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002782 const ASTTemplateArgumentListInfo *TemplArgInfo
2783 = PartialSpec->getTemplateArgsAsWritten();
2784 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2785 TemplArgInfo->RAngleLoc);
2786 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2787 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002788 InstTemplateArgs, TemplateArgs))
Craig Topperc3ec1492014-05-26 06:22:03 +00002789 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002790
2791 // Check that the template argument list is well-formed for this
2792 // class template.
2793 SmallVector<TemplateArgument, 4> Converted;
2794 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2795 InstTemplateArgs, false, Converted))
Craig Topperc3ec1492014-05-26 06:22:03 +00002796 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002797
2798 // Figure out where to insert this variable template partial specialization
2799 // in the member template's set of variable template partial specializations.
Craig Topperc3ec1492014-05-26 06:22:03 +00002800 void *InsertPos = nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002801 VarTemplateSpecializationDecl *PrevDecl =
2802 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2803 InsertPos);
2804
2805 // Build the canonical type that describes the converted template
2806 // arguments of the variable template partial specialization.
2807 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2808 TemplateName(VarTemplate), Converted.data(), Converted.size());
2809
2810 // Build the fully-sugared type for this variable template
2811 // specialization as the user wrote in the specialization
2812 // itself. This means that we'll pretty-print the type retrieved
2813 // from the specialization's declaration the way that the user
2814 // actually wrote the specialization, rather than formatting the
2815 // name based on the "canonical" representation used to store the
2816 // template arguments in the specialization.
2817 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2818 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2819 CanonType);
2820
2821 if (PrevDecl) {
2822 // We've already seen a partial specialization with the same template
2823 // parameters and template arguments. This can happen, for example, when
2824 // substituting the outer template arguments ends up causing two
2825 // variable template partial specializations of a member variable template
2826 // to have identical forms, e.g.,
2827 //
2828 // template<typename T, typename U>
2829 // struct Outer {
2830 // template<typename X, typename Y> pair<X,Y> p;
2831 // template<typename Y> pair<T, Y> p;
2832 // template<typename Y> pair<U, Y> p;
2833 // };
2834 //
2835 // Outer<int, int> outer; // error: the partial specializations of Inner
2836 // // have the same signature.
2837 SemaRef.Diag(PartialSpec->getLocation(),
2838 diag::err_var_partial_spec_redeclared)
2839 << WrittenTy->getType();
2840 SemaRef.Diag(PrevDecl->getLocation(),
2841 diag::note_var_prev_partial_spec_here);
Craig Topperc3ec1492014-05-26 06:22:03 +00002842 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002843 }
2844
2845 // Do substitution on the type of the declaration
2846 TypeSourceInfo *DI = SemaRef.SubstType(
2847 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2848 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2849 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00002850 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002851
2852 if (DI->getType()->isFunctionType()) {
2853 SemaRef.Diag(PartialSpec->getLocation(),
2854 diag::err_variable_instantiates_to_function)
2855 << PartialSpec->isStaticDataMember() << DI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00002856 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002857 }
2858
2859 // Create the variable template partial specialization declaration.
2860 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2861 VarTemplatePartialSpecializationDecl::Create(
2862 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2863 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2864 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002865 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002866
2867 // Substitute the nested name specifier, if any.
2868 if (SubstQualifier(PartialSpec, InstPartialSpec))
Craig Topperc3ec1492014-05-26 06:22:03 +00002869 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002870
2871 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2872 InstPartialSpec->setTypeAsWritten(WrittenTy);
2873
Larisse Voufo39a1e502013-08-06 01:03:05 +00002874 // Add this partial specialization to the set of variable template partial
2875 // specializations. The instantiation of the initializer is not necessary.
Craig Topperc3ec1492014-05-26 06:22:03 +00002876 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002877
Larisse Voufo4cda4612013-08-22 00:28:27 +00002878 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002879 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002880
Larisse Voufo39a1e502013-08-06 01:03:05 +00002881 return InstPartialSpec;
2882}
2883
John McCall58f10c32010-03-11 09:03:00 +00002884TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002885TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002886 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002887 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2888 assert(OldTInfo && "substituting function without type source info");
2889 assert(Params.empty() && "parameter vector is non-empty at start");
Craig Topperc3ec1492014-05-26 06:22:03 +00002890
2891 CXXRecordDecl *ThisContext = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +00002892 unsigned ThisTypeQuals = 0;
2893 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002894 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002895 ThisTypeQuals = Method->getTypeQualifiers();
2896 }
2897
John McCallb29f78f2010-04-09 17:38:44 +00002898 TypeSourceInfo *NewTInfo
2899 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2900 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002901 D->getDeclName(),
2902 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002903 if (!NewTInfo)
Craig Topperc3ec1492014-05-26 06:22:03 +00002904 return nullptr;
Douglas Gregor21342092009-03-24 00:38:23 +00002905
Reid Klecknera09e44c2013-07-31 21:00:18 +00002906 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2907 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2908 if (NewTInfo != OldTInfo) {
2909 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002910 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002911 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002912 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002913 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00002914 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002915 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002916 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2917
David Blaikie05785d12013-02-20 22:23:23 +00002918 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002919 if (OldParam->isParameterPack())
2920 NumArgumentsInExpansion =
2921 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2922 TemplateArgs);
2923 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002924 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002925 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002926 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002927 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002928 Scope->InstantiatedLocal(OldParam, NewParam);
2929 } else {
2930 // Parameter pack expansion: make the instantiation an argument pack.
2931 Scope->MakeInstantiatedLocalArgPack(OldParam);
2932 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002933 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002934 Params.push_back(NewParam);
2935 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2936 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002937 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002938 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002939 } else {
2940 // The function type itself was not dependent and therefore no
2941 // substitution occurred. However, we still need to instantiate
2942 // the function parameters themselves.
2943 const FunctionProtoType *OldProto =
2944 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002945 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
2946 ++i) {
2947 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00002948 if (!OldParam) {
2949 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00002950 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00002951 continue;
2952 }
2953
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002954 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002955 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002956 if (!Parm)
Craig Topperc3ec1492014-05-26 06:22:03 +00002957 return nullptr;
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002958 Params.push_back(Parm);
2959 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002960 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002961 } else {
2962 // If the type of this function, after ignoring parentheses, is not
2963 // *directly* a function type, then we're instantiating a function that
2964 // was declared via a typedef or with attributes, e.g.,
2965 //
2966 // typedef int functype(int, int);
2967 // functype func;
2968 // int __cdecl meth(int, int);
2969 //
2970 // In this case, we'll just go instantiate the ParmVarDecls that we
2971 // synthesized in the method declaration.
2972 SmallVector<QualType, 4> ParamTypes;
2973 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2974 D->getNumParams(), TemplateArgs, ParamTypes,
2975 &Params))
Craig Topperc3ec1492014-05-26 06:22:03 +00002976 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00002977 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002978
John McCall58f10c32010-03-11 09:03:00 +00002979 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002980}
2981
Richard Smithf623c962012-04-17 00:58:00 +00002982/// Introduce the instantiated function parameters into the local
2983/// instantiation scope, and set the parameter names to those used
2984/// in the template.
2985static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2986 const FunctionDecl *PatternDecl,
2987 LocalInstantiationScope &Scope,
2988 const MultiLevelTemplateArgumentList &TemplateArgs) {
2989 unsigned FParamIdx = 0;
2990 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2991 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2992 if (!PatternParam->isParameterPack()) {
2993 // Simple case: not a parameter pack.
2994 assert(FParamIdx < Function->getNumParams());
2995 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smithaae40582014-03-13 00:28:45 +00002996 // If the parameter's type is not dependent, update it to match the type
2997 // in the pattern. They can differ in top-level cv-qualifiers, and we want
2998 // the pattern's type here. If the type is dependent, they can't differ,
2999 // per core issue 1668.
3000 // FIXME: Updating the type to work around this is at best fragile.
3001 if (!PatternDecl->getType()->isDependentType())
3002 FunctionParam->setType(PatternParam->getType());
3003
Richard Smithf623c962012-04-17 00:58:00 +00003004 FunctionParam->setDeclName(PatternParam->getDeclName());
3005 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3006 ++FParamIdx;
3007 continue;
3008 }
3009
3010 // Expand the parameter pack.
3011 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003012 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003013 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003014 assert(NumArgumentsInExpansion &&
3015 "should only be called when all template arguments are known");
3016 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003017 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smithaae40582014-03-13 00:28:45 +00003018 if (!PatternDecl->getType()->isDependentType())
3019 FunctionParam->setType(PatternParam->getType());
3020
Richard Smithf623c962012-04-17 00:58:00 +00003021 FunctionParam->setDeclName(PatternParam->getDeclName());
3022 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3023 ++FParamIdx;
3024 }
3025 }
3026}
3027
3028static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
3029 const FunctionProtoType *Proto,
3030 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00003031 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
3032
Richard Smithf623c962012-04-17 00:58:00 +00003033 // C++11 [expr.prim.general]p3:
3034 // If a declaration declares a member function or member function
3035 // template of a class X, the expression this is a prvalue of type
3036 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3037 // and the end of the function-definition, member-declarator, or
3038 // declarator.
Craig Topperc3ec1492014-05-26 06:22:03 +00003039 CXXRecordDecl *ThisContext = nullptr;
Richard Smithf623c962012-04-17 00:58:00 +00003040 unsigned ThisTypeQuals = 0;
3041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3042 ThisContext = Method->getParent();
3043 ThisTypeQuals = Method->getTypeQualifiers();
3044 }
3045 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003046 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00003047
3048 // The function has an exception specification or a "noreturn"
3049 // attribute. Substitute into each of the exception types.
3050 SmallVector<QualType, 4> Exceptions;
3051 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3052 // FIXME: Poor location information!
3053 if (const PackExpansionType *PackExpansion
3054 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3055 // We have a pack expansion. Instantiate it.
3056 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3057 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3058 Unexpanded);
3059 assert(!Unexpanded.empty() &&
3060 "Pack expansion without parameter packs?");
3061
3062 bool Expand = false;
3063 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003064 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00003065 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3066 SourceRange(),
3067 Unexpanded,
3068 TemplateArgs,
3069 Expand,
3070 RetainExpansion,
3071 NumExpansions))
3072 break;
3073
3074 if (!Expand) {
3075 // We can't expand this pack expansion into separate arguments yet;
3076 // just substitute into the pattern and create a new pack expansion
3077 // type.
3078 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3079 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3080 TemplateArgs,
3081 New->getLocation(), New->getDeclName());
3082 if (T.isNull())
3083 break;
3084
3085 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3086 Exceptions.push_back(T);
3087 continue;
3088 }
3089
3090 // Substitute into the pack expansion pattern for each template
3091 bool Invalid = false;
3092 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3093 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3094
3095 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3096 TemplateArgs,
3097 New->getLocation(), New->getDeclName());
3098 if (T.isNull()) {
3099 Invalid = true;
3100 break;
3101 }
3102
3103 Exceptions.push_back(T);
3104 }
3105
3106 if (Invalid)
3107 break;
3108
3109 continue;
3110 }
3111
3112 QualType T
3113 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3114 New->getLocation(), New->getDeclName());
3115 if (T.isNull() ||
3116 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3117 continue;
3118
3119 Exceptions.push_back(T);
3120 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003121 Expr *NoexceptExpr = nullptr;
Richard Smithf623c962012-04-17 00:58:00 +00003122 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3123 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3124 Sema::ConstantEvaluated);
3125 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3126 if (E.isUsable())
3127 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3128
3129 if (E.isUsable()) {
3130 NoexceptExpr = E.take();
3131 if (!NoexceptExpr->isTypeDependent() &&
3132 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00003133 NoexceptExpr
3134 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003135 nullptr, diag::err_noexcept_needs_constant_expression,
Douglas Gregore2b37442012-05-04 22:38:52 +00003136 /*AllowFold*/ false).take();
Richard Smithf623c962012-04-17 00:58:00 +00003137 }
3138 }
3139
Richard Smith564417a2014-03-20 21:47:22 +00003140 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithf623c962012-04-17 00:58:00 +00003141 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
3142 EPI.NumExceptions = Exceptions.size();
3143 EPI.Exceptions = Exceptions.data();
3144 EPI.NoexceptExpr = NoexceptExpr;
3145
Richard Smith564417a2014-03-20 21:47:22 +00003146 SemaRef.UpdateExceptionSpec(New, 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.
Richard Smith564417a2014-03-20 21:47:22 +00003160 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003161 EPI.ExceptionSpecType = EST_None;
Richard Smith564417a2014-03-20 21:47:22 +00003162 UpdateExceptionSpec(Decl, EPI);
Richard Smithf623c962012-04-17 00:58:00 +00003163 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003164 }
Richard Smithf623c962012-04-17 00:58:00 +00003165
3166 // Enter the scope of this instantiation. We don't use
3167 // PushDeclContext because we don't have a scope.
3168 Sema::ContextRAII savedContext(*this, Decl);
3169 LocalInstantiationScope Scope(*this);
3170
3171 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003172 getTemplateInstantiationArgs(Decl, nullptr, /*RelativeToPrimary*/true);
Richard Smithf623c962012-04-17 00:58:00 +00003173
Richard Smithd3729422012-04-19 00:08:28 +00003174 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3175 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003176
Richard Smithd3729422012-04-19 00:08:28 +00003177 ::InstantiateExceptionSpec(*this, Decl,
3178 Template->getType()->castAs<FunctionProtoType>(),
3179 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003180}
3181
Mike Stump11289f42009-09-09 15:08:12 +00003182/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003183/// declaration (New) from the corresponding fields of its template (Tmpl).
3184///
3185/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003186bool
3187TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003188 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003189 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003190 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003191
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003192 // Forward the mangling number from the template to the instantiated decl.
3193 SemaRef.Context.setManglingNumber(New,
3194 SemaRef.Context.getManglingNumber(Tmpl));
3195
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003196 // If we are performing substituting explicitly-specified template arguments
3197 // or deduced template arguments into a function template and we reach this
3198 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003199 // to keeping the new function template specialization. We therefore
3200 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003201 // into a template instantiation for this specific function template
3202 // specialization, which is not a SFINAE context, so that we diagnose any
3203 // further errors in the declaration itself.
3204 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3205 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3206 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3207 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003208 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003209 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003210 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003211 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003212 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003213 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003214 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003215 }
3216 }
Mike Stump11289f42009-09-09 15:08:12 +00003217
Douglas Gregor049bdca2009-12-08 17:45:32 +00003218 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3219 assert(Proto && "Function template without prototype?");
3220
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003221 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003222 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003223
Richard Smithf623c962012-04-17 00:58:00 +00003224 // DR1330: In C++11, defer instantiation of a non-trivial
3225 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003226 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithf623c962012-04-17 00:58:00 +00003227 EPI.ExceptionSpecType != EST_None &&
3228 EPI.ExceptionSpecType != EST_DynamicNone &&
3229 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003230 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3231 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3232 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003233 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3234 if (EPI.ExceptionSpecType == EST_Unevaluated)
3235 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003236
Richard Smithf623c962012-04-17 00:58:00 +00003237 // Mark the function has having an uninstantiated exception specification.
3238 const FunctionProtoType *NewProto
3239 = New->getType()->getAs<FunctionProtoType>();
3240 assert(NewProto && "Template instantiation without function prototype?");
3241 EPI = NewProto->getExtProtoInfo();
Richard Smith185be182013-04-10 05:48:59 +00003242 EPI.ExceptionSpecType = NewEST;
Richard Smithf623c962012-04-17 00:58:00 +00003243 EPI.ExceptionSpecDecl = New;
Richard Smithd3729422012-04-19 00:08:28 +00003244 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003245 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003246 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003247 } else {
3248 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3249 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003250 }
3251
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003252 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003253 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003254 Tmpl->isDefined(Definition);
3255
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003256 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3257 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003258
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003259 return false;
3260}
3261
Douglas Gregor21342092009-03-24 00:38:23 +00003262/// \brief Initializes common fields of an instantiated method
3263/// declaration (New) from the corresponding fields of its template
3264/// (Tmpl).
3265///
3266/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003267bool
3268TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003269 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003270 if (InitFunctionInstantiation(New, Tmpl))
3271 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003272
Douglas Gregor21342092009-03-24 00:38:23 +00003273 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003274 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003275 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003276
Douglas Gregor21342092009-03-24 00:38:23 +00003277 // FIXME: New needs a pointer to Tmpl
3278 return false;
3279}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003280
3281/// \brief Instantiate the definition of the given function from its
3282/// template.
3283///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003284/// \param PointOfInstantiation the point at which the instantiation was
3285/// required. Note that this is not precisely a "point of instantiation"
3286/// for the function, but it's close.
3287///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003288/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003289/// function template specialization or member function of a class template
3290/// specialization.
3291///
3292/// \param Recursive if true, recursively instantiates any functions that
3293/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003294///
3295/// \param DefinitionRequired if true, then we are performing an explicit
3296/// instantiation where the body of the function is required. Complain if
3297/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003298void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003299 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003300 bool Recursive,
3301 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003302 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003303 return;
3304
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003305 // Never instantiate an explicit specialization except if it is a class scope
3306 // explicit specialization.
3307 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3308 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003309 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003310
Douglas Gregor24c332b2009-05-14 21:06:31 +00003311 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003312 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003313 assert(PatternDecl && "instantiating a non-template");
3314
3315 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3316 assert(PatternDecl && "template definition is not a template");
3317 if (!Pattern) {
3318 // Try to find a defaulted definition
3319 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003320 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003321 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003322
Francois Pichet1c229c02011-04-22 22:18:13 +00003323 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003324 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003325 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003326 PendingInstantiations.push_back(
3327 std::make_pair(Function, PointOfInstantiation));
3328 return;
3329 }
3330
David Majnemerf0a84f22013-08-16 08:29:13 +00003331 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003332 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003333 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003334 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003335 // FIXME: Optimize to allow individual templates to be deserialized.
3336 if (PatternDecl->isFromASTFile())
3337 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3338
3339 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3340 assert(LPT && "missing LateParsedTemplate");
3341 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003342 Pattern = PatternDecl->getBody(PatternDecl);
3343 }
3344
Alexis Hunt23f6b832011-05-27 20:00:14 +00003345 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003346 if (DefinitionRequired) {
3347 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003348 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003349 diag::err_explicit_instantiation_undefined_func_template)
3350 << Function->getPrimaryTemplate();
3351 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003352 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003353 diag::err_explicit_instantiation_undefined_member)
3354 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003355
Douglas Gregora8b89d22009-10-15 14:05:49 +00003356 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003357 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003358 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003359 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003360 } else if (Function->getTemplateSpecializationKind()
3361 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003362 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003363 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003364 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003365
Douglas Gregor24c332b2009-05-14 21:06:31 +00003366 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003367 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003368
Richard Smith2a7d4812013-05-04 07:00:32 +00003369 // C++1y [temp.explicit]p10:
3370 // Except for inline functions, declarations with types deduced from their
3371 // initializer or return value, and class template specializations, other
3372 // explicit instantiation declarations have the effect of suppressing the
3373 // implicit instantiation of the entity to which they refer.
Alp Toker314cc812014-01-25 16:55:45 +00003374 if (Function->getTemplateSpecializationKind() ==
3375 TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003376 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003377 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003378 return;
Mike Stump11289f42009-09-09 15:08:12 +00003379
Richard Smithf3814ad2013-01-25 00:08:28 +00003380 if (PatternDecl->isInlined())
3381 Function->setImplicitlyInline();
3382
Douglas Gregor85673582009-05-18 17:01:57 +00003383 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003384 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003385 return;
3386
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003387 // Copy the inner loc start from the pattern.
3388 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3389
Douglas Gregordda7ced2009-06-30 17:20:14 +00003390 // If we're performing recursive template instantiation, create our own
3391 // queue of pending implicit instantiations that we will instantiate later,
3392 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003393 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003394 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003395 SavePendingLocalImplicitInstantiationsRAII
3396 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003397 if (Recursive) {
3398 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003399 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003400 }
Mike Stump11289f42009-09-09 15:08:12 +00003401
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003402 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003403 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003404
Douglas Gregorb4850462009-05-14 23:26:13 +00003405 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003406 // recorded, unless we're actually a member function within a local
3407 // class, in which case we need to merge our results with the parent
3408 // scope (of the enclosing function).
3409 bool MergeWithParentScope = false;
3410 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3411 MergeWithParentScope = Rec->isLocalClass();
3412
3413 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003414
Richard Smithbd305122012-12-11 01:14:52 +00003415 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003416 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003417 else {
Craig Topperc3ec1492014-05-26 06:22:03 +00003418 ActOnStartOfFunctionDef(nullptr, Function);
Richard Smithbd305122012-12-11 01:14:52 +00003419
3420 // Enter the scope of this instantiation. We don't use
3421 // PushDeclContext because we don't have a scope.
3422 Sema::ContextRAII savedContext(*this, Function);
3423
3424 MultiLevelTemplateArgumentList TemplateArgs =
Craig Topperc3ec1492014-05-26 06:22:03 +00003425 getTemplateInstantiationArgs(Function, nullptr, false, PatternDecl);
Richard Smithbd305122012-12-11 01:14:52 +00003426
3427 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3428 TemplateArgs);
3429
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003430 // If this is a constructor, instantiate the member initializers.
3431 if (const CXXConstructorDecl *Ctor =
3432 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3433 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3434 TemplateArgs);
3435 }
3436
3437 // Instantiate the function body.
3438 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3439
3440 if (Body.isInvalid())
3441 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003442
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003443 ActOnFinishFunctionBody(Function, Body.get(),
3444 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003445
3446 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3447
Richard Smithd28ac5b2014-03-22 23:33:22 +00003448 if (auto *Listener = getASTMutationListener())
3449 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00003450
Richard Smithbd305122012-12-11 01:14:52 +00003451 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003452 }
3453
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003454 DeclGroupRef DG(Function);
3455 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003456
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003457 // This class may have local implicit instantiations that need to be
3458 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003459 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003460 Scope.Exit();
3461
Douglas Gregordda7ced2009-06-30 17:20:14 +00003462 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003463 // Define any pending vtables.
3464 DefineUsedVTables();
3465
Douglas Gregordda7ced2009-06-30 17:20:14 +00003466 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003467 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003468 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003469
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003470 // Restore the set of pending vtables.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003471 assert(VTableUses.empty() &&
3472 "VTableUses should be empty before it is discarded.");
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003473 VTableUses.swap(SavedVTableUses);
3474
Douglas Gregordda7ced2009-06-30 17:20:14 +00003475 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003476 assert(PendingInstantiations.empty() &&
3477 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003478 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregordda7ced2009-06-30 17:20:14 +00003479 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003480}
3481
Larisse Voufo39a1e502013-08-06 01:03:05 +00003482VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3483 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3484 const TemplateArgumentList &TemplateArgList,
3485 const TemplateArgumentListInfo &TemplateArgsInfo,
3486 SmallVectorImpl<TemplateArgument> &Converted,
3487 SourceLocation PointOfInstantiation, void *InsertPos,
3488 LateInstantiatedAttrVec *LateAttrs,
3489 LocalInstantiationScope *StartingScope) {
3490 if (FromVar->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00003491 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003492
3493 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003494 if (Inst.isInvalid())
Craig Topperc3ec1492014-05-26 06:22:03 +00003495 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003496
3497 MultiLevelTemplateArgumentList TemplateArgLists;
3498 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3499
Richard Smith8809a0c2013-09-27 20:14:12 +00003500 // Instantiate the first declaration of the variable template: for a partial
3501 // specialization of a static data member template, the first declaration may
3502 // or may not be the declaration in the class; if it's in the class, we want
3503 // to instantiate a member in the class (a declaration), and if it's outside,
3504 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00003505 //
3506 // If we're instantiating an explicitly-specialized member template or member
3507 // partial specialization, don't do this. The member specialization completely
3508 // replaces the original declaration in this case.
3509 bool IsMemberSpec = false;
3510 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3511 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3512 IsMemberSpec = PartialSpec->isMemberSpecialization();
3513 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3514 IsMemberSpec = FromTemplate->isMemberSpecialization();
3515 if (!IsMemberSpec)
3516 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003517
Manuel Klimek5843add2013-09-30 13:29:01 +00003518 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3519 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3520 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003521
3522 // TODO: Set LateAttrs and StartingScope ...
3523
3524 return cast_or_null<VarTemplateSpecializationDecl>(
3525 Instantiator.VisitVarTemplateSpecializationDecl(
3526 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3527}
3528
3529/// \brief Instantiates a variable template specialization by completing it
3530/// with appropriate type information and initializer.
3531VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3532 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3533 const MultiLevelTemplateArgumentList &TemplateArgs) {
3534
3535 // Do substitution on the type of the declaration
3536 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003537 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003538 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3539 if (!DI)
Craig Topperc3ec1492014-05-26 06:22:03 +00003540 return nullptr;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003541
3542 // Update the type of this variable template specialization.
3543 VarSpec->setType(DI->getType());
3544
3545 // Instantiate the initializer.
3546 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3547
3548 return VarSpec;
3549}
3550
3551/// BuildVariableInstantiation - Used after a new variable has been created.
3552/// Sets basic variable data and decides whether to postpone the
3553/// variable instantiation.
3554void Sema::BuildVariableInstantiation(
3555 VarDecl *NewVar, VarDecl *OldVar,
3556 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003557 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3558 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003559 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003560
Richard Smith541b38b2013-09-20 01:15:31 +00003561 // If we are instantiating a local extern declaration, the
3562 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003563 // If we are instantiating a static data member defined
3564 // out-of-line, the instantiation will have the same lexical
3565 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00003566 if (OldVar->isLocalExternDecl()) {
3567 NewVar->setLocalExternDecl();
3568 NewVar->setLexicalDeclContext(Owner);
3569 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003570 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3571 NewVar->setTSCSpec(OldVar->getTSCSpec());
3572 NewVar->setInitStyle(OldVar->getInitStyle());
3573 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3574 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00003575 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00003576 NewVar->setPreviousDeclInSameBlockScope(
3577 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003578 NewVar->setAccess(OldVar->getAccess());
3579
Richard Smith0b551192013-09-23 23:12:22 +00003580 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00003581 if (OldVar->isUsed(false))
3582 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003583 NewVar->setReferenced(OldVar->isReferenced());
3584 }
3585
David Majnemer50ce8352013-09-17 23:57:10 +00003586 // See if the old variable had a type-specifier that defined an anonymous tag.
3587 // If it did, mark the new variable as being the declarator for the new
3588 // anonymous tag.
3589 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3590 TagDecl *OldTag = OldTagType->getDecl();
3591 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3592 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3593 assert(!NewTag->hasNameForLinkage() &&
3594 !NewTag->hasDeclaratorForAnonDecl());
3595 NewTag->setDeclaratorForAnonDecl(NewVar);
3596 }
3597 }
3598
Larisse Voufo39a1e502013-08-06 01:03:05 +00003599 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3600
Richard Smith541b38b2013-09-20 01:15:31 +00003601 LookupResult Previous(
3602 *this, NewVar->getDeclName(), NewVar->getLocation(),
3603 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3604 : Sema::LookupOrdinaryName,
3605 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003606
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00003607 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3608 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3609 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003610 // We have a previous declaration. Use that one, so we merge with the
3611 // right type.
3612 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3613 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3614 Previous.addDecl(NewPrev);
3615 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3616 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003617 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003618 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003619
Richard Smith541b38b2013-09-20 01:15:31 +00003620 if (!InstantiatingVarTemplate) {
3621 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3622 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003623 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00003624 }
3625
3626 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003627 if (NewVar->getDeclContext()->isFunctionOrMethod())
3628 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3629 }
3630
3631 // Link instantiations of static data members back to the template from
3632 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003633 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003634 NewVar->setInstantiationOfStaticDataMember(OldVar,
3635 TSK_ImplicitInstantiation);
3636
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003637 // Forward the mangling number from the template to the instantiated decl.
3638 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00003639 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003640
Richard Smith8809a0c2013-09-27 20:14:12 +00003641 // Delay instantiation of the initializer for variable templates until a
Richard Smithd292b242014-03-16 01:00:40 +00003642 // definition of the variable is needed. We need it right away if the type
3643 // contains 'auto'.
3644 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3645 !InstantiatingVarTemplate) ||
3646 NewVar->getType()->isUndeducedType())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003647 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3648
3649 // Diagnose unused local variables with dependent types, where the diagnostic
3650 // will have been deferred.
3651 if (!NewVar->isInvalidDecl() &&
3652 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3653 OldVar->getType()->isDependentType())
3654 DiagnoseUnusedDecl(NewVar);
3655}
3656
3657/// \brief Instantiate the initializer of a variable.
3658void Sema::InstantiateVariableInitializer(
3659 VarDecl *Var, VarDecl *OldVar,
3660 const MultiLevelTemplateArgumentList &TemplateArgs) {
3661
3662 if (Var->getAnyInitializer())
3663 // We already have an initializer in the class.
3664 return;
3665
3666 if (OldVar->getInit()) {
3667 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3668 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3669 else
3670 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3671
3672 // Instantiate the initializer.
3673 ExprResult Init =
3674 SubstInitializer(OldVar->getInit(), TemplateArgs,
3675 OldVar->getInitStyle() == VarDecl::CallInit);
3676 if (!Init.isInvalid()) {
3677 bool TypeMayContainAuto = true;
3678 if (Init.get()) {
3679 bool DirectInit = OldVar->isDirectInit();
3680 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3681 } else
3682 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3683 } else {
3684 // FIXME: Not too happy about invalidating the declaration
3685 // because of a bogus initializer.
3686 Var->setInvalidDecl();
3687 }
3688
3689 PopExpressionEvaluationContext();
3690 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3691 !Var->isCXXForRangeDecl())
3692 ActOnUninitializedDecl(Var, false);
3693}
3694
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003695/// \brief Instantiate the definition of the given variable from its
3696/// template.
3697///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003698/// \param PointOfInstantiation the point at which the instantiation was
3699/// required. Note that this is not precisely a "point of instantiation"
3700/// for the function, but it's close.
3701///
3702/// \param Var the already-instantiated declaration of a static member
3703/// variable of a class template specialization.
3704///
3705/// \param Recursive if true, recursively instantiates any functions that
3706/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003707///
3708/// \param DefinitionRequired if true, then we are performing an explicit
3709/// instantiation where an out-of-line definition of the member variable
3710/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003711void Sema::InstantiateStaticDataMemberDefinition(
3712 SourceLocation PointOfInstantiation,
3713 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003714 bool Recursive,
3715 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003716 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3717 DefinitionRequired);
3718}
3719
3720void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3721 VarDecl *Var, bool Recursive,
3722 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003723 if (Var->isInvalidDecl())
3724 return;
Mike Stump11289f42009-09-09 15:08:12 +00003725
Larisse Voufo39a1e502013-08-06 01:03:05 +00003726 VarTemplateSpecializationDecl *VarSpec =
3727 dyn_cast<VarTemplateSpecializationDecl>(Var);
Craig Topperc3ec1492014-05-26 06:22:03 +00003728 VarDecl *PatternDecl = nullptr, *Def = nullptr;
Richard Smith8809a0c2013-09-27 20:14:12 +00003729 MultiLevelTemplateArgumentList TemplateArgs =
3730 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003731
Larisse Voufo39a1e502013-08-06 01:03:05 +00003732 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003733 // If this is a variable template specialization, make sure that it is
3734 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003735 bool InstantiationDependent = false;
3736 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3737 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3738 "Only instantiate variable template specializations that are "
3739 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003740 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003741
Richard Smith8809a0c2013-09-27 20:14:12 +00003742 // Find the variable initialization that we'll be substituting. If the
3743 // pattern was instantiated from a member template, look back further to
3744 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003745 assert(VarSpec->getSpecializedTemplate() &&
3746 "Specialization without specialized template?");
3747 llvm::PointerUnion<VarTemplateDecl *,
3748 VarTemplatePartialSpecializationDecl *> PatternPtr =
3749 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003750 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003751 VarTemplatePartialSpecializationDecl *Tmpl =
3752 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3753 while (VarTemplatePartialSpecializationDecl *From =
3754 Tmpl->getInstantiatedFromMember()) {
3755 if (Tmpl->isMemberSpecialization())
3756 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003757
Richard Smith8809a0c2013-09-27 20:14:12 +00003758 Tmpl = From;
3759 }
3760 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003761 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003762 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3763 while (VarTemplateDecl *From =
3764 Tmpl->getInstantiatedFromMemberTemplate()) {
3765 if (Tmpl->isMemberSpecialization())
3766 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003767
Richard Smith8809a0c2013-09-27 20:14:12 +00003768 Tmpl = From;
3769 }
3770 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003771 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003772
3773 // If this is a static data member template, there might be an
3774 // uninstantiated initializer on the declaration. If so, instantiate
3775 // it now.
3776 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003777 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003778 !Var->hasInit()) {
3779 // FIXME: Factor out the duplicated instantiation context setup/tear down
3780 // code here.
3781 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003782 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003783 return;
3784
3785 // If we're performing recursive template instantiation, create our own
3786 // queue of pending implicit instantiations that we will instantiate
3787 // later, while we're still within our own instantiation context.
3788 SmallVector<VTableUse, 16> SavedVTableUses;
3789 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3790 if (Recursive) {
3791 VTableUses.swap(SavedVTableUses);
3792 PendingInstantiations.swap(SavedPendingInstantiations);
3793 }
3794
3795 LocalInstantiationScope Local(*this);
3796
3797 // Enter the scope of this instantiation. We don't use
3798 // PushDeclContext because we don't have a scope.
3799 ContextRAII PreviousContext(*this, Var->getDeclContext());
3800 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3801 PreviousContext.pop();
3802
3803 // FIXME: Need to inform the ASTConsumer that we instantiated the
3804 // initializer?
3805
3806 // This variable may have local implicit instantiations that need to be
3807 // instantiated within this scope.
3808 PerformPendingInstantiations(/*LocalOnly=*/true);
3809
3810 Local.Exit();
3811
3812 if (Recursive) {
3813 // Define any newly required vtables.
3814 DefineUsedVTables();
3815
3816 // Instantiate any pending implicit instantiations found during the
3817 // instantiation of this template.
3818 PerformPendingInstantiations();
3819
3820 // Restore the set of pending vtables.
3821 assert(VTableUses.empty() &&
3822 "VTableUses should be empty before it is discarded.");
3823 VTableUses.swap(SavedVTableUses);
3824
3825 // Restore the set of pending implicit instantiations.
3826 assert(PendingInstantiations.empty() &&
3827 "PendingInstantiations should be empty before it is discarded.");
3828 PendingInstantiations.swap(SavedPendingInstantiations);
3829 }
3830 }
3831
3832 // Find actual definition
3833 Def = PatternDecl->getDefinition(getASTContext());
3834 } else {
3835 // If this is a static data member, find its out-of-line definition.
3836 assert(Var->isStaticDataMember() && "not a static data member?");
3837 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3838
3839 assert(PatternDecl && "data member was not instantiated from a template?");
3840 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3841 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003842 }
3843
Richard Smith8809a0c2013-09-27 20:14:12 +00003844 // If we don't have a definition of the variable template, we won't perform
3845 // any instantiation. Rather, we rely on the user to instantiate this
3846 // definition (or provide a specialization for it) in another translation
3847 // unit.
3848 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003849 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003850 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003851 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003852 diag::err_explicit_instantiation_undefined_var_template) << Var;
3853 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003854 Diag(PointOfInstantiation,
3855 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003856 << 2 << Var->getDeclName() << Var->getDeclContext();
3857 Diag(PatternDecl->getLocation(),
3858 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003859 if (VarSpec)
3860 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003861 } else if (Var->getTemplateSpecializationKind()
3862 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003863 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003864 std::make_pair(Var, PointOfInstantiation));
3865 }
3866
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003867 return;
3868 }
3869
Rafael Espindola189fa742012-03-05 10:54:55 +00003870 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3871
Douglas Gregor86d142a2009-10-08 07:24:58 +00003872 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003873 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003874 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003875
Larisse Voufo39a1e502013-08-06 01:03:05 +00003876 // C++11 [temp.explicit]p10:
3877 // Except for inline functions, [...] explicit instantiation declarations
3878 // have the effect of suppressing the implicit instantiation of the entity
3879 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003880 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003881 return;
Mike Stump11289f42009-09-09 15:08:12 +00003882
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003883 // Make sure to pass the instantiated variable to the consumer at the end.
3884 struct PassToConsumerRAII {
3885 ASTConsumer &Consumer;
3886 VarDecl *Var;
3887
3888 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3889 : Consumer(Consumer), Var(Var) { }
3890
3891 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003892 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003893 }
3894 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003895
Richard Smith8809a0c2013-09-27 20:14:12 +00003896 // If we already have a definition, we're done.
3897 if (VarDecl *Def = Var->getDefinition()) {
3898 // We may be explicitly instantiating something we've already implicitly
3899 // instantiated.
3900 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3901 PointOfInstantiation);
3902 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003903 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003904
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003905 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003906 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003907 return;
Mike Stump11289f42009-09-09 15:08:12 +00003908
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003909 // If we're performing recursive template instantiation, create our own
3910 // queue of pending implicit instantiations that we will instantiate later,
3911 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003912 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003913 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003914 SavePendingLocalImplicitInstantiationsRAII
3915 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003916 if (Recursive) {
3917 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003918 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003919 }
Mike Stump11289f42009-09-09 15:08:12 +00003920
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003921 // Enter the scope of this instantiation. We don't use
3922 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003923 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003924 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003925
Larisse Voufo39a1e502013-08-06 01:03:05 +00003926 VarDecl *OldVar = Var;
3927 if (!VarSpec)
3928 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003929 TemplateArgs));
3930 else if (Var->isStaticDataMember() &&
3931 Var->getLexicalDeclContext()->isRecord()) {
3932 // We need to instantiate the definition of a static data member template,
3933 // and all we have is the in-class declaration of it. Instantiate a separate
3934 // declaration of the definition.
3935 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3936 TemplateArgs);
3937 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
Craig Topperc3ec1492014-05-26 06:22:03 +00003938 VarSpec->getSpecializedTemplate(), Def, nullptr,
Richard Smith8809a0c2013-09-27 20:14:12 +00003939 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3940 if (Var) {
3941 llvm::PointerUnion<VarTemplateDecl *,
3942 VarTemplatePartialSpecializationDecl *> PatternPtr =
3943 VarSpec->getSpecializedTemplateOrPartial();
3944 if (VarTemplatePartialSpecializationDecl *Partial =
3945 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3946 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3947 Partial, &VarSpec->getTemplateInstantiationArgs());
3948
3949 // Merge the definition with the declaration.
3950 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3951 LookupOrdinaryName, ForRedeclaration);
3952 R.addDecl(OldVar);
3953 MergeVarDecl(Var, R);
3954
3955 // Attach the initializer.
3956 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3957 }
3958 } else
3959 // Complete the existing variable's definition with an appropriately
3960 // substituted type and initializer.
3961 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003962
3963 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003964
3965 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003966 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003967 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3968 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003969 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003970
3971 // This variable may have local implicit instantiations that need to be
3972 // instantiated within this scope.
3973 PerformPendingInstantiations(/*LocalOnly=*/true);
3974
Douglas Gregora86bc002012-02-16 21:36:18 +00003975 Local.Exit();
3976
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003977 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003978 // Define any newly required vtables.
3979 DefineUsedVTables();
3980
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003981 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003982 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003983 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003984
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003985 // Restore the set of pending vtables.
3986 assert(VTableUses.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003987 "VTableUses should be empty before it is discarded.");
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003988 VTableUses.swap(SavedVTableUses);
3989
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003990 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003991 assert(PendingInstantiations.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003992 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003993 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00003994 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003995}
Douglas Gregor51783312009-05-27 05:35:12 +00003996
Anders Carlsson70553942009-08-29 05:16:22 +00003997void
3998Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3999 const CXXConstructorDecl *Tmpl,
4000 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004001
Richard Trieu9becef62011-09-09 03:18:59 +00004002 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004003 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004004
Anders Carlsson70553942009-08-29 05:16:22 +00004005 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004006 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004007 // Only instantiate written initializers, let Sema re-construct implicit
4008 // ones.
4009 if (!Init->isWritten())
4010 continue;
4011
Douglas Gregor44e7df62011-01-04 00:32:56 +00004012 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004013
Douglas Gregor44e7df62011-01-04 00:32:56 +00004014 if (Init->isPackExpansion()) {
4015 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004016 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004017 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004018 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004019 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004020 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004021 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004022 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004023 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004024 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004025 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004026 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004027 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004028 NumExpansions)) {
4029 AnyErrors = true;
4030 New->setInvalidDecl();
4031 continue;
4032 }
4033 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004034
4035 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004036 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004037 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4038
4039 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004040 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4041 /*CXXDirectInit=*/true);
4042 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004043 AnyErrors = true;
4044 break;
4045 }
4046
4047 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004048 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004049 TemplateArgs,
4050 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004051 New->getDeclName());
4052 if (!BaseTInfo) {
4053 AnyErrors = true;
4054 break;
4055 }
4056
4057 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004058 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redla9351792012-02-11 23:51:47 +00004059 BaseTInfo, TempInit.take(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004060 New->getParent(),
4061 SourceLocation());
4062 if (NewInit.isInvalid()) {
4063 AnyErrors = true;
4064 break;
4065 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004066
Douglas Gregor44e7df62011-01-04 00:32:56 +00004067 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004068 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004069
Douglas Gregor44e7df62011-01-04 00:32:56 +00004070 continue;
4071 }
4072
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004073 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004074 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4075 /*CXXDirectInit=*/true);
4076 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004077 AnyErrors = true;
4078 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004079 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004080
Anders Carlsson70553942009-08-29 05:16:22 +00004081 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004082 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4083 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4084 TemplateArgs,
4085 Init->getSourceLocation(),
4086 New->getDeclName());
4087 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004088 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004089 New->setInvalidDecl();
4090 continue;
4091 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004092
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004093 if (Init->isBaseInitializer())
Sebastian Redla9351792012-02-11 23:51:47 +00004094 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004095 New->getParent(), EllipsisLoc);
4096 else
Sebastian Redla9351792012-02-11 23:51:47 +00004097 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004098 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004099 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004100 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004101 Init->getMemberLocation(),
4102 Init->getMember(),
4103 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004104 if (!Member) {
4105 AnyErrors = true;
4106 New->setInvalidDecl();
4107 continue;
4108 }
Mike Stump11289f42009-09-09 15:08:12 +00004109
Sebastian Redla9351792012-02-11 23:51:47 +00004110 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004111 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004112 } else if (Init->isIndirectMemberInitializer()) {
4113 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004114 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004115 Init->getMemberLocation(),
4116 Init->getIndirectMember(), TemplateArgs));
4117
Douglas Gregor55e6b312011-03-04 19:46:35 +00004118 if (!IndirectMember) {
4119 AnyErrors = true;
4120 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004121 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004122 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004123
Sebastian Redla9351792012-02-11 23:51:47 +00004124 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004125 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004126 }
4127
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004128 if (NewInit.isInvalid()) {
4129 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004130 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004131 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004132 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004133 }
4134 }
Mike Stump11289f42009-09-09 15:08:12 +00004135
Anders Carlsson70553942009-08-29 05:16:22 +00004136 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004137 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004138 /*FIXME: ColonLoc */
4139 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004140 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004141 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004142}
4143
John McCall59660882009-08-29 08:11:13 +00004144// TODO: this could be templated if the various decl types used the
4145// same method name.
4146static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4147 ClassTemplateDecl *Instance) {
4148 Pattern = Pattern->getCanonicalDecl();
4149
4150 do {
4151 Instance = Instance->getCanonicalDecl();
4152 if (Pattern == Instance) return true;
4153 Instance = Instance->getInstantiatedFromMemberTemplate();
4154 } while (Instance);
4155
4156 return false;
4157}
4158
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004159static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4160 FunctionTemplateDecl *Instance) {
4161 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004162
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004163 do {
4164 Instance = Instance->getCanonicalDecl();
4165 if (Pattern == Instance) return true;
4166 Instance = Instance->getInstantiatedFromMemberTemplate();
4167 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004168
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004169 return false;
4170}
4171
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004172static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004173isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4174 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004175 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004176 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4177 do {
4178 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4179 Instance->getCanonicalDecl());
4180 if (Pattern == Instance)
4181 return true;
4182 Instance = Instance->getInstantiatedFromMember();
4183 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004184
Douglas Gregor21610382009-10-29 00:04:11 +00004185 return false;
4186}
4187
John McCall59660882009-08-29 08:11:13 +00004188static bool isInstantiationOf(CXXRecordDecl *Pattern,
4189 CXXRecordDecl *Instance) {
4190 Pattern = Pattern->getCanonicalDecl();
4191
4192 do {
4193 Instance = Instance->getCanonicalDecl();
4194 if (Pattern == Instance) return true;
4195 Instance = Instance->getInstantiatedFromMemberClass();
4196 } while (Instance);
4197
4198 return false;
4199}
4200
4201static bool isInstantiationOf(FunctionDecl *Pattern,
4202 FunctionDecl *Instance) {
4203 Pattern = Pattern->getCanonicalDecl();
4204
4205 do {
4206 Instance = Instance->getCanonicalDecl();
4207 if (Pattern == Instance) return true;
4208 Instance = Instance->getInstantiatedFromMemberFunction();
4209 } while (Instance);
4210
4211 return false;
4212}
4213
4214static bool isInstantiationOf(EnumDecl *Pattern,
4215 EnumDecl *Instance) {
4216 Pattern = Pattern->getCanonicalDecl();
4217
4218 do {
4219 Instance = Instance->getCanonicalDecl();
4220 if (Pattern == Instance) return true;
4221 Instance = Instance->getInstantiatedFromMemberEnum();
4222 } while (Instance);
4223
4224 return false;
4225}
4226
John McCallb96ec562009-12-04 22:46:56 +00004227static bool isInstantiationOf(UsingShadowDecl *Pattern,
4228 UsingShadowDecl *Instance,
4229 ASTContext &C) {
4230 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4231}
4232
4233static bool isInstantiationOf(UsingDecl *Pattern,
4234 UsingDecl *Instance,
4235 ASTContext &C) {
4236 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4237}
4238
John McCalle61f2ba2009-11-18 02:36:19 +00004239static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4240 UsingDecl *Instance,
4241 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004242 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00004243}
4244
4245static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004246 UsingDecl *Instance,
4247 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004248 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004249}
4250
John McCall59660882009-08-29 08:11:13 +00004251static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4252 VarDecl *Instance) {
4253 assert(Instance->isStaticDataMember());
4254
4255 Pattern = Pattern->getCanonicalDecl();
4256
4257 do {
4258 Instance = Instance->getCanonicalDecl();
4259 if (Pattern == Instance) return true;
4260 Instance = Instance->getInstantiatedFromStaticDataMember();
4261 } while (Instance);
4262
4263 return false;
4264}
4265
John McCallb96ec562009-12-04 22:46:56 +00004266// Other is the prospective instantiation
4267// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004268static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004269 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004270 if (UnresolvedUsingTypenameDecl *UUD
4271 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4272 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4273 return isInstantiationOf(UUD, UD, Ctx);
4274 }
4275 }
4276
4277 if (UnresolvedUsingValueDecl *UUD
4278 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004279 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4280 return isInstantiationOf(UUD, UD, Ctx);
4281 }
4282 }
Douglas Gregor51783312009-05-27 05:35:12 +00004283
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004284 return false;
4285 }
Mike Stump11289f42009-09-09 15:08:12 +00004286
John McCall59660882009-08-29 08:11:13 +00004287 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4288 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004289
John McCall59660882009-08-29 08:11:13 +00004290 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4291 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004292
John McCall59660882009-08-29 08:11:13 +00004293 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4294 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004295
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004296 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004297 if (Var->isStaticDataMember())
4298 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4299
4300 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4301 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004302
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004303 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4304 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4305
Douglas Gregor21610382009-10-29 00:04:11 +00004306 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4307 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4308 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4309 PartialSpec);
4310
Anders Carlsson5da84842009-09-01 04:26:58 +00004311 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4312 if (!Field->getDeclName()) {
4313 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00004314 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00004315 cast<FieldDecl>(D);
4316 }
4317 }
Mike Stump11289f42009-09-09 15:08:12 +00004318
John McCallb96ec562009-12-04 22:46:56 +00004319 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4320 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4321
4322 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4323 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4324
Douglas Gregor51783312009-05-27 05:35:12 +00004325 return D->getDeclName() && isa<NamedDecl>(Other) &&
4326 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4327}
4328
4329template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004330static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004331 NamedDecl *D,
4332 ForwardIterator first,
4333 ForwardIterator last) {
4334 for (; first != last; ++first)
4335 if (isInstantiationOf(Ctx, D, *first))
4336 return cast<NamedDecl>(*first);
4337
Craig Topperc3ec1492014-05-26 06:22:03 +00004338 return nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004339}
4340
John McCallaa74a0c2009-08-28 07:59:38 +00004341/// \brief Finds the instantiation of the given declaration context
4342/// within the current instantiation.
4343///
4344/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004345DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004346 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004347 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004348 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004349 return cast_or_null<DeclContext>(ID);
4350 } else return DC;
4351}
4352
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004353/// \brief Find the instantiation of the given declaration within the
4354/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004355///
4356/// This routine is intended to be used when \p D is a declaration
4357/// referenced from within a template, that needs to mapped into the
4358/// corresponding declaration within an instantiation. For example,
4359/// given:
4360///
4361/// \code
4362/// template<typename T>
4363/// struct X {
4364/// enum Kind {
4365/// KnownValue = sizeof(T)
4366/// };
4367///
4368/// bool getKind() const { return KnownValue; }
4369/// };
4370///
4371/// template struct X<int>;
4372/// \endcode
4373///
Serge Pavloved5fe902013-07-10 04:59:14 +00004374/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4375/// \p EnumConstantDecl for \p KnownValue (which refers to
4376/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4377/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4378/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004379NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004380 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004381 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004382 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4383 // parameters (p below) can have their ParentDC set to the translation-unit
4384 // - thus we can not consistently check if the ParentDC of such a parameter
4385 // is Dependent or/and a FunctionOrMethod.
4386 // For e.g. this code, during Template argument deduction tries to
4387 // find an instantiated decl for (T y) when the ParentDC for y is
4388 // the translation unit.
4389 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004390 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004391 // Foo(baz);
4392 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4393 // it gets here, always has a FunctionOrMethod as its ParentDC??
4394 // For now:
4395 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4396 // whose type is not instantiation dependent, do nothing to the decl
4397 // - otherwise find its instantiated decl.
4398 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4399 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4400 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004401 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004402 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004403 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4404 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004405 // D is a local of some kind. Look into the map of local
4406 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00004407 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4408 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4409 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004410
Chris Lattnercab02a62011-02-17 20:34:02 +00004411 if (Found) {
4412 if (Decl *FD = Found->dyn_cast<Decl *>())
4413 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004414
Richard Smithb15fe3a2012-09-12 00:56:43 +00004415 int PackIdx = ArgumentPackSubstitutionIndex;
4416 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00004417 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4418 }
4419
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004420 // If we're performing a partial substitution during template argument
4421 // deduction, we may not have values for template parameters yet. They
4422 // just map to themselves.
4423 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4424 isa<TemplateTemplateParmDecl>(D))
4425 return D;
4426
Serge Pavlov074a5182013-08-10 12:00:21 +00004427 if (D->isInvalidDecl())
Craig Topperc3ec1492014-05-26 06:22:03 +00004428 return nullptr;
Serge Pavlov074a5182013-08-10 12:00:21 +00004429
Chris Lattnercab02a62011-02-17 20:34:02 +00004430 // If we didn't find the decl, then we must have a label decl that hasn't
4431 // been found yet. Lazily instantiate it and return it now.
4432 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004433
Chris Lattnercab02a62011-02-17 20:34:02 +00004434 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4435 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004436
Chris Lattnercab02a62011-02-17 20:34:02 +00004437 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4438 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004439 }
Douglas Gregor51783312009-05-27 05:35:12 +00004440
Larisse Voufo39a1e502013-08-06 01:03:05 +00004441 // For variable template specializations, update those that are still
4442 // type-dependent.
4443 if (VarTemplateSpecializationDecl *VarSpec =
4444 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4445 bool InstantiationDependent = false;
4446 const TemplateArgumentListInfo &VarTemplateArgs =
4447 VarSpec->getTemplateArgsInfo();
4448 if (TemplateSpecializationType::anyDependentTemplateArguments(
4449 VarTemplateArgs, InstantiationDependent))
4450 D = cast<NamedDecl>(
4451 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4452 return D;
4453 }
4454
Douglas Gregor64621e62009-09-16 18:34:49 +00004455 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4456 if (!Record->isDependentContext())
4457 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004458
Douglas Gregor4109afa2011-11-07 17:43:18 +00004459 // Determine whether this record is the "templated" declaration describing
4460 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004461 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004462 if (ClassTemplate)
4463 ClassTemplate = ClassTemplate->getCanonicalDecl();
4464 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4465 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4466 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004467
Douglas Gregor4109afa2011-11-07 17:43:18 +00004468 // Walk the current context to find either the record or an instantiation of
4469 // it.
4470 DeclContext *DC = CurContext;
4471 while (!DC->isFileContext()) {
4472 // If we're performing substitution while we're inside the template
4473 // definition, we'll find our own context. We're done.
4474 if (DC->Equals(Record))
4475 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004476
Douglas Gregor4109afa2011-11-07 17:43:18 +00004477 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4478 // Check whether we're in the process of instantiating a class template
4479 // specialization of the template we're mapping.
4480 if (ClassTemplateSpecializationDecl *InstSpec
4481 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4482 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4483 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4484 return InstRecord;
4485 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004486
Douglas Gregor4109afa2011-11-07 17:43:18 +00004487 // Check whether we're in the process of instantiating a member class.
4488 if (isInstantiationOf(Record, InstRecord))
4489 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004490 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004491
Douglas Gregor4109afa2011-11-07 17:43:18 +00004492 // Move to the outer template scope.
4493 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4494 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4495 DC = FD->getLexicalDeclContext();
4496 continue;
4497 }
John McCall59660882009-08-29 08:11:13 +00004498 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004499
Douglas Gregor4109afa2011-11-07 17:43:18 +00004500 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004501 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004502
Douglas Gregor64621e62009-09-16 18:34:49 +00004503 // Fall through to deal with other dependent record types (e.g.,
4504 // anonymous unions in class templates).
4505 }
John McCall59660882009-08-29 08:11:13 +00004506
Douglas Gregor64621e62009-09-16 18:34:49 +00004507 if (!ParentDC->isDependentContext())
4508 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004509
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004510 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004511 if (!ParentDC)
Craig Topperc3ec1492014-05-26 06:22:03 +00004512 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00004513
Douglas Gregor51783312009-05-27 05:35:12 +00004514 if (ParentDC != D->getDeclContext()) {
4515 // We performed some kind of instantiation in the parent context,
4516 // so now we need to look into the instantiated parent context to
4517 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004518
John McCalle78aac42010-03-10 03:28:59 +00004519 // If our context used to be dependent, we may need to instantiate
4520 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004521 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004522 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004523 if (!Spec->isDependentContext()) {
4524 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004525 const RecordType *Tag = T->getAs<RecordType>();
4526 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004527 if (Tag->isBeingDefined())
4528 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004529 if (!Tag->isBeingDefined() &&
4530 RequireCompleteType(Loc, T, diag::err_incomplete_type))
Craig Topperc3ec1492014-05-26 06:22:03 +00004531 return nullptr;
Douglas Gregor25edf432010-11-05 23:22:45 +00004532
4533 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004534 }
4535 }
4536
Craig Topperc3ec1492014-05-26 06:22:03 +00004537 NamedDecl *Result = nullptr;
Douglas Gregor51783312009-05-27 05:35:12 +00004538 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004539 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004540 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004541 } else {
4542 // Since we don't have a name for the entity we're looking for,
4543 // our only option is to walk through all of the declarations to
4544 // find that name. This will occur in a few cases:
4545 //
4546 // - anonymous struct/union within a template
4547 // - unnamed class/struct/union/enum within a template
4548 //
4549 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004550 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004551 ParentDC->decls_begin(),
4552 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004553 }
Mike Stump11289f42009-09-09 15:08:12 +00004554
Douglas Gregor528ad932011-03-06 20:12:45 +00004555 if (!Result) {
4556 if (isa<UsingShadowDecl>(D)) {
4557 // UsingShadowDecls can instantiate to nothing because of using hiding.
4558 } else if (Diags.hasErrorOccurred()) {
4559 // We've already complained about something, so most likely this
4560 // declaration failed to instantiate. There's no point in complaining
4561 // further, since this is normal in invalid code.
4562 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004563 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004564 // instantiated, and we haven't gotten around to instantiating this
4565 // member yet. This can happen when the code uses forward declarations
4566 // of member classes, and introduces ordering dependencies via
4567 // template instantiation.
4568 Diag(Loc, diag::err_member_not_yet_instantiated)
4569 << D->getDeclName()
4570 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4571 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004572 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4573 // This enumeration constant was found when the template was defined,
4574 // but can't be found in the instantiation. This can happen if an
4575 // unscoped enumeration member is explicitly specialized.
4576 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4577 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4578 TemplateArgs));
4579 assert(Spec->getTemplateSpecializationKind() ==
4580 TSK_ExplicitSpecialization);
4581 Diag(Loc, diag::err_enumerator_does_not_exist)
4582 << D->getDeclName()
4583 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4584 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4585 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004586 } else {
4587 // We should have found something, but didn't.
4588 llvm_unreachable("Unable to find instantiation of declaration!");
4589 }
4590 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004591
Douglas Gregor51783312009-05-27 05:35:12 +00004592 D = Result;
4593 }
4594
Douglas Gregor51783312009-05-27 05:35:12 +00004595 return D;
4596}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004597
Mike Stump11289f42009-09-09 15:08:12 +00004598/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004599/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004600void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004601 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004602 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004603 PendingImplicitInstantiation Inst;
4604
4605 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004606 Inst = PendingInstantiations.front();
4607 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004608 } else {
4609 Inst = PendingLocalImplicitInstantiations.front();
4610 PendingLocalImplicitInstantiations.pop_front();
4611 }
Mike Stump11289f42009-09-09 15:08:12 +00004612
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004613 // Instantiate function definitions
4614 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004615 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4616 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004617 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4618 TSK_ExplicitInstantiationDefinition;
4619 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4620 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004621 continue;
4622 }
Mike Stump11289f42009-09-09 15:08:12 +00004623
Larisse Voufo39a1e502013-08-06 01:03:05 +00004624 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004625 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004626
4627 assert((Var->isStaticDataMember() ||
4628 isa<VarTemplateSpecializationDecl>(Var)) &&
4629 "Not a static data member, nor a variable template"
4630 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004631
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004632 // Don't try to instantiate declarations if the most recent redeclaration
4633 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004634 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004635 continue;
4636
4637 // Check if the most recent declaration has changed the specialization kind
4638 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004639 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004640 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004641 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004642 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004643 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004644 continue; // No longer need to instantiate this type.
4645 case TSK_ExplicitInstantiationDefinition:
4646 // We only need an instantiation if the pending instantiation *is* the
4647 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004648 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004649 case TSK_ImplicitInstantiation:
4650 break;
4651 }
4652
Larisse Voufo39a1e502013-08-06 01:03:05 +00004653 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4654 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004655 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4656 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004657
4658 // Instantiate static data member definitions or variable template
4659 // specializations.
4660 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4661 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004662 }
4663}
John McCallc62bb642010-03-24 05:22:00 +00004664
4665void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4666 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00004667 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00004668 switch (DD->getKind()) {
4669 case DependentDiagnostic::Access:
4670 HandleDependentAccessCheck(*DD, TemplateArgs);
4671 break;
4672 }
4673 }
4674}