blob: b10cb397ffe2c89640fb84191db92ee2671851d8 [file] [log] [blame]
Douglas Gregord7e7a512009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
John McCall58f10c32010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Douglas Gregor402250f2009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000025
26using namespace clang;
27
David Majnemer192d1792013-11-27 08:20:38 +000028static bool isDeclWithinFunction(const Decl *D) {
29 const DeclContext *DC = D->getDeclContext();
30 if (DC->isFunctionOrMethod())
31 return true;
32
33 if (DC->isRecord())
34 return cast<CXXRecordDecl>(DC)->isLocalClass();
35
36 return false;
37}
38
John McCall3e11ebe2010-03-15 10:12:16 +000039bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
40 DeclaratorDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000041 if (!OldDecl->getQualifierLoc())
42 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000043
Douglas Gregor14454802011-02-25 02:25:35 +000044 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000045 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000046 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000047
Douglas Gregor14454802011-02-25 02:25:35 +000048 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000049 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000050
Douglas Gregor14454802011-02-25 02:25:35 +000051 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000052 return false;
53}
54
55bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
56 TagDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000057 if (!OldDecl->getQualifierLoc())
58 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000059
Douglas Gregor14454802011-02-25 02:25:35 +000060 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000061 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000062 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000063
Douglas Gregor14454802011-02-25 02:25:35 +000064 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000065 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000066
Douglas Gregor14454802011-02-25 02:25:35 +000067 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000068 return false;
69}
70
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000071// Include attribute instantiation code.
72#include "clang/Sema/AttrTemplateInstantiate.inc"
73
Richard Smith44c247f2013-02-22 08:32:16 +000074static void instantiateDependentAlignedAttr(
75 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
76 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
77 if (Aligned->isAlignmentExpr()) {
78 // The alignment expression is a constant expression.
79 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
80 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
81 if (!Result.isInvalid())
82 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83 Aligned->getSpellingListIndex(), IsPackExpansion);
84 } else {
85 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
86 TemplateArgs, Aligned->getLocation(),
87 DeclarationName());
88 if (Result)
89 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
90 Aligned->getSpellingListIndex(), IsPackExpansion);
91 }
92}
93
94static void instantiateDependentAlignedAttr(
95 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
96 const AlignedAttr *Aligned, Decl *New) {
97 if (!Aligned->isPackExpansion()) {
98 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
99 return;
100 }
101
102 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
103 if (Aligned->isAlignmentExpr())
104 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
105 Unexpanded);
106 else
107 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
108 Unexpanded);
109 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
110
111 // Determine whether we can expand this attribute pack yet.
112 bool Expand = true, RetainExpansion = false;
113 Optional<unsigned> NumExpansions;
114 // FIXME: Use the actual location of the ellipsis.
115 SourceLocation EllipsisLoc = Aligned->getLocation();
116 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
117 Unexpanded, TemplateArgs, Expand,
118 RetainExpansion, NumExpansions))
119 return;
120
121 if (!Expand) {
122 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
123 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
124 } else {
125 for (unsigned I = 0; I != *NumExpansions; ++I) {
126 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
127 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
128 }
129 }
130}
131
John McCall6602bb12010-08-01 02:01:53 +0000132void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000133 const Decl *Tmpl, Decl *New,
134 LateInstantiatedAttrVec *LateAttrs,
135 LocalInstantiationScope *OuterMostScope) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000136 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
137 i != e; ++i) {
138 const Attr *TmplAttr = *i;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000139
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000140 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000141 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
142 if (Aligned && Aligned->isAlignmentDependent()) {
143 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
144 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000145 }
146
Richard Smith44c247f2013-02-22 08:32:16 +0000147 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000148 if (TmplAttr->isLateParsed() && LateAttrs) {
149 // Late parsed attributes must be instantiated and attached after the
150 // enclosing class has been instantiated. See Sema::InstantiateClass.
151 LocalInstantiationScope *Saved = 0;
152 if (CurrentInstantiationScope)
153 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
154 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
155 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000156 // Allow 'this' within late-parsed attributes.
157 NamedDecl *ND = dyn_cast<NamedDecl>(New);
158 CXXRecordDecl *ThisContext =
159 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
160 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
161 ND && ND->isCXXInstanceMember());
162
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000163 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
164 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000165 if (NewAttr)
166 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000167 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000168 }
169}
170
Douglas Gregor8a655532009-03-25 15:45:12 +0000171Decl *
172TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000173 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000174}
175
176Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000177TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
178 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
179 D->getIdentifier());
180 Owner->addDecl(Inst);
181 return Inst;
182}
183
184Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000185TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000186 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000187}
188
John McCalld8d0d432010-02-16 06:53:13 +0000189Decl *
190TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
191 NamespaceAliasDecl *Inst
192 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
193 D->getNamespaceLoc(),
194 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000195 D->getIdentifier(),
196 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000197 D->getTargetNameLoc(),
198 D->getNamespace());
199 Owner->addDecl(Inst);
200 return Inst;
201}
202
Richard Smith3f1b5d02011-05-05 21:57:07 +0000203Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
204 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000205 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000206 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000207 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000208 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000209 DI = SemaRef.SubstType(DI, TemplateArgs,
210 D->getLocation(), D->getDeclName());
211 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000212 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000213 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000214 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000215 } else {
216 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000217 }
Mike Stump11289f42009-09-09 15:08:12 +0000218
Richard Smith2ddcbab2012-10-23 00:32:41 +0000219 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
220 // libstdc++ relies upon this bug in its implementation of common_type.
221 // If we happen to be processing that implementation, fake up the g++ ?:
222 // semantics. See LWG issue 2141 for more information on the bug.
223 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
224 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
225 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
226 DT->isReferenceType() &&
227 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
228 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
229 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
230 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
231 // Fold it to the (non-reference) type which g++ would have produced.
232 DI = SemaRef.Context.getTrivialTypeSourceInfo(
233 DI->getType().getNonReferenceType());
234
Douglas Gregord7e7a512009-03-17 21:15:40 +0000235 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000236 TypedefNameDecl *Typedef;
237 if (IsTypeAlias)
238 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
239 D->getLocation(), D->getIdentifier(), DI);
240 else
241 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
242 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000243 if (Invalid)
244 Typedef->setInvalidDecl();
245
John McCall04fcd0d2011-02-01 08:20:08 +0000246 // If the old typedef was the name for linkage purposes of an anonymous
247 // tag decl, re-establish that relationship for the new typedef.
248 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
249 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000250 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000251 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000252 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000253 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000254 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000255 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000256
Douglas Gregorec9fd132012-01-14 16:38:05 +0000257 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000258 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
259 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000260 if (!InstPrev)
261 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000262
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000263 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
264
265 // If the typedef types are not identical, reject them.
266 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
267
Rafael Espindola8db352d2013-10-17 15:37:26 +0000268 Typedef->setPreviousDecl(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000269 }
270
John McCall6602bb12010-08-01 02:01:53 +0000271 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000272
John McCall401982f2010-01-20 21:53:11 +0000273 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000274
Douglas Gregord7e7a512009-03-17 21:15:40 +0000275 return Typedef;
276}
277
Richard Smithdda56e42011-04-15 14:24:37 +0000278Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000279 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
280 Owner->addDecl(Typedef);
281 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000282}
283
284Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000285 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
286 Owner->addDecl(Typedef);
287 return Typedef;
288}
289
290Decl *
291TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
292 // Create a local instantiation scope for this type alias template, which
293 // will contain the instantiations of the template parameters.
294 LocalInstantiationScope Scope(SemaRef);
295
296 TemplateParameterList *TempParams = D->getTemplateParameters();
297 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
298 if (!InstParams)
299 return 0;
300
301 TypeAliasDecl *Pattern = D->getTemplatedDecl();
302
303 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000304 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000305 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000306 if (!Found.empty()) {
307 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000308 }
309 }
310
311 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
312 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
313 if (!AliasInst)
314 return 0;
315
316 TypeAliasTemplateDecl *Inst
317 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
318 D->getDeclName(), InstParams, AliasInst);
319 if (PrevAliasTemplate)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000320 Inst->setPreviousDecl(PrevAliasTemplate);
Richard Smith3f1b5d02011-05-05 21:57:07 +0000321
322 Inst->setAccess(D->getAccess());
323
324 if (!PrevAliasTemplate)
325 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000326
Richard Smith3f1b5d02011-05-05 21:57:07 +0000327 Owner->addDecl(Inst);
328
329 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000330}
331
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000332Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000333 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000334}
335
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000336Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
337 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +0000338
Douglas Gregor04163182010-05-21 00:31:19 +0000339 // If this is the variable for an anonymous struct or union,
340 // instantiate the anonymous struct/union type first.
341 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
342 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
343 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
344 return 0;
345
John McCall76d824f2009-08-25 22:02:44 +0000346 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000347 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000348 TemplateArgs,
349 D->getTypeSpecStartLoc(),
350 D->getDeclName());
351 if (!DI)
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000352 return 0;
353
Douglas Gregor61623342010-09-12 07:37:24 +0000354 if (DI->getType()->isFunctionType()) {
355 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
356 << D->isStaticDataMember() << DI->getType();
357 return 0;
358 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000359
Richard Smith541b38b2013-09-20 01:15:31 +0000360 DeclContext *DC = Owner;
361 if (D->isLocalExternDecl())
362 SemaRef.adjustContextForLocalExternDecl(DC);
363
Larisse Voufo39a1e502013-08-06 01:03:05 +0000364 // Build the instantiated declaration.
Richard Smith541b38b2013-09-20 01:15:31 +0000365 VarDecl *Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000366 D->getLocation(), D->getIdentifier(),
Larisse Voufo39a1e502013-08-06 01:03:05 +0000367 DI->getType(), DI, D->getStorageClass());
Mike Stump11289f42009-09-09 15:08:12 +0000368
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000369 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000370 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000371 SemaRef.inferObjCARCLifetime(Var))
372 Var->setInvalidDecl();
373
Larisse Voufo39a1e502013-08-06 01:03:05 +0000374 // Substitute the nested name specifier, if any.
375 if (SubstQualifier(D, Var))
376 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000377
Richard Smith541b38b2013-09-20 01:15:31 +0000378 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000379 StartingScope, InstantiatingVarTemplate);
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000380 return Var;
381}
382
Abramo Bagnarad7340582010-06-05 05:09:32 +0000383Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
384 AccessSpecDecl* AD
385 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
386 D->getAccessSpecifierLoc(), D->getColonLoc());
387 Owner->addHiddenDecl(AD);
388 return AD;
389}
390
Douglas Gregord7e7a512009-03-17 21:15:40 +0000391Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
392 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000393 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000394 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000395 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000396 DI = SemaRef.SubstType(DI, TemplateArgs,
397 D->getLocation(), D->getDeclName());
398 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000399 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000400 Invalid = true;
401 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000402 // C++ [temp.arg.type]p3:
403 // If a declaration acquires a function type through a type
404 // dependent on a template-parameter and this causes a
405 // declaration that does not use the syntactic form of a
406 // function declarator to have function type, the program is
407 // ill-formed.
408 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000409 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000410 Invalid = true;
411 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000412 } else {
413 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000414 }
415
416 Expr *BitWidth = D->getBitWidth();
417 if (Invalid)
418 BitWidth = 0;
419 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000420 // The bit-width expression is a constant expression.
421 EnterExpressionEvaluationContext Unevaluated(SemaRef,
422 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000423
John McCalldadc5752010-08-24 06:29:42 +0000424 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000425 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000426 if (InstantiatedBitWidth.isInvalid()) {
427 Invalid = true;
428 BitWidth = 0;
429 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000430 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000431 }
432
John McCall90459c52009-10-22 23:33:21 +0000433 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
434 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000435 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000436 D->getLocation(),
437 D->isMutable(),
438 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000439 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000440 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000441 D->getAccess(),
442 0);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000443 if (!Field) {
444 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000445 return 0;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000446 }
Mike Stump11289f42009-09-09 15:08:12 +0000447
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000448 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000449
Richard Smith848e1f12013-02-01 08:12:08 +0000450 if (Field->hasAttrs())
451 SemaRef.CheckAlignasUnderalignment(Field);
452
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000453 if (Invalid)
454 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000455
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000456 if (!Field->getDeclName()) {
457 // Keep track of where this decl came from.
458 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000459 }
Douglas Gregor04163182010-05-21 00:31:19 +0000460 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
461 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000462 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000463 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000464 }
Mike Stump11289f42009-09-09 15:08:12 +0000465
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000466 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000467 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000468 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000469
470 return Field;
471}
472
John McCall5e77d762013-04-16 07:28:30 +0000473Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
474 bool Invalid = false;
475 TypeSourceInfo *DI = D->getTypeSourceInfo();
476
477 if (DI->getType()->isVariablyModifiedType()) {
478 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
479 << D->getName();
480 Invalid = true;
481 } else if (DI->getType()->isInstantiationDependentType()) {
482 DI = SemaRef.SubstType(DI, TemplateArgs,
483 D->getLocation(), D->getDeclName());
484 if (!DI) {
485 DI = D->getTypeSourceInfo();
486 Invalid = true;
487 } else if (DI->getType()->isFunctionType()) {
488 // C++ [temp.arg.type]p3:
489 // If a declaration acquires a function type through a type
490 // dependent on a template-parameter and this causes a
491 // declaration that does not use the syntactic form of a
492 // function declarator to have function type, the program is
493 // ill-formed.
494 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
495 << DI->getType();
496 Invalid = true;
497 }
498 } else {
499 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
500 }
501
Richard Smithf7981722013-11-22 09:01:48 +0000502 MSPropertyDecl *Property = MSPropertyDecl::Create(
503 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
504 DI, D->getLocStart(), D->getGetterId(), D->getSetterId());
John McCall5e77d762013-04-16 07:28:30 +0000505
506 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
507 StartingScope);
508
509 if (Invalid)
510 Property->setInvalidDecl();
511
512 Property->setAccess(D->getAccess());
513 Owner->addDecl(Property);
514
515 return Property;
516}
517
Francois Pichet783dd6e2010-11-21 06:08:52 +0000518Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
519 NamedDecl **NamedChain =
520 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
521
522 int i = 0;
523 for (IndirectFieldDecl::chain_iterator PI =
524 D->chain_begin(), PE = D->chain_end();
Douglas Gregor55e6b312011-03-04 19:46:35 +0000525 PI != PE; ++PI) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000526 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000527 TemplateArgs);
528 if (!Next)
529 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000530
Douglas Gregor55e6b312011-03-04 19:46:35 +0000531 NamedChain[i++] = Next;
532 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000533
Francois Pichetdbafc192010-12-09 10:07:54 +0000534 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000535 IndirectFieldDecl* IndirectField
536 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000537 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000538 NamedChain, D->getChainingSize());
539
540
541 IndirectField->setImplicit(D->isImplicit());
542 IndirectField->setAccess(D->getAccess());
543 Owner->addDecl(IndirectField);
544 return IndirectField;
545}
546
John McCallaa74a0c2009-08-28 07:59:38 +0000547Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000548 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000549 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000550 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000551 TypeSourceInfo *InstTy;
552 // If this is an unsupported friend, don't bother substituting template
553 // arguments into it. The actual type referred to won't be used by any
554 // parts of Clang, and may not be valid for instantiating. Just use the
555 // same info for the instantiated friend.
556 if (D->isUnsupportedFriend()) {
557 InstTy = Ty;
558 } else {
559 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
560 D->getLocation(), DeclarationName());
561 }
562 if (!InstTy)
Douglas Gregor33636e62009-12-24 20:56:24 +0000563 return 0;
John McCallaa74a0c2009-08-28 07:59:38 +0000564
Richard Smitha31a89a2012-09-20 01:31:00 +0000565 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000566 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000567 if (!FD)
568 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000569
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000570 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000571 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000572 Owner->addDecl(FD);
573 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000574 }
575
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000576 NamedDecl *ND = D->getFriendDecl();
577 assert(ND && "friend decl must be a decl or a type!");
578
John McCallb9c78482010-04-08 09:05:18 +0000579 // All of the Visit implementations for the various potential friend
580 // declarations have to be carefully written to work for friend
581 // objects, with the most important detail being that the target
582 // decl should almost certainly not be placed in Owner.
583 Decl *NewND = Visit(ND);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000584 if (!NewND) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000585
John McCallaa74a0c2009-08-28 07:59:38 +0000586 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000587 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000588 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000589 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000590 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000591 Owner->addDecl(FD);
592 return FD;
John McCall58de3582009-08-14 02:03:10 +0000593}
594
Douglas Gregord7e7a512009-03-17 21:15:40 +0000595Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
596 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000597
Richard Smith764d2fe2011-12-20 02:08:33 +0000598 // The expression in a static assertion is a constant expression.
599 EnterExpressionEvaluationContext Unevaluated(SemaRef,
600 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000601
John McCalldadc5752010-08-24 06:29:42 +0000602 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000603 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000604 if (InstantiatedAssertExpr.isInvalid())
605 return 0;
606
Richard Smithded9c2e2012-07-11 22:37:56 +0000607 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000608 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000609 D->getMessage(),
610 D->getRParenLoc(),
611 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000612}
613
614Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith2e6610a2012-03-26 04:58:10 +0000615 EnumDecl *PrevDecl = 0;
616 if (D->getPreviousDecl()) {
617 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
618 D->getPreviousDecl(),
619 TemplateArgs);
620 if (!Prev) return 0;
621 PrevDecl = cast<EnumDecl>(Prev);
622 }
623
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000624 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000625 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000626 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000627 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000628 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000629 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000630 // If we have type source information for the underlying type, it means it
631 // has been explicitly set by the user. Perform substitution on it before
632 // moving on.
633 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000634 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
635 DeclarationName());
636 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000637 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000638 else
639 Enum->setIntegerTypeSourceInfo(NewTI);
640 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000641 assert(!D->getIntegerType()->isDependentType()
642 && "Dependent type without type source info");
643 Enum->setIntegerType(D->getIntegerType());
644 }
645 }
646
John McCall811a0f52010-10-22 23:36:17 +0000647 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
648
Richard Smith4b38ded2012-03-14 23:13:10 +0000649 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000650 Enum->setAccess(D->getAccess());
David Majnemerdbc0c8f2013-12-04 09:01:55 +0000651 // Forward the mangling number from the template to the instantiated decl.
652 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
John McCall3e11ebe2010-03-15 10:12:16 +0000653 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000654 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000655
Richard Smith258a7442012-03-26 04:08:46 +0000656 EnumDecl *Def = D->getDefinition();
657 if (Def && Def != D) {
658 // If this is an out-of-line definition of an enum member template, check
659 // that the underlying types match in the instantiation of both
660 // declarations.
661 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
662 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
663 QualType DefnUnderlying =
664 SemaRef.SubstType(TI->getType(), TemplateArgs,
665 UnderlyingLoc, DeclarationName());
666 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
667 DefnUnderlying, Enum);
668 }
669 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000670
Richard Smith4b38ded2012-03-14 23:13:10 +0000671 // C++11 [temp.inst]p1: The implicit instantiation of a class template
672 // specialization causes the implicit instantiation of the declarations, but
673 // not the definitions of scoped member enumerations.
David Majnemer192d1792013-11-27 08:20:38 +0000674 //
675 // DR1484 clarifies that enumeration definitions inside of a template
676 // declaration aren't considered entities that can be separately instantiated
677 // from the rest of the entity they are declared inside of.
678 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
679 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
Richard Smith258a7442012-03-26 04:08:46 +0000680 InstantiateEnumDefinition(Enum, Def);
David Majnemer192d1792013-11-27 08:20:38 +0000681 }
Richard Smith4b38ded2012-03-14 23:13:10 +0000682
683 return Enum;
684}
685
686void TemplateDeclInstantiator::InstantiateEnumDefinition(
687 EnumDecl *Enum, EnumDecl *Pattern) {
688 Enum->startDefinition();
689
Richard Smith7d137e32012-03-23 03:33:32 +0000690 // Update the location to refer to the definition.
691 Enum->setLocation(Pattern->getLocation());
692
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000693 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000694
695 EnumConstantDecl *LastEnumConst = 0;
Richard Smith4b38ded2012-03-14 23:13:10 +0000696 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
697 ECEnd = Pattern->enumerator_end();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000698 EC != ECEnd; ++EC) {
699 // The specified value for the enumerator.
John McCalldadc5752010-08-24 06:29:42 +0000700 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000701 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000702 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000703 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000704 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000705
John McCall76d824f2009-08-25 22:02:44 +0000706 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000707 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000708
709 // Drop the initial value and continue.
710 bool isInvalid = false;
711 if (Value.isInvalid()) {
712 Value = SemaRef.Owned((Expr *)0);
713 isInvalid = true;
714 }
715
Mike Stump11289f42009-09-09 15:08:12 +0000716 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000717 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
718 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000719 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000720
721 if (isInvalid) {
722 if (EnumConst)
723 EnumConst->setInvalidDecl();
724 Enum->setInvalidDecl();
725 }
726
727 if (EnumConst) {
David Blaikie40ed2972012-06-06 20:45:41 +0000728 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000729
John McCallf9b528c2010-01-23 22:37:59 +0000730 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000731 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000732 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000733 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000734
Richard Smith4b38ded2012-03-14 23:13:10 +0000735 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
736 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000737 // If the enumeration is within a function or method, record the enum
738 // constant as a local.
David Blaikie40ed2972012-06-06 20:45:41 +0000739 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000740 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000741 }
742 }
Mike Stump11289f42009-09-09 15:08:12 +0000743
Richard Smith4b38ded2012-03-14 23:13:10 +0000744 // FIXME: Fixup LBraceLoc
745 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
746 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000747 Enumerators,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +0000748 0, 0);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000749}
750
Douglas Gregor9106b822009-03-25 15:04:13 +0000751Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000752 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000753}
754
John McCall87a44eb2009-08-20 01:44:21 +0000755Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000756 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
757
Douglas Gregor954de172009-10-31 17:21:17 +0000758 // Create a local instantiation scope for this class template, which
759 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000760 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000761 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000762 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000763 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000764 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +0000765
766 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000767
768 // Instantiate the qualifier. We have to do this first in case
769 // we're a friend declaration, because if we are then we need to put
770 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000771 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
772 if (QualifierLoc) {
773 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
774 TemplateArgs);
775 if (!QualifierLoc)
776 return 0;
John McCall598b4402010-03-25 06:39:04 +0000777 }
778
779 CXXRecordDecl *PrevDecl = 0;
780 ClassTemplateDecl *PrevClassTemplate = 0;
781
Douglas Gregorec9fd132012-01-14 16:38:05 +0000782 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000783 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000784 if (!Found.empty()) {
785 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000786 if (PrevClassTemplate)
787 PrevDecl = PrevClassTemplate->getTemplatedDecl();
788 }
789 }
790
John McCall598b4402010-03-25 06:39:04 +0000791 // If this isn't a friend, then it's a member template, in which
792 // case we just want to build the instantiation in the
793 // specialization. If it is a friend, we want to build it in
794 // the appropriate context.
795 DeclContext *DC = Owner;
796 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000797 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000798 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000799 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000800 DC = SemaRef.computeDeclContext(SS);
801 if (!DC) return 0;
802 } else {
803 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
804 Pattern->getDeclContext(),
805 TemplateArgs);
806 }
807
808 // Look for a previous declaration of the template in the owning
809 // context.
810 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
811 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
812 SemaRef.LookupQualifiedName(R, DC);
813
814 if (R.isSingleResult()) {
815 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
816 if (PrevClassTemplate)
817 PrevDecl = PrevClassTemplate->getTemplatedDecl();
818 }
819
Douglas Gregor14454802011-02-25 02:25:35 +0000820 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000821 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000822 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000823 << QualifierLoc.getSourceRange();
John McCall598b4402010-03-25 06:39:04 +0000824 return 0;
825 }
826
Douglas Gregor01e09d92010-04-08 18:16:15 +0000827 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000828 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000829 bool Complain = true;
830
831 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
832 // template for struct std::tr1::__detail::_Map_base, where the
833 // template parameters of the friend declaration don't match the
834 // template parameters of the original declaration. In this one
835 // case, we don't complain about the ill-formed friend
836 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000837 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000838 Pattern->getIdentifier()->isStr("_Map_base") &&
839 DC->isNamespace() &&
840 cast<NamespaceDecl>(DC)->getIdentifier() &&
841 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
842 DeclContext *DCParent = DC->getParent();
843 if (DCParent->isNamespace() &&
844 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
845 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
846 DeclContext *DCParent2 = DCParent->getParent();
847 if (DCParent2->isNamespace() &&
848 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
849 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
850 DCParent2->getParent()->isTranslationUnit())
851 Complain = false;
852 }
853 }
854
John McCall598b4402010-03-25 06:39:04 +0000855 TemplateParameterList *PrevParams
856 = PrevClassTemplate->getTemplateParameters();
857
858 // Make sure the parameter lists match.
859 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000860 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000861 Sema::TPL_TemplateMatch)) {
862 if (Complain)
863 return 0;
864
865 AdoptedPreviousTemplateParams = true;
866 InstParams = PrevParams;
867 }
John McCall598b4402010-03-25 06:39:04 +0000868
869 // Do some additional validation, then merge default arguments
870 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000871 if (!AdoptedPreviousTemplateParams &&
872 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000873 Sema::TPC_ClassTemplate))
874 return 0;
875 }
876 }
877
John McCall87a44eb2009-08-20 01:44:21 +0000878 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000879 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000880 Pattern->getLocStart(), Pattern->getLocation(),
881 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000882 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000883
Douglas Gregor14454802011-02-25 02:25:35 +0000884 if (QualifierLoc)
885 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000886
John McCall87a44eb2009-08-20 01:44:21 +0000887 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000888 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
889 D->getIdentifier(), InstParams, RecordInst,
890 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000891 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000892
John McCall598b4402010-03-25 06:39:04 +0000893 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000894 if (PrevClassTemplate)
895 Inst->setAccess(PrevClassTemplate->getAccess());
896 else
897 Inst->setAccess(D->getAccess());
898
Richard Smith64017682013-07-17 23:53:16 +0000899 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000900 // TODO: do we want to track the instantiation progeny of this
901 // friend target decl?
902 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000903 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000904 if (!PrevClassTemplate)
905 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000906 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000907
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000908 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000909 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000910 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000911
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000912 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000913 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000914 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000915 Inst->setLexicalDeclContext(Owner);
916 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000917 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000918 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000919
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000920 if (D->isOutOfLine()) {
921 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
922 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
923 }
924
John McCall87a44eb2009-08-20 01:44:21 +0000925 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000926
927 if (!PrevClassTemplate) {
928 // Queue up any out-of-line partial specializations of this member
929 // class template; the client will force their instantiation once
930 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000931 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000932 D->getPartialSpecializations(PartialSpecs);
933 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +0000934 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Douglas Gregor869853e2010-11-10 19:44:59 +0000935 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
936 }
937
John McCall87a44eb2009-08-20 01:44:21 +0000938 return Inst;
939}
940
Douglas Gregore704c9d2009-08-27 16:57:43 +0000941Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000942TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
943 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000944 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000945
Douglas Gregor21610382009-10-29 00:04:11 +0000946 // Lookup the already-instantiated declaration in the instantiation
947 // of the class template and return that.
948 DeclContext::lookup_result Found
949 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000950 if (Found.empty())
Douglas Gregor21610382009-10-29 00:04:11 +0000951 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000952
Douglas Gregor21610382009-10-29 00:04:11 +0000953 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +0000954 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +0000955 if (!InstClassTemplate)
956 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000957
Douglas Gregor869853e2010-11-10 19:44:59 +0000958 if (ClassTemplatePartialSpecializationDecl *Result
959 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
960 return Result;
961
962 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +0000963}
964
Larisse Voufo39a1e502013-08-06 01:03:05 +0000965Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
966 assert(D->getTemplatedDecl()->isStaticDataMember() &&
967 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +0000968
969 // Create a local instantiation scope for this variable template, which
970 // will contain the instantiations of the template parameters.
971 LocalInstantiationScope Scope(SemaRef);
972 TemplateParameterList *TempParams = D->getTemplateParameters();
973 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
974 if (!InstParams)
975 return NULL;
976
977 VarDecl *Pattern = D->getTemplatedDecl();
978 VarTemplateDecl *PrevVarTemplate = 0;
979
980 if (Pattern->getPreviousDecl()) {
981 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
982 if (!Found.empty())
983 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
984 }
985
Richard Smith1c34fb72013-08-13 18:18:50 +0000986 VarDecl *VarInst =
Larisse Voufo72caf2b2013-08-22 00:59:14 +0000987 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
988 /*InstantiatingVarTemplate=*/true));
Larisse Voufo39a1e502013-08-06 01:03:05 +0000989
990 DeclContext *DC = Owner;
991
Larisse Voufo39a1e502013-08-06 01:03:05 +0000992 VarTemplateDecl *Inst = VarTemplateDecl::Create(
993 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
994 VarInst, PrevVarTemplate);
995 VarInst->setDescribedVarTemplate(Inst);
996
997 Inst->setAccess(D->getAccess());
998 if (!PrevVarTemplate)
999 Inst->setInstantiatedFromMemberTemplate(D);
1000
1001 if (D->isOutOfLine()) {
1002 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1003 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1004 }
1005
1006 Owner->addDecl(Inst);
1007
1008 if (!PrevVarTemplate) {
1009 // Queue up any out-of-line partial specializations of this member
1010 // variable template; the client will force their instantiation once
1011 // the enclosing class has been instantiated.
1012 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1013 D->getPartialSpecializations(PartialSpecs);
1014 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
Rafael Espindola8db352d2013-10-17 15:37:26 +00001015 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00001016 OutOfLineVarPartialSpecs.push_back(
1017 std::make_pair(Inst, PartialSpecs[I]));
1018 }
1019
1020 return Inst;
1021}
1022
1023Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1024 VarTemplatePartialSpecializationDecl *D) {
1025 assert(D->isStaticDataMember() &&
1026 "Only static data member templates are allowed.");
Larisse Voufo39a1e502013-08-06 01:03:05 +00001027
1028 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1029
1030 // Lookup the already-instantiated declaration and return that.
1031 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1032 assert(!Found.empty() && "Instantiation found nothing?");
1033
1034 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1035 assert(InstVarTemplate && "Instantiation did not find a variable template?");
1036
1037 if (VarTemplatePartialSpecializationDecl *Result =
1038 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1039 return Result;
1040
1041 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1042}
1043
Douglas Gregore4b05162009-10-07 17:21:34 +00001044Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001045TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001046 // Create a local instantiation scope for this function template, which
1047 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001048 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001049 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001050 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001051
Douglas Gregore704c9d2009-08-27 16:57:43 +00001052 TemplateParameterList *TempParams = D->getTemplateParameters();
1053 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001054 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001055 return NULL;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001056
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001057 FunctionDecl *Instantiated = 0;
1058 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001059 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001060 InstParams));
1061 else
1062 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001063 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001064 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001065
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001066 if (!Instantiated)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001067 return 0;
1068
Mike Stump11289f42009-09-09 15:08:12 +00001069 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001070 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001071 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001072 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001073 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001074 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001075 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001076
John McCall30837102010-03-26 23:10:15 +00001077 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1078
John McCall2079d0b2009-12-14 23:19:40 +00001079 // Link the instantiation back to the pattern *unless* this is a
1080 // non-definition friend declaration.
1081 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001082 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001083 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001084
John McCall30837102010-03-26 23:10:15 +00001085 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001086 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001087 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001088 } else if (InstTemplate->getDeclContext()->isRecord() &&
1089 !D->getPreviousDecl()) {
1090 SemaRef.CheckFriendAccess(InstTemplate);
1091 }
John McCall30837102010-03-26 23:10:15 +00001092
Douglas Gregore704c9d2009-08-27 16:57:43 +00001093 return InstTemplate;
1094}
1095
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001096Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1097 CXXRecordDecl *PrevDecl = 0;
1098 if (D->isInjectedClassName())
1099 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001100 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001101 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001102 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001103 TemplateArgs);
1104 if (!Prev) return 0;
1105 PrevDecl = cast<CXXRecordDecl>(Prev);
1106 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001107
1108 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001109 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001110 D->getLocStart(), D->getLocation(),
1111 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001112
1113 // Substitute the nested name specifier, if any.
1114 if (SubstQualifier(D, Record))
1115 return 0;
1116
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001117 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001118 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1119 // the tag decls introduced by friend class declarations don't have an access
1120 // specifier. Remove once this area of the code gets sorted out.
1121 if (D->getAccess() != AS_none)
1122 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001123 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001124 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001125
John McCallaa74a0c2009-08-28 07:59:38 +00001126 // If the original function was part of a friend declaration,
1127 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001128 if (D->getFriendObjectKind())
1129 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001130
Douglas Gregor04163182010-05-21 00:31:19 +00001131 // Make sure that anonymous structs and unions are recorded.
David Majnemer192d1792013-11-27 08:20:38 +00001132 if (D->isAnonymousStructOrUnion())
Douglas Gregor04163182010-05-21 00:31:19 +00001133 Record->setAnonymousStructOrUnion(true);
David Majnemer192d1792013-11-27 08:20:38 +00001134
1135 if (D->isLocalClass())
1136 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
Anders Carlsson5da84842009-09-01 04:26:58 +00001137
David Majnemerdbc0c8f2013-12-04 09:01:55 +00001138 // Forward the mangling number from the template to the instantiated decl.
1139 SemaRef.Context.setManglingNumber(Record,
1140 SemaRef.Context.getManglingNumber(D));
1141
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001142 Owner->addDecl(Record);
David Majnemer192d1792013-11-27 08:20:38 +00001143
1144 // DR1484 clarifies that the members of a local class are instantiated as part
1145 // of the instantiation of their enclosing entity.
1146 if (D->isCompleteDefinition() && D->isLocalClass()) {
1147 if (SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1148 TSK_ImplicitInstantiation,
1149 /*Complain=*/true)) {
1150 llvm_unreachable("InstantiateClass shouldn't fail here!");
1151 } else {
1152 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1153 TSK_ImplicitInstantiation);
1154 }
1155 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001156 return Record;
1157}
1158
Douglas Gregor89f593a2012-09-13 21:56:43 +00001159/// \brief Adjust the given function type for an instantiation of the
1160/// given declaration, to cope with modifications to the function's type that
1161/// aren't reflected in the type-source information.
1162///
1163/// \param D The declaration we're instantiating.
1164/// \param TInfo The already-instantiated type.
1165static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1166 FunctionDecl *D,
1167 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001168 const FunctionProtoType *OrigFunc
1169 = D->getType()->castAs<FunctionProtoType>();
1170 const FunctionProtoType *NewFunc
1171 = TInfo->getType()->castAs<FunctionProtoType>();
1172 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1173 return TInfo->getType();
1174
1175 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1176 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1177 return Context.getFunctionType(NewFunc->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00001178 NewFunc->getArgTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001179}
1180
John McCallaa74a0c2009-08-28 07:59:38 +00001181/// Normal class members are of more specific types and therefore
1182/// don't make it here. This function serves two purposes:
1183/// 1) instantiating function templates
1184/// 2) substituting friend declarations
1185/// FIXME: preserve function definitions in case #2
Douglas Gregor33636e62009-12-24 20:56:24 +00001186Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001187 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001188 // Check whether there is already a function template specialization for
1189 // this declaration.
1190 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001191 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001192 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001193
Douglas Gregorce9978f2012-03-28 14:34:23 +00001194 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001195 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001196 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001197 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001198
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001199 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001200 if (SpecFunc)
1201 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001202 }
Mike Stump11289f42009-09-09 15:08:12 +00001203
John McCall2f88d7d2010-03-27 05:57:59 +00001204 bool isFriend;
1205 if (FunctionTemplate)
1206 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1207 else
1208 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1209
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001210 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001211 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001212 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001213 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001214 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001215
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001216 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001217 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001218 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001219 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001220 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001221
Douglas Gregor14454802011-02-25 02:25:35 +00001222 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1223 if (QualifierLoc) {
1224 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1225 TemplateArgs);
1226 if (!QualifierLoc)
1227 return 0;
John McCalle0b2ddb2010-03-26 04:53:08 +00001228 }
1229
John McCallce410662010-02-06 01:50:47 +00001230 // If we're instantiating a local function declaration, put the result
Richard Smith541b38b2013-09-20 01:15:31 +00001231 // in the enclosing namespace; otherwise we need to find the instantiated
1232 // context.
John McCallce410662010-02-06 01:50:47 +00001233 DeclContext *DC;
Richard Smith541b38b2013-09-20 01:15:31 +00001234 if (D->isLocalExternDecl()) {
John McCallce410662010-02-06 01:50:47 +00001235 DC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001236 SemaRef.adjustContextForLocalExternDecl(DC);
1237 } else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001238 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001239 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001240 DC = SemaRef.computeDeclContext(SS);
1241 if (!DC) return 0;
1242 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001243 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001244 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001245 }
John McCallce410662010-02-06 01:50:47 +00001246
John McCallaa74a0c2009-08-28 07:59:38 +00001247 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001248 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001249 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001250 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001251 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001252 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001253 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001254
Richard Smithf3814ad2013-01-25 00:08:28 +00001255 if (D->isInlined())
1256 Function->setImplicitlyInline();
1257
Douglas Gregor14454802011-02-25 02:25:35 +00001258 if (QualifierLoc)
1259 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001260
Richard Smith541b38b2013-09-20 01:15:31 +00001261 if (D->isLocalExternDecl())
1262 Function->setLocalExternDecl();
1263
John McCall30837102010-03-26 23:10:15 +00001264 DeclContext *LexicalDC = Owner;
Richard Smith541b38b2013-09-20 01:15:31 +00001265 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
John McCall30837102010-03-26 23:10:15 +00001266 assert(D->getDeclContext()->isFileContext());
1267 LexicalDC = D->getDeclContext();
1268 }
1269
1270 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001271
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001272 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001273 for (unsigned P = 0; P < Params.size(); ++P)
1274 if (Params[P])
1275 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001276 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001277
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001278 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001279 if (TemplateParams) {
1280 // Our resulting instantiation is actually a function template, since we
1281 // are substituting only the outer template parameters. For example, given
1282 //
1283 // template<typename T>
1284 // struct X {
1285 // template<typename U> friend void f(T, U);
1286 // };
1287 //
1288 // X<int> x;
1289 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001290 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001291 // which means substituting int for T, but leaving "f" as a friend function
1292 // template.
1293 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001294 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001295 Function->getLocation(),
1296 Function->getDeclName(),
1297 TemplateParams, Function);
1298 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001299
1300 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001301
1302 if (isFriend && D->isThisDeclarationADefinition()) {
1303 // TODO: should we remember this connection regardless of whether
1304 // the friend declaration provided a body?
1305 FunctionTemplate->setInstantiatedFromMemberTemplate(
1306 D->getDescribedFunctionTemplate());
1307 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001308 } else if (FunctionTemplate) {
1309 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001310 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001311 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001312 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001313 Innermost.begin(),
1314 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001315 /*InsertPos=*/0);
Chandler Carruth48b28312011-08-18 09:09:59 +00001316 } else if (isFriend) {
1317 // Note, we need this connection even if the friend doesn't have a body.
1318 // Its body may exist but not have been attached yet due to deferred
1319 // parsing.
1320 // FIXME: It might be cleaner to set this when attaching the body to the
1321 // friend function declaration, however that would require finding all the
1322 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001323 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001324 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001325
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001326 if (InitFunctionInstantiation(Function, D))
1327 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001328
John McCallb9c78482010-04-08 09:05:18 +00001329 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001330
Richard Smith541b38b2013-09-20 01:15:31 +00001331 LookupResult Previous(
1332 SemaRef, Function->getDeclName(), SourceLocation(),
1333 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
1334 : Sema::LookupOrdinaryName,
1335 Sema::ForRedeclaration);
John McCall1f82f242009-11-18 22:49:29 +00001336
John McCallb9c78482010-04-08 09:05:18 +00001337 if (DependentFunctionTemplateSpecializationInfo *Info
1338 = D->getDependentSpecializationInfo()) {
1339 assert(isFriend && "non-friend has dependent specialization info?");
1340
1341 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001342 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001343
1344 // Instantiate the explicit template arguments.
1345 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1346 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001347 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1348 ExplicitArgs, TemplateArgs))
1349 return 0;
John McCallb9c78482010-04-08 09:05:18 +00001350
1351 // Map the candidate templates to their instantiations.
1352 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1353 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1354 Info->getTemplate(I),
1355 TemplateArgs);
1356 if (!Temp) return 0;
1357
1358 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1359 }
1360
1361 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1362 &ExplicitArgs,
1363 Previous))
1364 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001365
John McCallb9c78482010-04-08 09:05:18 +00001366 isExplicitSpecialization = true;
1367
1368 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001369 // Look only into the namespace where the friend would be declared to
1370 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001371 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001372 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001373
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001374 // In C++, the previous declaration we find might be a tag type
1375 // (class or enum). In this case, the new declaration will hide the
1376 // tag type. Note that this does does not apply if we're declaring a
1377 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001378 if (Previous.isSingleTagDecl())
1379 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001380 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001381
John McCall84d87672009-12-10 09:41:52 +00001382 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001383 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001384
John McCallb9467b62010-04-24 01:30:58 +00001385 NamedDecl *PrincipalDecl = (TemplateParams
1386 ? cast<NamedDecl>(FunctionTemplate)
1387 : Function);
1388
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001389 // If the original function was part of a friend declaration,
1390 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001391 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001392 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001393 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001394
Gabor Greif12866172010-08-30 22:25:56 +00001395 bool queuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001396
Richard Smitha066ccf2011-10-19 00:54:10 +00001397 // C++98 [temp.friend]p5: When a function is defined in a friend function
1398 // declaration in a class template, the function is defined at each
1399 // instantiation of the class template. The function is defined even if it
1400 // is never used.
1401 // C++11 [temp.friend]p4: When a function is defined in a friend function
1402 // declaration in a class template, the function is instantiated when the
1403 // function is odr-used.
1404 //
1405 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1406 // redefinition, but don't instantiate the function.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001407 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smitha066ccf2011-10-19 00:54:10 +00001408 SemaRef.Diags.getDiagnosticLevel(
1409 diag::warn_cxx98_compat_friend_redefinition,
1410 Function->getLocation())
1411 != DiagnosticsEngine::Ignored) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001412 D->isThisDeclarationADefinition()) {
1413 // Check for a function body.
1414 const FunctionDecl *Definition = 0;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001415 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001416 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smitha066ccf2011-10-19 00:54:10 +00001417 SemaRef.Diag(Function->getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001418 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smitha066ccf2011-10-19 00:54:10 +00001419 diag::warn_cxx98_compat_friend_redefinition :
1420 diag::err_redefinition) << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001421 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001422 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smitha066ccf2011-10-19 00:54:10 +00001423 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001424 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001425 // Check for redefinitions due to other instantiations of this or
1426 // a similar friend function.
1427 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1428 REnd = Function->redecls_end();
1429 R != REnd; ++R) {
Gabor Greif122f1eb2010-08-28 15:42:30 +00001430 if (*R == Function)
1431 continue;
Gabor Greif718d5152010-08-30 21:10:05 +00001432 switch (R->getFriendObjectKind()) {
1433 case Decl::FOK_None:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001434 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smitha066ccf2011-10-19 00:54:10 +00001435 !queuedInstantiation && R->isUsed(false)) {
Gabor Greif718d5152010-08-30 21:10:05 +00001436 if (MemberSpecializationInfo *MSInfo
1437 = Function->getMemberSpecializationInfo()) {
1438 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1439 SourceLocation Loc = R->getLocation(); // FIXME
1440 MSInfo->setPointOfInstantiation(Loc);
1441 SemaRef.PendingLocalImplicitInstantiations.push_back(
1442 std::make_pair(Function, Loc));
1443 queuedInstantiation = true;
1444 }
1445 }
1446 }
1447 break;
1448 default:
Douglas Gregorb92ea592010-05-18 05:45:02 +00001449 if (const FunctionDecl *RPattern
Gabor Greifae849e42010-08-28 15:46:56 +00001450 = R->getTemplateInstantiationPattern())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001451 if (RPattern->isDefined(RPattern)) {
Richard Smitha066ccf2011-10-19 00:54:10 +00001452 SemaRef.Diag(Function->getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001453 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smitha066ccf2011-10-19 00:54:10 +00001454 diag::warn_cxx98_compat_friend_redefinition :
1455 diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001456 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001457 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001458 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smitha066ccf2011-10-19 00:54:10 +00001459 Function->setInvalidDecl();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001460 break;
1461 }
1462 }
1463 }
1464 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001465 }
1466
Richard Smith541b38b2013-09-20 01:15:31 +00001467 if (Function->isLocalExternDecl() && !Function->getPreviousDecl())
1468 DC->makeDeclVisibleInContext(PrincipalDecl);
1469
John McCallb9467b62010-04-24 01:30:58 +00001470 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1471 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1472 PrincipalDecl->setNonMemberOperator();
1473
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001474 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001475 return Function;
1476}
1477
Douglas Gregore704c9d2009-08-27 16:57:43 +00001478Decl *
1479TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001480 TemplateParameterList *TemplateParams,
1481 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001482 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001483 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001484 // We are creating a function template specialization from a function
1485 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001486 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001487 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001488
Douglas Gregorce9978f2012-03-28 14:34:23 +00001489 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001490 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001491 = FunctionTemplate->findSpecialization(Innermost.begin(),
1492 Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001493 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001494
Douglas Gregor97628d62009-08-21 00:16:32 +00001495 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001496 if (SpecFunc)
1497 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001498 }
1499
John McCall2f88d7d2010-03-27 05:57:59 +00001500 bool isFriend;
1501 if (FunctionTemplate)
1502 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1503 else
1504 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1505
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001506 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001507 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001508 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001509 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001510
John McCalld0e23ec2010-10-19 02:26:41 +00001511 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001512 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001513 unsigned NumTempParamLists = 0;
1514 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1515 TempParamLists.set_size(NumTempParamLists);
1516 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1517 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1518 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1519 if (!InstParams)
1520 return NULL;
1521 TempParamLists[I] = InstParams;
1522 }
1523 }
1524
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001525 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001526 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001527 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001528 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001529 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001530
Douglas Gregor14454802011-02-25 02:25:35 +00001531 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1532 if (QualifierLoc) {
1533 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001534 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001535 if (!QualifierLoc)
Douglas Gregor14454802011-02-25 02:25:35 +00001536 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001537 }
1538
1539 DeclContext *DC = Owner;
1540 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001541 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001542 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001543 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001544 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001545
1546 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1547 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001548 } else {
1549 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1550 D->getDeclContext(),
1551 TemplateArgs);
1552 }
1553 if (!DC) return 0;
1554 }
1555
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001556 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001557 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001558 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001559
Abramo Bagnaradff19302011-03-08 08:55:46 +00001560 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001561 DeclarationNameInfo NameInfo
1562 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001563 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001564 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001565 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001566 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001567 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001568 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001569
Richard Smith185be182013-04-10 05:48:59 +00001570 // Claim that the instantiation of a constructor or constructor template
1571 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001572 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1573 Constructor->getInheritedConstructor())) {
1574 // If we're instantiating a specialization of a function template, our
1575 // "inherited constructor" will actually itself be a function template.
1576 // Instantiate a declaration of it, too.
1577 if (FunctionTemplate) {
1578 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1579 !Inh->getParent()->isDependentContext() &&
1580 "inheriting constructor template in dependent context?");
1581 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1582 Inh);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001583 if (Inst.isInvalid())
Richard Smith4c163a02013-05-17 02:19:35 +00001584 return 0;
1585 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1586 LocalInstantiationScope LocalScope(SemaRef);
1587
1588 // Use the same template arguments that we deduced for the inheriting
1589 // constructor. There's no way they could be deduced differently.
1590 MultiLevelTemplateArgumentList InheritedArgs;
1591 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1592 Inh = cast_or_null<CXXConstructorDecl>(
1593 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1594 if (!Inh)
1595 return 0;
1596 }
Richard Smith185be182013-04-10 05:48:59 +00001597 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001598 }
Douglas Gregore8394862009-08-21 22:43:28 +00001599 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001600 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001601 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001602 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001603 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001604 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001605 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001606 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001607 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001608 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001609 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001610 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001611 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001612 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001613 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001614 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001615 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001616 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001617 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001618
Richard Smithf3814ad2013-01-25 00:08:28 +00001619 if (D->isInlined())
1620 Method->setImplicitlyInline();
1621
Douglas Gregor14454802011-02-25 02:25:35 +00001622 if (QualifierLoc)
1623 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001624
Douglas Gregore704c9d2009-08-27 16:57:43 +00001625 if (TemplateParams) {
1626 // Our resulting instantiation is actually a function template, since we
1627 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001628 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001629 // template<typename T>
1630 // struct X {
1631 // template<typename U> void f(T, U);
1632 // };
1633 //
1634 // X<int> x;
1635 //
1636 // We are instantiating the member template "f" within X<int>, which means
1637 // substituting int for T, but leaving "f" as a member function template.
1638 // Build the function template itself.
1639 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1640 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001641 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001642 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001643 if (isFriend) {
1644 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001645 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001646 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001647 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001648 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001649 } else if (FunctionTemplate) {
1650 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001651 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001652 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001653 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001654 Innermost.begin(),
1655 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001656 /*InsertPos=*/0);
John McCall2f88d7d2010-03-27 05:57:59 +00001657 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001658 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001659 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001660 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001661
Mike Stump11289f42009-09-09 15:08:12 +00001662 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001663 // out-of-line, the instantiation will have the same lexical
1664 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001665 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001666 if (NumTempParamLists)
1667 Method->setTemplateParameterListsInfo(SemaRef.Context,
1668 NumTempParamLists,
1669 TempParamLists.data());
1670
John McCall2f88d7d2010-03-27 05:57:59 +00001671 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001672 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001673 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001674 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001675
Douglas Gregor21342092009-03-24 00:38:23 +00001676 // Attach the parameters
1677 for (unsigned P = 0; P < Params.size(); ++P)
1678 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001679 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001680
1681 if (InitMethodInstantiation(Method, D))
1682 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001683
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001684 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1685 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001686
John McCall2f88d7d2010-03-27 05:57:59 +00001687 if (!FunctionTemplate || TemplateParams || isFriend) {
1688 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001689
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001690 // In C++, the previous declaration we find might be a tag type
1691 // (class or enum). In this case, the new declaration will hide the
1692 // tag type. Note that this does does not apply if we're declaring a
1693 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001694 if (Previous.isSingleTagDecl())
1695 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001696 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001697
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001698 if (!IsClassScopeSpecialization)
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001699 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001700
Douglas Gregor21920e372009-12-01 17:24:26 +00001701 if (D->isPure())
1702 SemaRef.CheckPureMethod(Method, SourceRange());
1703
John McCalla0a96892012-08-10 03:15:35 +00001704 // Propagate access. For a non-friend declaration, the access is
1705 // whatever we're propagating from. For a friend, it should be the
1706 // previous declaration we just found.
1707 if (isFriend && Method->getPreviousDecl())
1708 Method->setAccess(Method->getPreviousDecl()->getAccess());
1709 else
1710 Method->setAccess(D->getAccess());
1711 if (FunctionTemplate)
1712 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001713
Anders Carlsson7c812f52011-01-20 06:52:44 +00001714 SemaRef.CheckOverrideControl(Method);
1715
Eli Friedman41340732011-11-15 22:39:08 +00001716 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001717 if (D->isExplicitlyDefaulted())
1718 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001719 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001720 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001721
John McCalla0a96892012-08-10 03:15:35 +00001722 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001723 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001724 // do nothing
1725
1726 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001727 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001728 // do nothing
1729
1730 // Otherwise, check access to friends and make them visible.
1731 } else if (isFriend) {
1732 // We only need to re-check access for methods which we didn't
1733 // manage to match during parsing.
1734 if (!D->getPreviousDecl())
1735 SemaRef.CheckFriendAccess(Method);
1736
1737 Record->makeDeclVisibleInContext(Method);
1738
1739 // Otherwise, add the declaration. We don't need to do this for
1740 // class-scope specializations because we'll have matched them with
1741 // the appropriate template.
1742 } else if (!IsClassScopeSpecialization) {
1743 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001744 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001745
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001746 return Method;
1747}
1748
Douglas Gregor4044d992009-03-24 16:43:20 +00001749Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001750 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001751}
1752
Douglas Gregor654b07e2009-03-24 00:15:49 +00001753Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001754 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001755}
1756
Douglas Gregor1880ba52009-03-25 00:34:44 +00001757Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001758 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001759}
1760
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001761Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001762 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1763 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001764}
1765
John McCall87a44eb2009-08-20 01:44:21 +00001766Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1767 TemplateTypeParmDecl *D) {
1768 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001769 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001770
John McCall87a44eb2009-08-20 01:44:21 +00001771 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001772 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1773 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001774 D->getDepth() - TemplateArgs.getNumLevels(),
1775 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001776 D->wasDeclaredWithTypename(),
1777 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001778 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001779
David Majnemer89189202013-08-28 23:48:32 +00001780 if (D->hasDefaultArgument()) {
1781 TypeSourceInfo *InstantiatedDefaultArg =
1782 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
1783 D->getDefaultArgumentLoc(), D->getDeclName());
1784 if (InstantiatedDefaultArg)
1785 Inst->setDefaultArgument(InstantiatedDefaultArg, false);
1786 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001787
1788 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001789 // scope.
1790 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001791
John McCall87a44eb2009-08-20 01:44:21 +00001792 return Inst;
1793}
1794
Douglas Gregor6b815c82009-10-23 23:25:44 +00001795Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1796 NonTypeTemplateParmDecl *D) {
1797 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001798 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001799 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1800 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001801 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001802 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001803 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001804 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001805
1806 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001807 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001808 // expansion of types. Substitute into each of the expanded types.
1809 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1810 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1811 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1812 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1813 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001814 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001815 D->getDeclName());
1816 if (!NewDI)
1817 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001818
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001819 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1820 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1821 D->getLocation());
1822 if (NewT.isNull())
1823 return 0;
1824 ExpandedParameterPackTypes.push_back(NewT);
1825 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001826
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001827 IsExpandedParameterPack = true;
1828 DI = D->getTypeSourceInfo();
1829 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001830 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001831 // The non-type template parameter pack's type is a pack expansion of types.
1832 // Determine whether we need to expand this parameter pack into separate
1833 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001834 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001835 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001836 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001837 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001838
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001839 // Determine whether the set of unexpanded parameter packs can and should
1840 // be expanded.
1841 bool Expand = true;
1842 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001843 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001844 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001845 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001846 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1847 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001848 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001849 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001850 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001851 NumExpansions))
1852 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001853
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001854 if (Expand) {
1855 for (unsigned I = 0; I != *NumExpansions; ++I) {
1856 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1857 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001858 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001859 D->getDeclName());
1860 if (!NewDI)
1861 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001862
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001863 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1864 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1865 NewDI->getType(),
1866 D->getLocation());
1867 if (NewT.isNull())
1868 return 0;
1869 ExpandedParameterPackTypes.push_back(NewT);
1870 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001871
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001872 // Note that we have an expanded parameter pack. The "type" of this
1873 // expanded parameter pack is the original expansion type, but callers
1874 // will end up using the expanded parameter pack types for type-checking.
1875 IsExpandedParameterPack = true;
1876 DI = D->getTypeSourceInfo();
1877 T = DI->getType();
1878 } else {
1879 // We cannot fully expand the pack expansion now, so substitute into the
1880 // pattern and create a new pack expansion type.
1881 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1882 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001883 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001884 D->getDeclName());
1885 if (!NewPattern)
1886 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001887
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001888 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1889 NumExpansions);
1890 if (!DI)
1891 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001892
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001893 T = DI->getType();
1894 }
1895 } else {
1896 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001897 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001898 D->getLocation(), D->getDeclName());
1899 if (!DI)
1900 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001901
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001902 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001903 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001904 D->getLocation());
1905 if (T.isNull()) {
1906 T = SemaRef.Context.IntTy;
1907 Invalid = true;
1908 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001909 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001910
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001911 NonTypeTemplateParmDecl *Param;
1912 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001913 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001914 D->getInnerLocStart(),
1915 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001916 D->getDepth() - TemplateArgs.getNumLevels(),
1917 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001918 D->getIdentifier(), T,
1919 DI,
1920 ExpandedParameterPackTypes.data(),
1921 ExpandedParameterPackTypes.size(),
1922 ExpandedParameterPackTypesAsWritten.data());
1923 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001924 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001925 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001926 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001927 D->getDepth() - TemplateArgs.getNumLevels(),
1928 D->getPosition(),
1929 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001930 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001931
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001932 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001933 if (Invalid)
1934 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001935
David Majnemer89189202013-08-28 23:48:32 +00001936 if (D->hasDefaultArgument()) {
1937 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
1938 if (!Value.isInvalid())
1939 Param->setDefaultArgument(Value.get(), false);
1940 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001941
1942 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001943 // scope.
1944 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001945 return Param;
1946}
1947
Richard Smith1fde8ec2012-09-07 02:06:42 +00001948static void collectUnexpandedParameterPacks(
1949 Sema &S,
1950 TemplateParameterList *Params,
1951 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1952 for (TemplateParameterList::const_iterator I = Params->begin(),
1953 E = Params->end(); I != E; ++I) {
1954 if ((*I)->isTemplateParameterPack())
1955 continue;
1956 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1957 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1958 Unexpanded);
1959 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1960 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1961 Unexpanded);
1962 }
1963}
1964
Anders Carlsson4bd78752009-08-28 15:18:15 +00001965Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001966TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1967 TemplateTemplateParmDecl *D) {
1968 // Instantiate the template parameter list of the template template parameter.
1969 TemplateParameterList *TempParams = D->getTemplateParameters();
1970 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001971 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1972
1973 bool IsExpandedParameterPack = false;
1974
1975 if (D->isExpandedParameterPack()) {
1976 // The template template parameter pack is an already-expanded pack
1977 // expansion of template parameters. Substitute into each of the expanded
1978 // parameters.
1979 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1980 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1981 I != N; ++I) {
1982 LocalInstantiationScope Scope(SemaRef);
1983 TemplateParameterList *Expansion =
1984 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1985 if (!Expansion)
1986 return 0;
1987 ExpandedParams.push_back(Expansion);
1988 }
1989
1990 IsExpandedParameterPack = true;
1991 InstParams = TempParams;
1992 } else if (D->isPackExpansion()) {
1993 // The template template parameter pack expands to a pack of template
1994 // template parameters. Determine whether we need to expand this parameter
1995 // pack into separate parameters.
1996 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1997 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1998 Unexpanded);
1999
2000 // Determine whether the set of unexpanded parameter packs can and should
2001 // be expanded.
2002 bool Expand = true;
2003 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00002004 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00002005 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
2006 TempParams->getSourceRange(),
2007 Unexpanded,
2008 TemplateArgs,
2009 Expand, RetainExpansion,
2010 NumExpansions))
2011 return 0;
2012
2013 if (Expand) {
2014 for (unsigned I = 0; I != *NumExpansions; ++I) {
2015 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2016 LocalInstantiationScope Scope(SemaRef);
2017 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
2018 if (!Expansion)
2019 return 0;
2020 ExpandedParams.push_back(Expansion);
2021 }
2022
2023 // Note that we have an expanded parameter pack. The "type" of this
2024 // expanded parameter pack is the original expansion type, but callers
2025 // will end up using the expanded parameter pack types for type-checking.
2026 IsExpandedParameterPack = true;
2027 InstParams = TempParams;
2028 } else {
2029 // We cannot fully expand the pack expansion now, so just substitute
2030 // into the pattern.
2031 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2032
2033 LocalInstantiationScope Scope(SemaRef);
2034 InstParams = SubstTemplateParams(TempParams);
2035 if (!InstParams)
2036 return 0;
2037 }
2038 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00002039 // Perform the actual substitution of template parameters within a new,
2040 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00002041 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00002042 InstParams = SubstTemplateParams(TempParams);
2043 if (!InstParams)
Richard Smith1fde8ec2012-09-07 02:06:42 +00002044 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002045 }
2046
Douglas Gregor38fee962009-11-11 16:58:32 +00002047 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00002048 TemplateTemplateParmDecl *Param;
2049 if (IsExpandedParameterPack)
2050 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2051 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002052 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002053 D->getPosition(),
2054 D->getIdentifier(), InstParams,
2055 ExpandedParams);
2056 else
2057 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2058 D->getLocation(),
2059 D->getDepth() - TemplateArgs.getNumLevels(),
2060 D->getPosition(),
2061 D->isParameterPack(),
2062 D->getIdentifier(), InstParams);
David Majnemer89189202013-08-28 23:48:32 +00002063 if (D->hasDefaultArgument()) {
2064 NestedNameSpecifierLoc QualifierLoc =
2065 D->getDefaultArgument().getTemplateQualifierLoc();
2066 QualifierLoc =
2067 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
2068 TemplateName TName = SemaRef.SubstTemplateName(
2069 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
2070 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
2071 if (!TName.isNull())
2072 Param->setDefaultArgument(
2073 TemplateArgumentLoc(TemplateArgument(TName),
2074 D->getDefaultArgument().getTemplateQualifierLoc(),
2075 D->getDefaultArgument().getTemplateNameLoc()),
2076 false);
2077 }
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002078 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002079
2080 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002081 // scope.
2082 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002083
Douglas Gregor38fee962009-11-11 16:58:32 +00002084 return Param;
2085}
2086
Douglas Gregore0b28662009-11-17 06:07:40 +00002087Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002088 // Using directives are never dependent (and never contain any types or
2089 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002090
Douglas Gregore0b28662009-11-17 06:07:40 +00002091 UsingDirectiveDecl *Inst
2092 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002093 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002094 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002095 D->getIdentLocation(),
2096 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002097 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002098
2099 // Add the using directive to its declaration context
2100 // only if this is not a function or method.
2101 if (!Owner->isFunctionOrMethod())
2102 Owner->addDecl(Inst);
2103
Douglas Gregore0b28662009-11-17 06:07:40 +00002104 return Inst;
2105}
2106
John McCallb96ec562009-12-04 22:46:56 +00002107Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002108
2109 // The nested name specifier may be dependent, for example
2110 // template <typename T> struct t {
2111 // struct s1 { T f1(); };
2112 // struct s2 : s1 { using s1::f1; };
2113 // };
2114 // template struct t<int>;
2115 // Here, in using s1::f1, s1 refers to t<T>::s1;
2116 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002117 NestedNameSpecifierLoc QualifierLoc
2118 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2119 TemplateArgs);
2120 if (!QualifierLoc)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00002121 return 0;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002122
2123 // The name info is non-dependent, so no transformation
2124 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002125 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002126
John McCall84d87672009-12-10 09:41:52 +00002127 // We only need to do redeclaration lookups if we're in a class
2128 // scope (in fact, it's not really even possible in non-class
2129 // scopes).
2130 bool CheckRedeclaration = Owner->isRecord();
2131
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002132 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2133 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002134
John McCallb96ec562009-12-04 22:46:56 +00002135 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002136 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002137 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002138 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002139 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002140
Douglas Gregor0499ab62011-02-25 15:54:31 +00002141 CXXScopeSpec SS;
2142 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002143 if (CheckRedeclaration) {
2144 Prev.setHideTags(false);
2145 SemaRef.LookupQualifiedName(Prev, Owner);
2146
2147 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002148 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2149 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002150 D->getLocation(), Prev))
2151 NewUD->setInvalidDecl();
2152
2153 }
2154
2155 if (!NewUD->isInvalidDecl() &&
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002156 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCallb96ec562009-12-04 22:46:56 +00002157 D->getLocation()))
2158 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002159
John McCallb96ec562009-12-04 22:46:56 +00002160 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2161 NewUD->setAccess(D->getAccess());
2162 Owner->addDecl(NewUD);
2163
John McCall84d87672009-12-10 09:41:52 +00002164 // Don't process the shadow decls for an invalid decl.
2165 if (NewUD->isInvalidDecl())
2166 return NewUD;
2167
Richard Smith23d55872012-04-02 01:30:27 +00002168 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2169 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2170 NewUD->setInvalidDecl();
2171 return NewUD;
2172 }
2173
John McCalla1d85502009-12-22 22:26:37 +00002174 bool isFunctionScope = Owner->isFunctionOrMethod();
2175
John McCall84d87672009-12-10 09:41:52 +00002176 // Process the shadow decls.
2177 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2178 I != E; ++I) {
2179 UsingShadowDecl *Shadow = *I;
2180 NamedDecl *InstTarget =
Richard Smithfd8634a2013-10-23 02:17:46 +00002181 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2182 Shadow->getLocation(), Shadow->getTargetDecl(), TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00002183 if (!InstTarget)
2184 return 0;
John McCall84d87672009-12-10 09:41:52 +00002185
Richard Smithfd8634a2013-10-23 02:17:46 +00002186 UsingShadowDecl *PrevDecl = 0;
2187 if (CheckRedeclaration) {
2188 if (SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev, PrevDecl))
2189 continue;
2190 } else if (UsingShadowDecl *OldPrev = Shadow->getPreviousDecl()) {
2191 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
2192 Shadow->getLocation(), OldPrev, TemplateArgs));
2193 }
John McCall84d87672009-12-10 09:41:52 +00002194
Richard Smithfd8634a2013-10-23 02:17:46 +00002195 UsingShadowDecl *InstShadow =
2196 SemaRef.BuildUsingShadowDecl(/*Scope*/0, NewUD, InstTarget, PrevDecl);
John McCall84d87672009-12-10 09:41:52 +00002197 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002198
2199 if (isFunctionScope)
2200 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002201 }
John McCallb96ec562009-12-04 22:46:56 +00002202
2203 return NewUD;
2204}
2205
2206Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002207 // Ignore these; we handle them in bulk when processing the UsingDecl.
2208 return 0;
John McCallb96ec562009-12-04 22:46:56 +00002209}
2210
John McCalle61f2ba2009-11-18 02:36:19 +00002211Decl * TemplateDeclInstantiator
2212 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002213 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002214 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002215 TemplateArgs);
2216 if (!QualifierLoc)
Anders Carlsson4bd78752009-08-28 15:18:15 +00002217 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002218
Anders Carlsson4bd78752009-08-28 15:18:15 +00002219 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002220 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002221
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002222 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002223 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002224 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002225 NamedDecl *UD =
John McCall3f746822009-11-17 05:59:44 +00002226 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002227 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002228 /*instantiation*/ true,
2229 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002230 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002231 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2232
John McCalle61f2ba2009-11-18 02:36:19 +00002233 return UD;
2234}
2235
2236Decl * TemplateDeclInstantiator
2237 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002238 NestedNameSpecifierLoc QualifierLoc
2239 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2240 if (!QualifierLoc)
John McCalle61f2ba2009-11-18 02:36:19 +00002241 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002242
John McCalle61f2ba2009-11-18 02:36:19 +00002243 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002244 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002245
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002246 DeclarationNameInfo NameInfo
2247 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2248
John McCalle61f2ba2009-11-18 02:36:19 +00002249 NamedDecl *UD =
2250 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002251 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002252 /*instantiation*/ true,
2253 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002254 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002255 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2256
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002257 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002258}
2259
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002260
2261Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2262 ClassScopeFunctionSpecializationDecl *Decl) {
2263 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002264 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2265 0, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002266
2267 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2268 Sema::ForRedeclaration);
2269
Nico Weber7b5a7162012-06-25 17:21:05 +00002270 TemplateArgumentListInfo TemplateArgs;
2271 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2272 if (Decl->hasExplicitTemplateArgs()) {
2273 TemplateArgs = Decl->templateArgs();
2274 TemplateArgsPtr = &TemplateArgs;
2275 }
2276
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002277 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002278 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2279 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002280 NewFD->setInvalidDecl();
2281 return NewFD;
2282 }
2283
2284 // Associate the specialization with the pattern.
2285 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2286 assert(Specialization && "Class scope Specialization is null");
2287 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2288
2289 return NewFD;
2290}
2291
Alexey Bataeva769e072013-03-22 06:34:35 +00002292Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2293 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002294 SmallVector<Expr *, 5> Vars;
2295 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2296 E = D->varlist_end();
Alexey Bataeva769e072013-03-22 06:34:35 +00002297 I != E; ++I) {
2298 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2299 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002300 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002301 }
2302
2303 OMPThreadPrivateDecl *TD =
2304 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2305
2306 return TD;
2307}
2308
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002309Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2310 return VisitFunctionDecl(D, 0);
2311}
2312
2313Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2314 return VisitCXXMethodDecl(D, 0);
2315}
2316
2317Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2318 llvm_unreachable("There are only CXXRecordDecls in C++");
2319}
2320
2321Decl *
2322TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2323 ClassTemplateSpecializationDecl *D) {
2324 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2325 "inside templates");
2326}
2327
Larisse Voufo39a1e502013-08-06 01:03:05 +00002328Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2329 VarTemplateSpecializationDecl *D) {
2330
2331 TemplateArgumentListInfo VarTemplateArgsInfo;
2332 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
2333 assert(VarTemplate &&
2334 "A template specialization without specialized template?");
2335
2336 // Substitute the current template arguments.
2337 const TemplateArgumentListInfo &TemplateArgsInfo = D->getTemplateArgsInfo();
2338 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo.getLAngleLoc());
2339 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo.getRAngleLoc());
2340
2341 if (SemaRef.Subst(TemplateArgsInfo.getArgumentArray(),
2342 TemplateArgsInfo.size(), VarTemplateArgsInfo, TemplateArgs))
2343 return 0;
2344
2345 // Check that the template argument list is well-formed for this template.
2346 SmallVector<TemplateArgument, 4> Converted;
2347 bool ExpansionIntoFixedList = false;
2348 if (SemaRef.CheckTemplateArgumentList(
2349 VarTemplate, VarTemplate->getLocStart(),
2350 const_cast<TemplateArgumentListInfo &>(VarTemplateArgsInfo), false,
2351 Converted, &ExpansionIntoFixedList))
2352 return 0;
2353
2354 // Find the variable template specialization declaration that
2355 // corresponds to these arguments.
2356 void *InsertPos = 0;
2357 if (VarTemplateSpecializationDecl *VarSpec = VarTemplate->findSpecialization(
2358 Converted.data(), Converted.size(), InsertPos))
2359 // If we already have a variable template specialization, return it.
2360 return VarSpec;
2361
2362 return VisitVarTemplateSpecializationDecl(VarTemplate, D, InsertPos,
2363 VarTemplateArgsInfo, Converted);
2364}
2365
2366Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
2367 VarTemplateDecl *VarTemplate, VarDecl *D, void *InsertPos,
2368 const TemplateArgumentListInfo &TemplateArgsInfo,
Richard Smith8809a0c2013-09-27 20:14:12 +00002369 llvm::ArrayRef<TemplateArgument> Converted) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00002370
2371 // If this is the variable for an anonymous struct or union,
2372 // instantiate the anonymous struct/union type first.
2373 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
2374 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
2375 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
2376 return 0;
2377
2378 // Do substitution on the type of the declaration
2379 TypeSourceInfo *DI =
2380 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2381 D->getTypeSpecStartLoc(), D->getDeclName());
2382 if (!DI)
2383 return 0;
2384
2385 if (DI->getType()->isFunctionType()) {
2386 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
2387 << D->isStaticDataMember() << DI->getType();
2388 return 0;
2389 }
2390
2391 // Build the instantiated declaration
2392 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
2393 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
2394 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted.data(),
2395 Converted.size());
2396 Var->setTemplateArgsInfo(TemplateArgsInfo);
Richard Smith8809a0c2013-09-27 20:14:12 +00002397 if (InsertPos)
2398 VarTemplate->AddSpecialization(Var, InsertPos);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002399
2400 // Substitute the nested name specifier, if any.
2401 if (SubstQualifier(D, Var))
2402 return 0;
2403
2404 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs,
Richard Smith541b38b2013-09-20 01:15:31 +00002405 Owner, StartingScope);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002406
2407 return Var;
2408}
2409
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002410Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2411 llvm_unreachable("@defs is not supported in Objective-C++");
2412}
2413
2414Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2415 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2416 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2417 DiagnosticsEngine::Error,
2418 "cannot instantiate %0 yet");
2419 SemaRef.Diag(D->getLocation(), DiagID)
2420 << D->getDeclKindName();
2421
2422 return 0;
2423}
2424
2425Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2426 llvm_unreachable("Unexpected decl");
2427}
2428
John McCall76d824f2009-08-25 22:02:44 +00002429Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002430 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002431 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002432 if (D->isInvalidDecl())
2433 return 0;
2434
Douglas Gregord7e7a512009-03-17 21:15:40 +00002435 return Instantiator.Visit(D);
2436}
2437
John McCall87a44eb2009-08-20 01:44:21 +00002438/// \brief Instantiates a nested template parameter list in the current
2439/// instantiation context.
2440///
2441/// \param L The parameter list to instantiate
2442///
2443/// \returns NULL if there was an error
2444TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002445TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002446 // Get errors for all the parameters before bailing out.
2447 bool Invalid = false;
2448
2449 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002450 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002451 ParamVector Params;
2452 Params.reserve(N);
2453 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2454 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002455 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002456 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002457 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002458 }
2459
2460 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002461 if (Invalid)
John McCall87a44eb2009-08-20 01:44:21 +00002462 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +00002463
2464 TemplateParameterList *InstL
2465 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2466 L->getLAngleLoc(), &Params.front(), N,
2467 L->getRAngleLoc());
2468 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002469}
John McCall87a44eb2009-08-20 01:44:21 +00002470
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002471/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002472/// specialization.
2473///
2474/// \param ClassTemplate the (instantiated) class template that is partially
2475// specialized by the instantiation of \p PartialSpec.
2476///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002477/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002478/// specialization that we are instantiating.
2479///
Douglas Gregor869853e2010-11-10 19:44:59 +00002480/// \returns The instantiated partial specialization, if successful; otherwise,
2481/// NULL to indicate an error.
2482ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002483TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2484 ClassTemplateDecl *ClassTemplate,
2485 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002486 // Create a local instantiation scope for this class template partial
2487 // specialization, which will contain the instantiations of the template
2488 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002489 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002490
Douglas Gregor21610382009-10-29 00:04:11 +00002491 // Substitute into the template parameters of the class template partial
2492 // specialization.
2493 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2494 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2495 if (!InstParams)
Douglas Gregor869853e2010-11-10 19:44:59 +00002496 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002497
Douglas Gregor21610382009-10-29 00:04:11 +00002498 // Substitute into the template arguments of the class template partial
2499 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002500 const ASTTemplateArgumentListInfo *TemplArgInfo
2501 = PartialSpec->getTemplateArgsAsWritten();
2502 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2503 TemplArgInfo->RAngleLoc);
2504 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2505 TemplArgInfo->NumTemplateArgs,
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002506 InstTemplateArgs, TemplateArgs))
2507 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002508
Douglas Gregor21610382009-10-29 00:04:11 +00002509 // Check that the template argument list is well-formed for this
2510 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002511 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002512 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002513 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002514 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002515 false,
2516 Converted))
Douglas Gregor869853e2010-11-10 19:44:59 +00002517 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002518
2519 // Figure out where to insert this class template partial specialization
2520 // in the member template's set of class template partial specializations.
Douglas Gregor21610382009-10-29 00:04:11 +00002521 void *InsertPos = 0;
2522 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002523 = ClassTemplate->findPartialSpecialization(Converted.data(),
2524 Converted.size(), InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002525
Douglas Gregor21610382009-10-29 00:04:11 +00002526 // Build the canonical type that describes the converted template
2527 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002528 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002529 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002530 Converted.data(),
2531 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002532
2533 // Build the fully-sugared type for this class template
2534 // specialization as the user wrote in the specialization
2535 // itself. This means that we'll pretty-print the type retrieved
2536 // from the specialization's declaration the way that the user
2537 // actually wrote the specialization, rather than formatting the
2538 // name based on the "canonical" representation used to store the
2539 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002540 TypeSourceInfo *WrittenTy
2541 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2542 TemplateName(ClassTemplate),
2543 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002544 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002545 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002546
Douglas Gregor21610382009-10-29 00:04:11 +00002547 if (PrevDecl) {
2548 // We've already seen a partial specialization with the same template
2549 // parameters and template arguments. This can happen, for example, when
2550 // substituting the outer template arguments ends up causing two
2551 // class template partial specializations of a member class template
2552 // to have identical forms, e.g.,
2553 //
2554 // template<typename T, typename U>
2555 // struct Outer {
2556 // template<typename X, typename Y> struct Inner;
2557 // template<typename Y> struct Inner<T, Y>;
2558 // template<typename Y> struct Inner<U, Y>;
2559 // };
2560 //
2561 // Outer<int, int> outer; // error: the partial specializations of Inner
2562 // // have the same signature.
2563 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002564 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002565 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2566 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregor869853e2010-11-10 19:44:59 +00002567 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002568 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002569
2570
Douglas Gregor21610382009-10-29 00:04:11 +00002571 // Create the class template partial specialization declaration.
2572 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002573 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002574 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002575 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002576 PartialSpec->getLocStart(),
2577 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002578 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002579 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002580 Converted.data(),
2581 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002582 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002583 CanonType,
Richard Smithb2f61b42013-08-22 23:27:37 +00002584 0);
John McCall3e11ebe2010-03-15 10:12:16 +00002585 // Substitute the nested name specifier, if any.
2586 if (SubstQualifier(PartialSpec, InstPartialSpec))
2587 return 0;
2588
Douglas Gregor21610382009-10-29 00:04:11 +00002589 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002590 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002591
Douglas Gregor21610382009-10-29 00:04:11 +00002592 // Add this partial specialization to the set of class template partial
2593 // specializations.
Douglas Gregorce9978f2012-03-28 14:34:23 +00002594 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregor869853e2010-11-10 19:44:59 +00002595 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002596}
2597
Larisse Voufo39a1e502013-08-06 01:03:05 +00002598/// \brief Instantiate the declaration of a variable template partial
2599/// specialization.
2600///
2601/// \param VarTemplate the (instantiated) variable template that is partially
2602/// specialized by the instantiation of \p PartialSpec.
2603///
2604/// \param PartialSpec the (uninstantiated) variable template partial
2605/// specialization that we are instantiating.
2606///
2607/// \returns The instantiated partial specialization, if successful; otherwise,
2608/// NULL to indicate an error.
2609VarTemplatePartialSpecializationDecl *
2610TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
2611 VarTemplateDecl *VarTemplate,
2612 VarTemplatePartialSpecializationDecl *PartialSpec) {
2613 // Create a local instantiation scope for this variable template partial
2614 // specialization, which will contain the instantiations of the template
2615 // parameters.
2616 LocalInstantiationScope Scope(SemaRef);
2617
2618 // Substitute into the template parameters of the variable template partial
2619 // specialization.
2620 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2621 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2622 if (!InstParams)
2623 return 0;
2624
2625 // Substitute into the template arguments of the variable template partial
2626 // specialization.
Enea Zaffanella6dbe1872013-08-10 07:24:53 +00002627 const ASTTemplateArgumentListInfo *TemplArgInfo
2628 = PartialSpec->getTemplateArgsAsWritten();
2629 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
2630 TemplArgInfo->RAngleLoc);
2631 if (SemaRef.Subst(TemplArgInfo->getTemplateArgs(),
2632 TemplArgInfo->NumTemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00002633 InstTemplateArgs, TemplateArgs))
2634 return 0;
2635
2636 // Check that the template argument list is well-formed for this
2637 // class template.
2638 SmallVector<TemplateArgument, 4> Converted;
2639 if (SemaRef.CheckTemplateArgumentList(VarTemplate, PartialSpec->getLocation(),
2640 InstTemplateArgs, false, Converted))
2641 return 0;
2642
2643 // Figure out where to insert this variable template partial specialization
2644 // in the member template's set of variable template partial specializations.
2645 void *InsertPos = 0;
2646 VarTemplateSpecializationDecl *PrevDecl =
2647 VarTemplate->findPartialSpecialization(Converted.data(), Converted.size(),
2648 InsertPos);
2649
2650 // Build the canonical type that describes the converted template
2651 // arguments of the variable template partial specialization.
2652 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
2653 TemplateName(VarTemplate), Converted.data(), Converted.size());
2654
2655 // Build the fully-sugared type for this variable template
2656 // specialization as the user wrote in the specialization
2657 // itself. This means that we'll pretty-print the type retrieved
2658 // from the specialization's declaration the way that the user
2659 // actually wrote the specialization, rather than formatting the
2660 // name based on the "canonical" representation used to store the
2661 // template arguments in the specialization.
2662 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
2663 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
2664 CanonType);
2665
2666 if (PrevDecl) {
2667 // We've already seen a partial specialization with the same template
2668 // parameters and template arguments. This can happen, for example, when
2669 // substituting the outer template arguments ends up causing two
2670 // variable template partial specializations of a member variable template
2671 // to have identical forms, e.g.,
2672 //
2673 // template<typename T, typename U>
2674 // struct Outer {
2675 // template<typename X, typename Y> pair<X,Y> p;
2676 // template<typename Y> pair<T, Y> p;
2677 // template<typename Y> pair<U, Y> p;
2678 // };
2679 //
2680 // Outer<int, int> outer; // error: the partial specializations of Inner
2681 // // have the same signature.
2682 SemaRef.Diag(PartialSpec->getLocation(),
2683 diag::err_var_partial_spec_redeclared)
2684 << WrittenTy->getType();
2685 SemaRef.Diag(PrevDecl->getLocation(),
2686 diag::note_var_prev_partial_spec_here);
2687 return 0;
2688 }
2689
2690 // Do substitution on the type of the declaration
2691 TypeSourceInfo *DI = SemaRef.SubstType(
2692 PartialSpec->getTypeSourceInfo(), TemplateArgs,
2693 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
2694 if (!DI)
2695 return 0;
2696
2697 if (DI->getType()->isFunctionType()) {
2698 SemaRef.Diag(PartialSpec->getLocation(),
2699 diag::err_variable_instantiates_to_function)
2700 << PartialSpec->isStaticDataMember() << DI->getType();
2701 return 0;
2702 }
2703
2704 // Create the variable template partial specialization declaration.
2705 VarTemplatePartialSpecializationDecl *InstPartialSpec =
2706 VarTemplatePartialSpecializationDecl::Create(
2707 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
2708 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
2709 DI, PartialSpec->getStorageClass(), Converted.data(),
Richard Smithb2f61b42013-08-22 23:27:37 +00002710 Converted.size(), InstTemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00002711
2712 // Substitute the nested name specifier, if any.
2713 if (SubstQualifier(PartialSpec, InstPartialSpec))
2714 return 0;
2715
2716 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
2717 InstPartialSpec->setTypeAsWritten(WrittenTy);
2718
Larisse Voufo39a1e502013-08-06 01:03:05 +00002719 // Add this partial specialization to the set of variable template partial
2720 // specializations. The instantiation of the initializer is not necessary.
2721 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002722
Larisse Voufo4cda4612013-08-22 00:28:27 +00002723 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00002724 LateAttrs, Owner, StartingScope);
Larisse Voufo4cda4612013-08-22 00:28:27 +00002725
Larisse Voufo39a1e502013-08-06 01:03:05 +00002726 return InstPartialSpec;
2727}
2728
John McCall58f10c32010-03-11 09:03:00 +00002729TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002730TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002731 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002732 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2733 assert(OldTInfo && "substituting function without type source info");
2734 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregor3024f072012-04-16 07:05:22 +00002735
2736 CXXRecordDecl *ThisContext = 0;
2737 unsigned ThisTypeQuals = 0;
2738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002739 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002740 ThisTypeQuals = Method->getTypeQualifiers();
2741 }
2742
John McCallb29f78f2010-04-09 17:38:44 +00002743 TypeSourceInfo *NewTInfo
2744 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2745 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002746 D->getDeclName(),
2747 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002748 if (!NewTInfo)
2749 return 0;
Douglas Gregor21342092009-03-24 00:38:23 +00002750
Reid Klecknera09e44c2013-07-31 21:00:18 +00002751 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2752 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2753 if (NewTInfo != OldTInfo) {
2754 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002755 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002756 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002757 unsigned NewIdx = 0;
David Blaikie6adc78e2013-02-18 22:06:02 +00002758 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregorf3010112011-01-07 16:43:16 +00002759 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002760 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002761 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2762
David Blaikie05785d12013-02-20 22:23:23 +00002763 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002764 if (OldParam->isParameterPack())
2765 NumArgumentsInExpansion =
2766 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2767 TemplateArgs);
2768 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002769 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002770 // instantiated to a (still-dependent) parameter pack.
David Blaikie6adc78e2013-02-18 22:06:02 +00002771 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002772 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002773 Scope->InstantiatedLocal(OldParam, NewParam);
2774 } else {
2775 // Parameter pack expansion: make the instantiation an argument pack.
2776 Scope->MakeInstantiatedLocalArgPack(OldParam);
2777 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002778 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002779 Params.push_back(NewParam);
2780 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2781 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002782 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002783 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002784 } else {
2785 // The function type itself was not dependent and therefore no
2786 // substitution occurred. However, we still need to instantiate
2787 // the function parameters themselves.
2788 const FunctionProtoType *OldProto =
2789 cast<FunctionProtoType>(OldProtoLoc.getType());
David Blaikie6adc78e2013-02-18 22:06:02 +00002790 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00002791 ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2792 if (!OldParam) {
2793 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2794 D, D->getLocation(), OldProto->getArgType(i)));
2795 continue;
2796 }
2797
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002798 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002799 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002800 if (!Parm)
2801 return 0;
2802 Params.push_back(Parm);
2803 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002804 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002805 } else {
2806 // If the type of this function, after ignoring parentheses, is not
2807 // *directly* a function type, then we're instantiating a function that
2808 // was declared via a typedef or with attributes, e.g.,
2809 //
2810 // typedef int functype(int, int);
2811 // functype func;
2812 // int __cdecl meth(int, int);
2813 //
2814 // In this case, we'll just go instantiate the ParmVarDecls that we
2815 // synthesized in the method declaration.
2816 SmallVector<QualType, 4> ParamTypes;
2817 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2818 D->getNumParams(), TemplateArgs, ParamTypes,
2819 &Params))
2820 return 0;
Douglas Gregor940bca72010-04-12 07:48:19 +00002821 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002822
John McCall58f10c32010-03-11 09:03:00 +00002823 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002824}
2825
Richard Smithf623c962012-04-17 00:58:00 +00002826/// Introduce the instantiated function parameters into the local
2827/// instantiation scope, and set the parameter names to those used
2828/// in the template.
2829static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2830 const FunctionDecl *PatternDecl,
2831 LocalInstantiationScope &Scope,
2832 const MultiLevelTemplateArgumentList &TemplateArgs) {
2833 unsigned FParamIdx = 0;
2834 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2835 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2836 if (!PatternParam->isParameterPack()) {
2837 // Simple case: not a parameter pack.
2838 assert(FParamIdx < Function->getNumParams());
2839 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2840 FunctionParam->setDeclName(PatternParam->getDeclName());
2841 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2842 ++FParamIdx;
2843 continue;
2844 }
2845
2846 // Expand the parameter pack.
2847 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00002848 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00002849 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00002850 assert(NumArgumentsInExpansion &&
2851 "should only be called when all template arguments are known");
2852 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00002853 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2854 FunctionParam->setDeclName(PatternParam->getDeclName());
2855 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2856 ++FParamIdx;
2857 }
2858 }
2859}
2860
2861static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2862 const FunctionProtoType *Proto,
2863 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00002864 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2865
Richard Smithf623c962012-04-17 00:58:00 +00002866 // C++11 [expr.prim.general]p3:
2867 // If a declaration declares a member function or member function
2868 // template of a class X, the expression this is a prvalue of type
2869 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2870 // and the end of the function-definition, member-declarator, or
2871 // declarator.
2872 CXXRecordDecl *ThisContext = 0;
2873 unsigned ThisTypeQuals = 0;
2874 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2875 ThisContext = Method->getParent();
2876 ThisTypeQuals = Method->getTypeQualifiers();
2877 }
2878 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002879 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00002880
2881 // The function has an exception specification or a "noreturn"
2882 // attribute. Substitute into each of the exception types.
2883 SmallVector<QualType, 4> Exceptions;
2884 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2885 // FIXME: Poor location information!
2886 if (const PackExpansionType *PackExpansion
2887 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2888 // We have a pack expansion. Instantiate it.
2889 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2890 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2891 Unexpanded);
2892 assert(!Unexpanded.empty() &&
2893 "Pack expansion without parameter packs?");
2894
2895 bool Expand = false;
2896 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002897 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00002898 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2899 SourceRange(),
2900 Unexpanded,
2901 TemplateArgs,
2902 Expand,
2903 RetainExpansion,
2904 NumExpansions))
2905 break;
2906
2907 if (!Expand) {
2908 // We can't expand this pack expansion into separate arguments yet;
2909 // just substitute into the pattern and create a new pack expansion
2910 // type.
2911 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2912 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2913 TemplateArgs,
2914 New->getLocation(), New->getDeclName());
2915 if (T.isNull())
2916 break;
2917
2918 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2919 Exceptions.push_back(T);
2920 continue;
2921 }
2922
2923 // Substitute into the pack expansion pattern for each template
2924 bool Invalid = false;
2925 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2926 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2927
2928 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2929 TemplateArgs,
2930 New->getLocation(), New->getDeclName());
2931 if (T.isNull()) {
2932 Invalid = true;
2933 break;
2934 }
2935
2936 Exceptions.push_back(T);
2937 }
2938
2939 if (Invalid)
2940 break;
2941
2942 continue;
2943 }
2944
2945 QualType T
2946 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2947 New->getLocation(), New->getDeclName());
2948 if (T.isNull() ||
2949 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2950 continue;
2951
2952 Exceptions.push_back(T);
2953 }
2954 Expr *NoexceptExpr = 0;
2955 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2956 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2957 Sema::ConstantEvaluated);
2958 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2959 if (E.isUsable())
2960 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2961
2962 if (E.isUsable()) {
2963 NoexceptExpr = E.take();
2964 if (!NoexceptExpr->isTypeDependent() &&
2965 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00002966 NoexceptExpr
2967 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2968 0, diag::err_noexcept_needs_constant_expression,
2969 /*AllowFold*/ false).take();
Richard Smithf623c962012-04-17 00:58:00 +00002970 }
2971 }
2972
2973 // Rebuild the function type
2974 const FunctionProtoType *NewProto
2975 = New->getType()->getAs<FunctionProtoType>();
2976 assert(NewProto && "Template instantiation without function prototype?");
2977
2978 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2979 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2980 EPI.NumExceptions = Exceptions.size();
2981 EPI.Exceptions = Exceptions.data();
2982 EPI.NoexceptExpr = NoexceptExpr;
2983
2984 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00002985 NewProto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00002986}
2987
2988void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2989 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00002990 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2991 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00002992 return;
2993
2994 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2995 InstantiatingTemplate::ExceptionSpecification());
Alp Tokerd4a72d52013-10-08 08:09:04 +00002996 if (Inst.isInvalid()) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00002997 // We hit the instantiation depth limit. Clear the exception specification
2998 // so that our callers don't have to cope with EST_Uninstantiated.
2999 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
3000 EPI.ExceptionSpecType = EST_None;
3001 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00003002 Proto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003003 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00003004 }
Richard Smithf623c962012-04-17 00:58:00 +00003005
3006 // Enter the scope of this instantiation. We don't use
3007 // PushDeclContext because we don't have a scope.
3008 Sema::ContextRAII savedContext(*this, Decl);
3009 LocalInstantiationScope Scope(*this);
3010
3011 MultiLevelTemplateArgumentList TemplateArgs =
3012 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
3013
Richard Smithd3729422012-04-19 00:08:28 +00003014 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
3015 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003016
Richard Smithd3729422012-04-19 00:08:28 +00003017 ::InstantiateExceptionSpec(*this, Decl,
3018 Template->getType()->castAs<FunctionProtoType>(),
3019 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00003020}
3021
Mike Stump11289f42009-09-09 15:08:12 +00003022/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003023/// declaration (New) from the corresponding fields of its template (Tmpl).
3024///
3025/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003026bool
3027TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003028 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00003029 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003030 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00003031
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003032 // Forward the mangling number from the template to the instantiated decl.
3033 SemaRef.Context.setManglingNumber(New,
3034 SemaRef.Context.getManglingNumber(Tmpl));
3035
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003036 // If we are performing substituting explicitly-specified template arguments
3037 // or deduced template arguments into a function template and we reach this
3038 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00003039 // to keeping the new function template specialization. We therefore
3040 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003041 // into a template instantiation for this specific function template
3042 // specialization, which is not a SFINAE context, so that we diagnose any
3043 // further errors in the declaration itself.
3044 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
3045 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
3046 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
3047 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00003048 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003049 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00003050 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003051 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00003052 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003053 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00003054 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00003055 }
3056 }
Mike Stump11289f42009-09-09 15:08:12 +00003057
Douglas Gregor049bdca2009-12-08 17:45:32 +00003058 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
3059 assert(Proto && "Function template without prototype?");
3060
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003061 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00003062 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00003063
Richard Smithf623c962012-04-17 00:58:00 +00003064 // DR1330: In C++11, defer instantiation of a non-trivial
3065 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003066 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithf623c962012-04-17 00:58:00 +00003067 EPI.ExceptionSpecType != EST_None &&
3068 EPI.ExceptionSpecType != EST_DynamicNone &&
3069 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00003070 FunctionDecl *ExceptionSpecTemplate = Tmpl;
3071 if (EPI.ExceptionSpecType == EST_Uninstantiated)
3072 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith185be182013-04-10 05:48:59 +00003073 ExceptionSpecificationType NewEST = EST_Uninstantiated;
3074 if (EPI.ExceptionSpecType == EST_Unevaluated)
3075 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00003076
Richard Smithf623c962012-04-17 00:58:00 +00003077 // Mark the function has having an uninstantiated exception specification.
3078 const FunctionProtoType *NewProto
3079 = New->getType()->getAs<FunctionProtoType>();
3080 assert(NewProto && "Template instantiation without function prototype?");
3081 EPI = NewProto->getExtProtoInfo();
Richard Smith185be182013-04-10 05:48:59 +00003082 EPI.ExceptionSpecType = NewEST;
Richard Smithf623c962012-04-17 00:58:00 +00003083 EPI.ExceptionSpecDecl = New;
Richard Smithd3729422012-04-19 00:08:28 +00003084 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00003085 New->setType(SemaRef.Context.getFunctionType(
3086 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00003087 } else {
3088 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
3089 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00003090 }
3091
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003092 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00003093 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00003094 Tmpl->isDefined(Definition);
3095
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00003096 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
3097 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00003098
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003099 return false;
3100}
3101
Douglas Gregor21342092009-03-24 00:38:23 +00003102/// \brief Initializes common fields of an instantiated method
3103/// declaration (New) from the corresponding fields of its template
3104/// (Tmpl).
3105///
3106/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00003107bool
3108TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00003109 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003110 if (InitFunctionInstantiation(New, Tmpl))
3111 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003112
Douglas Gregor21342092009-03-24 00:38:23 +00003113 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00003114 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00003115 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00003116
Douglas Gregor21342092009-03-24 00:38:23 +00003117 // FIXME: New needs a pointer to Tmpl
3118 return false;
3119}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003120
3121/// \brief Instantiate the definition of the given function from its
3122/// template.
3123///
Douglas Gregordda7ced2009-06-30 17:20:14 +00003124/// \param PointOfInstantiation the point at which the instantiation was
3125/// required. Note that this is not precisely a "point of instantiation"
3126/// for the function, but it's close.
3127///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003128/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00003129/// function template specialization or member function of a class template
3130/// specialization.
3131///
3132/// \param Recursive if true, recursively instantiates any functions that
3133/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003134///
3135/// \param DefinitionRequired if true, then we are performing an explicit
3136/// instantiation where the body of the function is required. Complain if
3137/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00003138void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00003139 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003140 bool Recursive,
3141 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00003142 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00003143 return;
3144
Francois Pichet00c7e6c2011-08-14 03:52:19 +00003145 // Never instantiate an explicit specialization except if it is a class scope
3146 // explicit specialization.
3147 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
3148 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00003149 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00003150
Douglas Gregor24c332b2009-05-14 21:06:31 +00003151 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00003152 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00003153 assert(PatternDecl && "instantiating a non-template");
3154
3155 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
3156 assert(PatternDecl && "template definition is not a template");
3157 if (!Pattern) {
3158 // Try to find a defaulted definition
3159 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00003160 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00003161 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00003162
Francois Pichet1c229c02011-04-22 22:18:13 +00003163 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003164 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00003165 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00003166 PendingInstantiations.push_back(
3167 std::make_pair(Function, PointOfInstantiation));
3168 return;
3169 }
3170
David Majnemerf0a84f22013-08-16 08:29:13 +00003171 // Call the LateTemplateParser callback if there is a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003172 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00003173 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00003174 LateTemplateParser) {
Richard Smithe40f2ba2013-08-07 21:41:30 +00003175 // FIXME: Optimize to allow individual templates to be deserialized.
3176 if (PatternDecl->isFromASTFile())
3177 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
3178
3179 LateParsedTemplate *LPT = LateParsedTemplateMap.lookup(PatternDecl);
3180 assert(LPT && "missing LateParsedTemplate");
3181 LateTemplateParser(OpaqueParser, *LPT);
Francois Pichet1c229c02011-04-22 22:18:13 +00003182 Pattern = PatternDecl->getBody(PatternDecl);
3183 }
3184
Alexis Hunt23f6b832011-05-27 20:00:14 +00003185 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003186 if (DefinitionRequired) {
3187 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003188 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003189 diag::err_explicit_instantiation_undefined_func_template)
3190 << Function->getPrimaryTemplate();
3191 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003192 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003193 diag::err_explicit_instantiation_undefined_member)
3194 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003195
Douglas Gregora8b89d22009-10-15 14:05:49 +00003196 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003197 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00003198 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00003199 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003200 } else if (Function->getTemplateSpecializationKind()
3201 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003202 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003203 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00003204 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003205
Douglas Gregor24c332b2009-05-14 21:06:31 +00003206 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00003207 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00003208
Richard Smith2a7d4812013-05-04 07:00:32 +00003209 // C++1y [temp.explicit]p10:
3210 // Except for inline functions, declarations with types deduced from their
3211 // initializer or return value, and class template specializations, other
3212 // explicit instantiation declarations have the effect of suppressing the
3213 // implicit instantiation of the entity to which they refer.
Mike Stump11289f42009-09-09 15:08:12 +00003214 if (Function->getTemplateSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003215 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00003216 !PatternDecl->isInlined() &&
Richard Smithc58f38f2013-08-14 20:16:31 +00003217 !PatternDecl->getResultType()->getContainedAutoType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00003218 return;
Mike Stump11289f42009-09-09 15:08:12 +00003219
Richard Smithf3814ad2013-01-25 00:08:28 +00003220 if (PatternDecl->isInlined())
3221 Function->setImplicitlyInline();
3222
Douglas Gregor85673582009-05-18 17:01:57 +00003223 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003224 if (Inst.isInvalid())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003225 return;
3226
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00003227 // Copy the inner loc start from the pattern.
3228 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
3229
Douglas Gregordda7ced2009-06-30 17:20:14 +00003230 // If we're performing recursive template instantiation, create our own
3231 // queue of pending implicit instantiations that we will instantiate later,
3232 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003233 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003234 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003235 SavePendingLocalImplicitInstantiationsRAII
3236 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003237 if (Recursive) {
3238 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003239 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003240 }
Mike Stump11289f42009-09-09 15:08:12 +00003241
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003242 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00003243 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00003244
Douglas Gregorb4850462009-05-14 23:26:13 +00003245 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003246 // recorded, unless we're actually a member function within a local
3247 // class, in which case we need to merge our results with the parent
3248 // scope (of the enclosing function).
3249 bool MergeWithParentScope = false;
3250 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
3251 MergeWithParentScope = Rec->isLocalClass();
3252
3253 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00003254
Richard Smithbd305122012-12-11 01:14:52 +00003255 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003256 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00003257 else {
3258 ActOnStartOfFunctionDef(0, Function);
3259
3260 // Enter the scope of this instantiation. We don't use
3261 // PushDeclContext because we don't have a scope.
3262 Sema::ContextRAII savedContext(*this, Function);
3263
3264 MultiLevelTemplateArgumentList TemplateArgs =
3265 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
3266
3267 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
3268 TemplateArgs);
3269
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003270 // If this is a constructor, instantiate the member initializers.
3271 if (const CXXConstructorDecl *Ctor =
3272 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
3273 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
3274 TemplateArgs);
3275 }
3276
3277 // Instantiate the function body.
3278 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
3279
3280 if (Body.isInvalid())
3281 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003282
Alexis Hunt61ae8d32011-05-23 23:14:04 +00003283 ActOnFinishFunctionBody(Function, Body.get(),
3284 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00003285
3286 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
3287
3288 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00003289 }
3290
Douglas Gregor28ad4b52009-05-26 20:50:29 +00003291 DeclGroupRef DG(Function);
3292 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003293
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003294 // This class may have local implicit instantiations that need to be
3295 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003296 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003297 Scope.Exit();
3298
Douglas Gregordda7ced2009-06-30 17:20:14 +00003299 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003300 // Define any pending vtables.
3301 DefineUsedVTables();
3302
Douglas Gregordda7ced2009-06-30 17:20:14 +00003303 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003304 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003305 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003306
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003307 // Restore the set of pending vtables.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003308 assert(VTableUses.empty() &&
3309 "VTableUses should be empty before it is discarded.");
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003310 VTableUses.swap(SavedVTableUses);
3311
Douglas Gregordda7ced2009-06-30 17:20:14 +00003312 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003313 assert(PendingInstantiations.empty() &&
3314 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003315 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregordda7ced2009-06-30 17:20:14 +00003316 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003317}
3318
Larisse Voufo39a1e502013-08-06 01:03:05 +00003319VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
3320 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
3321 const TemplateArgumentList &TemplateArgList,
3322 const TemplateArgumentListInfo &TemplateArgsInfo,
3323 SmallVectorImpl<TemplateArgument> &Converted,
3324 SourceLocation PointOfInstantiation, void *InsertPos,
3325 LateInstantiatedAttrVec *LateAttrs,
3326 LocalInstantiationScope *StartingScope) {
3327 if (FromVar->isInvalidDecl())
3328 return 0;
3329
3330 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003331 if (Inst.isInvalid())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003332 return 0;
3333
3334 MultiLevelTemplateArgumentList TemplateArgLists;
3335 TemplateArgLists.addOuterTemplateArguments(&TemplateArgList);
3336
Richard Smith8809a0c2013-09-27 20:14:12 +00003337 // Instantiate the first declaration of the variable template: for a partial
3338 // specialization of a static data member template, the first declaration may
3339 // or may not be the declaration in the class; if it's in the class, we want
3340 // to instantiate a member in the class (a declaration), and if it's outside,
3341 // we want to instantiate a definition.
Rafael Espindola8db352d2013-10-17 15:37:26 +00003342 FromVar = FromVar->getFirstDecl();
Richard Smith8809a0c2013-09-27 20:14:12 +00003343
Manuel Klimek5843add2013-09-30 13:29:01 +00003344 MultiLevelTemplateArgumentList MultiLevelList(TemplateArgList);
3345 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
3346 MultiLevelList);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003347
3348 // TODO: Set LateAttrs and StartingScope ...
3349
3350 return cast_or_null<VarTemplateSpecializationDecl>(
3351 Instantiator.VisitVarTemplateSpecializationDecl(
3352 VarTemplate, FromVar, InsertPos, TemplateArgsInfo, Converted));
3353}
3354
3355/// \brief Instantiates a variable template specialization by completing it
3356/// with appropriate type information and initializer.
3357VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
3358 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
3359 const MultiLevelTemplateArgumentList &TemplateArgs) {
3360
3361 // Do substitution on the type of the declaration
3362 TypeSourceInfo *DI =
Richard Smith8809a0c2013-09-27 20:14:12 +00003363 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
Larisse Voufo39a1e502013-08-06 01:03:05 +00003364 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
3365 if (!DI)
3366 return 0;
3367
3368 // Update the type of this variable template specialization.
3369 VarSpec->setType(DI->getType());
3370
3371 // Instantiate the initializer.
3372 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
3373
3374 return VarSpec;
3375}
3376
3377/// BuildVariableInstantiation - Used after a new variable has been created.
3378/// Sets basic variable data and decides whether to postpone the
3379/// variable instantiation.
3380void Sema::BuildVariableInstantiation(
3381 VarDecl *NewVar, VarDecl *OldVar,
3382 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith541b38b2013-09-20 01:15:31 +00003383 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
3384 LocalInstantiationScope *StartingScope,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003385 bool InstantiatingVarTemplate) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003386
Richard Smith541b38b2013-09-20 01:15:31 +00003387 // If we are instantiating a local extern declaration, the
3388 // instantiation belongs lexically to the containing function.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003389 // If we are instantiating a static data member defined
3390 // out-of-line, the instantiation will have the same lexical
3391 // context (which will be a namespace scope) as the template.
Richard Smith541b38b2013-09-20 01:15:31 +00003392 if (OldVar->isLocalExternDecl()) {
3393 NewVar->setLocalExternDecl();
3394 NewVar->setLexicalDeclContext(Owner);
3395 } else if (OldVar->isOutOfLine())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003396 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
3397 NewVar->setTSCSpec(OldVar->getTSCSpec());
3398 NewVar->setInitStyle(OldVar->getInitStyle());
3399 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
3400 NewVar->setConstexpr(OldVar->isConstexpr());
Richard Smithbb13c9a2013-09-28 04:02:39 +00003401 NewVar->setInitCapture(OldVar->isInitCapture());
Richard Smith1c34fb72013-08-13 18:18:50 +00003402 NewVar->setPreviousDeclInSameBlockScope(
3403 OldVar->isPreviousDeclInSameBlockScope());
Larisse Voufo39a1e502013-08-06 01:03:05 +00003404 NewVar->setAccess(OldVar->getAccess());
3405
Richard Smith0b551192013-09-23 23:12:22 +00003406 if (!OldVar->isStaticDataMember()) {
Rafael Espindolae4865d22013-10-23 16:46:34 +00003407 if (OldVar->isUsed(false))
3408 NewVar->setIsUsed();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003409 NewVar->setReferenced(OldVar->isReferenced());
3410 }
3411
David Majnemer50ce8352013-09-17 23:57:10 +00003412 // See if the old variable had a type-specifier that defined an anonymous tag.
3413 // If it did, mark the new variable as being the declarator for the new
3414 // anonymous tag.
3415 if (const TagType *OldTagType = OldVar->getType()->getAs<TagType>()) {
3416 TagDecl *OldTag = OldTagType->getDecl();
3417 if (OldTag->getDeclaratorForAnonDecl() == OldVar) {
3418 TagDecl *NewTag = NewVar->getType()->castAs<TagType>()->getDecl();
3419 assert(!NewTag->hasNameForLinkage() &&
3420 !NewTag->hasDeclaratorForAnonDecl());
3421 NewTag->setDeclaratorForAnonDecl(NewVar);
3422 }
3423 }
3424
Larisse Voufo39a1e502013-08-06 01:03:05 +00003425 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
3426
3427 if (NewVar->hasAttrs())
3428 CheckAlignasUnderalignment(NewVar);
3429
Richard Smith541b38b2013-09-20 01:15:31 +00003430 LookupResult Previous(
3431 *this, NewVar->getDeclName(), NewVar->getLocation(),
3432 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
3433 : Sema::LookupOrdinaryName,
3434 Sema::ForRedeclaration);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003435
Argyrios Kyrtzidis91486222013-11-27 08:34:14 +00003436 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
3437 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
3438 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
Richard Smith1c34fb72013-08-13 18:18:50 +00003439 // We have a previous declaration. Use that one, so we merge with the
3440 // right type.
3441 if (NamedDecl *NewPrev = FindInstantiatedDecl(
3442 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
3443 Previous.addDecl(NewPrev);
3444 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
3445 OldVar->hasLinkage())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003446 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003447 CheckVariableDeclaration(NewVar, Previous);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003448
Richard Smith541b38b2013-09-20 01:15:31 +00003449 if (!InstantiatingVarTemplate) {
3450 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
3451 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
Larisse Voufo39a1e502013-08-06 01:03:05 +00003452 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
Richard Smith541b38b2013-09-20 01:15:31 +00003453 }
3454
3455 if (!OldVar->isOutOfLine()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003456 if (NewVar->getDeclContext()->isFunctionOrMethod())
3457 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
3458 }
3459
3460 // Link instantiations of static data members back to the template from
3461 // which they were instantiated.
Larisse Voufo72caf2b2013-08-22 00:59:14 +00003462 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003463 NewVar->setInstantiationOfStaticDataMember(OldVar,
3464 TSK_ImplicitInstantiation);
3465
David Majnemerdbc0c8f2013-12-04 09:01:55 +00003466 // Forward the mangling number from the template to the instantiated decl.
3467 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
3468
Richard Smith8809a0c2013-09-27 20:14:12 +00003469 // Delay instantiation of the initializer for variable templates until a
3470 // definition of the variable is needed.
3471 if (!isa<VarTemplateSpecializationDecl>(NewVar) && !InstantiatingVarTemplate)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003472 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
3473
3474 // Diagnose unused local variables with dependent types, where the diagnostic
3475 // will have been deferred.
3476 if (!NewVar->isInvalidDecl() &&
3477 NewVar->getDeclContext()->isFunctionOrMethod() && !NewVar->isUsed() &&
3478 OldVar->getType()->isDependentType())
3479 DiagnoseUnusedDecl(NewVar);
3480}
3481
3482/// \brief Instantiate the initializer of a variable.
3483void Sema::InstantiateVariableInitializer(
3484 VarDecl *Var, VarDecl *OldVar,
3485 const MultiLevelTemplateArgumentList &TemplateArgs) {
3486
3487 if (Var->getAnyInitializer())
3488 // We already have an initializer in the class.
3489 return;
3490
3491 if (OldVar->getInit()) {
3492 if (Var->isStaticDataMember() && !OldVar->isOutOfLine())
3493 PushExpressionEvaluationContext(Sema::ConstantEvaluated, OldVar);
3494 else
3495 PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, OldVar);
3496
3497 // Instantiate the initializer.
3498 ExprResult Init =
3499 SubstInitializer(OldVar->getInit(), TemplateArgs,
3500 OldVar->getInitStyle() == VarDecl::CallInit);
3501 if (!Init.isInvalid()) {
3502 bool TypeMayContainAuto = true;
3503 if (Init.get()) {
3504 bool DirectInit = OldVar->isDirectInit();
3505 AddInitializerToDecl(Var, Init.take(), DirectInit, TypeMayContainAuto);
3506 } else
3507 ActOnUninitializedDecl(Var, TypeMayContainAuto);
3508 } else {
3509 // FIXME: Not too happy about invalidating the declaration
3510 // because of a bogus initializer.
3511 Var->setInvalidDecl();
3512 }
3513
3514 PopExpressionEvaluationContext();
3515 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
3516 !Var->isCXXForRangeDecl())
3517 ActOnUninitializedDecl(Var, false);
3518}
3519
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003520/// \brief Instantiate the definition of the given variable from its
3521/// template.
3522///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003523/// \param PointOfInstantiation the point at which the instantiation was
3524/// required. Note that this is not precisely a "point of instantiation"
3525/// for the function, but it's close.
3526///
3527/// \param Var the already-instantiated declaration of a static member
3528/// variable of a class template specialization.
3529///
3530/// \param Recursive if true, recursively instantiates any functions that
3531/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003532///
3533/// \param DefinitionRequired if true, then we are performing an explicit
3534/// instantiation where an out-of-line definition of the member variable
3535/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003536void Sema::InstantiateStaticDataMemberDefinition(
3537 SourceLocation PointOfInstantiation,
3538 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003539 bool Recursive,
3540 bool DefinitionRequired) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003541 InstantiateVariableDefinition(PointOfInstantiation, Var, Recursive,
3542 DefinitionRequired);
3543}
3544
3545void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
3546 VarDecl *Var, bool Recursive,
3547 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003548 if (Var->isInvalidDecl())
3549 return;
Mike Stump11289f42009-09-09 15:08:12 +00003550
Larisse Voufo39a1e502013-08-06 01:03:05 +00003551 VarTemplateSpecializationDecl *VarSpec =
3552 dyn_cast<VarTemplateSpecializationDecl>(Var);
Richard Smith8809a0c2013-09-27 20:14:12 +00003553 VarDecl *PatternDecl = 0, *Def = 0;
3554 MultiLevelTemplateArgumentList TemplateArgs =
3555 getTemplateInstantiationArgs(Var);
Mike Stump11289f42009-09-09 15:08:12 +00003556
Larisse Voufo39a1e502013-08-06 01:03:05 +00003557 if (VarSpec) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003558 // If this is a variable template specialization, make sure that it is
3559 // non-dependent, then find its instantiation pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003560 bool InstantiationDependent = false;
3561 assert(!TemplateSpecializationType::anyDependentTemplateArguments(
3562 VarSpec->getTemplateArgsInfo(), InstantiationDependent) &&
3563 "Only instantiate variable template specializations that are "
3564 "not type-dependent");
Larisse Voufo4154f462013-08-06 03:57:41 +00003565 (void)InstantiationDependent;
Larisse Voufo39a1e502013-08-06 01:03:05 +00003566
Richard Smith8809a0c2013-09-27 20:14:12 +00003567 // Find the variable initialization that we'll be substituting. If the
3568 // pattern was instantiated from a member template, look back further to
3569 // find the real pattern.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003570 assert(VarSpec->getSpecializedTemplate() &&
3571 "Specialization without specialized template?");
3572 llvm::PointerUnion<VarTemplateDecl *,
3573 VarTemplatePartialSpecializationDecl *> PatternPtr =
3574 VarSpec->getSpecializedTemplateOrPartial();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003575 if (PatternPtr.is<VarTemplatePartialSpecializationDecl *>()) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003576 VarTemplatePartialSpecializationDecl *Tmpl =
3577 PatternPtr.get<VarTemplatePartialSpecializationDecl *>();
3578 while (VarTemplatePartialSpecializationDecl *From =
3579 Tmpl->getInstantiatedFromMember()) {
3580 if (Tmpl->isMemberSpecialization())
3581 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003582
Richard Smith8809a0c2013-09-27 20:14:12 +00003583 Tmpl = From;
3584 }
3585 PatternDecl = Tmpl;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003586 } else {
Richard Smith8809a0c2013-09-27 20:14:12 +00003587 VarTemplateDecl *Tmpl = PatternPtr.get<VarTemplateDecl *>();
3588 while (VarTemplateDecl *From =
3589 Tmpl->getInstantiatedFromMemberTemplate()) {
3590 if (Tmpl->isMemberSpecialization())
3591 break;
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003592
Richard Smith8809a0c2013-09-27 20:14:12 +00003593 Tmpl = From;
3594 }
3595 PatternDecl = Tmpl->getTemplatedDecl();
Larisse Voufoa11bd8a2013-08-13 02:02:26 +00003596 }
Richard Smith8809a0c2013-09-27 20:14:12 +00003597
3598 // If this is a static data member template, there might be an
3599 // uninstantiated initializer on the declaration. If so, instantiate
3600 // it now.
3601 if (PatternDecl->isStaticDataMember() &&
Rafael Espindola8db352d2013-10-17 15:37:26 +00003602 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
Richard Smith8809a0c2013-09-27 20:14:12 +00003603 !Var->hasInit()) {
3604 // FIXME: Factor out the duplicated instantiation context setup/tear down
3605 // code here.
3606 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003607 if (Inst.isInvalid())
Richard Smith8809a0c2013-09-27 20:14:12 +00003608 return;
3609
3610 // If we're performing recursive template instantiation, create our own
3611 // queue of pending implicit instantiations that we will instantiate
3612 // later, while we're still within our own instantiation context.
3613 SmallVector<VTableUse, 16> SavedVTableUses;
3614 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
3615 if (Recursive) {
3616 VTableUses.swap(SavedVTableUses);
3617 PendingInstantiations.swap(SavedPendingInstantiations);
3618 }
3619
3620 LocalInstantiationScope Local(*this);
3621
3622 // Enter the scope of this instantiation. We don't use
3623 // PushDeclContext because we don't have a scope.
3624 ContextRAII PreviousContext(*this, Var->getDeclContext());
3625 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
3626 PreviousContext.pop();
3627
3628 // FIXME: Need to inform the ASTConsumer that we instantiated the
3629 // initializer?
3630
3631 // This variable may have local implicit instantiations that need to be
3632 // instantiated within this scope.
3633 PerformPendingInstantiations(/*LocalOnly=*/true);
3634
3635 Local.Exit();
3636
3637 if (Recursive) {
3638 // Define any newly required vtables.
3639 DefineUsedVTables();
3640
3641 // Instantiate any pending implicit instantiations found during the
3642 // instantiation of this template.
3643 PerformPendingInstantiations();
3644
3645 // Restore the set of pending vtables.
3646 assert(VTableUses.empty() &&
3647 "VTableUses should be empty before it is discarded.");
3648 VTableUses.swap(SavedVTableUses);
3649
3650 // Restore the set of pending implicit instantiations.
3651 assert(PendingInstantiations.empty() &&
3652 "PendingInstantiations should be empty before it is discarded.");
3653 PendingInstantiations.swap(SavedPendingInstantiations);
3654 }
3655 }
3656
3657 // Find actual definition
3658 Def = PatternDecl->getDefinition(getASTContext());
3659 } else {
3660 // If this is a static data member, find its out-of-line definition.
3661 assert(Var->isStaticDataMember() && "not a static data member?");
3662 PatternDecl = Var->getInstantiatedFromStaticDataMember();
3663
3664 assert(PatternDecl && "data member was not instantiated from a template?");
3665 assert(PatternDecl->isStaticDataMember() && "not a static data member?");
3666 Def = PatternDecl->getOutOfLineDefinition();
Larisse Voufo39a1e502013-08-06 01:03:05 +00003667 }
3668
Richard Smith8809a0c2013-09-27 20:14:12 +00003669 // If we don't have a definition of the variable template, we won't perform
3670 // any instantiation. Rather, we rely on the user to instantiate this
3671 // definition (or provide a specialization for it) in another translation
3672 // unit.
3673 if (!Def) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00003674 if (DefinitionRequired) {
Richard Smith8809a0c2013-09-27 20:14:12 +00003675 if (VarSpec)
Larisse Voufo39a1e502013-08-06 01:03:05 +00003676 Diag(PointOfInstantiation,
Richard Smith8809a0c2013-09-27 20:14:12 +00003677 diag::err_explicit_instantiation_undefined_var_template) << Var;
3678 else
Larisse Voufo39a1e502013-08-06 01:03:05 +00003679 Diag(PointOfInstantiation,
3680 diag::err_explicit_instantiation_undefined_member)
Richard Smith8809a0c2013-09-27 20:14:12 +00003681 << 2 << Var->getDeclName() << Var->getDeclContext();
3682 Diag(PatternDecl->getLocation(),
3683 diag::note_explicit_instantiation_here);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003684 if (VarSpec)
3685 Var->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003686 } else if (Var->getTemplateSpecializationKind()
3687 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003688 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003689 std::make_pair(Var, PointOfInstantiation));
3690 }
3691
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003692 return;
3693 }
3694
Rafael Espindola189fa742012-03-05 10:54:55 +00003695 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3696
Douglas Gregor86d142a2009-10-08 07:24:58 +00003697 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003698 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003699 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003700
Larisse Voufo39a1e502013-08-06 01:03:05 +00003701 // C++11 [temp.explicit]p10:
3702 // Except for inline functions, [...] explicit instantiation declarations
3703 // have the effect of suppressing the implicit instantiation of the entity
3704 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003705 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003706 return;
Mike Stump11289f42009-09-09 15:08:12 +00003707
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003708 // Make sure to pass the instantiated variable to the consumer at the end.
3709 struct PassToConsumerRAII {
3710 ASTConsumer &Consumer;
3711 VarDecl *Var;
3712
3713 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3714 : Consumer(Consumer), Var(Var) { }
3715
3716 ~PassToConsumerRAII() {
Richard Smith8809a0c2013-09-27 20:14:12 +00003717 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003718 }
3719 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003720
Richard Smith8809a0c2013-09-27 20:14:12 +00003721 // If we already have a definition, we're done.
3722 if (VarDecl *Def = Var->getDefinition()) {
3723 // We may be explicitly instantiating something we've already implicitly
3724 // instantiated.
3725 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3726 PointOfInstantiation);
3727 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003728 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003729
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003730 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
Alp Tokerd4a72d52013-10-08 08:09:04 +00003731 if (Inst.isInvalid())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003732 return;
Mike Stump11289f42009-09-09 15:08:12 +00003733
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003734 // If we're performing recursive template instantiation, create our own
3735 // queue of pending implicit instantiations that we will instantiate later,
3736 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003737 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003738 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
David Majnemerfd6c685f2013-11-27 22:57:44 +00003739 SavePendingLocalImplicitInstantiationsRAII
3740 SavedPendingLocalImplicitInstantiations(*this);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003741 if (Recursive) {
3742 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003743 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003744 }
Mike Stump11289f42009-09-09 15:08:12 +00003745
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003746 // Enter the scope of this instantiation. We don't use
3747 // PushDeclContext because we don't have a scope.
Larisse Voufo39a1e502013-08-06 01:03:05 +00003748 ContextRAII PreviousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003749 LocalInstantiationScope Local(*this);
John McCall2957e3e2011-02-14 20:37:25 +00003750
Larisse Voufo39a1e502013-08-06 01:03:05 +00003751 VarDecl *OldVar = Var;
3752 if (!VarSpec)
3753 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Richard Smith8809a0c2013-09-27 20:14:12 +00003754 TemplateArgs));
3755 else if (Var->isStaticDataMember() &&
3756 Var->getLexicalDeclContext()->isRecord()) {
3757 // We need to instantiate the definition of a static data member template,
3758 // and all we have is the in-class declaration of it. Instantiate a separate
3759 // declaration of the definition.
3760 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
3761 TemplateArgs);
3762 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
3763 VarSpec->getSpecializedTemplate(), Def, 0,
3764 VarSpec->getTemplateArgsInfo(), VarSpec->getTemplateArgs().asArray()));
3765 if (Var) {
3766 llvm::PointerUnion<VarTemplateDecl *,
3767 VarTemplatePartialSpecializationDecl *> PatternPtr =
3768 VarSpec->getSpecializedTemplateOrPartial();
3769 if (VarTemplatePartialSpecializationDecl *Partial =
3770 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
3771 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
3772 Partial, &VarSpec->getTemplateInstantiationArgs());
3773
3774 // Merge the definition with the declaration.
3775 LookupResult R(*this, Var->getDeclName(), Var->getLocation(),
3776 LookupOrdinaryName, ForRedeclaration);
3777 R.addDecl(OldVar);
3778 MergeVarDecl(Var, R);
3779
3780 // Attach the initializer.
3781 InstantiateVariableInitializer(Var, Def, TemplateArgs);
3782 }
3783 } else
3784 // Complete the existing variable's definition with an appropriately
3785 // substituted type and initializer.
3786 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
Larisse Voufo39a1e502013-08-06 01:03:05 +00003787
3788 PreviousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003789
3790 if (Var) {
Larisse Voufo39a1e502013-08-06 01:03:05 +00003791 PassToConsumerRAII.Var = Var;
Richard Smith8809a0c2013-09-27 20:14:12 +00003792 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
3793 OldVar->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003794 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00003795
3796 // This variable may have local implicit instantiations that need to be
3797 // instantiated within this scope.
3798 PerformPendingInstantiations(/*LocalOnly=*/true);
3799
Douglas Gregora86bc002012-02-16 21:36:18 +00003800 Local.Exit();
3801
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003802 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003803 // Define any newly required vtables.
3804 DefineUsedVTables();
3805
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003806 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003807 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003808 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003809
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003810 // Restore the set of pending vtables.
3811 assert(VTableUses.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003812 "VTableUses should be empty before it is discarded.");
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003813 VTableUses.swap(SavedVTableUses);
3814
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003815 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003816 assert(PendingInstantiations.empty() &&
Larisse Voufo39a1e502013-08-06 01:03:05 +00003817 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003818 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00003819 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003820}
Douglas Gregor51783312009-05-27 05:35:12 +00003821
Anders Carlsson70553942009-08-29 05:16:22 +00003822void
3823Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3824 const CXXConstructorDecl *Tmpl,
3825 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003826
Richard Trieu9becef62011-09-09 03:18:59 +00003827 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00003828 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003829
Anders Carlsson70553942009-08-29 05:16:22 +00003830 // Instantiate all the initializers.
3831 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregora3a3f6f2009-09-01 21:04:42 +00003832 InitsEnd = Tmpl->init_end();
3833 Inits != InitsEnd; ++Inits) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003834 CXXCtorInitializer *Init = *Inits;
Anders Carlsson70553942009-08-29 05:16:22 +00003835
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00003836 // Only instantiate written initializers, let Sema re-construct implicit
3837 // ones.
3838 if (!Init->isWritten())
3839 continue;
3840
Douglas Gregor44e7df62011-01-04 00:32:56 +00003841 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003842
Douglas Gregor44e7df62011-01-04 00:32:56 +00003843 if (Init->isPackExpansion()) {
3844 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003845 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00003846 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003847 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00003848 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003849 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003850 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00003851 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003852 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003853 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00003854 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003855 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003856 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003857 NumExpansions)) {
3858 AnyErrors = true;
3859 New->setInvalidDecl();
3860 continue;
3861 }
3862 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003863
3864 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003865 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003866 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3867
3868 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00003869 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3870 /*CXXDirectInit=*/true);
3871 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003872 AnyErrors = true;
3873 break;
3874 }
3875
3876 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003877 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003878 TemplateArgs,
3879 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003880 New->getDeclName());
3881 if (!BaseTInfo) {
3882 AnyErrors = true;
3883 break;
3884 }
3885
3886 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00003887 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redla9351792012-02-11 23:51:47 +00003888 BaseTInfo, TempInit.take(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003889 New->getParent(),
3890 SourceLocation());
3891 if (NewInit.isInvalid()) {
3892 AnyErrors = true;
3893 break;
3894 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003895
Douglas Gregor44e7df62011-01-04 00:32:56 +00003896 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00003897 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003898
Douglas Gregor44e7df62011-01-04 00:32:56 +00003899 continue;
3900 }
3901
Douglas Gregorb30f22b2010-03-02 07:38:39 +00003902 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00003903 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3904 /*CXXDirectInit=*/true);
3905 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00003906 AnyErrors = true;
3907 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00003908 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003909
Anders Carlsson70553942009-08-29 05:16:22 +00003910 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003911 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3912 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3913 TemplateArgs,
3914 Init->getSourceLocation(),
3915 New->getDeclName());
3916 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003917 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003918 New->setInvalidDecl();
3919 continue;
3920 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003921
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003922 if (Init->isBaseInitializer())
Sebastian Redla9351792012-02-11 23:51:47 +00003923 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003924 New->getParent(), EllipsisLoc);
3925 else
Sebastian Redla9351792012-02-11 23:51:47 +00003926 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003927 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00003928 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00003929 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00003930 Init->getMemberLocation(),
3931 Init->getMember(),
3932 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00003933 if (!Member) {
3934 AnyErrors = true;
3935 New->setInvalidDecl();
3936 continue;
3937 }
Mike Stump11289f42009-09-09 15:08:12 +00003938
Sebastian Redla9351792012-02-11 23:51:47 +00003939 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00003940 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00003941 } else if (Init->isIndirectMemberInitializer()) {
3942 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00003943 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00003944 Init->getMemberLocation(),
3945 Init->getIndirectMember(), TemplateArgs));
3946
Douglas Gregor55e6b312011-03-04 19:46:35 +00003947 if (!IndirectMember) {
3948 AnyErrors = true;
3949 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00003950 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00003951 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003952
Sebastian Redla9351792012-02-11 23:51:47 +00003953 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00003954 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00003955 }
3956
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003957 if (NewInit.isInvalid()) {
3958 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00003959 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003960 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00003961 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00003962 }
3963 }
Mike Stump11289f42009-09-09 15:08:12 +00003964
Anders Carlsson70553942009-08-29 05:16:22 +00003965 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00003966 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00003967 /*FIXME: ColonLoc */
3968 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00003969 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003970 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00003971}
3972
John McCall59660882009-08-29 08:11:13 +00003973// TODO: this could be templated if the various decl types used the
3974// same method name.
3975static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3976 ClassTemplateDecl *Instance) {
3977 Pattern = Pattern->getCanonicalDecl();
3978
3979 do {
3980 Instance = Instance->getCanonicalDecl();
3981 if (Pattern == Instance) return true;
3982 Instance = Instance->getInstantiatedFromMemberTemplate();
3983 } while (Instance);
3984
3985 return false;
3986}
3987
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003988static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3989 FunctionTemplateDecl *Instance) {
3990 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003991
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003992 do {
3993 Instance = Instance->getCanonicalDecl();
3994 if (Pattern == Instance) return true;
3995 Instance = Instance->getInstantiatedFromMemberTemplate();
3996 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003997
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003998 return false;
3999}
4000
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004001static bool
Douglas Gregor21610382009-10-29 00:04:11 +00004002isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
4003 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004004 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00004005 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
4006 do {
4007 Instance = cast<ClassTemplatePartialSpecializationDecl>(
4008 Instance->getCanonicalDecl());
4009 if (Pattern == Instance)
4010 return true;
4011 Instance = Instance->getInstantiatedFromMember();
4012 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004013
Douglas Gregor21610382009-10-29 00:04:11 +00004014 return false;
4015}
4016
John McCall59660882009-08-29 08:11:13 +00004017static bool isInstantiationOf(CXXRecordDecl *Pattern,
4018 CXXRecordDecl *Instance) {
4019 Pattern = Pattern->getCanonicalDecl();
4020
4021 do {
4022 Instance = Instance->getCanonicalDecl();
4023 if (Pattern == Instance) return true;
4024 Instance = Instance->getInstantiatedFromMemberClass();
4025 } while (Instance);
4026
4027 return false;
4028}
4029
4030static bool isInstantiationOf(FunctionDecl *Pattern,
4031 FunctionDecl *Instance) {
4032 Pattern = Pattern->getCanonicalDecl();
4033
4034 do {
4035 Instance = Instance->getCanonicalDecl();
4036 if (Pattern == Instance) return true;
4037 Instance = Instance->getInstantiatedFromMemberFunction();
4038 } while (Instance);
4039
4040 return false;
4041}
4042
4043static bool isInstantiationOf(EnumDecl *Pattern,
4044 EnumDecl *Instance) {
4045 Pattern = Pattern->getCanonicalDecl();
4046
4047 do {
4048 Instance = Instance->getCanonicalDecl();
4049 if (Pattern == Instance) return true;
4050 Instance = Instance->getInstantiatedFromMemberEnum();
4051 } while (Instance);
4052
4053 return false;
4054}
4055
John McCallb96ec562009-12-04 22:46:56 +00004056static bool isInstantiationOf(UsingShadowDecl *Pattern,
4057 UsingShadowDecl *Instance,
4058 ASTContext &C) {
4059 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
4060}
4061
4062static bool isInstantiationOf(UsingDecl *Pattern,
4063 UsingDecl *Instance,
4064 ASTContext &C) {
4065 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
4066}
4067
John McCalle61f2ba2009-11-18 02:36:19 +00004068static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
4069 UsingDecl *Instance,
4070 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004071 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00004072}
4073
4074static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004075 UsingDecl *Instance,
4076 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00004077 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004078}
4079
John McCall59660882009-08-29 08:11:13 +00004080static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
4081 VarDecl *Instance) {
4082 assert(Instance->isStaticDataMember());
4083
4084 Pattern = Pattern->getCanonicalDecl();
4085
4086 do {
4087 Instance = Instance->getCanonicalDecl();
4088 if (Pattern == Instance) return true;
4089 Instance = Instance->getInstantiatedFromStaticDataMember();
4090 } while (Instance);
4091
4092 return false;
4093}
4094
John McCallb96ec562009-12-04 22:46:56 +00004095// Other is the prospective instantiation
4096// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00004097static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004098 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00004099 if (UnresolvedUsingTypenameDecl *UUD
4100 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
4101 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4102 return isInstantiationOf(UUD, UD, Ctx);
4103 }
4104 }
4105
4106 if (UnresolvedUsingValueDecl *UUD
4107 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004108 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
4109 return isInstantiationOf(UUD, UD, Ctx);
4110 }
4111 }
Douglas Gregor51783312009-05-27 05:35:12 +00004112
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00004113 return false;
4114 }
Mike Stump11289f42009-09-09 15:08:12 +00004115
John McCall59660882009-08-29 08:11:13 +00004116 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
4117 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00004118
John McCall59660882009-08-29 08:11:13 +00004119 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
4120 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00004121
John McCall59660882009-08-29 08:11:13 +00004122 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
4123 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00004124
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004125 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00004126 if (Var->isStaticDataMember())
4127 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
4128
4129 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
4130 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00004131
Douglas Gregor14d1bf42009-09-28 06:34:35 +00004132 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
4133 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
4134
Douglas Gregor21610382009-10-29 00:04:11 +00004135 if (ClassTemplatePartialSpecializationDecl *PartialSpec
4136 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
4137 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
4138 PartialSpec);
4139
Anders Carlsson5da84842009-09-01 04:26:58 +00004140 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
4141 if (!Field->getDeclName()) {
4142 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00004143 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00004144 cast<FieldDecl>(D);
4145 }
4146 }
Mike Stump11289f42009-09-09 15:08:12 +00004147
John McCallb96ec562009-12-04 22:46:56 +00004148 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
4149 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
4150
4151 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
4152 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
4153
Douglas Gregor51783312009-05-27 05:35:12 +00004154 return D->getDeclName() && isa<NamedDecl>(Other) &&
4155 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
4156}
4157
4158template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00004159static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00004160 NamedDecl *D,
4161 ForwardIterator first,
4162 ForwardIterator last) {
4163 for (; first != last; ++first)
4164 if (isInstantiationOf(Ctx, D, *first))
4165 return cast<NamedDecl>(*first);
4166
4167 return 0;
4168}
4169
John McCallaa74a0c2009-08-28 07:59:38 +00004170/// \brief Finds the instantiation of the given declaration context
4171/// within the current instantiation.
4172///
4173/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004174DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00004175 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00004176 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004177 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00004178 return cast_or_null<DeclContext>(ID);
4179 } else return DC;
4180}
4181
Douglas Gregorcd3a0972009-05-27 17:54:46 +00004182/// \brief Find the instantiation of the given declaration within the
4183/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00004184///
4185/// This routine is intended to be used when \p D is a declaration
4186/// referenced from within a template, that needs to mapped into the
4187/// corresponding declaration within an instantiation. For example,
4188/// given:
4189///
4190/// \code
4191/// template<typename T>
4192/// struct X {
4193/// enum Kind {
4194/// KnownValue = sizeof(T)
4195/// };
4196///
4197/// bool getKind() const { return KnownValue; }
4198/// };
4199///
4200/// template struct X<int>;
4201/// \endcode
4202///
Serge Pavloved5fe902013-07-10 04:59:14 +00004203/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
4204/// \p EnumConstantDecl for \p KnownValue (which refers to
4205/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
4206/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
4207/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004208NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00004209 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00004210 DeclContext *ParentDC = D->getDeclContext();
Faisal Vali2cba1332013-10-23 06:44:28 +00004211 // FIXME: Parmeters of pointer to functions (y below) that are themselves
4212 // parameters (p below) can have their ParentDC set to the translation-unit
4213 // - thus we can not consistently check if the ParentDC of such a parameter
4214 // is Dependent or/and a FunctionOrMethod.
4215 // For e.g. this code, during Template argument deduction tries to
4216 // find an instantiated decl for (T y) when the ParentDC for y is
4217 // the translation unit.
4218 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
4219 // float baz(float(*)()) { return 0.0; }
4220 // Foo(baz);
4221 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
4222 // it gets here, always has a FunctionOrMethod as its ParentDC??
4223 // For now:
4224 // - as long as we have a ParmVarDecl whose parent is non-dependent and
4225 // whose type is not instantiation dependent, do nothing to the decl
4226 // - otherwise find its instantiated decl.
4227 if (isa<ParmVarDecl>(D) && !ParentDC->isDependentContext() &&
4228 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
4229 return D;
Rafael Espindola09b00e32013-10-23 04:12:23 +00004230 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00004231 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00004232 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
4233 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004234 // D is a local of some kind. Look into the map of local
4235 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00004236 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
4237 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
4238 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004239
Chris Lattnercab02a62011-02-17 20:34:02 +00004240 if (Found) {
4241 if (Decl *FD = Found->dyn_cast<Decl *>())
4242 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004243
Richard Smithb15fe3a2012-09-12 00:56:43 +00004244 int PackIdx = ArgumentPackSubstitutionIndex;
4245 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00004246 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
4247 }
4248
Serge Pavlov7cd8f602013-07-15 06:14:07 +00004249 // If we're performing a partial substitution during template argument
4250 // deduction, we may not have values for template parameters yet. They
4251 // just map to themselves.
4252 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4253 isa<TemplateTemplateParmDecl>(D))
4254 return D;
4255
Serge Pavlov074a5182013-08-10 12:00:21 +00004256 if (D->isInvalidDecl())
4257 return 0;
4258
Chris Lattnercab02a62011-02-17 20:34:02 +00004259 // If we didn't find the decl, then we must have a label decl that hasn't
4260 // been found yet. Lazily instantiate it and return it now.
4261 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004262
Chris Lattnercab02a62011-02-17 20:34:02 +00004263 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
4264 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004265
Chris Lattnercab02a62011-02-17 20:34:02 +00004266 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
4267 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00004268 }
Douglas Gregor51783312009-05-27 05:35:12 +00004269
Larisse Voufo39a1e502013-08-06 01:03:05 +00004270 // For variable template specializations, update those that are still
4271 // type-dependent.
4272 if (VarTemplateSpecializationDecl *VarSpec =
4273 dyn_cast<VarTemplateSpecializationDecl>(D)) {
4274 bool InstantiationDependent = false;
4275 const TemplateArgumentListInfo &VarTemplateArgs =
4276 VarSpec->getTemplateArgsInfo();
4277 if (TemplateSpecializationType::anyDependentTemplateArguments(
4278 VarTemplateArgs, InstantiationDependent))
4279 D = cast<NamedDecl>(
4280 SubstDecl(D, VarSpec->getDeclContext(), TemplateArgs));
4281 return D;
4282 }
4283
Douglas Gregor64621e62009-09-16 18:34:49 +00004284 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
4285 if (!Record->isDependentContext())
4286 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004287
Douglas Gregor4109afa2011-11-07 17:43:18 +00004288 // Determine whether this record is the "templated" declaration describing
4289 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00004290 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00004291 if (ClassTemplate)
4292 ClassTemplate = ClassTemplate->getCanonicalDecl();
4293 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
4294 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
4295 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
Larisse Voufo39a1e502013-08-06 01:03:05 +00004296
Douglas Gregor4109afa2011-11-07 17:43:18 +00004297 // Walk the current context to find either the record or an instantiation of
4298 // it.
4299 DeclContext *DC = CurContext;
4300 while (!DC->isFileContext()) {
4301 // If we're performing substitution while we're inside the template
4302 // definition, we'll find our own context. We're done.
4303 if (DC->Equals(Record))
4304 return Record;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004305
Douglas Gregor4109afa2011-11-07 17:43:18 +00004306 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
4307 // Check whether we're in the process of instantiating a class template
4308 // specialization of the template we're mapping.
4309 if (ClassTemplateSpecializationDecl *InstSpec
4310 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
4311 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
4312 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
4313 return InstRecord;
4314 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004315
Douglas Gregor4109afa2011-11-07 17:43:18 +00004316 // Check whether we're in the process of instantiating a member class.
4317 if (isInstantiationOf(Record, InstRecord))
4318 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00004319 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004320
Douglas Gregor4109afa2011-11-07 17:43:18 +00004321 // Move to the outer template scope.
4322 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
4323 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
4324 DC = FD->getLexicalDeclContext();
4325 continue;
4326 }
John McCall59660882009-08-29 08:11:13 +00004327 }
Larisse Voufo39a1e502013-08-06 01:03:05 +00004328
Douglas Gregor4109afa2011-11-07 17:43:18 +00004329 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00004330 }
Douglas Gregord225fa02010-02-05 22:40:03 +00004331
Douglas Gregor64621e62009-09-16 18:34:49 +00004332 // Fall through to deal with other dependent record types (e.g.,
4333 // anonymous unions in class templates).
4334 }
John McCall59660882009-08-29 08:11:13 +00004335
Douglas Gregor64621e62009-09-16 18:34:49 +00004336 if (!ParentDC->isDependentContext())
4337 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004338
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004339 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00004340 if (!ParentDC)
Douglas Gregor2ffd9652009-09-01 17:53:10 +00004341 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004342
Douglas Gregor51783312009-05-27 05:35:12 +00004343 if (ParentDC != D->getDeclContext()) {
4344 // We performed some kind of instantiation in the parent context,
4345 // so now we need to look into the instantiated parent context to
4346 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004347
John McCalle78aac42010-03-10 03:28:59 +00004348 // If our context used to be dependent, we may need to instantiate
4349 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00004350 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00004351 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004352 if (!Spec->isDependentContext()) {
4353 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00004354 const RecordType *Tag = T->getAs<RecordType>();
4355 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00004356 if (Tag->isBeingDefined())
4357 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00004358 if (!Tag->isBeingDefined() &&
4359 RequireCompleteType(Loc, T, diag::err_incomplete_type))
4360 return 0;
Douglas Gregor25edf432010-11-05 23:22:45 +00004361
4362 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00004363 }
4364 }
4365
Douglas Gregor51783312009-05-27 05:35:12 +00004366 NamedDecl *Result = 0;
4367 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004368 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00004369 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00004370 } else {
4371 // Since we don't have a name for the entity we're looking for,
4372 // our only option is to walk through all of the declarations to
4373 // find that name. This will occur in a few cases:
4374 //
4375 // - anonymous struct/union within a template
4376 // - unnamed class/struct/union/enum within a template
4377 //
4378 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00004379 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004380 ParentDC->decls_begin(),
4381 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00004382 }
Mike Stump11289f42009-09-09 15:08:12 +00004383
Douglas Gregor528ad932011-03-06 20:12:45 +00004384 if (!Result) {
4385 if (isa<UsingShadowDecl>(D)) {
4386 // UsingShadowDecls can instantiate to nothing because of using hiding.
4387 } else if (Diags.hasErrorOccurred()) {
4388 // We've already complained about something, so most likely this
4389 // declaration failed to instantiate. There's no point in complaining
4390 // further, since this is normal in invalid code.
4391 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004392 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00004393 // instantiated, and we haven't gotten around to instantiating this
4394 // member yet. This can happen when the code uses forward declarations
4395 // of member classes, and introduces ordering dependencies via
4396 // template instantiation.
4397 Diag(Loc, diag::err_member_not_yet_instantiated)
4398 << D->getDeclName()
4399 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
4400 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00004401 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
4402 // This enumeration constant was found when the template was defined,
4403 // but can't be found in the instantiation. This can happen if an
4404 // unscoped enumeration member is explicitly specialized.
4405 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
4406 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
4407 TemplateArgs));
4408 assert(Spec->getTemplateSpecializationKind() ==
4409 TSK_ExplicitSpecialization);
4410 Diag(Loc, diag::err_enumerator_does_not_exist)
4411 << D->getDeclName()
4412 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
4413 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
4414 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00004415 } else {
4416 // We should have found something, but didn't.
4417 llvm_unreachable("Unable to find instantiation of declaration!");
4418 }
4419 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004420
Douglas Gregor51783312009-05-27 05:35:12 +00004421 D = Result;
4422 }
4423
Douglas Gregor51783312009-05-27 05:35:12 +00004424 return D;
4425}
Douglas Gregor77b50e12009-06-22 23:06:13 +00004426
Mike Stump11289f42009-09-09 15:08:12 +00004427/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00004428/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00004429void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregore39f97c2011-07-28 19:49:54 +00004430 // Load pending instantiations from the external source.
4431 if (!LocalOnly && ExternalSource) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00004432 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregore39f97c2011-07-28 19:49:54 +00004433 ExternalSource->ReadPendingInstantiations(Pending);
4434 PendingInstantiations.insert(PendingInstantiations.begin(),
4435 Pending.begin(), Pending.end());
4436 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00004437
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004438 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00004439 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004440 PendingImplicitInstantiation Inst;
4441
4442 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00004443 Inst = PendingInstantiations.front();
4444 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00004445 } else {
4446 Inst = PendingLocalImplicitInstantiations.front();
4447 PendingLocalImplicitInstantiations.pop_front();
4448 }
Mike Stump11289f42009-09-09 15:08:12 +00004449
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004450 // Instantiate function definitions
4451 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00004452 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
4453 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004454 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
4455 TSK_ExplicitInstantiationDefinition;
4456 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
4457 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004458 continue;
4459 }
Mike Stump11289f42009-09-09 15:08:12 +00004460
Larisse Voufo39a1e502013-08-06 01:03:05 +00004461 // Instantiate variable definitions
Douglas Gregora6ef8f02009-07-24 20:34:43 +00004462 VarDecl *Var = cast<VarDecl>(Inst.first);
Larisse Voufo39a1e502013-08-06 01:03:05 +00004463
4464 assert((Var->isStaticDataMember() ||
4465 isa<VarTemplateSpecializationDecl>(Var)) &&
4466 "Not a static data member, nor a variable template"
4467 " specialization?");
Anders Carlsson62215c42009-09-01 05:12:24 +00004468
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004469 // Don't try to instantiate declarations if the most recent redeclaration
4470 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004471 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004472 continue;
4473
4474 // Check if the most recent declaration has changed the specialization kind
4475 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004476 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004477 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00004478 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004479 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004480 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004481 continue; // No longer need to instantiate this type.
4482 case TSK_ExplicitInstantiationDefinition:
4483 // We only need an instantiation if the pending instantiation *is* the
4484 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00004485 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00004486 case TSK_ImplicitInstantiation:
4487 break;
4488 }
4489
Larisse Voufo39a1e502013-08-06 01:03:05 +00004490 PrettyDeclStackTraceEntry CrashInfo(*this, Var, SourceLocation(),
4491 "instantiating variable definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00004492 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
4493 TSK_ExplicitInstantiationDefinition;
Larisse Voufo39a1e502013-08-06 01:03:05 +00004494
4495 // Instantiate static data member definitions or variable template
4496 // specializations.
4497 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
4498 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00004499 }
4500}
John McCallc62bb642010-03-24 05:22:00 +00004501
4502void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
4503 const MultiLevelTemplateArgumentList &TemplateArgs) {
4504 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
4505 E = Pattern->ddiag_end(); I != E; ++I) {
4506 DependentDiagnostic *DD = *I;
4507
4508 switch (DD->getKind()) {
4509 case DependentDiagnostic::Access:
4510 HandleDependentAccessCheck(*DD, TemplateArgs);
4511 break;
4512 }
4513 }
4514}