blob: de23a1952f2917737f2468aaadc92d36fcc3eca5 [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"
Douglas Gregor402250f2009-08-26 21:14:46 +000022#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/Lookup.h"
24#include "clang/Sema/PrettyDeclStackTrace.h"
25#include "clang/Sema/Template.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000026
27using namespace clang;
28
David Majnemer192d1792013-11-27 08:20:38 +000029static bool isDeclWithinFunction(const Decl *D) {
30 const DeclContext *DC = D->getDeclContext();
31 if (DC->isFunctionOrMethod())
32 return true;
33
34 if (DC->isRecord())
35 return cast<CXXRecordDecl>(DC)->isLocalClass();
36
37 return false;
38}
39
John McCall3e11ebe2010-03-15 10:12:16 +000040bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
41 DeclaratorDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000042 if (!OldDecl->getQualifierLoc())
43 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000044
Douglas Gregor14454802011-02-25 02:25:35 +000045 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000046 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000047 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000048
Douglas Gregor14454802011-02-25 02:25:35 +000049 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000050 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000051
Douglas Gregor14454802011-02-25 02:25:35 +000052 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000053 return false;
54}
55
56bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
57 TagDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000058 if (!OldDecl->getQualifierLoc())
59 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000060
Douglas Gregor14454802011-02-25 02:25:35 +000061 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000062 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000063 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000064
Douglas Gregor14454802011-02-25 02:25:35 +000065 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000066 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000067
Douglas Gregor14454802011-02-25 02:25:35 +000068 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000069 return false;
70}
71
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000072// Include attribute instantiation code.
73#include "clang/Sema/AttrTemplateInstantiate.inc"
74
Richard Smith44c247f2013-02-22 08:32:16 +000075static void instantiateDependentAlignedAttr(
76 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
77 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
78 if (Aligned->isAlignmentExpr()) {
79 // The alignment expression is a constant expression.
80 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
81 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
82 if (!Result.isInvalid())
83 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
84 Aligned->getSpellingListIndex(), IsPackExpansion);
85 } else {
86 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
87 TemplateArgs, Aligned->getLocation(),
88 DeclarationName());
89 if (Result)
90 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
91 Aligned->getSpellingListIndex(), IsPackExpansion);
92 }
93}
94
95static void instantiateDependentAlignedAttr(
96 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
97 const AlignedAttr *Aligned, Decl *New) {
98 if (!Aligned->isPackExpansion()) {
99 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
100 return;
101 }
102
103 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
104 if (Aligned->isAlignmentExpr())
105 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
106 Unexpanded);
107 else
108 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
109 Unexpanded);
110 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
111
112 // Determine whether we can expand this attribute pack yet.
113 bool Expand = true, RetainExpansion = false;
114 Optional<unsigned> NumExpansions;
115 // FIXME: Use the actual location of the ellipsis.
116 SourceLocation EllipsisLoc = Aligned->getLocation();
117 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
118 Unexpanded, TemplateArgs, Expand,
119 RetainExpansion, NumExpansions))
120 return;
121
122 if (!Expand) {
123 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
124 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
125 } else {
126 for (unsigned I = 0; I != *NumExpansions; ++I) {
127 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
128 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
129 }
130 }
131}
132
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000133static void instantiateDependentEnableIfAttr(
134 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
135 const EnableIfAttr *A, const Decl *Tmpl, Decl *New) {
136 Expr *Cond = 0;
137 {
138 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
139 ExprResult Result = S.SubstExpr(A->getCond(), TemplateArgs);
140 if (Result.isInvalid())
141 return;
142 Cond = Result.takeAs<Expr>();
143 }
144 if (A->getCond()->isTypeDependent() && !Cond->isTypeDependent()) {
145 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
146 if (Converted.isInvalid())
147 return;
148 Cond = Converted.take();
149 }
150
151 SmallVector<PartialDiagnosticAt, 8> Diags;
152 if (A->getCond()->isValueDependent() && !Cond->isValueDependent() &&
153 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(Tmpl),
154 Diags)) {
155 S.Diag(A->getLocation(), diag::err_enable_if_never_constant_expr);
156 for (int I = 0, N = Diags.size(); I != N; ++I)
157 S.Diag(Diags[I].first, Diags[I].second);
158 return;
159 }
160
Aaron Ballman36a53502014-01-16 13:03:14 +0000161 EnableIfAttr *EIA = new (S.getASTContext())
162 EnableIfAttr(A->getLocation(), S.getASTContext(), Cond,
163 A->getMessage(),
164 A->getSpellingListIndex());
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000165 New->addAttr(EIA);
166}
167
John McCall6602bb12010-08-01 02:01:53 +0000168void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000169 const Decl *Tmpl, Decl *New,
170 LateInstantiatedAttrVec *LateAttrs,
171 LocalInstantiationScope *OuterMostScope) {
Aaron Ballmanb97112e2014-03-08 22:19:01 +0000172 for (const auto *TmplAttr : Tmpl->attrs()) {
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000173 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000174 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
175 if (Aligned && Aligned->isAlignmentDependent()) {
176 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
177 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000178 }
179
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000180 const EnableIfAttr *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr);
181 if (EnableIf && EnableIf->getCond()->isValueDependent()) {
182 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
183 New);
184 continue;
185 }
186
Richard Smith44c247f2013-02-22 08:32:16 +0000187 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000188 if (TmplAttr->isLateParsed() && LateAttrs) {
189 // Late parsed attributes must be instantiated and attached after the
190 // enclosing class has been instantiated. See Sema::InstantiateClass.
191 LocalInstantiationScope *Saved = 0;
192 if (CurrentInstantiationScope)
193 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
194 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
195 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000196 // Allow 'this' within late-parsed attributes.
197 NamedDecl *ND = dyn_cast<NamedDecl>(New);
198 CXXRecordDecl *ThisContext =
199 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
200 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
201 ND && ND->isCXXInstanceMember());
202
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000203 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
204 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000205 if (NewAttr)
206 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000207 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000208 }
209}
210
Douglas Gregor8a655532009-03-25 15:45:12 +0000211Decl *
212TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000213 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000214}
215
216Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000217TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
218 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
219 D->getIdentifier());
220 Owner->addDecl(Inst);
221 return Inst;
222}
223
224Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000225TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000226 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000227}
228
John McCalld8d0d432010-02-16 06:53:13 +0000229Decl *
230TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
231 NamespaceAliasDecl *Inst
232 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
233 D->getNamespaceLoc(),
234 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000235 D->getIdentifier(),
236 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000237 D->getTargetNameLoc(),
238 D->getNamespace());
239 Owner->addDecl(Inst);
240 return Inst;
241}
242
Richard Smith3f1b5d02011-05-05 21:57:07 +0000243Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
244 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000245 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000246 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000247 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000248 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000249 DI = SemaRef.SubstType(DI, TemplateArgs,
250 D->getLocation(), D->getDeclName());
251 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000252 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000253 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000254 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000255 } else {
256 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000257 }
Mike Stump11289f42009-09-09 15:08:12 +0000258
Richard Smith2ddcbab2012-10-23 00:32:41 +0000259 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
260 // libstdc++ relies upon this bug in its implementation of common_type.
261 // If we happen to be processing that implementation, fake up the g++ ?:
262 // semantics. See LWG issue 2141 for more information on the bug.
263 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
264 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
265 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
266 DT->isReferenceType() &&
267 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
268 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
269 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
270 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
271 // Fold it to the (non-reference) type which g++ would have produced.
272 DI = SemaRef.Context.getTrivialTypeSourceInfo(
273 DI->getType().getNonReferenceType());
274
Douglas Gregord7e7a512009-03-17 21:15:40 +0000275 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000276 TypedefNameDecl *Typedef;
277 if (IsTypeAlias)
278 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
279 D->getLocation(), D->getIdentifier(), DI);
280 else
281 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
282 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000283 if (Invalid)
284 Typedef->setInvalidDecl();
285
John McCall04fcd0d2011-02-01 08:20:08 +0000286 // If the old typedef was the name for linkage purposes of an anonymous
287 // tag decl, re-establish that relationship for the new typedef.
288 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
289 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000290 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000291 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000292 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000293 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000294 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000295 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000296
Douglas Gregorec9fd132012-01-14 16:38:05 +0000297 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000298 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
299 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000300 if (!InstPrev)
301 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000302
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000303 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
304
305 // If the typedef types are not identical, reject them.
306 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
307
Rafael Espindola8db352d2013-10-17 15:37:26 +0000308 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000309 }
310
John McCall6602bb12010-08-01 02:01:53 +0000311 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000312
John McCall401982f2010-01-20 21:53:11 +0000313 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000314
Douglas Gregord7e7a512009-03-17 21:15:40 +0000315 return Typedef;
316}
317
Richard Smithdda56e42011-04-15 14:24:37 +0000318Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000319 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
320 Owner->addDecl(Typedef);
321 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000322}
323
324Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000325 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
326 Owner->addDecl(Typedef);
327 return Typedef;
328}
329
330Decl *
331TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
332 // Create a local instantiation scope for this type alias template, which
333 // will contain the instantiations of the template parameters.
334 LocalInstantiationScope Scope(SemaRef);
335
336 TemplateParameterList *TempParams = D->getTemplateParameters();
337 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
338 if (!InstParams)
339 return 0;
340
341 TypeAliasDecl *Pattern = D->getTemplatedDecl();
342
343 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000344 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000345 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000346 if (!Found.empty()) {
347 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000348 }
349 }
350
351 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
352 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
353 if (!AliasInst)
354 return 0;
355
356 TypeAliasTemplateDecl *Inst
357 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
358 D->getDeclName(), InstParams, AliasInst);
359 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000360 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000361
362 Inst->setAccess(D->getAccess());
363
364 if (!PrevAliasTemplate)
365 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000366
Richard Smith3f1b5d02011-05-05 21:57:07 +0000367 Owner->addDecl(Inst);
368
369 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000370}
371
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000372Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000373 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000374}
375
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000376Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
377 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000378
Douglas Gregor04163182010-05-21 00:31:19 +0000379 // If this is the variable for an anonymous struct or union,
380 // instantiate the anonymous struct/union type first.
381 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
382 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
383 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
384 return 0;
385
John McCall76d824f2009-08-25 22:02:44 +0000386 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000387 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000388 TemplateArgs,
389 D->getTypeSpecStartLoc(),
390 D->getDeclName());
391 if (!DI)
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000392 return 0;
393
Douglas Gregor61623342010-09-12 07:37:24 +0000394 if (DI->getType()->isFunctionType()) {
395 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
396 << D->isStaticDataMember() << DI->getType();
397 return 0;
398 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000399
Richard Smith541b38b2013-09-20 01:15:31 +0000400 DeclContext *DC = Owner;
401 if (D->isLocalExternDecl())
402 SemaRef.adjustContextForLocalExternDecl(DC);
403
Larisse Voufo39a1e502013-08-06 01:03:05 +0000404 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000405 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000406 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000407 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000408
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000409 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000410 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000411 SemaRef.inferObjCARCLifetime(Var))
412 Var->setInvalidDecl();
413
Larisse Voufo39a1e502013-08-06 01:03:05 +0000414 // Substitute the nested name specifier, if any.
415 if (SubstQualifier(D, Var))
416 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000417
Richard Smith541b38b2013-09-20 01:15:31 +0000418 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000419 StartingScope, InstantiatingVarTemplate);
Nick Lewyckyd78f92f2014-05-03 00:41:18 +0000420
421 if (D->isNRVOVariable()) {
422 QualType ReturnType = cast<FunctionDecl>(DC)->getReturnType();
423 if (SemaRef.isCopyElisionCandidate(ReturnType, Var, false))
424 Var->setNRVOVariable(true);
425 }
426
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000427 return Var;
428}
429
Abramo Bagnarad7340582010-06-05 05:09:32 +0000430Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
431 AccessSpecDecl* AD
432 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
433 D->getAccessSpecifierLoc(), D->getColonLoc());
434 Owner->addHiddenDecl(AD);
435 return AD;
436}
437
Douglas Gregord7e7a512009-03-17 21:15:40 +0000438Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
439 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000440 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000441 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000442 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000443 DI = SemaRef.SubstType(DI, TemplateArgs,
444 D->getLocation(), D->getDeclName());
445 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000446 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000447 Invalid = true;
448 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000449 // C++ [temp.arg.type]p3:
450 // If a declaration acquires a function type through a type
451 // dependent on a template-parameter and this causes a
452 // declaration that does not use the syntactic form of a
453 // function declarator to have function type, the program is
454 // ill-formed.
455 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000456 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000457 Invalid = true;
458 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000459 } else {
460 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000461 }
462
463 Expr *BitWidth = D->getBitWidth();
464 if (Invalid)
465 BitWidth = 0;
466 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000467 // The bit-width expression is a constant expression.
468 EnterExpressionEvaluationContext Unevaluated(SemaRef,
469 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000470
John McCalldadc5752010-08-24 06:29:42 +0000471 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000472 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000473 if (InstantiatedBitWidth.isInvalid()) {
474 Invalid = true;
475 BitWidth = 0;
476 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000477 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000478 }
479
John McCall90459c52009-10-22 23:33:21 +0000480 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
481 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000482 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000483 D->getLocation(),
484 D->isMutable(),
485 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000486 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000487 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000488 D->getAccess(),
489 0);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000490 if (!Field) {
491 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000492 return 0;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000493 }
Mike Stump11289f42009-09-09 15:08:12 +0000494
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000495 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000496
Richard Smith848e1f12013-02-01 08:12:08 +0000497 if (Field->hasAttrs())
498 SemaRef.CheckAlignasUnderalignment(Field);
499
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000500 if (Invalid)
501 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000502
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000503 if (!Field->getDeclName()) {
504 // Keep track of where this decl came from.
505 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000506 }
Douglas Gregor04163182010-05-21 00:31:19 +0000507 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
508 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000509 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000510 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000511 }
Mike Stump11289f42009-09-09 15:08:12 +0000512
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000513 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000514 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000515 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000516
517 return Field;
518}
519
John McCall5e77d762013-04-16 07:28:30 +0000520Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
521 bool Invalid = false;
522 TypeSourceInfo *DI = D->getTypeSourceInfo();
523
524 if (DI->getType()->isVariablyModifiedType()) {
525 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
Aaron Ballman1bda4592014-01-03 01:09:27 +0000526 << D;
John McCall5e77d762013-04-16 07:28:30 +0000527 Invalid = true;
528 } else if (DI->getType()->isInstantiationDependentType()) {
529 DI = SemaRef.SubstType(DI, TemplateArgs,
530 D->getLocation(), D->getDeclName());
531 if (!DI) {
532 DI = D->getTypeSourceInfo();
533 Invalid = true;
534 } else if (DI->getType()->isFunctionType()) {
535 // C++ [temp.arg.type]p3:
536 // If a declaration acquires a function type through a type
537 // dependent on a template-parameter and this causes a
538 // declaration that does not use the syntactic form of a
539 // function declarator to have function type, the program is
540 // ill-formed.
541 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
542 << DI->getType();
543 Invalid = true;
544 }
545 } else {
546 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
547 }
548
Richard Smithf7981722013-11-22 09:01:48 +0000549 MSPropertyDecl *Property = MSPropertyDecl::Create(
550 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
551 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000552
553 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
554 StartingScope);
555
556 if (Invalid)
557 Property->setInvalidDecl();
558
559 Property->setAccess(D->getAccess());
560 Owner->addDecl(Property);
561
562 return Property;
563}
564
Francois Pichet783dd6e2010-11-21 06:08:52 +0000565Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
566 NamedDecl **NamedChain =
567 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
568
569 int i = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +0000570 for (auto *PI : D->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +0000571 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000572 TemplateArgs);
573 if (!Next)
574 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000575
Douglas Gregor55e6b312011-03-04 19:46:35 +0000576 NamedChain[i++] = Next;
577 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000578
Francois Pichetdbafc192010-12-09 10:07:54 +0000579 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000580 IndirectFieldDecl* IndirectField
581 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000582 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000583 NamedChain, D->getChainingSize());
584
585
586 IndirectField->setImplicit(D->isImplicit());
587 IndirectField->setAccess(D->getAccess());
588 Owner->addDecl(IndirectField);
589 return IndirectField;
590}
591
John McCallaa74a0c2009-08-28 07:59:38 +0000592Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000593 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000594 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000595 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000596 TypeSourceInfo *InstTy;
597 // If this is an unsupported friend, don't bother substituting template
598 // arguments into it. The actual type referred to won't be used by any
599 // parts of Clang, and may not be valid for instantiating. Just use the
600 // same info for the instantiated friend.
601 if (D->isUnsupportedFriend()) {
602 InstTy = Ty;
603 } else {
604 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
605 D->getLocation(), DeclarationName());
606 }
607 if (!InstTy)
Douglas Gregor33636e62009-12-24 20:56:24 +0000608 return 0;
John McCallaa74a0c2009-08-28 07:59:38 +0000609
Richard Smitha31a89a2012-09-20 01:31:00 +0000610 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000611 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000612 if (!FD)
613 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000614
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000615 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000616 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000617 Owner->addDecl(FD);
618 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000619 }
620
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000621 NamedDecl *ND = D->getFriendDecl();
622 assert(ND && "friend decl must be a decl or a type!");
623
John McCallb9c78482010-04-08 09:05:18 +0000624 // All of the Visit implementations for the various potential friend
625 // declarations have to be carefully written to work for friend
626 // objects, with the most important detail being that the target
627 // decl should almost certainly not be placed in Owner.
628 Decl *NewND = Visit(ND);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000629 if (!NewND) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000630
John McCallaa74a0c2009-08-28 07:59:38 +0000631 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000632 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000633 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000634 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000635 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000636 Owner->addDecl(FD);
637 return FD;
John McCall58de3582009-08-14 02:03:10 +0000638}
639
Douglas Gregord7e7a512009-03-17 21:15:40 +0000640Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
641 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000642
Richard Smith764d2fe2011-12-20 02:08:33 +0000643 // The expression in a static assertion is a constant expression.
644 EnterExpressionEvaluationContext Unevaluated(SemaRef,
645 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000646
John McCalldadc5752010-08-24 06:29:42 +0000647 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000648 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000649 if (InstantiatedAssertExpr.isInvalid())
650 return 0;
651
Richard Smithded9c2e2012-07-11 22:37:56 +0000652 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000653 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000654 D->getMessage(),
655 D->getRParenLoc(),
656 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000657}
658
659Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith2e6610a2012-03-26 04:58:10 +0000660 EnumDecl *PrevDecl = 0;
661 if (D->getPreviousDecl()) {
662 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
663 D->getPreviousDecl(),
664 TemplateArgs);
665 if (!Prev) return 0;
666 PrevDecl = cast<EnumDecl>(Prev);
667 }
668
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000669 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000670 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000671 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000672 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000673 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000674 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000675 // If we have type source information for the underlying type, it means it
676 // has been explicitly set by the user. Perform substitution on it before
677 // moving on.
678 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000679 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
680 DeclarationName());
681 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000682 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000683 else
684 Enum->setIntegerTypeSourceInfo(NewTI);
685 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000686 assert(!D->getIntegerType()->isDependentType()
687 && "Dependent type without type source info");
688 Enum->setIntegerType(D->getIntegerType());
689 }
690 }
691
John McCall811a0f52010-10-22 23:36:17 +0000692 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
693
Richard Smith4b38ded2012-03-14 23:13:10 +0000694 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000695 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +0000696 // Forward the mangling number from the template to the instantiated decl.
697 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
John McCall3e11ebe2010-03-15 10:12:16 +0000698 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000699 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000700
Richard Smith258a7442012-03-26 04:08:46 +0000701 EnumDecl *Def = D->getDefinition();
702 if (Def && Def != D) {
703 // If this is an out-of-line definition of an enum member template, check
704 // that the underlying types match in the instantiation of both
705 // declarations.
706 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
707 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
708 QualType DefnUnderlying =
709 SemaRef.SubstType(TI->getType(), TemplateArgs,
710 UnderlyingLoc, DeclarationName());
711 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
712 DefnUnderlying, Enum);
713 }
714 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000715
Richard Smith4b38ded2012-03-14 23:13:10 +0000716 // C++11 [temp.inst]p1: The implicit instantiation of a class template
717 // specialization causes the implicit instantiation of the declarations, but
718 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000719 //
720 // DR1484 clarifies that enumeration definitions inside of a template
721 // declaration aren't considered entities that can be separately instantiated
722 // from the rest of the entity they are declared inside of.
723 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
724 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000725 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000726 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000727
728 return Enum;
729}
730
731void TemplateDeclInstantiator::InstantiateEnumDefinition(
732 EnumDecl *Enum, EnumDecl *Pattern) {
733 Enum->startDefinition();
734
Richard Smith7d137e32012-03-23 03:33:32 +0000735 // Update the location to refer to the definition.
736 Enum->setLocation(Pattern->getLocation());
737
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000738 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000739
740 EnumConstantDecl *LastEnumConst = 0;
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000741 for (auto *EC : Pattern->enumerators()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000742 // The specified value for the enumerator.
John McCalldadc5752010-08-24 06:29:42 +0000743 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000744 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000745 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000746 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000747 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000748
John McCall76d824f2009-08-25 22:02:44 +0000749 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000750 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000751
752 // Drop the initial value and continue.
753 bool isInvalid = false;
754 if (Value.isInvalid()) {
755 Value = SemaRef.Owned((Expr *)0);
756 isInvalid = true;
757 }
758
Mike Stump11289f42009-09-09 15:08:12 +0000759 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000760 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
761 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000762 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000763
764 if (isInvalid) {
765 if (EnumConst)
766 EnumConst->setInvalidDecl();
767 Enum->setInvalidDecl();
768 }
769
770 if (EnumConst) {
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000771 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000772
John McCallf9b528c2010-01-23 22:37:59 +0000773 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000774 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000775 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000776 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000777
Richard Smith4b38ded2012-03-14 23:13:10 +0000778 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
779 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000780 // If the enumeration is within a function or method, record the enum
781 // constant as a local.
Aaron Ballman23a6dcb2014-03-08 18:45:14 +0000782 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000783 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000784 }
785 }
Mike Stump11289f42009-09-09 15:08:12 +0000786
Richard Smith4b38ded2012-03-14 23:13:10 +0000787 // FIXME: Fixup LBraceLoc
788 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
789 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000790 Enumerators,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +0000791 0, 0);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000792}
793
Douglas Gregor9106b822009-03-25 15:04:13 +0000794Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000795 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000796}
797
John McCall87a44eb2009-08-20 01:44:21 +0000798Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000799 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
800
Douglas Gregor954de172009-10-31 17:21:17 +0000801 // Create a local instantiation scope for this class template, which
802 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000803 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000804 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000805 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000806 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000807 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +0000808
809 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000810
811 // Instantiate the qualifier. We have to do this first in case
812 // we're a friend declaration, because if we are then we need to put
813 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000814 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
815 if (QualifierLoc) {
816 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
817 TemplateArgs);
818 if (!QualifierLoc)
819 return 0;
John McCall598b4402010-03-25 06:39:04 +0000820 }
821
822 CXXRecordDecl *PrevDecl = 0;
823 ClassTemplateDecl *PrevClassTemplate = 0;
824
Douglas Gregorec9fd132012-01-14 16:38:05 +0000825 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000826 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000827 if (!Found.empty()) {
828 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000829 if (PrevClassTemplate)
830 PrevDecl = PrevClassTemplate->getTemplatedDecl();
831 }
832 }
833
John McCall598b4402010-03-25 06:39:04 +0000834 // If this isn't a friend, then it's a member template, in which
835 // case we just want to build the instantiation in the
836 // specialization. If it is a friend, we want to build it in
837 // the appropriate context.
838 DeclContext *DC = Owner;
839 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000840 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000841 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000842 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000843 DC = SemaRef.computeDeclContext(SS);
844 if (!DC) return 0;
845 } else {
846 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
847 Pattern->getDeclContext(),
848 TemplateArgs);
849 }
850
851 // Look for a previous declaration of the template in the owning
852 // context.
853 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
854 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
855 SemaRef.LookupQualifiedName(R, DC);
856
857 if (R.isSingleResult()) {
858 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
859 if (PrevClassTemplate)
860 PrevDecl = PrevClassTemplate->getTemplatedDecl();
861 }
862
Douglas Gregor14454802011-02-25 02:25:35 +0000863 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000864 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000865 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000866 << QualifierLoc.getSourceRange();
John McCall598b4402010-03-25 06:39:04 +0000867 return 0;
868 }
869
Douglas Gregor01e09d92010-04-08 18:16:15 +0000870 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000871 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000872 bool Complain = true;
873
874 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
875 // template for struct std::tr1::__detail::_Map_base, where the
876 // template parameters of the friend declaration don't match the
877 // template parameters of the original declaration. In this one
878 // case, we don't complain about the ill-formed friend
879 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000880 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000881 Pattern->getIdentifier()->isStr("_Map_base") &&
882 DC->isNamespace() &&
883 cast<NamespaceDecl>(DC)->getIdentifier() &&
884 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
885 DeclContext *DCParent = DC->getParent();
886 if (DCParent->isNamespace() &&
887 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
888 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
889 DeclContext *DCParent2 = DCParent->getParent();
890 if (DCParent2->isNamespace() &&
891 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
892 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
893 DCParent2->getParent()->isTranslationUnit())
894 Complain = false;
895 }
896 }
897
John McCall598b4402010-03-25 06:39:04 +0000898 TemplateParameterList *PrevParams
899 = PrevClassTemplate->getTemplateParameters();
900
901 // Make sure the parameter lists match.
902 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000903 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000904 Sema::TPL_TemplateMatch)) {
905 if (Complain)
906 return 0;
907
908 AdoptedPreviousTemplateParams = true;
909 InstParams = PrevParams;
910 }
John McCall598b4402010-03-25 06:39:04 +0000911
912 // Do some additional validation, then merge default arguments
913 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000914 if (!AdoptedPreviousTemplateParams &&
915 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000916 Sema::TPC_ClassTemplate))
917 return 0;
918 }
919 }
920
John McCall87a44eb2009-08-20 01:44:21 +0000921 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000922 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000923 Pattern->getLocStart(), Pattern->getLocation(),
924 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000925 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000926
Douglas Gregor14454802011-02-25 02:25:35 +0000927 if (QualifierLoc)
928 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000929
John McCall87a44eb2009-08-20 01:44:21 +0000930 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000931 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
932 D->getIdentifier(), InstParams, RecordInst,
933 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000934 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000935
John McCall598b4402010-03-25 06:39:04 +0000936 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000937 if (PrevClassTemplate)
938 Inst->setAccess(PrevClassTemplate->getAccess());
939 else
940 Inst->setAccess(D->getAccess());
941
Richard Smith64017682013-07-17 23:53:16 +0000942 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000943 // TODO: do we want to track the instantiation progeny of this
944 // friend target decl?
945 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000946 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000947 if (!PrevClassTemplate)
948 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000949 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000950
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000951 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000952 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000953 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000954
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000955 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000956 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000957 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000958 Inst->setLexicalDeclContext(Owner);
959 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000960 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000961 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000962
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000963 if (D->isOutOfLine()) {
964 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
965 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
966 }
967
John McCall87a44eb2009-08-20 01:44:21 +0000968 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000969
970 if (!PrevClassTemplate) {
971 // Queue up any out-of-line partial specializations of this member
972 // class template; the client will force their instantiation once
973 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000974 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000975 D->getPartialSpecializations(PartialSpecs);
976 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000977 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +0000978 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
979 }
980
John McCall87a44eb2009-08-20 01:44:21 +0000981 return Inst;
982}
983
Douglas Gregore704c9d2009-08-27 16:57:43 +0000984Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000985TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
986 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000987 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000988
Douglas Gregor21610382009-10-29 00:04:11 +0000989 // Lookup the already-instantiated declaration in the instantiation
990 // of the class template and return that.
991 DeclContext::lookup_result Found
992 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000993 if (Found.empty())
Douglas Gregor21610382009-10-29 00:04:11 +0000994 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000995
Douglas Gregor21610382009-10-29 00:04:11 +0000996 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +0000997 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +0000998 if (!InstClassTemplate)
999 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001000
Douglas Gregor869853e2010-11-10 19:44:59 +00001001 if (ClassTemplatePartialSpecializationDecl *Result
1002 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1003 return Result;
1004
1005 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001006}
1007
Larisse Voufo39a1e502013-08-06 01:03:05 +00001008Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1009 assert(D->getTemplatedDecl()->isStaticDataMember() &&
1010 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001011
1012 // Create a local instantiation scope for this variable template, which
1013 // will contain the instantiations of the template parameters.
1014 LocalInstantiationScope Scope(SemaRef);
1015 TemplateParameterList *TempParams = D->getTemplateParameters();
1016 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1017 if (!InstParams)
1018 return NULL;
1019
1020 VarDecl *Pattern = D->getTemplatedDecl();
1021 VarTemplateDecl *PrevVarTemplate = 0;
1022
1023 if (Pattern->getPreviousDecl()) {
1024 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1025 if (!Found.empty())
1026 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1027 }
1028
Richard Smith1c34fb72013-08-13 18:18:50 +00001029 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +00001030 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1031 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +00001032
1033 DeclContext *DC = Owner;
1034
Larisse Voufo39a1e502013-08-06 01:03:05 +00001035 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1036 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
Richard Smithbeef3452014-01-16 23:39:20 +00001037 VarInst);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001038 VarInst->setDescribedVarTemplate(Inst);
Richard Smithbeef3452014-01-16 23:39:20 +00001039 Inst->setPreviousDecl(PrevVarTemplate);
Larisse Voufo39a1e502013-08-06 01:03:05 +00001040
1041 Inst->setAccess(D->getAccess());
1042 if (!PrevVarTemplate)
1043 Inst->setInstantiatedFromMemberTemplate(D);
1044
1045 if (D->isOutOfLine()) {
1046 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1047 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1048 }
1049
1050 Owner->addDecl(Inst);
1051
1052 if (!PrevVarTemplate) {
1053 // Queue up any out-of-line partial specializations of this member
1054 // variable template; the client will force their instantiation once
1055 // the enclosing class has been instantiated.
1056 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1057 D->getPartialSpecializations(PartialSpecs);
1058 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001059 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001060 OutOfLineVarPartialSpecs.push_back(
1061 std::make_pair(Inst, PartialSpecs[I]));
1062 }
1063
1064 return Inst;
1065}
1066
1067Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1068 VarTemplatePartialSpecializationDecl *D) {
1069 assert(D->isStaticDataMember() &&
1070 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001071
1072 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1073
1074 // Lookup the already-instantiated declaration and return that.
1075 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1076 assert(!Found.empty() && "Instantiation found nothing?");
1077
1078 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1079 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1080
1081 if (VarTemplatePartialSpecializationDecl *Result =
1082 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1083 return Result;
1084
1085 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1086}
1087
Douglas Gregore4b05162009-10-07 17:21:34 +00001088Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001089TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001090 // Create a local instantiation scope for this function template, which
1091 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001092 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001093 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001094 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001095
Douglas Gregore704c9d2009-08-27 16:57:43 +00001096 TemplateParameterList *TempParams = D->getTemplateParameters();
1097 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001098 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001099 return NULL;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001100
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001101 FunctionDecl *Instantiated = 0;
1102 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001103 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001104 InstParams));
1105 else
1106 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001107 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001108 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001109
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001110 if (!Instantiated)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001111 return 0;
1112
Mike Stump11289f42009-09-09 15:08:12 +00001113 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001114 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001115 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001116 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001117 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001118 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001119 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001120
John McCall30837102010-03-26 23:10:15 +00001121 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1122
John McCall2079d0b2009-12-14 23:19:40 +00001123 // Link the instantiation back to the pattern *unless* this is a
1124 // non-definition friend declaration.
1125 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001126 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001127 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001128
John McCall30837102010-03-26 23:10:15 +00001129 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001130 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001131 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001132 } else if (InstTemplate->getDeclContext()->isRecord() &&
1133 !D->getPreviousDecl()) {
1134 SemaRef.CheckFriendAccess(InstTemplate);
1135 }
John McCall30837102010-03-26 23:10:15 +00001136
Douglas Gregore704c9d2009-08-27 16:57:43 +00001137 return InstTemplate;
1138}
1139
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001140Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1141 CXXRecordDecl *PrevDecl = 0;
1142 if (D->isInjectedClassName())
1143 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001144 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001145 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001146 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001147 TemplateArgs);
1148 if (!Prev) return 0;
1149 PrevDecl = cast<CXXRecordDecl>(Prev);
1150 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001151
1152 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001153 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001154 D->getLocStart(), D->getLocation(),
1155 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001156
1157 // Substitute the nested name specifier, if any.
1158 if (SubstQualifier(D, Record))
1159 return 0;
1160
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001161 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001162 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1163 // the tag decls introduced by friend class declarations don't have an access
1164 // specifier. Remove once this area of the code gets sorted out.
1165 if (D->getAccess() != AS_none)
1166 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001167 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001168 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001169
John McCallaa74a0c2009-08-28 07:59:38 +00001170 // If the original function was part of a friend declaration,
1171 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001172 if (D->getFriendObjectKind())
1173 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001174
Douglas Gregor04163182010-05-21 00:31:19 +00001175 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001176 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001177 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001178
1179 if (D->isLocalClass())
1180 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001181
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001182 // Forward the mangling number from the template to the instantiated decl.
1183 SemaRef.Context.setManglingNumber(Record,
1184 SemaRef.Context.getManglingNumber(D));
1185
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001186 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001187
1188 // DR1484 clarifies that the members of a local class are instantiated as part
1189 // of the instantiation of their enclosing entity.
1190 if (D->isCompleteDefinition() && D->isLocalClass()) {
David Majnemera64cb5a2014-02-22 00:17:46 +00001191 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1192 TSK_ImplicitInstantiation,
1193 /*Complain=*/true);
1194 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1195 TSK_ImplicitInstantiation);
David Majnemer192d1792013-11-27 08:20:38 +00001196 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001197 return Record;
1198}
1199
Douglas Gregor89f593a2012-09-13 21:56:43 +00001200/// \brief Adjust the given function type for an instantiation of the
1201/// given declaration, to cope with modifications to the function's type that
1202/// aren't reflected in the type-source information.
1203///
1204/// \param D The declaration we're instantiating.
1205/// \param TInfo The already-instantiated type.
1206static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1207 FunctionDecl *D,
1208 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001209 const FunctionProtoType *OrigFunc
1210 = D->getType()->castAs<FunctionProtoType>();
1211 const FunctionProtoType *NewFunc
1212 = TInfo->getType()->castAs<FunctionProtoType>();
1213 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1214 return TInfo->getType();
1215
1216 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1217 NewEPI.ExtInfo = OrigFunc->getExtInfo();
Alp Toker314cc812014-01-25 16:55:45 +00001218 return Context.getFunctionType(NewFunc->getReturnType(),
Alp Toker9cacbab2014-01-20 20:26:09 +00001219 NewFunc->getParamTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001220}
1221
John McCallaa74a0c2009-08-28 07:59:38 +00001222/// Normal class members are of more specific types and therefore
1223/// don't make it here. This function serves two purposes:
1224/// 1) instantiating function templates
1225/// 2) substituting friend declarations
Douglas Gregor33636e62009-12-24 20:56:24 +00001226Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001227 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001228 // Check whether there is already a function template specialization for
1229 // this declaration.
1230 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001231 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001232 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001233
Douglas Gregorce9978f2012-03-28 14:34:23 +00001234 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001235 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001236 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001237 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001238
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001239 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001240 if (SpecFunc)
1241 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001242 }
Mike Stump11289f42009-09-09 15:08:12 +00001243
John McCall2f88d7d2010-03-27 05:57:59 +00001244 bool isFriend;
1245 if (FunctionTemplate)
1246 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1247 else
1248 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1249
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001250 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001251 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001252 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001253 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001254 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001255
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001256 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001257 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001258 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001259 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001260 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001261
Douglas Gregor14454802011-02-25 02:25:35 +00001262 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1263 if (QualifierLoc) {
1264 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1265 TemplateArgs);
1266 if (!QualifierLoc)
1267 return 0;
John McCalle0b2ddb2010-03-26 04:53:08 +00001268 }
1269
John McCallce410662010-02-06 01:50:47 +00001270 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001271 // in the enclosing namespace; otherwise we need to find the instantiated
1272 // context.
John McCallce410662010-02-06 01:50:47 +00001273 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001274 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001275 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001276 SemaRef.adjustContextForLocalExternDecl(DC);
1277 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001278 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001279 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001280 DC = SemaRef.computeDeclContext(SS);
1281 if (!DC) return 0;
1282 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001283 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001284 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001285 }
John McCallce410662010-02-06 01:50:47 +00001286
John McCallaa74a0c2009-08-28 07:59:38 +00001287 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001288 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001289 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001290 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001291 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001292 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001293 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001294
Richard Smithf3814ad2013-01-25 00:08:28 +00001295 if (D->isInlined())
1296 Function->setImplicitlyInline();
1297
Douglas Gregor14454802011-02-25 02:25:35 +00001298 if (QualifierLoc)
1299 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001300
Richard Smith541b38b2013-09-20 01:15:31 +00001301 if (D->isLocalExternDecl())
1302 Function->setLocalExternDecl();
1303
John McCall30837102010-03-26 23:10:15 +00001304 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001305 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001306 assert(D->getDeclContext()->isFileContext());
1307 LexicalDC = D->getDeclContext();
1308 }
1309
1310 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001311
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001312 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001313 for (unsigned P = 0; P < Params.size(); ++P)
1314 if (Params[P])
1315 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001316 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001317
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001318 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001319 if (TemplateParams) {
1320 // Our resulting instantiation is actually a function template, since we
1321 // are substituting only the outer template parameters. For example, given
1322 //
1323 // template<typename T>
1324 // struct X {
1325 // template<typename U> friend void f(T, U);
1326 // };
1327 //
1328 // X<int> x;
1329 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001330 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001331 // which means substituting int for T, but leaving "f" as a friend function
1332 // template.
1333 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001334 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001335 Function->getLocation(),
1336 Function->getDeclName(),
1337 TemplateParams, Function);
1338 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001339
1340 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001341
1342 if (isFriend && D->isThisDeclarationADefinition()) {
1343 // TODO: should we remember this connection regardless of whether
1344 // the friend declaration provided a body?
1345 FunctionTemplate->setInstantiatedFromMemberTemplate(
1346 D->getDescribedFunctionTemplate());
1347 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001348 } else if (FunctionTemplate) {
1349 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001350 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001351 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001352 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001353 Innermost.begin(),
1354 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001355 /*InsertPos=*/0);
Chandler Carruth48b28312011-08-18 09:09:59 +00001356 } else if (isFriend) {
1357 // Note, we need this connection even if the friend doesn't have a body.
1358 // Its body may exist but not have been attached yet due to deferred
1359 // parsing.
1360 // FIXME: It might be cleaner to set this when attaching the body to the
1361 // friend function declaration, however that would require finding all the
1362 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001363 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001364 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001365
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001366 if (InitFunctionInstantiation(Function, D))
1367 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001368
John McCallb9c78482010-04-08 09:05:18 +00001369 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001370
Richard Smith541b38b2013-09-20 01:15:31 +00001371 LookupResult Previous(
1372 SemaRef, Function->getDeclName(), SourceLocation(),
1373 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1374 : Sema::LookupOrdinaryName,
1375 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001376
John McCallb9c78482010-04-08 09:05:18 +00001377 if (DependentFunctionTemplateSpecializationInfo *Info
1378 = D->getDependentSpecializationInfo()) {
1379 assert(isFriend && "non-friend has dependent specialization info?");
1380
1381 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001382 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001383
1384 // Instantiate the explicit template arguments.
1385 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1386 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001387 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1388 ExplicitArgs, TemplateArgs))
1389 return 0;
John McCallb9c78482010-04-08 09:05:18 +00001390
1391 // Map the candidate templates to their instantiations.
1392 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1393 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1394 Info->getTemplate(I),
1395 TemplateArgs);
1396 if (!Temp) return 0;
1397
1398 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1399 }
1400
1401 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1402 &ExplicitArgs,
1403 Previous))
1404 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001405
John McCallb9c78482010-04-08 09:05:18 +00001406 isExplicitSpecialization = true;
1407
1408 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001409 // Look only into the namespace where the friend would be declared to
1410 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001411 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001412 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001413
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001414 // In C++, the previous declaration we find might be a tag type
1415 // (class or enum). In this case, the new declaration will hide the
1416 // tag type. Note that this does does not apply if we're declaring a
1417 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001418 if (Previous.isSingleTagDecl())
1419 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001420 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001421
John McCall84d87672009-12-10 09:41:52 +00001422 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001423 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001424
John McCallb9467b62010-04-24 01:30:58 +00001425 NamedDecl *PrincipalDecl = (TemplateParams
1426 ? cast<NamedDecl>(FunctionTemplate)
1427 : Function);
1428
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001429 // If the original function was part of a friend declaration,
1430 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001431 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001432 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001433 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001434
Richard Smith91dfaac2014-02-03 02:37:59 +00001435 bool QueuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001436
Richard Smith91dfaac2014-02-03 02:37:59 +00001437 // C++11 [temp.friend]p4 (DR329):
1438 // When a function is defined in a friend function declaration in a class
1439 // template, the function is instantiated when the function is odr-used.
1440 // The same restrictions on multiple declarations and definitions that
1441 // apply to non-template function declarations and definitions also apply
1442 // to these implicit definitions.
1443 if (D->isThisDeclarationADefinition()) {
Douglas Gregorb92ea592010-05-18 05:45:02 +00001444 // Check for a function body.
1445 const FunctionDecl *Definition = 0;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001446 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001447 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001448 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1449 << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001450 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001451 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001452 // Check for redefinitions due to other instantiations of this or
1453 // a similar friend function.
Aaron Ballman86c93902014-03-06 23:45:36 +00001454 else for (auto R : Function->redecls()) {
1455 if (R == Function)
Gabor Greif122f1eb2010-08-28 15:42:30 +00001456 continue;
Richard Smith91dfaac2014-02-03 02:37:59 +00001457
1458 // If some prior declaration of this function has been used, we need
1459 // to instantiate its definition.
1460 if (!QueuedInstantiation && R->isUsed(false)) {
1461 if (MemberSpecializationInfo *MSInfo =
1462 Function->getMemberSpecializationInfo()) {
1463 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1464 SourceLocation Loc = R->getLocation(); // FIXME
1465 MSInfo->setPointOfInstantiation(Loc);
1466 SemaRef.PendingLocalImplicitInstantiations.push_back(
1467 std::make_pair(Function, Loc));
1468 QueuedInstantiation = true;
Gabor Greif718d5152010-08-30 21:10:05 +00001469 }
1470 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001471 }
1472
1473 // If some prior declaration of this function was a friend with an
1474 // uninstantiated definition, reject it.
1475 if (R->getFriendObjectKind()) {
1476 if (const FunctionDecl *RPattern =
1477 R->getTemplateInstantiationPattern()) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001478 if (RPattern->isDefined(RPattern)) {
Richard Smith91dfaac2014-02-03 02:37:59 +00001479 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001480 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001481 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregorb92ea592010-05-18 05:45:02 +00001482 break;
1483 }
Richard Smith91dfaac2014-02-03 02:37:59 +00001484 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001485 }
1486 }
1487 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001488 }
1489
Richard Smith541b38b2013-09-20 01:15:31 +00001490 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1491 DC->makeDeclVisibleInContext(PrincipalDecl);
1492
John McCallb9467b62010-04-24 01:30:58 +00001493 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1494 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1495 PrincipalDecl->setNonMemberOperator();
1496
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001497 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001498 return Function;
1499}
1500
Douglas Gregore704c9d2009-08-27 16:57:43 +00001501Decl *
1502TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001503 TemplateParameterList *TemplateParams,
1504 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001505 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001506 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001507 // We are creating a function template specialization from a function
1508 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001509 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001510 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001511
Douglas Gregorce9978f2012-03-28 14:34:23 +00001512 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001513 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001514 = FunctionTemplate->findSpecialization(Innermost.begin(),
1515 Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001516 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001517
Douglas Gregor97628d62009-08-21 00:16:32 +00001518 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001519 if (SpecFunc)
1520 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001521 }
1522
John McCall2f88d7d2010-03-27 05:57:59 +00001523 bool isFriend;
1524 if (FunctionTemplate)
1525 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1526 else
1527 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1528
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001529 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001530 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001531 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001532 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001533
John McCalld0e23ec2010-10-19 02:26:41 +00001534 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001535 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001536 unsigned NumTempParamLists = 0;
1537 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1538 TempParamLists.set_size(NumTempParamLists);
1539 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1540 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1541 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1542 if (!InstParams)
1543 return NULL;
1544 TempParamLists[I] = InstParams;
1545 }
1546 }
1547
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001548 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001549 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001550 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001551 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001552 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001553
Douglas Gregor14454802011-02-25 02:25:35 +00001554 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1555 if (QualifierLoc) {
1556 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001557 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001558 if (!QualifierLoc)
Douglas Gregor14454802011-02-25 02:25:35 +00001559 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001560 }
1561
1562 DeclContext *DC = Owner;
1563 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001564 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001565 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001566 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001567 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001568
1569 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1570 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001571 } else {
1572 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1573 D->getDeclContext(),
1574 TemplateArgs);
1575 }
1576 if (!DC) return 0;
1577 }
1578
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001579 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001580 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001581 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001582
Abramo Bagnaradff19302011-03-08 08:55:46 +00001583 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001584 DeclarationNameInfo NameInfo
1585 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001586 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001587 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001588 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001589 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001590 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001591 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001592
Richard Smith185be182013-04-10 05:48:59 +00001593 // Claim that the instantiation of a constructor or constructor template
1594 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001595 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1596 Constructor->getInheritedConstructor())) {
1597 // If we're instantiating a specialization of a function template, our
1598 // "inherited constructor" will actually itself be a function template.
1599 // Instantiate a declaration of it, too.
1600 if (FunctionTemplate) {
1601 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1602 !Inh->getParent()->isDependentContext() &&
1603 "inheriting constructor template in dependent context?");
1604 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1605 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001606 if (Inst.isInvalid())
Richard Smith4c163a02013-05-17 02:19:35 +00001607 return 0;
1608 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1609 LocalInstantiationScope LocalScope(SemaRef);
1610
1611 // Use the same template arguments that we deduced for the inheriting
1612 // constructor. There's no way they could be deduced differently.
1613 MultiLevelTemplateArgumentList InheritedArgs;
1614 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1615 Inh = cast_or_null<CXXConstructorDecl>(
1616 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1617 if (!Inh)
1618 return 0;
1619 }
Richard Smith185be182013-04-10 05:48:59 +00001620 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001621 }
Douglas Gregore8394862009-08-21 22:43:28 +00001622 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001623 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001624 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001625 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001626 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001627 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001628 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001629 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001630 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001631 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001632 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001633 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001634 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001635 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001636 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001637 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001638 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001639 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001640 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001641
Richard Smithf3814ad2013-01-25 00:08:28 +00001642 if (D->isInlined())
1643 Method->setImplicitlyInline();
1644
Douglas Gregor14454802011-02-25 02:25:35 +00001645 if (QualifierLoc)
1646 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001647
Douglas Gregore704c9d2009-08-27 16:57:43 +00001648 if (TemplateParams) {
1649 // Our resulting instantiation is actually a function template, since we
1650 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001651 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001652 // template<typename T>
1653 // struct X {
1654 // template<typename U> void f(T, U);
1655 // };
1656 //
1657 // X<int> x;
1658 //
1659 // We are instantiating the member template "f" within X<int>, which means
1660 // substituting int for T, but leaving "f" as a member function template.
1661 // Build the function template itself.
1662 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1663 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001664 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001665 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001666 if (isFriend) {
1667 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001668 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001669 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001670 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001671 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001672 } else if (FunctionTemplate) {
1673 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001674 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001675 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001676 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001677 Innermost.begin(),
1678 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001679 /*InsertPos=*/0);
John McCall2f88d7d2010-03-27 05:57:59 +00001680 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001681 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001682 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001683 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001684
Mike Stump11289f42009-09-09 15:08:12 +00001685 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001686 // out-of-line, the instantiation will have the same lexical
1687 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001688 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001689 if (NumTempParamLists)
1690 Method->setTemplateParameterListsInfo(SemaRef.Context,
1691 NumTempParamLists,
1692 TempParamLists.data());
1693
John McCall2f88d7d2010-03-27 05:57:59 +00001694 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001695 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001696 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001697 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001698
Douglas Gregor21342092009-03-24 00:38:23 +00001699 // Attach the parameters
1700 for (unsigned P = 0; P < Params.size(); ++P)
1701 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001702 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001703
1704 if (InitMethodInstantiation(Method, D))
1705 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001706
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001707 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1708 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001709
John McCall2f88d7d2010-03-27 05:57:59 +00001710 if (!FunctionTemplate || TemplateParams || isFriend) {
1711 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001712
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001713 // In C++, the previous declaration we find might be a tag type
1714 // (class or enum). In this case, the new declaration will hide the
1715 // tag type. Note that this does does not apply if we're declaring a
1716 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001717 if (Previous.isSingleTagDecl())
1718 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001719 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001720
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001721 if (!IsClassScopeSpecialization)
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001722 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001723
Douglas Gregor21920e372009-12-01 17:24:26 +00001724 if (D->isPure())
1725 SemaRef.CheckPureMethod(Method, SourceRange());
1726
John McCalla0a96892012-08-10 03:15:35 +00001727 // Propagate access. For a non-friend declaration, the access is
1728 // whatever we're propagating from. For a friend, it should be the
1729 // previous declaration we just found.
1730 if (isFriend && Method->getPreviousDecl())
1731 Method->setAccess(Method->getPreviousDecl()->getAccess());
1732 else
1733 Method->setAccess(D->getAccess());
1734 if (FunctionTemplate)
1735 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001736
Anders Carlsson7c812f52011-01-20 06:52:44 +00001737 SemaRef.CheckOverrideControl(Method);
1738
Eli Friedman41340732011-11-15 22:39:08 +00001739 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001740 if (D->isExplicitlyDefaulted())
1741 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001742 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001743 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001744
John McCalla0a96892012-08-10 03:15:35 +00001745 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001746 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001747 // do nothing
1748
1749 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001750 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001751 // do nothing
1752
1753 // Otherwise, check access to friends and make them visible.
1754 } else if (isFriend) {
1755 // We only need to re-check access for methods which we didn't
1756 // manage to match during parsing.
1757 if (!D->getPreviousDecl())
1758 SemaRef.CheckFriendAccess(Method);
1759
1760 Record->makeDeclVisibleInContext(Method);
1761
1762 // Otherwise, add the declaration. We don't need to do this for
1763 // class-scope specializations because we'll have matched them with
1764 // the appropriate template.
1765 } else if (!IsClassScopeSpecialization) {
1766 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001767 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001768
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001769 return Method;
1770}
1771
Douglas Gregor4044d992009-03-24 16:43:20 +00001772Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001773 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001774}
1775
Douglas Gregor654b07e2009-03-24 00:15:49 +00001776Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001777 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001778}
1779
Douglas Gregor1880ba52009-03-25 00:34:44 +00001780Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001781 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001782}
1783
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001784Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001785 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1786 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001787}
1788
John McCall87a44eb2009-08-20 01:44:21 +00001789Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1790 TemplateTypeParmDecl *D) {
1791 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001792 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001793
John McCall87a44eb2009-08-20 01:44:21 +00001794 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001795 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1796 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001797 D->getDepth() - TemplateArgs.getNumLevels(),
1798 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001799 D->wasDeclaredWithTypename(),
1800 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001801 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001802
David Majnemer89189202013-08-28 23:48:32 +00001803 if (D->hasDefaultArgument()) {
1804 TypeSourceInfo *InstantiatedDefaultArg =
1805 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1806 D->getDefaultArgumentLoc(), D->getDeclName());
1807 if (InstantiatedDefaultArg)
1808 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1809 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001810
1811 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001812 // scope.
1813 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001814
John McCall87a44eb2009-08-20 01:44:21 +00001815 return Inst;
1816}
1817
Douglas Gregor6b815c82009-10-23 23:25:44 +00001818Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1819 NonTypeTemplateParmDecl *D) {
1820 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001821 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001822 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1823 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001824 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001825 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001826 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001827 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001828
1829 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001830 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001831 // expansion of types. Substitute into each of the expanded types.
1832 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1833 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1834 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1835 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1836 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001837 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001838 D->getDeclName());
1839 if (!NewDI)
1840 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001841
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001842 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1843 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1844 D->getLocation());
1845 if (NewT.isNull())
1846 return 0;
1847 ExpandedParameterPackTypes.push_back(NewT);
1848 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001849
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001850 IsExpandedParameterPack = true;
1851 DI = D->getTypeSourceInfo();
1852 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001853 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001854 // The non-type template parameter pack's type is a pack expansion of types.
1855 // Determine whether we need to expand this parameter pack into separate
1856 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001857 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001858 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001859 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001860 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001861
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001862 // Determine whether the set of unexpanded parameter packs can and should
1863 // be expanded.
1864 bool Expand = true;
1865 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001866 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001867 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001868 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001869 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1870 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001871 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001872 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001873 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001874 NumExpansions))
1875 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001876
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001877 if (Expand) {
1878 for (unsigned I = 0; I != *NumExpansions; ++I) {
1879 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1880 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001881 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001882 D->getDeclName());
1883 if (!NewDI)
1884 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001885
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001886 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1887 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1888 NewDI->getType(),
1889 D->getLocation());
1890 if (NewT.isNull())
1891 return 0;
1892 ExpandedParameterPackTypes.push_back(NewT);
1893 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001894
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001895 // Note that we have an expanded parameter pack. The "type" of this
1896 // expanded parameter pack is the original expansion type, but callers
1897 // will end up using the expanded parameter pack types for type-checking.
1898 IsExpandedParameterPack = true;
1899 DI = D->getTypeSourceInfo();
1900 T = DI->getType();
1901 } else {
1902 // We cannot fully expand the pack expansion now, so substitute into the
1903 // pattern and create a new pack expansion type.
1904 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1905 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001906 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001907 D->getDeclName());
1908 if (!NewPattern)
1909 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001910
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001911 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1912 NumExpansions);
1913 if (!DI)
1914 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001915
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001916 T = DI->getType();
1917 }
1918 } else {
1919 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001920 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001921 D->getLocation(), D->getDeclName());
1922 if (!DI)
1923 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001924
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001925 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001926 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001927 D->getLocation());
1928 if (T.isNull()) {
1929 T = SemaRef.Context.IntTy;
1930 Invalid = true;
1931 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001932 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001933
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001934 NonTypeTemplateParmDecl *Param;
1935 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001936 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001937 D->getInnerLocStart(),
1938 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001939 D->getDepth() - TemplateArgs.getNumLevels(),
1940 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001941 D->getIdentifier(), T,
1942 DI,
1943 ExpandedParameterPackTypes.data(),
1944 ExpandedParameterPackTypes.size(),
1945 ExpandedParameterPackTypesAsWritten.data());
1946 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001947 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001948 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001949 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001950 D->getDepth() - TemplateArgs.getNumLevels(),
1951 D->getPosition(),
1952 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001953 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001954
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001955 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001956 if (Invalid)
1957 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001958
David Majnemer89189202013-08-28 23:48:32 +00001959 if (D->hasDefaultArgument()) {
1960 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1961 if (!Value.isInvalid())
1962 Param->setDefaultArgument(Value.get(), false);
1963 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001964
1965 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001966 // scope.
1967 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001968 return Param;
1969}
1970
Richard Smith1fde8ec2012-09-07 02:06:42 +00001971static void collectUnexpandedParameterPacks(
1972 Sema &S,
1973 TemplateParameterList *Params,
1974 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1975 for (TemplateParameterList::const_iterator I = Params->begin(),
1976 E = Params->end(); I != E; ++I) {
1977 if ((*I)->isTemplateParameterPack())
1978 continue;
1979 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1980 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1981 Unexpanded);
1982 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1983 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1984 Unexpanded);
1985 }
1986}
1987
Anders Carlsson4bd78752009-08-28 15:18:15 +00001988Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001989TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1990 TemplateTemplateParmDecl *D) {
1991 // Instantiate the template parameter list of the template template parameter.
1992 TemplateParameterList *TempParams = D->getTemplateParameters();
1993 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001994 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1995
1996 bool IsExpandedParameterPack = false;
1997
1998 if (D->isExpandedParameterPack()) {
1999 // The template template parameter pack is an already-expanded pack
2000 // expansion of template parameters. Substitute into each of the expanded
2001 // parameters.
2002 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
2003 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2004 I != N; ++I) {
2005 LocalInstantiationScope Scope(SemaRef);
2006 TemplateParameterList *Expansion =
2007 SubstTemplateParams(D->getExpansionTemplateParameters(I));
2008 if (!Expansion)
2009 return 0;
2010 ExpandedParams.push_back(Expansion);
2011 }
2012
2013 IsExpandedParameterPack = true;
2014 InstParams = TempParams;
2015 } else if (D->isPackExpansion()) {
2016 // The template template parameter pack expands to a pack of template
2017 // template parameters. Determine whether we need to expand this parameter
2018 // pack into separate parameters.
2019 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2020 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
2021 Unexpanded);
2022
2023 // Determine whether the set of unexpanded parameter packs can and should
2024 // be expanded.
2025 bool Expand = true;
2026 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002027 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002028 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2029 TempParams->getSourceRange(),
2030 Unexpanded,
2031 TemplateArgs,
2032 Expand, RetainExpansion,
2033 NumExpansions))
2034 return 0;
2035
2036 if (Expand) {
2037 for (unsigned I = 0; I != *NumExpansions; ++I) {
2038 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2039 LocalInstantiationScope Scope(SemaRef);
2040 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2041 if (!Expansion)
2042 return 0;
2043 ExpandedParams.push_back(Expansion);
2044 }
2045
2046 // Note that we have an expanded parameter pack. The "type" of this
2047 // expanded parameter pack is the original expansion type, but callers
2048 // will end up using the expanded parameter pack types for type-checking.
2049 IsExpandedParameterPack = true;
2050 InstParams = TempParams;
2051 } else {
2052 // We cannot fully expand the pack expansion now, so just substitute
2053 // into the pattern.
2054 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2055
2056 LocalInstantiationScope Scope(SemaRef);
2057 InstParams = SubstTemplateParams(TempParams);
2058 if (!InstParams)
2059 return 0;
2060 }
2061 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002062 // Perform the actual substitution of template parameters within a new,
2063 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002064 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002065 InstParams = SubstTemplateParams(TempParams);
2066 if (!InstParams)
Richard Smith1fde8ec2012-09-07 02:06:42 +00002067 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002068 }
2069
Douglas Gregor38fee962009-11-11 16:58:32 +00002070 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002071 TemplateTemplateParmDecl *Param;
2072 if (IsExpandedParameterPack)
2073 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2074 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002075 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002076 D->getPosition(),
2077 D->getIdentifier(), InstParams,
2078 ExpandedParams);
2079 else
2080 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2081 D->getLocation(),
2082 D->getDepth() - TemplateArgs.getNumLevels(),
2083 D->getPosition(),
2084 D->isParameterPack(),
2085 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002086 if (D->hasDefaultArgument()) {
2087 NestedNameSpecifierLoc QualifierLoc =
2088 D->getDefaultArgument().getTemplateQualifierLoc();
2089 QualifierLoc =
2090 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2091 TemplateName TName = SemaRef.SubstTemplateName(
2092 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2093 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2094 if (!TName.isNull())
2095 Param->setDefaultArgument(
2096 TemplateArgumentLoc(TemplateArgument(TName),
2097 D->getDefaultArgument().getTemplateQualifierLoc(),
2098 D->getDefaultArgument().getTemplateNameLoc()),
2099 false);
2100 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002101 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002102
2103 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002104 // scope.
2105 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002106
Douglas Gregor38fee962009-11-11 16:58:32 +00002107 return Param;
2108}
2109
Douglas Gregore0b28662009-11-17 06:07:40 +00002110Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002111 // Using directives are never dependent (and never contain any types or
2112 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002113
Douglas Gregore0b28662009-11-17 06:07:40 +00002114 UsingDirectiveDecl *Inst
2115 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002116 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002117 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002118 D->getIdentLocation(),
2119 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002120 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002121
2122 // Add the using directive to its declaration context
2123 // only if this is not a function or method.
2124 if (!Owner->isFunctionOrMethod())
2125 Owner->addDecl(Inst);
2126
Douglas Gregore0b28662009-11-17 06:07:40 +00002127 return Inst;
2128}
2129
John McCallb96ec562009-12-04 22:46:56 +00002130Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002131
2132 // The nested name specifier may be dependent, for example
2133 // template <typename T> struct t {
2134 // struct s1 { T f1(); };
2135 // struct s2 : s1 { using s1::f1; };
2136 // };
2137 // template struct t<int>;
2138 // Here, in using s1::f1, s1 refers to t<T>::s1;
2139 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002140 NestedNameSpecifierLoc QualifierLoc
2141 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2142 TemplateArgs);
2143 if (!QualifierLoc)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00002144 return 0;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002145
2146 // The name info is non-dependent, so no transformation
2147 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002148 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002149
John McCall84d87672009-12-10 09:41:52 +00002150 // We only need to do redeclaration lookups if we're in a class
2151 // scope (in fact, it's not really even possible in non-class
2152 // scopes).
2153 bool CheckRedeclaration = Owner->isRecord();
2154
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002155 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2156 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002157
John McCallb96ec562009-12-04 22:46:56 +00002158 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002159 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002160 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002161 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002162 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002163
Douglas Gregor0499ab62011-02-25 15:54:31 +00002164 CXXScopeSpec SS;
2165 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002166 if (CheckRedeclaration) {
2167 Prev.setHideTags(false);
2168 SemaRef.LookupQualifiedName(Prev, Owner);
2169
2170 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002171 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2172 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002173 D->getLocation(), Prev))
2174 NewUD->setInvalidDecl();
2175
2176 }
2177
2178 if (!NewUD->isInvalidDecl() &&
Richard Smith7ad0b882014-04-02 21:44:35 +00002179 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS, NameInfo,
John McCallb96ec562009-12-04 22:46:56 +00002180 D->getLocation()))
2181 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002182
John McCallb96ec562009-12-04 22:46:56 +00002183 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2184 NewUD->setAccess(D->getAccess());
2185 Owner->addDecl(NewUD);
2186
John McCall84d87672009-12-10 09:41:52 +00002187 // Don't process the shadow decls for an invalid decl.
2188 if (NewUD->isInvalidDecl())
2189 return NewUD;
2190
Richard Smith23d55872012-04-02 01:30:27 +00002191 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
Richard Smith09d5b3a2014-05-01 00:35:04 +00002192 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
Richard Smith23d55872012-04-02 01:30:27 +00002193 return NewUD;
2194 }
2195
John McCalla1d85502009-12-22 22:26:37 +00002196 bool isFunctionScope = Owner->isFunctionOrMethod();
2197
John McCall84d87672009-12-10 09:41:52 +00002198 // Process the shadow decls.
Aaron Ballman91cdc282014-03-13 18:07:29 +00002199 for (auto *Shadow : D->shadows()) {
John McCall84d87672009-12-10 09:41:52 +00002200 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002201 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2202 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002203 if (!InstTarget)
2204 return 0;
John McCall84d87672009-12-10 09:41:52 +00002205
Richard Smithfd8634a2013-10-23 02:17:46 +00002206 UsingShadowDecl *PrevDecl = 0;
2207 if (CheckRedeclaration) {
2208 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2209 continue;
2210 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2211 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2212 Shadow->getLocation(), OldPrev, TemplateArgs));
2213 }
John McCall84d87672009-12-10 09:41:52 +00002214
Richard Smithfd8634a2013-10-23 02:17:46 +00002215 UsingShadowDecl *InstShadow =
2216 SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002217 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002218
2219 if (isFunctionScope)
2220 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002221 }
John McCallb96ec562009-12-04 22:46:56 +00002222
2223 return NewUD;
2224}
2225
2226Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002227 // Ignore these; we handle them in bulk when processing the UsingDecl.
2228 return 0;
John McCallb96ec562009-12-04 22:46:56 +00002229}
2230
John McCalle61f2ba2009-11-18 02:36:19 +00002231Decl * TemplateDeclInstantiator
2232 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002233 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002234 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002235 TemplateArgs);
2236 if (!QualifierLoc)
Anders Carlsson4bd78752009-08-28 15:18:15 +00002237 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002238
Anders Carlsson4bd78752009-08-28 15:18:15 +00002239 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002240 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002241
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002242 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002243 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002244 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002245 NamedDecl *UD =
John McCall3f746822009-11-17 05:59:44 +00002246 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002247 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002248 /*instantiation*/ true,
2249 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002250 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002251 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2252
John McCalle61f2ba2009-11-18 02:36:19 +00002253 return UD;
2254}
2255
2256Decl * TemplateDeclInstantiator
2257 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002258 NestedNameSpecifierLoc QualifierLoc
2259 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2260 if (!QualifierLoc)
John McCalle61f2ba2009-11-18 02:36:19 +00002261 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002262
John McCalle61f2ba2009-11-18 02:36:19 +00002263 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002264 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002265
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002266 DeclarationNameInfo NameInfo
2267 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2268
John McCalle61f2ba2009-11-18 02:36:19 +00002269 NamedDecl *UD =
2270 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002271 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002272 /*instantiation*/ true,
2273 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002274 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002275 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2276
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002277 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002278}
2279
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002280
2281Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2282 ClassScopeFunctionSpecializationDecl *Decl) {
2283 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002284 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2285 0, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002286
2287 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2288 Sema::ForRedeclaration);
2289
Nico Weber7b5a7162012-06-25 17:21:05 +00002290 TemplateArgumentListInfo TemplateArgs;
2291 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2292 if (Decl->hasExplicitTemplateArgs()) {
2293 TemplateArgs = Decl->templateArgs();
2294 TemplateArgsPtr = &TemplateArgs;
2295 }
2296
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002297 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002298 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2299 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002300 NewFD->setInvalidDecl();
2301 return NewFD;
2302 }
2303
2304 // Associate the specialization with the pattern.
2305 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2306 assert(Specialization && "Class scope Specialization is null");
2307 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2308
2309 return NewFD;
2310}
2311
Alexey Bataeva769e072013-03-22 06:34:35 +00002312Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2313 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002314 SmallVector<Expr *, 5> Vars;
Aaron Ballman2205d2a2014-03-14 15:55:35 +00002315 for (auto *I : D->varlists()) {
2316 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).take();
Alexey Bataeva769e072013-03-22 06:34:35 +00002317 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002318 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002319 }
2320
2321 OMPThreadPrivateDecl *TD =
2322 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2323
Alexey Bataevd3db6ac2014-03-07 09:46:29 +00002324 TD->setAccess(AS_public);
2325 Owner->addDecl(TD);
2326
Alexey Bataeva769e072013-03-22 06:34:35 +00002327 return TD;
2328}
2329
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002330Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2331 return VisitFunctionDecl(D, 0);
2332}
2333
2334Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2335 return VisitCXXMethodDecl(D, 0);
2336}
2337
2338Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2339 llvm_unreachable("There are only CXXRecordDecls in C++");
2340}
2341
2342Decl *
2343TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2344 ClassTemplateSpecializationDecl *D) {
Richard Smith8a0dde72013-12-14 01:04:22 +00002345 // As a MS extension, we permit class-scope explicit specialization
2346 // of member class templates.
2347 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
2348 assert(ClassTemplate->getDeclContext()->isRecord() &&
2349 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2350 "can only instantiate an explicit specialization "
2351 "for a member class template");
2352
2353 // Lookup the already-instantiated declaration in the instantiation
2354 // of the class template. FIXME: Diagnose or assert if this fails?
2355 DeclContext::lookup_result Found
2356 = Owner->lookup(ClassTemplate->getDeclName());
2357 if (Found.empty())
2358 return 0;
2359 ClassTemplateDecl *InstClassTemplate
2360 = dyn_cast<ClassTemplateDecl>(Found.front());
2361 if (!InstClassTemplate)
2362 return 0;
2363
2364 // Substitute into the template arguments of the class template explicit
2365 // specialization.
2366 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
2367 castAs<TemplateSpecializationTypeLoc>();
2368 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
2369 Loc.getRAngleLoc());
2370 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
2371 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
2372 ArgLocs.push_back(Loc.getArgLoc(I));
2373 if (SemaRef.Subst(ArgLocs.data(), ArgLocs.size(),
2374 InstTemplateArgs, TemplateArgs))
2375 return 0;
2376
2377 // Check that the template argument list is well-formed for this
2378 // class template.
2379 SmallVector<TemplateArgument, 4> Converted;
2380 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate,
2381 D->getLocation(),
2382 InstTemplateArgs,
2383 false,
2384 Converted))
2385 return 0;
2386
2387 // Figure out where to insert this class template explicit specialization
2388 // in the member template's set of class template explicit specializations.
2389 void *InsertPos = 0;
2390 ClassTemplateSpecializationDecl *PrevDecl =
2391 InstClassTemplate->findSpecialization(Converted.data(), Converted.size(),
2392 InsertPos);
2393
2394 // Check whether we've already seen a conflicting instantiation of this
2395 // declaration (for instance, if there was a prior implicit instantiation).
2396 bool Ignored;
2397 if (PrevDecl &&
2398 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
2399 D->getSpecializationKind(),
2400 PrevDecl,
2401 PrevDecl->getSpecializationKind(),
2402 PrevDecl->getPointOfInstantiation(),
2403 Ignored))
2404 return 0;
2405
2406 // If PrevDecl was a definition and D is also a definition, diagnose.
2407 // This happens in cases like:
2408 //
2409 // template<typename T, typename U>
2410 // struct Outer {
2411 // template<typename X> struct Inner;
2412 // template<> struct Inner<T> {};
2413 // template<> struct Inner<U> {};
2414 // };
2415 //
2416 // Outer<int, int> outer; // error: the explicit specializations of Inner
2417 // // have the same signature.
2418 if (PrevDecl && PrevDecl->getDefinition() &&
2419 D->isThisDeclarationADefinition()) {
2420 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
2421 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
2422 diag::note_previous_definition);
2423 return 0;
2424 }
2425
2426 // Create the class template partial specialization declaration.
2427 ClassTemplateSpecializationDecl *InstD
2428 = ClassTemplateSpecializationDecl::Create(SemaRef.Context,
2429 D->getTagKind(),
2430 Owner,
2431 D->getLocStart(),
2432 D->getLocation(),
2433 InstClassTemplate,
2434 Converted.data(),
2435 Converted.size(),
2436 PrevDecl);
2437
2438 // Add this partial specialization to the set of class template partial
2439 // specializations.
2440 if (!PrevDecl)
2441 InstClassTemplate->AddSpecialization(InstD, InsertPos);
2442
2443 // Substitute the nested name specifier, if any.
2444 if (SubstQualifier(D, InstD))
2445 return 0;
2446
2447 // Build the canonical type that describes the converted template
2448 // arguments of the class template explicit specialization.
2449 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2450 TemplateName(InstClassTemplate), Converted.data(), Converted.size(),
2451 SemaRef.Context.getRecordType(InstD));
2452
2453 // Build the fully-sugared type for this class template
2454 // specialization as the user wrote in the specialization
2455 // itself. This means that we'll pretty-print the type retrieved
2456 // from the specialization's declaration the way that the user
2457 // actually wrote the specialization, rather than formatting the
2458 // name based on the "canonical" representation used to store the
2459 // template arguments in the specialization.
2460 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2461 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
2462 CanonType);
2463
2464 InstD->setAccess(D->getAccess());
2465 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
2466 InstD->setSpecializationKind(D->getSpecializationKind());
2467 InstD->setTypeAsWritten(WrittenTy);
2468 InstD->setExternLoc(D->getExternLoc());
2469 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
2470
2471 Owner->addDecl(InstD);
2472
2473 // Instantiate the members of the class-scope explicit specialization eagerly.
2474 // We don't have support for lazy instantiation of an explicit specialization
2475 // yet, and MSVC eagerly instantiates in this case.
2476 if (D->isThisDeclarationADefinition() &&
2477 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
2478 TSK_ImplicitInstantiation,
2479 /*Complain=*/true))
2480 return 0;
2481
2482 return InstD;
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002483}
2484
Larisse Voufo39a1e502013-08-06 01:03:05 +00002485Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2486 VarTemplateSpecializationDecl *D) {
2487
2488 TemplateArgumentListInfo VarTemplateArgsInfo;
2489 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2490 assert(VarTemplate &&
2491 "A template specialization without specialized template?");
2492
2493 // Substitute the current template arguments.
2494 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2495 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2496 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2497
2498 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2499 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2500 return 0;
2501
2502 // Check that the template argument list is well-formed for this template.
2503 SmallVector<TemplateArgument, 4> Converted;
Larisse Voufo39a1e502013-08-06 01:03:05 +00002504 if (SemaRef.CheckTemplateArgumentList(
2505 VarTemplate, VarTemplate->getLocStart(),
2506 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
Richard Smith83b11aa2014-01-09 02:22:22 +00002507 Converted))
Larisse Voufo39a1e502013-08-06 01:03:05 +00002508 return 0;
2509
2510 // Find the variable template specialization declaration that
2511 // corresponds to these arguments.
2512 void *InsertPos = 0;
2513 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2514 Converted.data(), Converted.size(), InsertPos))
2515 // If we already have a variable template specialization, return it.
2516 return VarSpec;
2517
2518 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2519 VarTemplateArgsInfo, Converted);
2520}
2521
2522Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2523 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2524 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smith8809a0c2013-09-27 20:14:12 +00002525 llvm::ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002526
2527 // If this is the variable for an anonymous struct or union,
2528 // instantiate the anonymous struct/union type first.
2529 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2530 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2531 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2532 return 0;
2533
2534 // Do substitution on the type of the declaration
2535 TypeSourceInfo *DI =
2536 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2537 D->getTypeSpecStartLoc(), D->getDeclName());
2538 if (!DI)
2539 return 0;
2540
2541 if (DI->getType()->isFunctionType()) {
2542 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2543 << D->isStaticDataMember() << DI->getType();
2544 return 0;
2545 }
2546
2547 // Build the instantiated declaration
2548 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2549 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2550 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2551 Converted.size());
2552 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002553 if (InsertPos)
2554 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002555
2556 // Substitute the nested name specifier, if any.
2557 if (SubstQualifier(D, Var))
2558 return 0;
2559
2560 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002561 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002562
2563 return Var;
2564}
2565
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002566Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2567 llvm_unreachable("@defs is not supported in Objective-C++");
2568}
2569
2570Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2571 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2572 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2573 DiagnosticsEngine::Error,
2574 "cannot instantiate %0 yet");
2575 SemaRef.Diag(D->getLocation(), DiagID)
2576 << D->getDeclKindName();
2577
2578 return 0;
2579}
2580
2581Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2582 llvm_unreachable("Unexpected decl");
2583}
2584
John McCall76d824f2009-08-25 22:02:44 +00002585Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002586 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002587 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002588 if (D->isInvalidDecl())
2589 return 0;
2590
Douglas Gregord7e7a512009-03-17 21:15:40 +00002591 return Instantiator.Visit(D);
2592}
2593
John McCall87a44eb2009-08-20 01:44:21 +00002594/// \brief Instantiates a nested template parameter list in the current
2595/// instantiation context.
2596///
2597/// \param L The parameter list to instantiate
2598///
2599/// \returns NULL if there was an error
2600TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002601TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002602 // Get errors for all the parameters before bailing out.
2603 bool Invalid = false;
2604
2605 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002606 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002607 ParamVector Params;
2608 Params.reserve(N);
2609 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2610 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002611 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002612 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002613 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002614 }
2615
2616 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002617 if (Invalid)
John McCall87a44eb2009-08-20 01:44:21 +00002618 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +00002619
2620 TemplateParameterList *InstL
2621 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2622 L->getLAngleLoc(), &Params.front(), N,
2623 L->getRAngleLoc());
2624 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002625}
John McCall87a44eb2009-08-20 01:44:21 +00002626
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002627/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002628/// specialization.
2629///
2630/// \param ClassTemplate the (instantiated) class template that is partially
2631// specialized by the instantiation of \p PartialSpec.
2632///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002633/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002634/// specialization that we are instantiating.
2635///
Douglas Gregor869853e2010-11-10 19:44:59 +00002636/// \returns The instantiated partial specialization, if successful; otherwise,
2637/// NULL to indicate an error.
2638ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002639TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2640 ClassTemplateDecl *ClassTemplate,
2641 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002642 // Create a local instantiation scope for this class template partial
2643 // specialization, which will contain the instantiations of the template
2644 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002645 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002646
Douglas Gregor21610382009-10-29 00:04:11 +00002647 // Substitute into the template parameters of the class template partial
2648 // specialization.
2649 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2650 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2651 if (!InstParams)
Douglas Gregor869853e2010-11-10 19:44:59 +00002652 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002653
Douglas Gregor21610382009-10-29 00:04:11 +00002654 // Substitute into the template arguments of the class template partial
2655 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002656 const ASTTemplateArgumentListInfo *TemplArgInfo
2657 = PartialSpec->getTemplateArgsAsWritten();
2658 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2659 TemplArgInfo->RAngleLoc);
2660 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2661 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002662 InstTemplateArgs, TemplateArgs))
2663 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002664
Douglas Gregor21610382009-10-29 00:04:11 +00002665 // Check that the template argument list is well-formed for this
2666 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002667 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002668 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002669 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002670 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002671 false,
2672 Converted))
Douglas Gregor869853e2010-11-10 19:44:59 +00002673 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002674
2675 // Figure out where to insert this class template partial specialization
2676 // in the member template's set of class template partial specializations.
Douglas Gregor21610382009-10-29 00:04:11 +00002677 void *InsertPos = 0;
2678 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002679 = ClassTemplate->findPartialSpecialization(Converted.data(),
2680 Converted.size(), InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002681
Douglas Gregor21610382009-10-29 00:04:11 +00002682 // Build the canonical type that describes the converted template
2683 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002684 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002685 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002686 Converted.data(),
2687 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002688
2689 // Build the fully-sugared type for this class template
2690 // specialization as the user wrote in the specialization
2691 // itself. This means that we'll pretty-print the type retrieved
2692 // from the specialization's declaration the way that the user
2693 // actually wrote the specialization, rather than formatting the
2694 // name based on the "canonical" representation used to store the
2695 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002696 TypeSourceInfo *WrittenTy
2697 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2698 TemplateName(ClassTemplate),
2699 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002700 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002701 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002702
Douglas Gregor21610382009-10-29 00:04:11 +00002703 if (PrevDecl) {
2704 // We've already seen a partial specialization with the same template
2705 // parameters and template arguments. This can happen, for example, when
2706 // substituting the outer template arguments ends up causing two
2707 // class template partial specializations of a member class template
2708 // to have identical forms, e.g.,
2709 //
2710 // template<typename T, typename U>
2711 // struct Outer {
2712 // template<typename X, typename Y> struct Inner;
2713 // template<typename Y> struct Inner<T, Y>;
2714 // template<typename Y> struct Inner<U, Y>;
2715 // };
2716 //
2717 // Outer<int, int> outer; // error: the partial specializations of Inner
2718 // // have the same signature.
2719 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002720 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002721 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2722 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregor869853e2010-11-10 19:44:59 +00002723 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002724 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002725
2726
Douglas Gregor21610382009-10-29 00:04:11 +00002727 // Create the class template partial specialization declaration.
2728 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002729 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002730 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002731 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002732 PartialSpec->getLocStart(),
2733 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002734 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002735 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002736 Converted.data(),
2737 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002738 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002739 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00002740 0);
John McCall3e11ebe2010-03-15 10:12:16 +00002741 // Substitute the nested name specifier, if any.
2742 if (SubstQualifier(PartialSpec, InstPartialSpec))
2743 return 0;
2744
Douglas Gregor21610382009-10-29 00:04:11 +00002745 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002746 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002747
Douglas Gregor21610382009-10-29 00:04:11 +00002748 // Add this partial specialization to the set of class template partial
2749 // specializations.
Douglas Gregorce9978f2012-03-28 14:34:23 +00002750 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregor869853e2010-11-10 19:44:59 +00002751 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002752}
2753
Larisse Voufo39a1e502013-08-06 01:03:05 +00002754/// \brief Instantiate the declaration of a variable template partial
2755/// specialization.
2756///
2757/// \param VarTemplate the (instantiated) variable template that is partially
2758/// specialized by the instantiation of \p PartialSpec.
2759///
2760/// \param PartialSpec the (uninstantiated) variable template partial
2761/// specialization that we are instantiating.
2762///
2763/// \returns The instantiated partial specialization, if successful; otherwise,
2764/// NULL to indicate an error.
2765VarTemplatePartialSpecializationDecl *
2766TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2767 VarTemplateDecl *VarTemplate,
2768 VarTemplatePartialSpecializationDecl *PartialSpec) {
2769 // Create a local instantiation scope for this variable template partial
2770 // specialization, which will contain the instantiations of the template
2771 // parameters.
2772 LocalInstantiationScope Scope(SemaRef);
2773
2774 // Substitute into the template parameters of the variable template partial
2775 // specialization.
2776 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2777 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2778 if (!InstParams)
2779 return 0;
2780
2781 // Substitute into the template arguments of the variable template partial
2782 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002783 const ASTTemplateArgumentListInfo *TemplArgInfo
2784 = PartialSpec->getTemplateArgsAsWritten();
2785 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2786 TemplArgInfo->RAngleLoc);
2787 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2788 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002789 InstTemplateArgs, TemplateArgs))
2790 return 0;
2791
2792 // Check that the template argument list is well-formed for this
2793 // class template.
2794 SmallVector<TemplateArgument, 4> Converted;
2795 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2796 InstTemplateArgs, false, Converted))
2797 return 0;
2798
2799 // Figure out where to insert this variable template partial specialization
2800 // in the member template's set of variable template partial specializations.
2801 void *InsertPos = 0;
2802 VarTemplateSpecializationDecl *PrevDecl =
2803 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2804 InsertPos);
2805
2806 // Build the canonical type that describes the converted template
2807 // arguments of the variable template partial specialization.
2808 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2809 TemplateName(VarTemplate), Converted.data(), Converted.size());
2810
2811 // Build the fully-sugared type for this variable template
2812 // specialization as the user wrote in the specialization
2813 // itself. This means that we'll pretty-print the type retrieved
2814 // from the specialization's declaration the way that the user
2815 // actually wrote the specialization, rather than formatting the
2816 // name based on the "canonical" representation used to store the
2817 // template arguments in the specialization.
2818 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2819 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2820 CanonType);
2821
2822 if (PrevDecl) {
2823 // We've already seen a partial specialization with the same template
2824 // parameters and template arguments. This can happen, for example, when
2825 // substituting the outer template arguments ends up causing two
2826 // variable template partial specializations of a member variable template
2827 // to have identical forms, e.g.,
2828 //
2829 // template<typename T, typename U>
2830 // struct Outer {
2831 // template<typename X, typename Y> pair<X,Y> p;
2832 // template<typename Y> pair<T, Y> p;
2833 // template<typename Y> pair<U, Y> p;
2834 // };
2835 //
2836 // Outer<int, int> outer; // error: the partial specializations of Inner
2837 // // have the same signature.
2838 SemaRef.Diag(PartialSpec->getLocation(),
2839 diag::err_var_partial_spec_redeclared)
2840 << WrittenTy->getType();
2841 SemaRef.Diag(PrevDecl->getLocation(),
2842 diag::note_var_prev_partial_spec_here);
2843 return 0;
2844 }
2845
2846 // Do substitution on the type of the declaration
2847 TypeSourceInfo *DI = SemaRef.SubstType(
2848 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2849 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2850 if (!DI)
2851 return 0;
2852
2853 if (DI->getType()->isFunctionType()) {
2854 SemaRef.Diag(PartialSpec->getLocation(),
2855 diag::err_variable_instantiates_to_function)
2856 << PartialSpec->isStaticDataMember() << DI->getType();
2857 return 0;
2858 }
2859
2860 // Create the variable template partial specialization declaration.
2861 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2862 VarTemplatePartialSpecializationDecl::Create(
2863 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2864 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2865 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002866 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002867
2868 // Substitute the nested name specifier, if any.
2869 if (SubstQualifier(PartialSpec, InstPartialSpec))
2870 return 0;
2871
2872 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2873 InstPartialSpec->setTypeAsWritten(WrittenTy);
2874
Larisse Voufo39a1e502013-08-06 01:03:05 +00002875 // Add this partial specialization to the set of variable template partial
2876 // specializations. The instantiation of the initializer is not necessary.
2877 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002878
Larisse Voufo4cda4612013-08-22 00:28:27 +00002879 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002880 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002881
Larisse Voufo39a1e502013-08-06 01:03:05 +00002882 return InstPartialSpec;
2883}
2884
John McCall58f10c32010-03-11 09:03:00 +00002885TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002886TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002887 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002888 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2889 assert(OldTInfo && "substituting function without type source info");
2890 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregor3024f072012-04-16 07:05:22 +00002891
2892 CXXRecordDecl *ThisContext = 0;
2893 unsigned ThisTypeQuals = 0;
2894 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002895 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002896 ThisTypeQuals = Method->getTypeQualifiers();
2897 }
2898
John McCallb29f78f2010-04-09 17:38:44 +00002899 TypeSourceInfo *NewTInfo
2900 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2901 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002902 D->getDeclName(),
2903 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002904 if (!NewTInfo)
2905 return 0;
Douglas Gregor21342092009-03-24 00:38:23 +00002906
Reid Klecknera09e44c2013-07-31 21:00:18 +00002907 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2908 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2909 if (NewTInfo != OldTInfo) {
2910 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002911 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002912 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002913 unsigned NewIdx = 0;
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002914 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
Douglas Gregorf3010112011-01-07 16:43:16 +00002915 OldIdx != NumOldParams; ++OldIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002916 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002917 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2918
David Blaikie05785d12013-02-20 22:23:23 +00002919 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002920 if (OldParam->isParameterPack())
2921 NumArgumentsInExpansion =
2922 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2923 TemplateArgs);
2924 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002925 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002926 // instantiated to a (still-dependent) parameter pack.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002927 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002928 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002929 Scope->InstantiatedLocal(OldParam, NewParam);
2930 } else {
2931 // Parameter pack expansion: make the instantiation an argument pack.
2932 Scope->MakeInstantiatedLocalArgPack(OldParam);
2933 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002934 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002935 Params.push_back(NewParam);
2936 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2937 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002938 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002939 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002940 } else {
2941 // The function type itself was not dependent and therefore no
2942 // substitution occurred. However, we still need to instantiate
2943 // the function parameters themselves.
2944 const FunctionProtoType *OldProto =
2945 cast<FunctionProtoType>(OldProtoLoc.getType());
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00002946 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
2947 ++i) {
2948 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
Reid Klecknera09e44c2013-07-31 21:00:18 +00002949 if (!OldParam) {
2950 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
Alp Toker9cacbab2014-01-20 20:26:09 +00002951 D, D->getLocation(), OldProto->getParamType(i)));
Reid Klecknera09e44c2013-07-31 21:00:18 +00002952 continue;
2953 }
2954
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002955 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002956 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002957 if (!Parm)
2958 return 0;
2959 Params.push_back(Parm);
2960 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002961 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002962 } else {
2963 // If the type of this function, after ignoring parentheses, is not
2964 // *directly* a function type, then we're instantiating a function that
2965 // was declared via a typedef or with attributes, e.g.,
2966 //
2967 // typedef int functype(int, int);
2968 // functype func;
2969 // int __cdecl meth(int, int);
2970 //
2971 // In this case, we'll just go instantiate the ParmVarDecls that we
2972 // synthesized in the method declaration.
2973 SmallVector<QualType, 4> ParamTypes;
2974 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2975 D->getNumParams(), TemplateArgs, ParamTypes,
2976 &Params))
2977 return 0;
Douglas Gregor940bca72010-04-12 07:48:19 +00002978 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002979
John McCall58f10c32010-03-11 09:03:00 +00002980 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002981}
2982
Richard Smithf623c962012-04-17 00:58:00 +00002983/// Introduce the instantiated function parameters into the local
2984/// instantiation scope, and set the parameter names to those used
2985/// in the template.
2986static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2987 const FunctionDecl *PatternDecl,
2988 LocalInstantiationScope &Scope,
2989 const MultiLevelTemplateArgumentList &TemplateArgs) {
2990 unsigned FParamIdx = 0;
2991 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2992 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2993 if (!PatternParam->isParameterPack()) {
2994 // Simple case: not a parameter pack.
2995 assert(FParamIdx < Function->getNumParams());
2996 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smithaae40582014-03-13 00:28:45 +00002997 // If the parameter's type is not dependent, update it to match the type
2998 // in the pattern. They can differ in top-level cv-qualifiers, and we want
2999 // the pattern's type here. If the type is dependent, they can't differ,
3000 // per core issue 1668.
3001 // FIXME: Updating the type to work around this is at best fragile.
3002 if (!PatternDecl->getType()->isDependentType())
3003 FunctionParam->setType(PatternParam->getType());
3004
Richard Smithf623c962012-04-17 00:58:00 +00003005 FunctionParam->setDeclName(PatternParam->getDeclName());
3006 Scope.InstantiatedLocal(PatternParam, FunctionParam);
3007 ++FParamIdx;
3008 continue;
3009 }
3010
3011 // Expand the parameter pack.
3012 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00003013 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00003014 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00003015 assert(NumArgumentsInExpansion &&
3016 "should only be called when all template arguments are known");
3017 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00003018 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
Richard Smithaae40582014-03-13 00:28:45 +00003019 if (!PatternDecl->getType()->isDependentType())
3020 FunctionParam->setType(PatternParam->getType());
3021
Richard Smithf623c962012-04-17 00:58:00 +00003022 FunctionParam->setDeclName(PatternParam->getDeclName());
3023 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
3024 ++FParamIdx;
3025 }
3026 }
3027}
3028
3029static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
3030 const FunctionProtoType *Proto,
3031 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00003032 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
3033
Richard Smithf623c962012-04-17 00:58:00 +00003034 // C++11 [expr.prim.general]p3:
3035 // If a declaration declares a member function or member function
3036 // template of a class X, the expression this is a prvalue of type
3037 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
3038 // and the end of the function-definition, member-declarator, or
3039 // declarator.
3040 CXXRecordDecl *ThisContext = 0;
3041 unsigned ThisTypeQuals = 0;
3042 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
3043 ThisContext = Method->getParent();
3044 ThisTypeQuals = Method->getTypeQualifiers();
3045 }
3046 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003047 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00003048
3049 // The function has an exception specification or a "noreturn"
3050 // attribute. Substitute into each of the exception types.
3051 SmallVector<QualType, 4> Exceptions;
3052 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
3053 // FIXME: Poor location information!
3054 if (const PackExpansionType *PackExpansion
3055 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
3056 // We have a pack expansion. Instantiate it.
3057 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3058 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
3059 Unexpanded);
3060 assert(!Unexpanded.empty() &&
3061 "Pack expansion without parameter packs?");
3062
3063 bool Expand = false;
3064 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00003065 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00003066 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
3067 SourceRange(),
3068 Unexpanded,
3069 TemplateArgs,
3070 Expand,
3071 RetainExpansion,
3072 NumExpansions))
3073 break;
3074
3075 if (!Expand) {
3076 // We can't expand this pack expansion into separate arguments yet;
3077 // just substitute into the pattern and create a new pack expansion
3078 // type.
3079 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3080 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3081 TemplateArgs,
3082 New->getLocation(), New->getDeclName());
3083 if (T.isNull())
3084 break;
3085
3086 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
3087 Exceptions.push_back(T);
3088 continue;
3089 }
3090
3091 // Substitute into the pack expansion pattern for each template
3092 bool Invalid = false;
3093 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
3094 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
3095
3096 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
3097 TemplateArgs,
3098 New->getLocation(), New->getDeclName());
3099 if (T.isNull()) {
3100 Invalid = true;
3101 break;
3102 }
3103
3104 Exceptions.push_back(T);
3105 }
3106
3107 if (Invalid)
3108 break;
3109
3110 continue;
3111 }
3112
3113 QualType T
3114 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
3115 New->getLocation(), New->getDeclName());
3116 if (T.isNull() ||
3117 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
3118 continue;
3119
3120 Exceptions.push_back(T);
3121 }
3122 Expr *NoexceptExpr = 0;
3123 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
3124 EnterExpressionEvaluationContext Unevaluated(SemaRef,
3125 Sema::ConstantEvaluated);
3126 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
3127 if (E.isUsable())
3128 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
3129
3130 if (E.isUsable()) {
3131 NoexceptExpr = E.take();
3132 if (!NoexceptExpr->isTypeDependent() &&
3133 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00003134 NoexceptExpr
3135 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
3136 0, diag::err_noexcept_needs_constant_expression,
3137 /*AllowFold*/ false).take();
Richard Smithf623c962012-04-17 00:58:00 +00003138 }
3139 }
3140
Richard Smith564417a2014-03-20 21:47:22 +00003141 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithf623c962012-04-17 00:58:00 +00003142 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
3143 EPI.NumExceptions = Exceptions.size();
3144 EPI.Exceptions = Exceptions.data();
3145 EPI.NoexceptExpr = NoexceptExpr;
3146
Richard Smith564417a2014-03-20 21:47:22 +00003147 SemaRef.UpdateExceptionSpec(New, EPI);
Richard Smithf623c962012-04-17 00:58:00 +00003148}
3149
3150void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
3151 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00003152 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
3153 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00003154 return;
3155
3156 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
3157 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00003158 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003159 // We hit the instantiation depth limit. Clear the exception specification
3160 // so that our callers don't have to cope with EST_Uninstantiated.
Richard Smith564417a2014-03-20 21:47:22 +00003161 FunctionProtoType::ExtProtoInfo EPI;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003162 EPI.ExceptionSpecType = EST_None;
Richard Smith564417a2014-03-20 21:47:22 +00003163 UpdateExceptionSpec(Decl, EPI);
Richard Smithf623c962012-04-17 00:58:00 +00003164 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003165 }
Richard Smithf623c962012-04-17 00:58:00 +00003166
3167 // Enter the scope of this instantiation. We don't use
3168 // PushDeclContext because we don't have a scope.
3169 Sema::ContextRAII savedContext(*this, Decl);
3170 LocalInstantiationScope Scope(*this);
3171
3172 MultiLevelTemplateArgumentList TemplateArgs =
3173 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
3174
Richard Smithd3729422012-04-19 00:08:28 +00003175 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3176 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003177
Richard Smithd3729422012-04-19 00:08:28 +00003178 ::InstantiateExceptionSpec(*this, Decl,
3179 Template->getType()->castAs<FunctionProtoType>(),
3180 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003181}
3182
Mike Stump11289f42009-09-09 15:08:12 +00003183/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003184/// declaration (New) from the corresponding fields of its template (Tmpl).
3185///
3186/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003187bool
3188TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003189 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003190 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003191 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003192
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003193 // Forward the mangling number from the template to the instantiated decl.
3194 SemaRef.Context.setManglingNumber(New,
3195 SemaRef.Context.getManglingNumber(Tmpl));
3196
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003197 // If we are performing substituting explicitly-specified template arguments
3198 // or deduced template arguments into a function template and we reach this
3199 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003200 // to keeping the new function template specialization. We therefore
3201 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003202 // into a template instantiation for this specific function template
3203 // specialization, which is not a SFINAE context, so that we diagnose any
3204 // further errors in the declaration itself.
3205 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3206 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3207 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3208 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003209 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003210 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003211 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003212 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003213 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003214 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003215 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003216 }
3217 }
Mike Stump11289f42009-09-09 15:08:12 +00003218
Douglas Gregor049bdca2009-12-08 17:45:32 +00003219 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3220 assert(Proto && "Function template without prototype?");
3221
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003222 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003223 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003224
Richard Smithf623c962012-04-17 00:58:00 +00003225 // DR1330: In C++11, defer instantiation of a non-trivial
3226 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003227 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithf623c962012-04-17 00:58:00 +00003228 EPI.ExceptionSpecType != EST_None &&
3229 EPI.ExceptionSpecType != EST_DynamicNone &&
3230 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003231 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3232 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3233 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003234 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3235 if (EPI.ExceptionSpecType == EST_Unevaluated)
3236 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003237
Richard Smithf623c962012-04-17 00:58:00 +00003238 // Mark the function has having an uninstantiated exception specification.
3239 const FunctionProtoType *NewProto
3240 = New->getType()->getAs<FunctionProtoType>();
3241 assert(NewProto && "Template instantiation without function prototype?");
3242 EPI = NewProto->getExtProtoInfo();
Richard Smith185be182013-04-10 05:48:59 +00003243 EPI.ExceptionSpecType = NewEST;
Richard Smithf623c962012-04-17 00:58:00 +00003244 EPI.ExceptionSpecDecl = New;
Richard Smithd3729422012-04-19 00:08:28 +00003245 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003246 New->setType(SemaRef.Context.getFunctionType(
Alp Toker314cc812014-01-25 16:55:45 +00003247 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003248 } else {
3249 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3250 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003251 }
3252
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003253 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003254 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003255 Tmpl->isDefined(Definition);
3256
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003257 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3258 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003259
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003260 return false;
3261}
3262
Douglas Gregor21342092009-03-24 00:38:23 +00003263/// \brief Initializes common fields of an instantiated method
3264/// declaration (New) from the corresponding fields of its template
3265/// (Tmpl).
3266///
3267/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003268bool
3269TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003270 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003271 if (InitFunctionInstantiation(New, Tmpl))
3272 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003273
Douglas Gregor21342092009-03-24 00:38:23 +00003274 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003275 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003276 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003277
Douglas Gregor21342092009-03-24 00:38:23 +00003278 // FIXME: New needs a pointer to Tmpl
3279 return false;
3280}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003281
3282/// \brief Instantiate the definition of the given function from its
3283/// template.
3284///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003285/// \param PointOfInstantiation the point at which the instantiation was
3286/// required. Note that this is not precisely a "point of instantiation"
3287/// for the function, but it's close.
3288///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003289/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003290/// function template specialization or member function of a class template
3291/// specialization.
3292///
3293/// \param Recursive if true, recursively instantiates any functions that
3294/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003295///
3296/// \param DefinitionRequired if true, then we are performing an explicit
3297/// instantiation where the body of the function is required. Complain if
3298/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003299void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003300 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003301 bool Recursive,
3302 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003303 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003304 return;
3305
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003306 // Never instantiate an explicit specialization except if it is a class scope
3307 // explicit specialization.
3308 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3309 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003310 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003311
Douglas Gregor24c332b2009-05-14 21:06:31 +00003312 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003313 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003314 assert(PatternDecl && "instantiating a non-template");
3315
3316 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3317 assert(PatternDecl && "template definition is not a template");
3318 if (!Pattern) {
3319 // Try to find a defaulted definition
3320 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003321 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003322 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003323
Francois Pichet1c229c02011-04-22 22:18:13 +00003324 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003325 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003326 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003327 PendingInstantiations.push_back(
3328 std::make_pair(Function, PointOfInstantiation));
3329 return;
3330 }
3331
David Majnemerf0a84f22013-08-16 08:29:13 +00003332 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003333 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003334 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003335 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003336 // FIXME: Optimize to allow individual templates to be deserialized.
3337 if (PatternDecl->isFromASTFile())
3338 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3339
3340 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3341 assert(LPT && "missing LateParsedTemplate");
3342 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003343 Pattern = PatternDecl->getBody(PatternDecl);
3344 }
3345
Alexis Hunt23f6b832011-05-27 20:00:14 +00003346 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003347 if (DefinitionRequired) {
3348 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003349 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003350 diag::err_explicit_instantiation_undefined_func_template)
3351 << Function->getPrimaryTemplate();
3352 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003353 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003354 diag::err_explicit_instantiation_undefined_member)
3355 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003356
Douglas Gregora8b89d22009-10-15 14:05:49 +00003357 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003358 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003359 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003360 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003361 } else if (Function->getTemplateSpecializationKind()
3362 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003363 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003364 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003365 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003366
Douglas Gregor24c332b2009-05-14 21:06:31 +00003367 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003368 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003369
Richard Smith2a7d4812013-05-04 07:00:32 +00003370 // C++1y [temp.explicit]p10:
3371 // Except for inline functions, declarations with types deduced from their
3372 // initializer or return value, and class template specializations, other
3373 // explicit instantiation declarations have the effect of suppressing the
3374 // implicit instantiation of the entity to which they refer.
Alp Toker314cc812014-01-25 16:55:45 +00003375 if (Function->getTemplateSpecializationKind() ==
3376 TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003377 !PatternDecl->isInlined() &&
Alp Toker314cc812014-01-25 16:55:45 +00003378 !PatternDecl->getReturnType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003379 return;
Mike Stump11289f42009-09-09 15:08:12 +00003380
Richard Smithf3814ad2013-01-25 00:08:28 +00003381 if (PatternDecl->isInlined())
3382 Function->setImplicitlyInline();
3383
Douglas Gregor85673582009-05-18 17:01:57 +00003384 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003385 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003386 return;
3387
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003388 // Copy the inner loc start from the pattern.
3389 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3390
Douglas Gregordda7ced2009-06-30 17:20:14 +00003391 // If we're performing recursive template instantiation, create our own
3392 // queue of pending implicit instantiations that we will instantiate later,
3393 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003394 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003395 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003396 SavePendingLocalImplicitInstantiationsRAII
3397 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003398 if (Recursive) {
3399 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003400 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003403 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003404 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003405
Douglas Gregorb4850462009-05-14 23:26:13 +00003406 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003407 // recorded, unless we're actually a member function within a local
3408 // class, in which case we need to merge our results with the parent
3409 // scope (of the enclosing function).
3410 bool MergeWithParentScope = false;
3411 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3412 MergeWithParentScope = Rec->isLocalClass();
3413
3414 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003415
Richard Smithbd305122012-12-11 01:14:52 +00003416 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003417 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003418 else {
3419 ActOnStartOfFunctionDef(0, Function);
3420
3421 // Enter the scope of this instantiation. We don't use
3422 // PushDeclContext because we don't have a scope.
3423 Sema::ContextRAII savedContext(*this, Function);
3424
3425 MultiLevelTemplateArgumentList TemplateArgs =
3426 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3427
3428 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3429 TemplateArgs);
3430
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003431 // If this is a constructor, instantiate the member initializers.
3432 if (const CXXConstructorDecl *Ctor =
3433 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3434 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3435 TemplateArgs);
3436 }
3437
3438 // Instantiate the function body.
3439 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3440
3441 if (Body.isInvalid())
3442 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003443
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003444 ActOnFinishFunctionBody(Function, Body.get(),
3445 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003446
3447 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3448
Richard Smithd28ac5b2014-03-22 23:33:22 +00003449 if (auto *Listener = getASTMutationListener())
3450 Listener->FunctionDefinitionInstantiated(Function);
Richard Smith0ac1b8f2014-03-22 01:43:32 +00003451
Richard Smithbd305122012-12-11 01:14:52 +00003452 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003453 }
3454
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003455 DeclGroupRef DG(Function);
3456 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003457
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003458 // This class may have local implicit instantiations that need to be
3459 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003460 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003461 Scope.Exit();
3462
Douglas Gregordda7ced2009-06-30 17:20:14 +00003463 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003464 // Define any pending vtables.
3465 DefineUsedVTables();
3466
Douglas Gregordda7ced2009-06-30 17:20:14 +00003467 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003468 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003469 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003470
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003471 // Restore the set of pending vtables.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003472 assert(VTableUses.empty() &&
3473 "VTableUses should be empty before it is discarded.");
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003474 VTableUses.swap(SavedVTableUses);
3475
Douglas Gregordda7ced2009-06-30 17:20:14 +00003476 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003477 assert(PendingInstantiations.empty() &&
3478 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003479 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregordda7ced2009-06-30 17:20:14 +00003480 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003481}
3482
Larisse Voufo39a1e502013-08-06 01:03:05 +00003483VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3484 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3485 const TemplateArgumentList &TemplateArgList,
3486 const TemplateArgumentListInfo &TemplateArgsInfo,
3487 SmallVectorImpl<TemplateArgument> &Converted,
3488 SourceLocation PointOfInstantiation, void *InsertPos,
3489 LateInstantiatedAttrVec *LateAttrs,
3490 LocalInstantiationScope *StartingScope) {
3491 if (FromVar->isInvalidDecl())
3492 return 0;
3493
3494 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003495 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003496 return 0;
3497
3498 MultiLevelTemplateArgumentList TemplateArgLists;
3499 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3500
Richard Smith8809a0c2013-09-27 20:14:12 +00003501 // Instantiate the first declaration of the variable template: for a partial
3502 // specialization of a static data member template, the first declaration may
3503 // or may not be the declaration in the class; if it's in the class, we want
3504 // to instantiate a member in the class (a declaration), and if it's outside,
3505 // we want to instantiate a definition.
Richard Smithbeef3452014-01-16 23:39:20 +00003506 //
3507 // If we're instantiating an explicitly-specialized member template or member
3508 // partial specialization, don't do this. The member specialization completely
3509 // replaces the original declaration in this case.
3510 bool IsMemberSpec = false;
3511 if (VarTemplatePartialSpecializationDecl *PartialSpec =
3512 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar))
3513 IsMemberSpec = PartialSpec->isMemberSpecialization();
3514 else if (VarTemplateDecl *FromTemplate = FromVar->getDescribedVarTemplate())
3515 IsMemberSpec = FromTemplate->isMemberSpecialization();
3516 if (!IsMemberSpec)
3517 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003518
Manuel Klimek5843add2013-09-30 13:29:01 +00003519 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3520 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3521 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003522
3523 // TODO: Set LateAttrs and StartingScope ...
3524
3525 return cast_or_null<VarTemplateSpecializationDecl>(
3526 Instantiator.VisitVarTemplateSpecializationDecl(
3527 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3528}
3529
3530/// \brief Instantiates a variable template specialization by completing it
3531/// with appropriate type information and initializer.
3532VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3533 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3534 const MultiLevelTemplateArgumentList &TemplateArgs) {
3535
3536 // Do substitution on the type of the declaration
3537 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003538 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003539 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3540 if (!DI)
3541 return 0;
3542
3543 // Update the type of this variable template specialization.
3544 VarSpec->setType(DI->getType());
3545
3546 // Instantiate the initializer.
3547 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3548
3549 return VarSpec;
3550}
3551
3552/// BuildVariableInstantiation - Used after a new variable has been created.
3553/// Sets basic variable data and decides whether to postpone the
3554/// variable instantiation.
3555void Sema::BuildVariableInstantiation(
3556 VarDecl *NewVar, VarDecl *OldVar,
3557 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003558 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3559 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003560 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003561
Richard Smith541b38b2013-09-20 01:15:31 +00003562 // If we are instantiating a local extern declaration, the
3563 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003564 // If we are instantiating a static data member defined
3565 // out-of-line, the instantiation will have the same lexical
3566 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00003567 if (OldVar->isLocalExternDecl()) {
3568 NewVar->setLocalExternDecl();
3569 NewVar->setLexicalDeclContext(Owner);
3570 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003571 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3572 NewVar->setTSCSpec(OldVar->getTSCSpec());
3573 NewVar->setInitStyle(OldVar->getInitStyle());
3574 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3575 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00003576 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00003577 NewVar->setPreviousDeclInSameBlockScope(
3578 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003579 NewVar->setAccess(OldVar->getAccess());
3580
Richard Smith0b551192013-09-23 23:12:22 +00003581 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00003582 if (OldVar->isUsed(false))
3583 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003584 NewVar->setReferenced(OldVar->isReferenced());
3585 }
3586
David Majnemer50ce8352013-09-17 23:57:10 +00003587 // See if the old variable had a type-specifier that defined an anonymous tag.
3588 // If it did, mark the new variable as being the declarator for the new
3589 // anonymous tag.
3590 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3591 TagDecl *OldTag = OldTagType->getDecl();
3592 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3593 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3594 assert(!NewTag->hasNameForLinkage() &&
3595 !NewTag->hasDeclaratorForAnonDecl());
3596 NewTag->setDeclaratorForAnonDecl(NewVar);
3597 }
3598 }
3599
Larisse Voufo39a1e502013-08-06 01:03:05 +00003600 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3601
Richard Smith541b38b2013-09-20 01:15:31 +00003602 LookupResult Previous(
3603 *this, NewVar->getDeclName(), NewVar->getLocation(),
3604 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3605 : Sema::LookupOrdinaryName,
3606 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003607
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00003608 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3609 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3610 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003611 // We have a previous declaration. Use that one, so we merge with the
3612 // right type.
3613 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3614 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3615 Previous.addDecl(NewPrev);
3616 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3617 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003618 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003619 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003620
Richard Smith541b38b2013-09-20 01:15:31 +00003621 if (!InstantiatingVarTemplate) {
3622 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3623 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003624 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00003625 }
3626
3627 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003628 if (NewVar->getDeclContext()->isFunctionOrMethod())
3629 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3630 }
3631
3632 // Link instantiations of static data members back to the template from
3633 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003634 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003635 NewVar->setInstantiationOfStaticDataMember(OldVar,
3636 TSK_ImplicitInstantiation);
3637
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003638 // Forward the mangling number from the template to the instantiated decl.
3639 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
David Majnemer2206bf52014-03-05 08:57:59 +00003640 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003641
Richard Smith8809a0c2013-09-27 20:14:12 +00003642 // Delay instantiation of the initializer for variable templates until a
Richard Smithd292b242014-03-16 01:00:40 +00003643 // definition of the variable is needed. We need it right away if the type
3644 // contains 'auto'.
3645 if ((!isa<VarTemplateSpecializationDecl>(NewVar) &&
3646 !InstantiatingVarTemplate) ||
3647 NewVar->getType()->isUndeducedType())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003648 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3649
3650 // Diagnose unused local variables with dependent types, where the diagnostic
3651 // will have been deferred.
3652 if (!NewVar->isInvalidDecl() &&
3653 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3654 OldVar->getType()->isDependentType())
3655 DiagnoseUnusedDecl(NewVar);
3656}
3657
3658/// \brief Instantiate the initializer of a variable.
3659void Sema::InstantiateVariableInitializer(
3660 VarDecl *Var, VarDecl *OldVar,
3661 const MultiLevelTemplateArgumentList &TemplateArgs) {
3662
3663 if (Var->getAnyInitializer())
3664 // We already have an initializer in the class.
3665 return;
3666
3667 if (OldVar->getInit()) {
3668 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3669 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3670 else
3671 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3672
3673 // Instantiate the initializer.
3674 ExprResult Init =
3675 SubstInitializer(OldVar->getInit(), TemplateArgs,
3676 OldVar->getInitStyle() == VarDecl::CallInit);
3677 if (!Init.isInvalid()) {
3678 bool TypeMayContainAuto = true;
3679 if (Init.get()) {
3680 bool DirectInit = OldVar->isDirectInit();
3681 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3682 } else
3683 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3684 } else {
3685 // FIXME: Not too happy about invalidating the declaration
3686 // because of a bogus initializer.
3687 Var->setInvalidDecl();
3688 }
3689
3690 PopExpressionEvaluationContext();
3691 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3692 !Var->isCXXForRangeDecl())
3693 ActOnUninitializedDecl(Var, false);
3694}
3695
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003696/// \brief Instantiate the definition of the given variable from its
3697/// template.
3698///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003699/// \param PointOfInstantiation the point at which the instantiation was
3700/// required. Note that this is not precisely a "point of instantiation"
3701/// for the function, but it's close.
3702///
3703/// \param Var the already-instantiated declaration of a static member
3704/// variable of a class template specialization.
3705///
3706/// \param Recursive if true, recursively instantiates any functions that
3707/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003708///
3709/// \param DefinitionRequired if true, then we are performing an explicit
3710/// instantiation where an out-of-line definition of the member variable
3711/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003712void Sema::InstantiateStaticDataMemberDefinition(
3713 SourceLocation PointOfInstantiation,
3714 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003715 bool Recursive,
3716 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003717 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3718 DefinitionRequired);
3719}
3720
3721void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3722 VarDecl *Var, bool Recursive,
3723 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003724 if (Var->isInvalidDecl())
3725 return;
Mike Stump11289f42009-09-09 15:08:12 +00003726
Larisse Voufo39a1e502013-08-06 01:03:05 +00003727 VarTemplateSpecializationDecl *VarSpec =
3728 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smith8809a0c2013-09-27 20:14:12 +00003729 VarDecl *PatternDecl = 0, *Def = 0;
3730 MultiLevelTemplateArgumentList TemplateArgs =
3731 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003732
Larisse Voufo39a1e502013-08-06 01:03:05 +00003733 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003734 // If this is a variable template specialization, make sure that it is
3735 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003736 bool InstantiationDependent = false;
3737 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3738 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3739 "Only instantiate variable template specializations that are "
3740 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003741 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003742
Richard Smith8809a0c2013-09-27 20:14:12 +00003743 // Find the variable initialization that we'll be substituting. If the
3744 // pattern was instantiated from a member template, look back further to
3745 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003746 assert(VarSpec->getSpecializedTemplate() &&
3747 "Specialization without specialized template?");
3748 llvm::PointerUnion<VarTemplateDecl *,
3749 VarTemplatePartialSpecializationDecl *> PatternPtr =
3750 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003751 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003752 VarTemplatePartialSpecializationDecl *Tmpl =
3753 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3754 while (VarTemplatePartialSpecializationDecl *From =
3755 Tmpl->getInstantiatedFromMember()) {
3756 if (Tmpl->isMemberSpecialization())
3757 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003758
Richard Smith8809a0c2013-09-27 20:14:12 +00003759 Tmpl = From;
3760 }
3761 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003762 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003763 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3764 while (VarTemplateDecl *From =
3765 Tmpl->getInstantiatedFromMemberTemplate()) {
3766 if (Tmpl->isMemberSpecialization())
3767 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003768
Richard Smith8809a0c2013-09-27 20:14:12 +00003769 Tmpl = From;
3770 }
3771 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003772 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003773
3774 // If this is a static data member template, there might be an
3775 // uninstantiated initializer on the declaration. If so, instantiate
3776 // it now.
3777 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003778 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003779 !Var->hasInit()) {
3780 // FIXME: Factor out the duplicated instantiation context setup/tear down
3781 // code here.
3782 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003783 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003784 return;
3785
3786 // If we're performing recursive template instantiation, create our own
3787 // queue of pending implicit instantiations that we will instantiate
3788 // later, while we're still within our own instantiation context.
3789 SmallVector<VTableUse, 16> SavedVTableUses;
3790 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3791 if (Recursive) {
3792 VTableUses.swap(SavedVTableUses);
3793 PendingInstantiations.swap(SavedPendingInstantiations);
3794 }
3795
3796 LocalInstantiationScope Local(*this);
3797
3798 // Enter the scope of this instantiation. We don't use
3799 // PushDeclContext because we don't have a scope.
3800 ContextRAII PreviousContext(*this, Var->getDeclContext());
3801 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3802 PreviousContext.pop();
3803
3804 // FIXME: Need to inform the ASTConsumer that we instantiated the
3805 // initializer?
3806
3807 // This variable may have local implicit instantiations that need to be
3808 // instantiated within this scope.
3809 PerformPendingInstantiations(/*LocalOnly=*/true);
3810
3811 Local.Exit();
3812
3813 if (Recursive) {
3814 // Define any newly required vtables.
3815 DefineUsedVTables();
3816
3817 // Instantiate any pending implicit instantiations found during the
3818 // instantiation of this template.
3819 PerformPendingInstantiations();
3820
3821 // Restore the set of pending vtables.
3822 assert(VTableUses.empty() &&
3823 "VTableUses should be empty before it is discarded.");
3824 VTableUses.swap(SavedVTableUses);
3825
3826 // Restore the set of pending implicit instantiations.
3827 assert(PendingInstantiations.empty() &&
3828 "PendingInstantiations should be empty before it is discarded.");
3829 PendingInstantiations.swap(SavedPendingInstantiations);
3830 }
3831 }
3832
3833 // Find actual definition
3834 Def = PatternDecl->getDefinition(getASTContext());
3835 } else {
3836 // If this is a static data member, find its out-of-line definition.
3837 assert(Var->isStaticDataMember() && "not a static data member?");
3838 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3839
3840 assert(PatternDecl && "data member was not instantiated from a template?");
3841 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3842 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003843 }
3844
Richard Smith8809a0c2013-09-27 20:14:12 +00003845 // If we don't have a definition of the variable template, we won't perform
3846 // any instantiation. Rather, we rely on the user to instantiate this
3847 // definition (or provide a specialization for it) in another translation
3848 // unit.
3849 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003850 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003851 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003852 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003853 diag::err_explicit_instantiation_undefined_var_template) << Var;
3854 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003855 Diag(PointOfInstantiation,
3856 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003857 << 2 << Var->getDeclName() << Var->getDeclContext();
3858 Diag(PatternDecl->getLocation(),
3859 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003860 if (VarSpec)
3861 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003862 } else if (Var->getTemplateSpecializationKind()
3863 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003864 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003865 std::make_pair(Var, PointOfInstantiation));
3866 }
3867
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003868 return;
3869 }
3870
Rafael Espindola189fa742012-03-05 10:54:55 +00003871 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3872
Douglas Gregor86d142a2009-10-08 07:24:58 +00003873 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003874 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003875 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003876
Larisse Voufo39a1e502013-08-06 01:03:05 +00003877 // C++11 [temp.explicit]p10:
3878 // Except for inline functions, [...] explicit instantiation declarations
3879 // have the effect of suppressing the implicit instantiation of the entity
3880 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003881 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003882 return;
Mike Stump11289f42009-09-09 15:08:12 +00003883
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003884 // Make sure to pass the instantiated variable to the consumer at the end.
3885 struct PassToConsumerRAII {
3886 ASTConsumer &Consumer;
3887 VarDecl *Var;
3888
3889 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3890 : Consumer(Consumer), Var(Var) { }
3891
3892 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003893 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003894 }
3895 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003896
Richard Smith8809a0c2013-09-27 20:14:12 +00003897 // If we already have a definition, we're done.
3898 if (VarDecl *Def = Var->getDefinition()) {
3899 // We may be explicitly instantiating something we've already implicitly
3900 // instantiated.
3901 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3902 PointOfInstantiation);
3903 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003904 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003905
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003906 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003907 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003908 return;
Mike Stump11289f42009-09-09 15:08:12 +00003909
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003910 // If we're performing recursive template instantiation, create our own
3911 // queue of pending implicit instantiations that we will instantiate later,
3912 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003913 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003914 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003915 SavePendingLocalImplicitInstantiationsRAII
3916 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003917 if (Recursive) {
3918 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003919 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003920 }
Mike Stump11289f42009-09-09 15:08:12 +00003921
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003922 // Enter the scope of this instantiation. We don't use
3923 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003924 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003925 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003926
Larisse Voufo39a1e502013-08-06 01:03:05 +00003927 VarDecl *OldVar = Var;
3928 if (!VarSpec)
3929 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003930 TemplateArgs));
3931 else if (Var->isStaticDataMember() &&
3932 Var->getLexicalDeclContext()->isRecord()) {
3933 // We need to instantiate the definition of a static data member template,
3934 // and all we have is the in-class declaration of it. Instantiate a separate
3935 // declaration of the definition.
3936 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3937 TemplateArgs);
3938 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3939 VarSpec->getSpecializedTemplate(), Def, 0,
3940 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3941 if (Var) {
3942 llvm::PointerUnion<VarTemplateDecl *,
3943 VarTemplatePartialSpecializationDecl *> PatternPtr =
3944 VarSpec->getSpecializedTemplateOrPartial();
3945 if (VarTemplatePartialSpecializationDecl *Partial =
3946 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3947 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3948 Partial, &VarSpec->getTemplateInstantiationArgs());
3949
3950 // Merge the definition with the declaration.
3951 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3952 LookupOrdinaryName, ForRedeclaration);
3953 R.addDecl(OldVar);
3954 MergeVarDecl(Var, R);
3955
3956 // Attach the initializer.
3957 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3958 }
3959 } else
3960 // Complete the existing variable's definition with an appropriately
3961 // substituted type and initializer.
3962 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003963
3964 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003965
3966 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003967 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003968 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3969 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003970 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003971
3972 // This variable may have local implicit instantiations that need to be
3973 // instantiated within this scope.
3974 PerformPendingInstantiations(/*LocalOnly=*/true);
3975
Douglas Gregora86bc002012-02-16 21:36:18 +00003976 Local.Exit();
3977
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003978 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003979 // Define any newly required vtables.
3980 DefineUsedVTables();
3981
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003982 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003983 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003984 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003985
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003986 // Restore the set of pending vtables.
3987 assert(VTableUses.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003988 "VTableUses should be empty before it is discarded.");
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003989 VTableUses.swap(SavedVTableUses);
3990
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003991 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003992 assert(PendingInstantiations.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003993 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003994 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00003995 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003996}
Douglas Gregor51783312009-05-27 05:35:12 +00003997
Anders Carlsson70553942009-08-29 05:16:22 +00003998void
3999Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
4000 const CXXConstructorDecl *Tmpl,
4001 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00004002
Richard Trieu9becef62011-09-09 03:18:59 +00004003 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00004004 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004005
Anders Carlsson70553942009-08-29 05:16:22 +00004006 // Instantiate all the initializers.
Aaron Ballman0ad78302014-03-13 17:34:31 +00004007 for (const auto *Init : Tmpl->inits()) {
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00004008 // Only instantiate written initializers, let Sema re-construct implicit
4009 // ones.
4010 if (!Init->isWritten())
4011 continue;
4012
Douglas Gregor44e7df62011-01-04 00:32:56 +00004013 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004014
Douglas Gregor44e7df62011-01-04 00:32:56 +00004015 if (Init->isPackExpansion()) {
4016 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004017 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00004018 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00004019 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00004020 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00004021 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004022 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00004023 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004024 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004025 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00004026 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004027 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00004028 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00004029 NumExpansions)) {
4030 AnyErrors = true;
4031 New->setInvalidDecl();
4032 continue;
4033 }
4034 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004035
4036 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00004037 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004038 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
4039
4040 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004041 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4042 /*CXXDirectInit=*/true);
4043 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00004044 AnyErrors = true;
4045 break;
4046 }
4047
4048 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004049 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004050 TemplateArgs,
4051 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004052 New->getDeclName());
4053 if (!BaseTInfo) {
4054 AnyErrors = true;
4055 break;
4056 }
4057
4058 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00004059 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redla9351792012-02-11 23:51:47 +00004060 BaseTInfo, TempInit.take(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00004061 New->getParent(),
4062 SourceLocation());
4063 if (NewInit.isInvalid()) {
4064 AnyErrors = true;
4065 break;
4066 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004067
Douglas Gregor44e7df62011-01-04 00:32:56 +00004068 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00004069 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004070
Douglas Gregor44e7df62011-01-04 00:32:56 +00004071 continue;
4072 }
4073
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004074 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00004075 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
4076 /*CXXDirectInit=*/true);
4077 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00004078 AnyErrors = true;
4079 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00004080 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004081
Anders Carlsson70553942009-08-29 05:16:22 +00004082 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004083 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
4084 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
4085 TemplateArgs,
4086 Init->getSourceLocation(),
4087 New->getDeclName());
4088 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004089 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00004090 New->setInvalidDecl();
4091 continue;
4092 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004093
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004094 if (Init->isBaseInitializer())
Sebastian Redla9351792012-02-11 23:51:47 +00004095 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004096 New->getParent(), EllipsisLoc);
4097 else
Sebastian Redla9351792012-02-11 23:51:47 +00004098 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00004099 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00004100 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00004101 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004102 Init->getMemberLocation(),
4103 Init->getMember(),
4104 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00004105 if (!Member) {
4106 AnyErrors = true;
4107 New->setInvalidDecl();
4108 continue;
4109 }
Mike Stump11289f42009-09-09 15:08:12 +00004110
Sebastian Redla9351792012-02-11 23:51:47 +00004111 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004112 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00004113 } else if (Init->isIndirectMemberInitializer()) {
4114 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00004115 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00004116 Init->getMemberLocation(),
4117 Init->getIndirectMember(), TemplateArgs));
4118
Douglas Gregor55e6b312011-03-04 19:46:35 +00004119 if (!IndirectMember) {
4120 AnyErrors = true;
4121 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00004122 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00004123 }
Sebastian Redla74948d2011-09-24 17:48:25 +00004124
Sebastian Redla9351792012-02-11 23:51:47 +00004125 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00004126 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00004127 }
4128
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004129 if (NewInit.isInvalid()) {
4130 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00004131 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004132 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00004133 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00004134 }
4135 }
Mike Stump11289f42009-09-09 15:08:12 +00004136
Anders Carlsson70553942009-08-29 05:16:22 +00004137 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00004138 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00004139 /*FIXME: ColonLoc */
4140 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00004141 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00004142 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00004143}
4144
John McCall59660882009-08-29 08:11:13 +00004145// TODO: this could be templated if the various decl types used the
4146// same method name.
4147static bool isInstantiationOf(ClassTemplateDecl *Pattern,
4148 ClassTemplateDecl *Instance) {
4149 Pattern = Pattern->getCanonicalDecl();
4150
4151 do {
4152 Instance = Instance->getCanonicalDecl();
4153 if (Pattern == Instance) return true;
4154 Instance = Instance->getInstantiatedFromMemberTemplate();
4155 } while (Instance);
4156
4157 return false;
4158}
4159
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004160static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
4161 FunctionTemplateDecl *Instance) {
4162 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004163
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004164 do {
4165 Instance = Instance->getCanonicalDecl();
4166 if (Pattern == Instance) return true;
4167 Instance = Instance->getInstantiatedFromMemberTemplate();
4168 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004169
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004170 return false;
4171}
4172
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004173static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004174isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4175 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004176 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004177 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4178 do {
4179 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4180 Instance->getCanonicalDecl());
4181 if (Pattern == Instance)
4182 return true;
4183 Instance = Instance->getInstantiatedFromMember();
4184 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004185
Douglas Gregor21610382009-10-29 00:04:11 +00004186 return false;
4187}
4188
John McCall59660882009-08-29 08:11:13 +00004189static bool isInstantiationOf(CXXRecordDecl *Pattern,
4190 CXXRecordDecl *Instance) {
4191 Pattern = Pattern->getCanonicalDecl();
4192
4193 do {
4194 Instance = Instance->getCanonicalDecl();
4195 if (Pattern == Instance) return true;
4196 Instance = Instance->getInstantiatedFromMemberClass();
4197 } while (Instance);
4198
4199 return false;
4200}
4201
4202static bool isInstantiationOf(FunctionDecl *Pattern,
4203 FunctionDecl *Instance) {
4204 Pattern = Pattern->getCanonicalDecl();
4205
4206 do {
4207 Instance = Instance->getCanonicalDecl();
4208 if (Pattern == Instance) return true;
4209 Instance = Instance->getInstantiatedFromMemberFunction();
4210 } while (Instance);
4211
4212 return false;
4213}
4214
4215static bool isInstantiationOf(EnumDecl *Pattern,
4216 EnumDecl *Instance) {
4217 Pattern = Pattern->getCanonicalDecl();
4218
4219 do {
4220 Instance = Instance->getCanonicalDecl();
4221 if (Pattern == Instance) return true;
4222 Instance = Instance->getInstantiatedFromMemberEnum();
4223 } while (Instance);
4224
4225 return false;
4226}
4227
John McCallb96ec562009-12-04 22:46:56 +00004228static bool isInstantiationOf(UsingShadowDecl *Pattern,
4229 UsingShadowDecl *Instance,
4230 ASTContext &C) {
4231 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4232}
4233
4234static bool isInstantiationOf(UsingDecl *Pattern,
4235 UsingDecl *Instance,
4236 ASTContext &C) {
4237 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4238}
4239
John McCalle61f2ba2009-11-18 02:36:19 +00004240static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4241 UsingDecl *Instance,
4242 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004243 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00004244}
4245
4246static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004247 UsingDecl *Instance,
4248 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004249 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004250}
4251
John McCall59660882009-08-29 08:11:13 +00004252static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4253 VarDecl *Instance) {
4254 assert(Instance->isStaticDataMember());
4255
4256 Pattern = Pattern->getCanonicalDecl();
4257
4258 do {
4259 Instance = Instance->getCanonicalDecl();
4260 if (Pattern == Instance) return true;
4261 Instance = Instance->getInstantiatedFromStaticDataMember();
4262 } while (Instance);
4263
4264 return false;
4265}
4266
John McCallb96ec562009-12-04 22:46:56 +00004267// Other is the prospective instantiation
4268// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004269static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004270 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004271 if (UnresolvedUsingTypenameDecl *UUD
4272 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4273 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4274 return isInstantiationOf(UUD, UD, Ctx);
4275 }
4276 }
4277
4278 if (UnresolvedUsingValueDecl *UUD
4279 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004280 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4281 return isInstantiationOf(UUD, UD, Ctx);
4282 }
4283 }
Douglas Gregor51783312009-05-27 05:35:12 +00004284
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004285 return false;
4286 }
Mike Stump11289f42009-09-09 15:08:12 +00004287
John McCall59660882009-08-29 08:11:13 +00004288 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4289 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004290
John McCall59660882009-08-29 08:11:13 +00004291 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4292 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004293
John McCall59660882009-08-29 08:11:13 +00004294 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4295 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004296
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004297 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004298 if (Var->isStaticDataMember())
4299 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4300
4301 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4302 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004303
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004304 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4305 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4306
Douglas Gregor21610382009-10-29 00:04:11 +00004307 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4308 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4309 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4310 PartialSpec);
4311
Anders Carlsson5da84842009-09-01 04:26:58 +00004312 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4313 if (!Field->getDeclName()) {
4314 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00004315 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00004316 cast<FieldDecl>(D);
4317 }
4318 }
Mike Stump11289f42009-09-09 15:08:12 +00004319
John McCallb96ec562009-12-04 22:46:56 +00004320 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4321 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4322
4323 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4324 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4325
Douglas Gregor51783312009-05-27 05:35:12 +00004326 return D->getDeclName() && isa<NamedDecl>(Other) &&
4327 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4328}
4329
4330template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004331static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004332 NamedDecl *D,
4333 ForwardIterator first,
4334 ForwardIterator last) {
4335 for (; first != last; ++first)
4336 if (isInstantiationOf(Ctx, D, *first))
4337 return cast<NamedDecl>(*first);
4338
4339 return 0;
4340}
4341
John McCallaa74a0c2009-08-28 07:59:38 +00004342/// \brief Finds the instantiation of the given declaration context
4343/// within the current instantiation.
4344///
4345/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004346DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004347 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004348 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004349 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004350 return cast_or_null<DeclContext>(ID);
4351 } else return DC;
4352}
4353
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004354/// \brief Find the instantiation of the given declaration within the
4355/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004356///
4357/// This routine is intended to be used when \p D is a declaration
4358/// referenced from within a template, that needs to mapped into the
4359/// corresponding declaration within an instantiation. For example,
4360/// given:
4361///
4362/// \code
4363/// template<typename T>
4364/// struct X {
4365/// enum Kind {
4366/// KnownValue = sizeof(T)
4367/// };
4368///
4369/// bool getKind() const { return KnownValue; }
4370/// };
4371///
4372/// template struct X<int>;
4373/// \endcode
4374///
Serge Pavloved5fe902013-07-10 04:59:14 +00004375/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4376/// \p EnumConstantDecl for \p KnownValue (which refers to
4377/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4378/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4379/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004380NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004381 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004382 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004383 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4384 // parameters (p below) can have their ParentDC set to the translation-unit
4385 // - thus we can not consistently check if the ParentDC of such a parameter
4386 // is Dependent or/and a FunctionOrMethod.
4387 // For e.g. this code, during Template argument deduction tries to
4388 // find an instantiated decl for (T y) when the ParentDC for y is
4389 // the translation unit.
4390 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
Aaron Ballman36a53502014-01-16 13:03:14 +00004391 // float baz(float(*)()) { return 0.0; }
Faisal Vali2cba1332013-10-23 06:44:28 +00004392 // Foo(baz);
4393 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4394 // it gets here, always has a FunctionOrMethod as its ParentDC??
4395 // For now:
4396 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4397 // whose type is not instantiation dependent, do nothing to the decl
4398 // - otherwise find its instantiated decl.
4399 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4400 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4401 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004402 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004403 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004404 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4405 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004406 // D is a local of some kind. Look into the map of local
4407 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00004408 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4409 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4410 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004411
Chris Lattnercab02a62011-02-17 20:34:02 +00004412 if (Found) {
4413 if (Decl *FD = Found->dyn_cast<Decl *>())
4414 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004415
Richard Smithb15fe3a2012-09-12 00:56:43 +00004416 int PackIdx = ArgumentPackSubstitutionIndex;
4417 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00004418 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4419 }
4420
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004421 // If we're performing a partial substitution during template argument
4422 // deduction, we may not have values for template parameters yet. They
4423 // just map to themselves.
4424 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4425 isa<TemplateTemplateParmDecl>(D))
4426 return D;
4427
Serge Pavlov074a5182013-08-10 12:00:21 +00004428 if (D->isInvalidDecl())
4429 return 0;
4430
Chris Lattnercab02a62011-02-17 20:34:02 +00004431 // If we didn't find the decl, then we must have a label decl that hasn't
4432 // been found yet. Lazily instantiate it and return it now.
4433 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004434
Chris Lattnercab02a62011-02-17 20:34:02 +00004435 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4436 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004437
Chris Lattnercab02a62011-02-17 20:34:02 +00004438 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4439 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004440 }
Douglas Gregor51783312009-05-27 05:35:12 +00004441
Larisse Voufo39a1e502013-08-06 01:03:05 +00004442 // For variable template specializations, update those that are still
4443 // type-dependent.
4444 if (VarTemplateSpecializationDecl *VarSpec =
4445 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4446 bool InstantiationDependent = false;
4447 const TemplateArgumentListInfo &VarTemplateArgs =
4448 VarSpec->getTemplateArgsInfo();
4449 if (TemplateSpecializationType::anyDependentTemplateArguments(
4450 VarTemplateArgs, InstantiationDependent))
4451 D = cast<NamedDecl>(
4452 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4453 return D;
4454 }
4455
Douglas Gregor64621e62009-09-16 18:34:49 +00004456 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4457 if (!Record->isDependentContext())
4458 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004459
Douglas Gregor4109afa2011-11-07 17:43:18 +00004460 // Determine whether this record is the "templated" declaration describing
4461 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004462 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004463 if (ClassTemplate)
4464 ClassTemplate = ClassTemplate->getCanonicalDecl();
4465 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4466 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4467 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004468
Douglas Gregor4109afa2011-11-07 17:43:18 +00004469 // Walk the current context to find either the record or an instantiation of
4470 // it.
4471 DeclContext *DC = CurContext;
4472 while (!DC->isFileContext()) {
4473 // If we're performing substitution while we're inside the template
4474 // definition, we'll find our own context. We're done.
4475 if (DC->Equals(Record))
4476 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004477
Douglas Gregor4109afa2011-11-07 17:43:18 +00004478 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4479 // Check whether we're in the process of instantiating a class template
4480 // specialization of the template we're mapping.
4481 if (ClassTemplateSpecializationDecl *InstSpec
4482 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4483 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4484 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4485 return InstRecord;
4486 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004487
Douglas Gregor4109afa2011-11-07 17:43:18 +00004488 // Check whether we're in the process of instantiating a member class.
4489 if (isInstantiationOf(Record, InstRecord))
4490 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004491 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004492
Douglas Gregor4109afa2011-11-07 17:43:18 +00004493 // Move to the outer template scope.
4494 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4495 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4496 DC = FD->getLexicalDeclContext();
4497 continue;
4498 }
John McCall59660882009-08-29 08:11:13 +00004499 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004500
Douglas Gregor4109afa2011-11-07 17:43:18 +00004501 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004502 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004503
Douglas Gregor64621e62009-09-16 18:34:49 +00004504 // Fall through to deal with other dependent record types (e.g.,
4505 // anonymous unions in class templates).
4506 }
John McCall59660882009-08-29 08:11:13 +00004507
Douglas Gregor64621e62009-09-16 18:34:49 +00004508 if (!ParentDC->isDependentContext())
4509 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004510
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004511 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004512 if (!ParentDC)
Douglas Gregor2ffd9652009-09-01 17:53:10 +00004513 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004514
Douglas Gregor51783312009-05-27 05:35:12 +00004515 if (ParentDC != D->getDeclContext()) {
4516 // We performed some kind of instantiation in the parent context,
4517 // so now we need to look into the instantiated parent context to
4518 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004519
John McCalle78aac42010-03-10 03:28:59 +00004520 // If our context used to be dependent, we may need to instantiate
4521 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004522 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004523 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004524 if (!Spec->isDependentContext()) {
4525 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004526 const RecordType *Tag = T->getAs<RecordType>();
4527 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004528 if (Tag->isBeingDefined())
4529 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004530 if (!Tag->isBeingDefined() &&
4531 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4532 return 0;
Douglas Gregor25edf432010-11-05 23:22:45 +00004533
4534 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004535 }
4536 }
4537
Douglas Gregor51783312009-05-27 05:35:12 +00004538 NamedDecl *Result = 0;
4539 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004540 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004541 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004542 } else {
4543 // Since we don't have a name for the entity we're looking for,
4544 // our only option is to walk through all of the declarations to
4545 // find that name. This will occur in a few cases:
4546 //
4547 // - anonymous struct/union within a template
4548 // - unnamed class/struct/union/enum within a template
4549 //
4550 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004551 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004552 ParentDC->decls_begin(),
4553 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004554 }
Mike Stump11289f42009-09-09 15:08:12 +00004555
Douglas Gregor528ad932011-03-06 20:12:45 +00004556 if (!Result) {
4557 if (isa<UsingShadowDecl>(D)) {
4558 // UsingShadowDecls can instantiate to nothing because of using hiding.
4559 } else if (Diags.hasErrorOccurred()) {
4560 // We've already complained about something, so most likely this
4561 // declaration failed to instantiate. There's no point in complaining
4562 // further, since this is normal in invalid code.
4563 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004564 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004565 // instantiated, and we haven't gotten around to instantiating this
4566 // member yet. This can happen when the code uses forward declarations
4567 // of member classes, and introduces ordering dependencies via
4568 // template instantiation.
4569 Diag(Loc, diag::err_member_not_yet_instantiated)
4570 << D->getDeclName()
4571 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4572 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004573 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4574 // This enumeration constant was found when the template was defined,
4575 // but can't be found in the instantiation. This can happen if an
4576 // unscoped enumeration member is explicitly specialized.
4577 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4578 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4579 TemplateArgs));
4580 assert(Spec->getTemplateSpecializationKind() ==
4581 TSK_ExplicitSpecialization);
4582 Diag(Loc, diag::err_enumerator_does_not_exist)
4583 << D->getDeclName()
4584 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4585 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4586 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004587 } else {
4588 // We should have found something, but didn't.
4589 llvm_unreachable("Unable to find instantiation of declaration!");
4590 }
4591 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004592
Douglas Gregor51783312009-05-27 05:35:12 +00004593 D = Result;
4594 }
4595
Douglas Gregor51783312009-05-27 05:35:12 +00004596 return D;
4597}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004598
Mike Stump11289f42009-09-09 15:08:12 +00004599/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004600/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004601void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004602 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004603 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004604 PendingImplicitInstantiation Inst;
4605
4606 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004607 Inst = PendingInstantiations.front();
4608 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004609 } else {
4610 Inst = PendingLocalImplicitInstantiations.front();
4611 PendingLocalImplicitInstantiations.pop_front();
4612 }
Mike Stump11289f42009-09-09 15:08:12 +00004613
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004614 // Instantiate function definitions
4615 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004616 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4617 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004618 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4619 TSK_ExplicitInstantiationDefinition;
4620 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4621 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004622 continue;
4623 }
Mike Stump11289f42009-09-09 15:08:12 +00004624
Larisse Voufo39a1e502013-08-06 01:03:05 +00004625 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004626 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004627
4628 assert((Var->isStaticDataMember() ||
4629 isa<VarTemplateSpecializationDecl>(Var)) &&
4630 "Not a static data member, nor a variable template"
4631 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004632
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004633 // Don't try to instantiate declarations if the most recent redeclaration
4634 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004635 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004636 continue;
4637
4638 // Check if the most recent declaration has changed the specialization kind
4639 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004640 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004641 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004642 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004643 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004644 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004645 continue; // No longer need to instantiate this type.
4646 case TSK_ExplicitInstantiationDefinition:
4647 // We only need an instantiation if the pending instantiation *is* the
4648 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004649 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004650 case TSK_ImplicitInstantiation:
4651 break;
4652 }
4653
Larisse Voufo39a1e502013-08-06 01:03:05 +00004654 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4655 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004656 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4657 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004658
4659 // Instantiate static data member definitions or variable template
4660 // specializations.
4661 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4662 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004663 }
4664}
John McCallc62bb642010-03-24 05:22:00 +00004665
4666void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4667 const MultiLevelTemplateArgumentList &TemplateArgs) {
Aaron Ballmanb105e492014-03-07 14:09:15 +00004668 for (auto DD : Pattern->ddiags()) {
John McCallc62bb642010-03-24 05:22:00 +00004669 switch (DD->getKind()) {
4670 case DependentDiagnostic::Access:
4671 HandleDependentAccessCheck(*DD, TemplateArgs);
4672 break;
4673 }
4674 }
4675}