blob: 52075229971a0c8474d2032f3a2bf463d1a08699 [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
John McCall3e11ebe2010-03-15 10:12:16 +000028bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000030 if (!OldDecl->getQualifierLoc())
31 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000032
Douglas Gregor14454802011-02-25 02:25:35 +000033 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000034 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000035 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000036
Douglas Gregor14454802011-02-25 02:25:35 +000037 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000038 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000039
Douglas Gregor14454802011-02-25 02:25:35 +000040 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000041 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
Douglas Gregor14454802011-02-25 02:25:35 +000046 if (!OldDecl->getQualifierLoc())
47 return false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000048
Douglas Gregor14454802011-02-25 02:25:35 +000049 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000050 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregor14454802011-02-25 02:25:35 +000051 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000052
Douglas Gregor14454802011-02-25 02:25:35 +000053 if (!NewQualifierLoc)
John McCall3e11ebe2010-03-15 10:12:16 +000054 return true;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +000055
Douglas Gregor14454802011-02-25 02:25:35 +000056 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +000057 return false;
58}
59
DeLesley Hutchinsceec3062012-01-20 22:37:06 +000060// Include attribute instantiation code.
61#include "clang/Sema/AttrTemplateInstantiate.inc"
62
Richard Smith44c247f2013-02-22 08:32:16 +000063static void instantiateDependentAlignedAttr(
64 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
65 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
66 if (Aligned->isAlignmentExpr()) {
67 // The alignment expression is a constant expression.
68 EnterExpressionEvaluationContext Unevaluated(S, Sema::ConstantEvaluated);
69 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
70 if (!Result.isInvalid())
71 S.AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
72 Aligned->getSpellingListIndex(), IsPackExpansion);
73 } else {
74 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
75 TemplateArgs, Aligned->getLocation(),
76 DeclarationName());
77 if (Result)
78 S.AddAlignedAttr(Aligned->getLocation(), New, Result,
79 Aligned->getSpellingListIndex(), IsPackExpansion);
80 }
81}
82
83static void instantiateDependentAlignedAttr(
84 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
85 const AlignedAttr *Aligned, Decl *New) {
86 if (!Aligned->isPackExpansion()) {
87 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
88 return;
89 }
90
91 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
92 if (Aligned->isAlignmentExpr())
93 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
94 Unexpanded);
95 else
96 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
97 Unexpanded);
98 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
99
100 // Determine whether we can expand this attribute pack yet.
101 bool Expand = true, RetainExpansion = false;
102 Optional<unsigned> NumExpansions;
103 // FIXME: Use the actual location of the ellipsis.
104 SourceLocation EllipsisLoc = Aligned->getLocation();
105 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
106 Unexpanded, TemplateArgs, Expand,
107 RetainExpansion, NumExpansions))
108 return;
109
110 if (!Expand) {
111 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
112 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
113 } else {
114 for (unsigned I = 0; I != *NumExpansions; ++I) {
115 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
116 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
117 }
118 }
119}
120
John McCall6602bb12010-08-01 02:01:53 +0000121void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000122 const Decl *Tmpl, Decl *New,
123 LateInstantiatedAttrVec *LateAttrs,
124 LocalInstantiationScope *OuterMostScope) {
Alexis Huntdcfba7b2010-08-18 23:23:40 +0000125 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
126 i != e; ++i) {
127 const Attr *TmplAttr = *i;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000128
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000129 // FIXME: This should be generalized to more than just the AlignedAttr.
Richard Smith44c247f2013-02-22 08:32:16 +0000130 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
131 if (Aligned && Aligned->isAlignmentDependent()) {
132 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
133 continue;
Chandler Carruthf40c42f2010-06-25 03:22:07 +0000134 }
135
Richard Smith44c247f2013-02-22 08:32:16 +0000136 assert(!TmplAttr->isPackExpansion());
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000137 if (TmplAttr->isLateParsed() && LateAttrs) {
138 // Late parsed attributes must be instantiated and attached after the
139 // enclosing class has been instantiated. See Sema::InstantiateClass.
140 LocalInstantiationScope *Saved = 0;
141 if (CurrentInstantiationScope)
142 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
143 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
144 } else {
Richard Smithc3d2ebb2013-06-07 02:33:37 +0000145 // Allow 'this' within late-parsed attributes.
146 NamedDecl *ND = dyn_cast<NamedDecl>(New);
147 CXXRecordDecl *ThisContext =
148 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
149 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
150 ND && ND->isCXXInstanceMember());
151
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +0000152 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
153 *this, TemplateArgs);
Rafael Espindola7f90b7d2012-05-15 14:09:55 +0000154 if (NewAttr)
155 New->addAttr(NewAttr);
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000156 }
Anders Carlsson3d709752009-11-07 06:07:58 +0000157 }
158}
159
Douglas Gregor8a655532009-03-25 15:45:12 +0000160Decl *
161TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000162 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000163}
164
165Decl *
Chris Lattnercab02a62011-02-17 20:34:02 +0000166TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
167 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
168 D->getIdentifier());
169 Owner->addDecl(Inst);
170 return Inst;
171}
172
173Decl *
Douglas Gregor8a655532009-03-25 15:45:12 +0000174TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000175 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor8a655532009-03-25 15:45:12 +0000176}
177
John McCalld8d0d432010-02-16 06:53:13 +0000178Decl *
179TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
180 NamespaceAliasDecl *Inst
181 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
182 D->getNamespaceLoc(),
183 D->getAliasLoc(),
Douglas Gregorc05ba2e2011-02-25 17:08:07 +0000184 D->getIdentifier(),
185 D->getQualifierLoc(),
John McCalld8d0d432010-02-16 06:53:13 +0000186 D->getTargetNameLoc(),
187 D->getNamespace());
188 Owner->addDecl(Inst);
189 return Inst;
190}
191
Richard Smith3f1b5d02011-05-05 21:57:07 +0000192Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
193 bool IsTypeAlias) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000194 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000195 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000196 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000197 DI->getType()->isVariablyModifiedType()) {
John McCall703a3f82009-10-24 08:00:42 +0000198 DI = SemaRef.SubstType(DI, TemplateArgs,
199 D->getLocation(), D->getDeclName());
200 if (!DI) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000201 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000202 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000203 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000204 } else {
205 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000206 }
Mike Stump11289f42009-09-09 15:08:12 +0000207
Richard Smith2ddcbab2012-10-23 00:32:41 +0000208 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
209 // libstdc++ relies upon this bug in its implementation of common_type.
210 // If we happen to be processing that implementation, fake up the g++ ?:
211 // semantics. See LWG issue 2141 for more information on the bug.
212 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
213 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
214 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
215 DT->isReferenceType() &&
216 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
217 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
218 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
219 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
220 // Fold it to the (non-reference) type which g++ would have produced.
221 DI = SemaRef.Context.getTrivialTypeSourceInfo(
222 DI->getType().getNonReferenceType());
223
Douglas Gregord7e7a512009-03-17 21:15:40 +0000224 // Create the new typedef
Richard Smithdda56e42011-04-15 14:24:37 +0000225 TypedefNameDecl *Typedef;
226 if (IsTypeAlias)
227 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
228 D->getLocation(), D->getIdentifier(), DI);
229 else
230 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
231 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000232 if (Invalid)
233 Typedef->setInvalidDecl();
234
John McCall04fcd0d2011-02-01 08:20:08 +0000235 // If the old typedef was the name for linkage purposes of an anonymous
236 // tag decl, re-establish that relationship for the new typedef.
237 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
238 TagDecl *oldTag = oldTagType->getDecl();
Douglas Gregord831d952013-03-08 22:15:15 +0000239 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
John McCall04fcd0d2011-02-01 08:20:08 +0000240 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
John McCall5ea95772013-03-09 00:54:27 +0000241 assert(!newTag->hasNameForLinkage());
Richard Smithdda56e42011-04-15 14:24:37 +0000242 newTag->setTypedefNameForAnonDecl(Typedef);
John McCall04fcd0d2011-02-01 08:20:08 +0000243 }
Douglas Gregor83eb5032010-04-23 16:25:07 +0000244 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000245
Douglas Gregorec9fd132012-01-14 16:38:05 +0000246 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000247 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
248 TemplateArgs);
Douglas Gregor55e6b312011-03-04 19:46:35 +0000249 if (!InstPrev)
250 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000251
Rafael Espindolacde2c8f2011-12-26 22:42:47 +0000252 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
253
254 // If the typedef types are not identical, reject them.
255 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
256
257 Typedef->setPreviousDeclaration(InstPrevTypedef);
John McCall91f1a022009-12-30 00:31:22 +0000258 }
259
John McCall6602bb12010-08-01 02:01:53 +0000260 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregor83eb5032010-04-23 16:25:07 +0000261
John McCall401982f2010-01-20 21:53:11 +0000262 Typedef->setAccess(D->getAccess());
Mike Stump11289f42009-09-09 15:08:12 +0000263
Douglas Gregord7e7a512009-03-17 21:15:40 +0000264 return Typedef;
265}
266
Richard Smithdda56e42011-04-15 14:24:37 +0000267Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000268 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
269 Owner->addDecl(Typedef);
270 return Typedef;
Richard Smithdda56e42011-04-15 14:24:37 +0000271}
272
273Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000274 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
275 Owner->addDecl(Typedef);
276 return Typedef;
277}
278
279Decl *
280TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
281 // Create a local instantiation scope for this type alias template, which
282 // will contain the instantiations of the template parameters.
283 LocalInstantiationScope Scope(SemaRef);
284
285 TemplateParameterList *TempParams = D->getTemplateParameters();
286 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
287 if (!InstParams)
288 return 0;
289
290 TypeAliasDecl *Pattern = D->getTemplatedDecl();
291
292 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregorec9fd132012-01-14 16:38:05 +0000293 if (Pattern->getPreviousDecl()) {
Richard Smith3f1b5d02011-05-05 21:57:07 +0000294 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000295 if (!Found.empty()) {
296 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
Richard Smith3f1b5d02011-05-05 21:57:07 +0000297 }
298 }
299
300 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
301 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
302 if (!AliasInst)
303 return 0;
304
305 TypeAliasTemplateDecl *Inst
306 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
307 D->getDeclName(), InstParams, AliasInst);
308 if (PrevAliasTemplate)
309 Inst->setPreviousDeclaration(PrevAliasTemplate);
310
311 Inst->setAccess(D->getAccess());
312
313 if (!PrevAliasTemplate)
314 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000315
Richard Smith3f1b5d02011-05-05 21:57:07 +0000316 Owner->addDecl(Inst);
317
318 return Inst;
Richard Smithdda56e42011-04-15 14:24:37 +0000319}
320
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000321Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor04163182010-05-21 00:31:19 +0000322 // If this is the variable for an anonymous struct or union,
323 // instantiate the anonymous struct/union type first.
324 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
325 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
326 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
327 return 0;
328
John McCall76d824f2009-08-25 22:02:44 +0000329 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000330 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000331 TemplateArgs,
332 D->getTypeSpecStartLoc(),
333 D->getDeclName());
334 if (!DI)
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000335 return 0;
336
Douglas Gregor61623342010-09-12 07:37:24 +0000337 if (DI->getType()->isFunctionType()) {
338 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
339 << D->isStaticDataMember() << DI->getType();
340 return 0;
341 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000342
Douglas Gregor923feac2009-05-15 00:01:03 +0000343 // Build the instantiated declaration
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000344 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000345 D->getInnerLocStart(),
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000346 D->getLocation(), D->getIdentifier(),
John McCallf1abcdc2009-10-21 02:39:02 +0000347 DI->getType(), DI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000348 D->getStorageClass());
Enea Zaffanellaacb8ecd2013-05-04 08:27:07 +0000349 Var->setTSCSpec(D->getTSCSpec());
Sebastian Redla9351792012-02-11 23:51:47 +0000350 Var->setInitStyle(D->getInitStyle());
Richard Smith02e85f32011-04-14 22:09:26 +0000351 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Richard Smith45bb4552012-01-19 22:46:17 +0000352 Var->setConstexpr(D->isConstexpr());
Mike Stump11289f42009-09-09 15:08:12 +0000353
John McCall3e11ebe2010-03-15 10:12:16 +0000354 // Substitute the nested name specifier, if any.
355 if (SubstQualifier(D, Var))
356 return 0;
357
Mike Stump11289f42009-09-09 15:08:12 +0000358 // If we are instantiating a static data member defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000359 // out-of-line, the instantiation will have the same lexical
360 // context (which will be a namespace scope) as the template.
361 if (D->isOutOfLine())
362 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000363
John McCall401982f2010-01-20 21:53:11 +0000364 Var->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000365
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000366 if (!D->isStaticDataMember()) {
Douglas Gregorebada0772010-06-17 23:14:26 +0000367 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis16180232011-04-19 19:51:10 +0000368 Var->setReferenced(D->isReferenced());
369 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000370
Richard Smithbc8caaf2013-02-22 04:55:39 +0000371 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
372
373 if (Var->hasAttrs())
374 SemaRef.CheckAlignasUnderalignment(Var);
375
Mike Stump87c57ac2009-05-16 07:39:55 +0000376 // FIXME: In theory, we could have a previous declaration for variables that
377 // are not static data members.
John McCall1f82f242009-11-18 22:49:29 +0000378 // FIXME: having to fake up a LookupResult is dumb.
379 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor79e31db2010-03-01 19:11:54 +0000380 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregore6565622010-02-09 07:26:29 +0000381 if (D->isStaticDataMember())
382 SemaRef.LookupQualifiedName(Previous, Owner, false);
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000383
384 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000385 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor8ca0c642011-12-10 01:22:52 +0000386 SemaRef.inferObjCARCLifetime(Var))
387 Var->setInvalidDecl();
388
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +0000389 SemaRef.CheckVariableDeclaration(Var, Previous);
Mike Stump11289f42009-09-09 15:08:12 +0000390
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000391 if (D->isOutOfLine()) {
Richard Smithed2974f2011-12-21 00:25:33 +0000392 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000393 Owner->makeDeclVisibleInContext(Var);
394 } else {
395 Owner->addDecl(Var);
Douglas Gregor70b21be2010-05-03 20:22:41 +0000396 if (Owner->isFunctionOrMethod())
397 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000398 }
Richard Smith848e1f12013-02-01 08:12:08 +0000399
Douglas Gregor86d142a2009-10-08 07:24:58 +0000400 // Link instantiations of static data members back to the template from
401 // which they were instantiated.
402 if (Var->isStaticDataMember())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000403 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregor0840cc02009-11-01 20:32:48 +0000404 TSK_ImplicitInstantiation);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000405
Douglas Gregore6565622010-02-09 07:26:29 +0000406 if (Var->getAnyInitializer()) {
407 // We already have an initializer in the class.
408 } else if (D->getInit()) {
Douglas Gregor580cd4a2009-12-03 17:10:37 +0000409 if (Var->isStaticDataMember() && !D->isOutOfLine())
Richard Smith505df232012-07-22 23:45:10 +0000410 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
Douglas Gregor580cd4a2009-12-03 17:10:37 +0000411 else
Richard Smith505df232012-07-22 23:45:10 +0000412 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
Douglas Gregor580cd4a2009-12-03 17:10:37 +0000413
Douglas Gregorb30f22b2010-03-02 07:38:39 +0000414 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +0000415 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
416 D->getInitStyle() == VarDecl::CallInit);
417 if (!Init.isInvalid()) {
Richard Smith30482bc2011-02-20 03:19:35 +0000418 bool TypeMayContainAuto = true;
Sebastian Redla9351792012-02-11 23:51:47 +0000419 if (Init.get()) {
420 bool DirectInit = D->isDirectInit();
421 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
422 TypeMayContainAuto);
423 } else
Eli Friedmande30e522012-01-05 22:34:08 +0000424 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregord196a582009-12-14 19:27:10 +0000425 } else {
Douglas Gregorb30f22b2010-03-02 07:38:39 +0000426 // FIXME: Not too happy about invalidating the declaration
427 // because of a bogus initializer.
428 Var->setInvalidDecl();
Douglas Gregord196a582009-12-14 19:27:10 +0000429 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000430
Douglas Gregor580cd4a2009-12-03 17:10:37 +0000431 SemaRef.PopExpressionEvaluationContext();
Richard Smith02e85f32011-04-14 22:09:26 +0000432 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
433 !Var->isCXXForRangeDecl())
John McCall48871652010-08-21 09:40:31 +0000434 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000435
Richard Smith2602a682011-06-21 23:42:09 +0000436 // Diagnose unused local variables with dependent types, where the diagnostic
437 // will have been deferred.
438 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
439 D->getType()->isDependentType())
Douglas Gregor14f232e2010-05-08 23:05:03 +0000440 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidis1b30d9c2010-08-15 01:15:20 +0000441
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000442 return Var;
443}
444
Abramo Bagnarad7340582010-06-05 05:09:32 +0000445Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
446 AccessSpecDecl* AD
447 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
448 D->getAccessSpecifierLoc(), D->getColonLoc());
449 Owner->addHiddenDecl(AD);
450 return AD;
451}
452
Douglas Gregord7e7a512009-03-17 21:15:40 +0000453Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
454 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000455 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor678d76c2011-07-01 01:22:09 +0000456 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor5a5073e2010-05-24 17:22:01 +0000457 DI->getType()->isVariablyModifiedType()) {
John McCall90459c52009-10-22 23:33:21 +0000458 DI = SemaRef.SubstType(DI, TemplateArgs,
459 D->getLocation(), D->getDeclName());
460 if (!DI) {
John McCallbcd03502009-12-07 02:54:59 +0000461 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000462 Invalid = true;
463 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-03-17 21:15:40 +0000464 // C++ [temp.arg.type]p3:
465 // If a declaration acquires a function type through a type
466 // dependent on a template-parameter and this causes a
467 // declaration that does not use the syntactic form of a
468 // function declarator to have function type, the program is
469 // ill-formed.
470 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall90459c52009-10-22 23:33:21 +0000471 << DI->getType();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000472 Invalid = true;
473 }
Douglas Gregor5597ab42010-05-07 23:12:07 +0000474 } else {
475 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000476 }
477
478 Expr *BitWidth = D->getBitWidth();
479 if (Invalid)
480 BitWidth = 0;
481 else if (BitWidth) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000482 // The bit-width expression is a constant expression.
483 EnterExpressionEvaluationContext Unevaluated(SemaRef,
484 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000485
John McCalldadc5752010-08-24 06:29:42 +0000486 ExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000487 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000488 if (InstantiatedBitWidth.isInvalid()) {
489 Invalid = true;
490 BitWidth = 0;
491 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000492 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000493 }
494
John McCall90459c52009-10-22 23:33:21 +0000495 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
496 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000497 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000498 D->getLocation(),
499 D->isMutable(),
500 BitWidth,
Richard Smith2b013182012-06-10 03:12:00 +0000501 D->getInClassInitStyle(),
Richard Smith47ad0172012-05-23 04:22:22 +0000502 D->getInnerLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000503 D->getAccess(),
504 0);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000505 if (!Field) {
506 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000507 return 0;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000508 }
Mike Stump11289f42009-09-09 15:08:12 +0000509
DeLesley Hutchins30398dd2012-01-20 22:50:54 +0000510 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000511
Richard Smith848e1f12013-02-01 08:12:08 +0000512 if (Field->hasAttrs())
513 SemaRef.CheckAlignasUnderalignment(Field);
514
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000515 if (Invalid)
516 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000517
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000518 if (!Field->getDeclName()) {
519 // Keep track of where this decl came from.
520 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000521 }
Douglas Gregor04163182010-05-21 00:31:19 +0000522 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
523 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl50c68252010-08-31 00:36:30 +0000524 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +0000525 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000528 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000529 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000530 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000531
532 return Field;
533}
534
John McCall5e77d762013-04-16 07:28:30 +0000535Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
536 bool Invalid = false;
537 TypeSourceInfo *DI = D->getTypeSourceInfo();
538
539 if (DI->getType()->isVariablyModifiedType()) {
540 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
541 << D->getName();
542 Invalid = true;
543 } else if (DI->getType()->isInstantiationDependentType()) {
544 DI = SemaRef.SubstType(DI, TemplateArgs,
545 D->getLocation(), D->getDeclName());
546 if (!DI) {
547 DI = D->getTypeSourceInfo();
548 Invalid = true;
549 } else if (DI->getType()->isFunctionType()) {
550 // C++ [temp.arg.type]p3:
551 // If a declaration acquires a function type through a type
552 // dependent on a template-parameter and this causes a
553 // declaration that does not use the syntactic form of a
554 // function declarator to have function type, the program is
555 // ill-formed.
556 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
557 << DI->getType();
558 Invalid = true;
559 }
560 } else {
561 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
562 }
563
564 MSPropertyDecl *Property = new (SemaRef.Context)
565 MSPropertyDecl(Owner, D->getLocation(),
566 D->getDeclName(), DI->getType(), DI,
567 D->getLocStart(),
568 D->getGetterId(), D->getSetterId());
569
570 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
571 StartingScope);
572
573 if (Invalid)
574 Property->setInvalidDecl();
575
576 Property->setAccess(D->getAccess());
577 Owner->addDecl(Property);
578
579 return Property;
580}
581
Francois Pichet783dd6e2010-11-21 06:08:52 +0000582Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
583 NamedDecl **NamedChain =
584 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
585
586 int i = 0;
587 for (IndirectFieldDecl::chain_iterator PI =
588 D->chain_begin(), PE = D->chain_end();
Douglas Gregor55e6b312011-03-04 19:46:35 +0000589 PI != PE; ++PI) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000590 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregor55e6b312011-03-04 19:46:35 +0000591 TemplateArgs);
592 if (!Next)
593 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000594
Douglas Gregor55e6b312011-03-04 19:46:35 +0000595 NamedChain[i++] = Next;
596 }
Francois Pichet783dd6e2010-11-21 06:08:52 +0000597
Francois Pichetdbafc192010-12-09 10:07:54 +0000598 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet783dd6e2010-11-21 06:08:52 +0000599 IndirectFieldDecl* IndirectField
600 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichetdbafc192010-12-09 10:07:54 +0000601 D->getIdentifier(), T,
Francois Pichet783dd6e2010-11-21 06:08:52 +0000602 NamedChain, D->getChainingSize());
603
604
605 IndirectField->setImplicit(D->isImplicit());
606 IndirectField->setAccess(D->getAccess());
607 Owner->addDecl(IndirectField);
608 return IndirectField;
609}
610
John McCallaa74a0c2009-08-28 07:59:38 +0000611Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCallaa74a0c2009-08-28 07:59:38 +0000612 // Handle friend type expressions by simply substituting template
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000613 // parameters into the pattern type and checking the result.
John McCall15ad0962010-03-25 18:04:51 +0000614 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth08836322011-05-01 00:51:33 +0000615 TypeSourceInfo *InstTy;
616 // If this is an unsupported friend, don't bother substituting template
617 // arguments into it. The actual type referred to won't be used by any
618 // parts of Clang, and may not be valid for instantiating. Just use the
619 // same info for the instantiated friend.
620 if (D->isUnsupportedFriend()) {
621 InstTy = Ty;
622 } else {
623 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
624 D->getLocation(), DeclarationName());
625 }
626 if (!InstTy)
Douglas Gregor33636e62009-12-24 20:56:24 +0000627 return 0;
John McCallaa74a0c2009-08-28 07:59:38 +0000628
Richard Smitha31a89a2012-09-20 01:31:00 +0000629 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara254b6302011-10-29 20:52:52 +0000630 D->getFriendLoc(), InstTy);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000631 if (!FD)
632 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000633
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000634 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000635 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000636 Owner->addDecl(FD);
637 return FD;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000638 }
639
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000640 NamedDecl *ND = D->getFriendDecl();
641 assert(ND && "friend decl must be a decl or a type!");
642
John McCallb9c78482010-04-08 09:05:18 +0000643 // All of the Visit implementations for the various potential friend
644 // declarations have to be carefully written to work for friend
645 // objects, with the most important detail being that the target
646 // decl should almost certainly not be placed in Owner.
647 Decl *NewND = Visit(ND);
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000648 if (!NewND) return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000649
John McCallaa74a0c2009-08-28 07:59:38 +0000650 FriendDecl *FD =
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000651 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor3b4abb62010-04-07 17:57:12 +0000652 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000653 FD->setAccess(AS_public);
John McCallace48cd2010-10-19 01:40:49 +0000654 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCallaa74a0c2009-08-28 07:59:38 +0000655 Owner->addDecl(FD);
656 return FD;
John McCall58de3582009-08-14 02:03:10 +0000657}
658
Douglas Gregord7e7a512009-03-17 21:15:40 +0000659Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
660 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000661
Richard Smith764d2fe2011-12-20 02:08:33 +0000662 // The expression in a static assertion is a constant expression.
663 EnterExpressionEvaluationContext Unevaluated(SemaRef,
664 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000665
John McCalldadc5752010-08-24 06:29:42 +0000666 ExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000667 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000668 if (InstantiatedAssertExpr.isInvalid())
669 return 0;
670
Richard Smithded9c2e2012-07-11 22:37:56 +0000671 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCallb268a282010-08-23 23:25:46 +0000672 InstantiatedAssertExpr.get(),
Richard Smithded9c2e2012-07-11 22:37:56 +0000673 D->getMessage(),
674 D->getRParenLoc(),
675 D->isFailed());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000676}
677
678Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith2e6610a2012-03-26 04:58:10 +0000679 EnumDecl *PrevDecl = 0;
680 if (D->getPreviousDecl()) {
681 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
682 D->getPreviousDecl(),
683 TemplateArgs);
684 if (!Prev) return 0;
685 PrevDecl = cast<EnumDecl>(Prev);
686 }
687
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000688 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000689 D->getLocation(), D->getIdentifier(),
Richard Smith2e6610a2012-03-26 04:58:10 +0000690 PrevDecl, D->isScoped(),
Abramo Bagnara0e05e242010-12-03 18:54:17 +0000691 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor0bf31402010-10-08 23:50:27 +0000692 if (D->isFixed()) {
Richard Smith4b38ded2012-03-14 23:13:10 +0000693 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000694 // If we have type source information for the underlying type, it means it
695 // has been explicitly set by the user. Perform substitution on it before
696 // moving on.
697 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smith4b38ded2012-03-14 23:13:10 +0000698 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
699 DeclarationName());
700 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor0bf31402010-10-08 23:50:27 +0000701 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smith4b38ded2012-03-14 23:13:10 +0000702 else
703 Enum->setIntegerTypeSourceInfo(NewTI);
704 } else {
Douglas Gregor0bf31402010-10-08 23:50:27 +0000705 assert(!D->getIntegerType()->isDependentType()
706 && "Dependent type without type source info");
707 Enum->setIntegerType(D->getIntegerType());
708 }
709 }
710
John McCall811a0f52010-10-22 23:36:17 +0000711 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
712
Richard Smith4b38ded2012-03-14 23:13:10 +0000713 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000714 Enum->setAccess(D->getAccess());
John McCall3e11ebe2010-03-15 10:12:16 +0000715 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000716 Owner->addDecl(Enum);
Richard Smith4b38ded2012-03-14 23:13:10 +0000717
Richard Smith258a7442012-03-26 04:08:46 +0000718 EnumDecl *Def = D->getDefinition();
719 if (Def && Def != D) {
720 // If this is an out-of-line definition of an enum member template, check
721 // that the underlying types match in the instantiation of both
722 // declarations.
723 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
724 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
725 QualType DefnUnderlying =
726 SemaRef.SubstType(TI->getType(), TemplateArgs,
727 UnderlyingLoc, DeclarationName());
728 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
729 DefnUnderlying, Enum);
730 }
731 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000732
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000733 if (D->getDeclContext()->isFunctionOrMethod())
734 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000735
Richard Smith4b38ded2012-03-14 23:13:10 +0000736 // C++11 [temp.inst]p1: The implicit instantiation of a class template
737 // specialization causes the implicit instantiation of the declarations, but
738 // not the definitions of scoped member enumerations.
739 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith2e6610a2012-03-26 04:58:10 +0000740 // within a block scope, but we treat that much like a member template. Only
741 // instantiate the definition when visiting the definition in that case, since
742 // we will visit all redeclarations.
743 if (!Enum->isScoped() && Def &&
744 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith258a7442012-03-26 04:08:46 +0000745 InstantiateEnumDefinition(Enum, Def);
Richard Smith4b38ded2012-03-14 23:13:10 +0000746
747 return Enum;
748}
749
750void TemplateDeclInstantiator::InstantiateEnumDefinition(
751 EnumDecl *Enum, EnumDecl *Pattern) {
752 Enum->startDefinition();
753
Richard Smith7d137e32012-03-23 03:33:32 +0000754 // Update the location to refer to the definition.
755 Enum->setLocation(Pattern->getLocation());
756
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000757 SmallVector<Decl*, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000758
759 EnumConstantDecl *LastEnumConst = 0;
Richard Smith4b38ded2012-03-14 23:13:10 +0000760 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
761 ECEnd = Pattern->enumerator_end();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000762 EC != ECEnd; ++EC) {
763 // The specified value for the enumerator.
John McCalldadc5752010-08-24 06:29:42 +0000764 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000765 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smith764d2fe2011-12-20 02:08:33 +0000766 // The enumerator's value expression is a constant expression.
Mike Stump11289f42009-09-09 15:08:12 +0000767 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smith764d2fe2011-12-20 02:08:33 +0000768 Sema::ConstantEvaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000769
John McCall76d824f2009-08-25 22:02:44 +0000770 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000771 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000772
773 // Drop the initial value and continue.
774 bool isInvalid = false;
775 if (Value.isInvalid()) {
776 Value = SemaRef.Owned((Expr *)0);
777 isInvalid = true;
778 }
779
Mike Stump11289f42009-09-09 15:08:12 +0000780 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-03-17 21:15:40 +0000781 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
782 EC->getLocation(), EC->getIdentifier(),
John McCallb268a282010-08-23 23:25:46 +0000783 Value.get());
Douglas Gregord7e7a512009-03-17 21:15:40 +0000784
785 if (isInvalid) {
786 if (EnumConst)
787 EnumConst->setInvalidDecl();
788 Enum->setInvalidDecl();
789 }
790
791 if (EnumConst) {
David Blaikie40ed2972012-06-06 20:45:41 +0000792 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall811a0f52010-10-22 23:36:17 +0000793
John McCallf9b528c2010-01-23 22:37:59 +0000794 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000795 Enum->addDecl(EnumConst);
John McCall48871652010-08-21 09:40:31 +0000796 Enumerators.push_back(EnumConst);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000797 LastEnumConst = EnumConst;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000798
Richard Smith4b38ded2012-03-14 23:13:10 +0000799 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
800 !Enum->isScoped()) {
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000801 // If the enumeration is within a function or method, record the enum
802 // constant as a local.
David Blaikie40ed2972012-06-06 20:45:41 +0000803 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000804 }
Douglas Gregord7e7a512009-03-17 21:15:40 +0000805 }
806 }
Mike Stump11289f42009-09-09 15:08:12 +0000807
Richard Smith4b38ded2012-03-14 23:13:10 +0000808 // FIXME: Fixup LBraceLoc
809 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
810 Enum->getRBraceLoc(), Enum,
Dmitri Gribenkoe5fde992013-04-27 20:23:52 +0000811 Enumerators,
Edward O'Callaghanc69169d2009-08-08 14:36:57 +0000812 0, 0);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000813}
814
Douglas Gregor9106b822009-03-25 15:04:13 +0000815Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikie83d382b2011-09-23 05:06:16 +0000816 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor9106b822009-03-25 15:04:13 +0000817}
818
John McCall87a44eb2009-08-20 01:44:21 +0000819Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000820 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
821
Douglas Gregor954de172009-10-31 17:21:17 +0000822 // Create a local instantiation scope for this class template, which
823 // will contain the instantiations of the template parameters.
John McCall19c1bfd2010-08-25 05:32:35 +0000824 LocalInstantiationScope Scope(SemaRef);
John McCall87a44eb2009-08-20 01:44:21 +0000825 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000826 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000827 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000828 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +0000829
830 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-03-25 06:39:04 +0000831
832 // Instantiate the qualifier. We have to do this first in case
833 // we're a friend declaration, because if we are then we need to put
834 // the new declaration in the appropriate context.
Douglas Gregor14454802011-02-25 02:25:35 +0000835 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
836 if (QualifierLoc) {
837 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
838 TemplateArgs);
839 if (!QualifierLoc)
840 return 0;
John McCall598b4402010-03-25 06:39:04 +0000841 }
842
843 CXXRecordDecl *PrevDecl = 0;
844 ClassTemplateDecl *PrevClassTemplate = 0;
845
Douglas Gregorec9fd132012-01-14 16:38:05 +0000846 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky61478912010-11-08 23:29:42 +0000847 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +0000848 if (!Found.empty()) {
849 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
Nick Lewycky61478912010-11-08 23:29:42 +0000850 if (PrevClassTemplate)
851 PrevDecl = PrevClassTemplate->getTemplatedDecl();
852 }
853 }
854
John McCall598b4402010-03-25 06:39:04 +0000855 // If this isn't a friend, then it's a member template, in which
856 // case we just want to build the instantiation in the
857 // specialization. If it is a friend, we want to build it in
858 // the appropriate context.
859 DeclContext *DC = Owner;
860 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +0000861 if (QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000862 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +0000863 SS.Adopt(QualifierLoc);
John McCall598b4402010-03-25 06:39:04 +0000864 DC = SemaRef.computeDeclContext(SS);
865 if (!DC) return 0;
866 } else {
867 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
868 Pattern->getDeclContext(),
869 TemplateArgs);
870 }
871
872 // Look for a previous declaration of the template in the owning
873 // context.
874 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
875 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
876 SemaRef.LookupQualifiedName(R, DC);
877
878 if (R.isSingleResult()) {
879 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
880 if (PrevClassTemplate)
881 PrevDecl = PrevClassTemplate->getTemplatedDecl();
882 }
883
Douglas Gregor14454802011-02-25 02:25:35 +0000884 if (!PrevClassTemplate && QualifierLoc) {
John McCall598b4402010-03-25 06:39:04 +0000885 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregorf5af3582010-03-31 23:17:41 +0000886 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregor14454802011-02-25 02:25:35 +0000887 << QualifierLoc.getSourceRange();
John McCall598b4402010-03-25 06:39:04 +0000888 return 0;
889 }
890
Douglas Gregor01e09d92010-04-08 18:16:15 +0000891 bool AdoptedPreviousTemplateParams = false;
John McCall598b4402010-03-25 06:39:04 +0000892 if (PrevClassTemplate) {
Douglas Gregor01e09d92010-04-08 18:16:15 +0000893 bool Complain = true;
894
895 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
896 // template for struct std::tr1::__detail::_Map_base, where the
897 // template parameters of the friend declaration don't match the
898 // template parameters of the original declaration. In this one
899 // case, we don't complain about the ill-formed friend
900 // declaration.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000901 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregor01e09d92010-04-08 18:16:15 +0000902 Pattern->getIdentifier()->isStr("_Map_base") &&
903 DC->isNamespace() &&
904 cast<NamespaceDecl>(DC)->getIdentifier() &&
905 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
906 DeclContext *DCParent = DC->getParent();
907 if (DCParent->isNamespace() &&
908 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
909 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
910 DeclContext *DCParent2 = DCParent->getParent();
911 if (DCParent2->isNamespace() &&
912 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
913 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
914 DCParent2->getParent()->isTranslationUnit())
915 Complain = false;
916 }
917 }
918
John McCall598b4402010-03-25 06:39:04 +0000919 TemplateParameterList *PrevParams
920 = PrevClassTemplate->getTemplateParameters();
921
922 // Make sure the parameter lists match.
923 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000924 Complain,
Douglas Gregor01e09d92010-04-08 18:16:15 +0000925 Sema::TPL_TemplateMatch)) {
926 if (Complain)
927 return 0;
928
929 AdoptedPreviousTemplateParams = true;
930 InstParams = PrevParams;
931 }
John McCall598b4402010-03-25 06:39:04 +0000932
933 // Do some additional validation, then merge default arguments
934 // from the existing declarations.
Douglas Gregor01e09d92010-04-08 18:16:15 +0000935 if (!AdoptedPreviousTemplateParams &&
936 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall598b4402010-03-25 06:39:04 +0000937 Sema::TPC_ClassTemplate))
938 return 0;
939 }
940 }
941
John McCall87a44eb2009-08-20 01:44:21 +0000942 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000943 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnara29c2d462011-03-09 14:09:51 +0000944 Pattern->getLocStart(), Pattern->getLocation(),
945 Pattern->getIdentifier(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000946 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000947
Douglas Gregor14454802011-02-25 02:25:35 +0000948 if (QualifierLoc)
949 RecordInst->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +0000950
John McCall87a44eb2009-08-20 01:44:21 +0000951 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000952 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
953 D->getIdentifier(), InstParams, RecordInst,
954 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000955 RecordInst->setDescribedClassTemplate(Inst);
John McCall17762b82010-04-08 20:25:50 +0000956
John McCall598b4402010-03-25 06:39:04 +0000957 if (isFriend) {
John McCall17762b82010-04-08 20:25:50 +0000958 if (PrevClassTemplate)
959 Inst->setAccess(PrevClassTemplate->getAccess());
960 else
961 Inst->setAccess(D->getAccess());
962
Richard Smith64017682013-07-17 23:53:16 +0000963 Inst->setObjectOfFriendDecl();
John McCall598b4402010-03-25 06:39:04 +0000964 // TODO: do we want to track the instantiation progeny of this
965 // friend target decl?
966 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000967 Inst->setAccess(D->getAccess());
Nick Lewycky61478912010-11-08 23:29:42 +0000968 if (!PrevClassTemplate)
969 Inst->setInstantiatedFromMemberTemplate(D);
John McCall598b4402010-03-25 06:39:04 +0000970 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000971
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000972 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000973 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor9961ce92010-07-08 18:37:38 +0000974 Inst->getInjectedClassNameSpecialization());
John McCall17762b82010-04-08 20:25:50 +0000975
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000976 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000977 if (isFriend) {
Richard Smith05afe5e2012-03-13 03:12:56 +0000978 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000979 Inst->setLexicalDeclContext(Owner);
980 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000981 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000982 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +0000983
Abramo Bagnaraedf99ff2011-11-26 13:33:46 +0000984 if (D->isOutOfLine()) {
985 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
986 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
987 }
988
John McCall87a44eb2009-08-20 01:44:21 +0000989 Owner->addDecl(Inst);
Douglas Gregor869853e2010-11-10 19:44:59 +0000990
991 if (!PrevClassTemplate) {
992 // Queue up any out-of-line partial specializations of this member
993 // class template; the client will force their instantiation once
994 // the enclosing class has been instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000995 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor869853e2010-11-10 19:44:59 +0000996 D->getPartialSpecializations(PartialSpecs);
997 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
998 if (PartialSpecs[I]->isOutOfLine())
999 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1000 }
1001
John McCall87a44eb2009-08-20 01:44:21 +00001002 return Inst;
1003}
1004
Douglas Gregore704c9d2009-08-27 16:57:43 +00001005Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +00001006TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1007 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +00001008 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001009
Douglas Gregor21610382009-10-29 00:04:11 +00001010 // Lookup the already-instantiated declaration in the instantiation
1011 // of the class template and return that.
1012 DeclContext::lookup_result Found
1013 = Owner->lookup(ClassTemplate->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00001014 if (Found.empty())
Douglas Gregor21610382009-10-29 00:04:11 +00001015 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001016
Douglas Gregor21610382009-10-29 00:04:11 +00001017 ClassTemplateDecl *InstClassTemplate
David Blaikieff7d47a2012-12-19 00:45:41 +00001018 = dyn_cast<ClassTemplateDecl>(Found.front());
Douglas Gregor21610382009-10-29 00:04:11 +00001019 if (!InstClassTemplate)
1020 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001021
Douglas Gregor869853e2010-11-10 19:44:59 +00001022 if (ClassTemplatePartialSpecializationDecl *Result
1023 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1024 return Result;
1025
1026 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregore4b05162009-10-07 17:21:34 +00001027}
1028
1029Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +00001030TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +00001031 // Create a local instantiation scope for this function template, which
1032 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001033 // merged with the local instantiation scope for the function template
Douglas Gregor954de172009-10-31 17:21:17 +00001034 // itself.
John McCall19c1bfd2010-08-25 05:32:35 +00001035 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor14cf7522010-04-30 18:55:50 +00001036
Douglas Gregore704c9d2009-08-27 16:57:43 +00001037 TemplateParameterList *TempParams = D->getTemplateParameters();
1038 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +00001039 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001040 return NULL;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001041
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001042 FunctionDecl *Instantiated = 0;
1043 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001044 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001045 InstParams));
1046 else
1047 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001048 D->getTemplatedDecl(),
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001049 InstParams));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001050
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001051 if (!Instantiated)
Douglas Gregore704c9d2009-08-27 16:57:43 +00001052 return 0;
1053
Mike Stump11289f42009-09-09 15:08:12 +00001054 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +00001055 // template from which it was instantiated.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001056 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001057 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +00001058 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001059 assert(InstTemplate &&
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001060 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +00001061
John McCall30837102010-03-26 23:10:15 +00001062 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1063
John McCall2079d0b2009-12-14 23:19:40 +00001064 // Link the instantiation back to the pattern *unless* this is a
1065 // non-definition friend declaration.
1066 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +00001067 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001068 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001069
John McCall30837102010-03-26 23:10:15 +00001070 // Make declarations visible in the appropriate context.
John McCalla0a96892012-08-10 03:15:35 +00001071 if (!isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001072 Owner->addDecl(InstTemplate);
John McCalla0a96892012-08-10 03:15:35 +00001073 } else if (InstTemplate->getDeclContext()->isRecord() &&
1074 !D->getPreviousDecl()) {
1075 SemaRef.CheckFriendAccess(InstTemplate);
1076 }
John McCall30837102010-03-26 23:10:15 +00001077
Douglas Gregore704c9d2009-08-27 16:57:43 +00001078 return InstTemplate;
1079}
1080
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001081Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1082 CXXRecordDecl *PrevDecl = 0;
1083 if (D->isInjectedClassName())
1084 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregorec9fd132012-01-14 16:38:05 +00001085 else if (D->getPreviousDecl()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001086 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregorec9fd132012-01-14 16:38:05 +00001087 D->getPreviousDecl(),
John McCalle9f92a02009-12-15 22:29:06 +00001088 TemplateArgs);
1089 if (!Prev) return 0;
1090 PrevDecl = cast<CXXRecordDecl>(Prev);
1091 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001092
1093 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +00001094 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001095 D->getLocStart(), D->getLocation(),
1096 D->getIdentifier(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +00001097
1098 // Substitute the nested name specifier, if any.
1099 if (SubstQualifier(D, Record))
1100 return 0;
1101
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001102 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +00001103 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1104 // the tag decls introduced by friend class declarations don't have an access
1105 // specifier. Remove once this area of the code gets sorted out.
1106 if (D->getAccess() != AS_none)
1107 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001108 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +00001109 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001110
John McCallaa74a0c2009-08-28 07:59:38 +00001111 // If the original function was part of a friend declaration,
1112 // inherit its namespace state.
Richard Smith64017682013-07-17 23:53:16 +00001113 if (D->getFriendObjectKind())
1114 Record->setObjectOfFriendDecl();
John McCallaa74a0c2009-08-28 07:59:38 +00001115
Douglas Gregor04163182010-05-21 00:31:19 +00001116 // Make sure that anonymous structs and unions are recorded.
1117 if (D->isAnonymousStructOrUnion()) {
1118 Record->setAnonymousStructOrUnion(true);
Sebastian Redl50c68252010-08-31 00:36:30 +00001119 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor04163182010-05-21 00:31:19 +00001120 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1121 }
Anders Carlsson5da84842009-09-01 04:26:58 +00001122
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001123 Owner->addDecl(Record);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001124 return Record;
1125}
1126
Douglas Gregor89f593a2012-09-13 21:56:43 +00001127/// \brief Adjust the given function type for an instantiation of the
1128/// given declaration, to cope with modifications to the function's type that
1129/// aren't reflected in the type-source information.
1130///
1131/// \param D The declaration we're instantiating.
1132/// \param TInfo The already-instantiated type.
1133static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1134 FunctionDecl *D,
1135 TypeSourceInfo *TInfo) {
Douglas Gregor1af8ad42012-09-13 22:01:49 +00001136 const FunctionProtoType *OrigFunc
1137 = D->getType()->castAs<FunctionProtoType>();
1138 const FunctionProtoType *NewFunc
1139 = TInfo->getType()->castAs<FunctionProtoType>();
1140 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1141 return TInfo->getType();
1142
1143 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1144 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1145 return Context.getFunctionType(NewFunc->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00001146 NewFunc->getArgTypes(), NewEPI);
Douglas Gregor89f593a2012-09-13 21:56:43 +00001147}
1148
John McCallaa74a0c2009-08-28 07:59:38 +00001149/// Normal class members are of more specific types and therefore
1150/// don't make it here. This function serves two purposes:
1151/// 1) instantiating function templates
1152/// 2) substituting friend declarations
1153/// FIXME: preserve function definitions in case #2
Douglas Gregor33636e62009-12-24 20:56:24 +00001154Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001155 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001156 // Check whether there is already a function template specialization for
1157 // this declaration.
1158 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCall2f88d7d2010-03-27 05:57:59 +00001159 if (FunctionTemplate && !TemplateParams) {
Richard Smith47752e42013-05-03 23:46:09 +00001160 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001161
Douglas Gregorce9978f2012-03-28 14:34:23 +00001162 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001163 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001164 = FunctionTemplate->findSpecialization(Innermost.begin(), Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001165 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001166
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001167 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001168 if (SpecFunc)
1169 return SpecFunc;
Douglas Gregor8f5d4422009-06-29 20:59:39 +00001170 }
Mike Stump11289f42009-09-09 15:08:12 +00001171
John McCall2f88d7d2010-03-27 05:57:59 +00001172 bool isFriend;
1173 if (FunctionTemplate)
1174 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1175 else
1176 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1177
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001178 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregor9f44d142010-05-21 21:25:08 +00001179 Owner->isFunctionOrMethod() ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001180 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001181 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001182 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001183
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001184 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie4d142962011-11-10 05:42:04 +00001185 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001186 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001187 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001188 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCall58de3582009-08-14 02:03:10 +00001189
Douglas Gregor14454802011-02-25 02:25:35 +00001190 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1191 if (QualifierLoc) {
1192 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1193 TemplateArgs);
1194 if (!QualifierLoc)
1195 return 0;
John McCalle0b2ddb2010-03-26 04:53:08 +00001196 }
1197
John McCallce410662010-02-06 01:50:47 +00001198 // If we're instantiating a local function declaration, put the result
1199 // in the owner; otherwise we need to find the instantiated context.
1200 DeclContext *DC;
1201 if (D->getDeclContext()->isFunctionOrMethod())
1202 DC = Owner;
Douglas Gregor14454802011-02-25 02:25:35 +00001203 else if (isFriend && QualifierLoc) {
John McCalle0b2ddb2010-03-26 04:53:08 +00001204 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001205 SS.Adopt(QualifierLoc);
John McCalle0b2ddb2010-03-26 04:53:08 +00001206 DC = SemaRef.computeDeclContext(SS);
1207 if (!DC) return 0;
1208 } else {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001209 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001210 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +00001211 }
John McCallce410662010-02-06 01:50:47 +00001212
John McCallaa74a0c2009-08-28 07:59:38 +00001213 FunctionDecl *Function =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001214 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara0d4fce12012-10-04 21:40:42 +00001215 D->getNameInfo(), T, TInfo,
Rafael Espindola9dd86de2013-04-16 02:29:15 +00001216 D->getCanonicalDecl()->getStorageClass(),
Richard Smitha77a0a62011-08-15 21:04:07 +00001217 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001218 D->isConstexpr());
Enea Zaffanella25723ce2013-07-19 18:02:36 +00001219 Function->setRangeEnd(D->getSourceRange().getEnd());
John McCall3e11ebe2010-03-15 10:12:16 +00001220
Richard Smithf3814ad2013-01-25 00:08:28 +00001221 if (D->isInlined())
1222 Function->setImplicitlyInline();
1223
Douglas Gregor14454802011-02-25 02:25:35 +00001224 if (QualifierLoc)
1225 Function->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001226
John McCall30837102010-03-26 23:10:15 +00001227 DeclContext *LexicalDC = Owner;
1228 if (!isFriend && D->isOutOfLine()) {
1229 assert(D->getDeclContext()->isFileContext());
1230 LexicalDC = D->getDeclContext();
1231 }
1232
1233 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +00001234
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001235 // Attach the parameters
Reid Klecknera09e44c2013-07-31 21:00:18 +00001236 for (unsigned P = 0; P < Params.size(); ++P)
1237 if (Params[P])
1238 Params[P]->setOwningFunction(Function);
David Blaikie9c70e042011-09-21 18:16:56 +00001239 Function->setParams(Params);
John McCallaa74a0c2009-08-28 07:59:38 +00001240
Douglas Gregor1cd6ea02010-05-17 16:38:00 +00001241 SourceLocation InstantiateAtPOI;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001242 if (TemplateParams) {
1243 // Our resulting instantiation is actually a function template, since we
1244 // are substituting only the outer template parameters. For example, given
1245 //
1246 // template<typename T>
1247 // struct X {
1248 // template<typename U> friend void f(T, U);
1249 // };
1250 //
1251 // X<int> x;
1252 //
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001253 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001254 // which means substituting int for T, but leaving "f" as a friend function
1255 // template.
1256 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +00001257 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001258 Function->getLocation(),
1259 Function->getDeclName(),
1260 TemplateParams, Function);
1261 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001262
1263 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001264
1265 if (isFriend && D->isThisDeclarationADefinition()) {
1266 // TODO: should we remember this connection regardless of whether
1267 // the friend declaration provided a body?
1268 FunctionTemplate->setInstantiatedFromMemberTemplate(
1269 D->getDescribedFunctionTemplate());
1270 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001271 } else if (FunctionTemplate) {
1272 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001273 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001274 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001275 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001276 Innermost.begin(),
1277 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001278 /*InsertPos=*/0);
Chandler Carruth48b28312011-08-18 09:09:59 +00001279 } else if (isFriend) {
1280 // Note, we need this connection even if the friend doesn't have a body.
1281 // Its body may exist but not have been attached yet due to deferred
1282 // parsing.
1283 // FIXME: It might be cleaner to set this when attaching the body to the
1284 // friend function declaration, however that would require finding all the
1285 // instantiations and modifying them.
John McCalle0b2ddb2010-03-26 04:53:08 +00001286 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001287 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001288
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001289 if (InitFunctionInstantiation(Function, D))
1290 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001291
John McCallb9c78482010-04-08 09:05:18 +00001292 bool isExplicitSpecialization = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001293
John McCall1f82f242009-11-18 22:49:29 +00001294 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1295 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1296
John McCallb9c78482010-04-08 09:05:18 +00001297 if (DependentFunctionTemplateSpecializationInfo *Info
1298 = D->getDependentSpecializationInfo()) {
1299 assert(isFriend && "non-friend has dependent specialization info?");
1300
1301 // This needs to be set now for future sanity.
Richard Smith64017682013-07-17 23:53:16 +00001302 Function->setObjectOfFriendDecl();
John McCallb9c78482010-04-08 09:05:18 +00001303
1304 // Instantiate the explicit template arguments.
1305 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1306 Info->getRAngleLoc());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00001307 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1308 ExplicitArgs, TemplateArgs))
1309 return 0;
John McCallb9c78482010-04-08 09:05:18 +00001310
1311 // Map the candidate templates to their instantiations.
1312 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1313 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1314 Info->getTemplate(I),
1315 TemplateArgs);
1316 if (!Temp) return 0;
1317
1318 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1319 }
1320
1321 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1322 &ExplicitArgs,
1323 Previous))
1324 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001325
John McCallb9c78482010-04-08 09:05:18 +00001326 isExplicitSpecialization = true;
1327
1328 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001329 // Look only into the namespace where the friend would be declared to
1330 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001331 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001332 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001333
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001334 // In C++, the previous declaration we find might be a tag type
1335 // (class or enum). In this case, the new declaration will hide the
1336 // tag type. Note that this does does not apply if we're declaring a
1337 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001338 if (Previous.isSingleTagDecl())
1339 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001340 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001341
John McCall84d87672009-12-10 09:41:52 +00001342 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001343 isExplicitSpecialization);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001344
John McCallb9467b62010-04-24 01:30:58 +00001345 NamedDecl *PrincipalDecl = (TemplateParams
1346 ? cast<NamedDecl>(FunctionTemplate)
1347 : Function);
1348
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001349 // If the original function was part of a friend declaration,
1350 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001351 if (isFriend) {
Richard Smith64017682013-07-17 23:53:16 +00001352 PrincipalDecl->setObjectOfFriendDecl();
Richard Smith05afe5e2012-03-13 03:12:56 +00001353 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greif718d5152010-08-30 21:10:05 +00001354
Gabor Greif12866172010-08-30 22:25:56 +00001355 bool queuedInstantiation = false;
Gabor Greif718d5152010-08-30 21:10:05 +00001356
Richard Smitha066ccf2011-10-19 00:54:10 +00001357 // C++98 [temp.friend]p5: When a function is defined in a friend function
1358 // declaration in a class template, the function is defined at each
1359 // instantiation of the class template. The function is defined even if it
1360 // is never used.
1361 // C++11 [temp.friend]p4: When a function is defined in a friend function
1362 // declaration in a class template, the function is instantiated when the
1363 // function is odr-used.
1364 //
1365 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1366 // redefinition, but don't instantiate the function.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001367 if ((!SemaRef.getLangOpts().CPlusPlus11 ||
Richard Smitha066ccf2011-10-19 00:54:10 +00001368 SemaRef.Diags.getDiagnosticLevel(
1369 diag::warn_cxx98_compat_friend_redefinition,
1370 Function->getLocation())
1371 != DiagnosticsEngine::Ignored) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001372 D->isThisDeclarationADefinition()) {
1373 // Check for a function body.
1374 const FunctionDecl *Definition = 0;
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001375 if (Function->isDefined(Definition) &&
Douglas Gregorb92ea592010-05-18 05:45:02 +00001376 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smitha066ccf2011-10-19 00:54:10 +00001377 SemaRef.Diag(Function->getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001378 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smitha066ccf2011-10-19 00:54:10 +00001379 diag::warn_cxx98_compat_friend_redefinition :
1380 diag::err_redefinition) << Function->getDeclName();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001381 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001382 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smitha066ccf2011-10-19 00:54:10 +00001383 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001384 }
Douglas Gregorb92ea592010-05-18 05:45:02 +00001385 // Check for redefinitions due to other instantiations of this or
1386 // a similar friend function.
1387 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1388 REnd = Function->redecls_end();
1389 R != REnd; ++R) {
Gabor Greif122f1eb2010-08-28 15:42:30 +00001390 if (*R == Function)
1391 continue;
Gabor Greif718d5152010-08-30 21:10:05 +00001392 switch (R->getFriendObjectKind()) {
1393 case Decl::FOK_None:
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001394 if (!SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smitha066ccf2011-10-19 00:54:10 +00001395 !queuedInstantiation && R->isUsed(false)) {
Gabor Greif718d5152010-08-30 21:10:05 +00001396 if (MemberSpecializationInfo *MSInfo
1397 = Function->getMemberSpecializationInfo()) {
1398 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1399 SourceLocation Loc = R->getLocation(); // FIXME
1400 MSInfo->setPointOfInstantiation(Loc);
1401 SemaRef.PendingLocalImplicitInstantiations.push_back(
1402 std::make_pair(Function, Loc));
1403 queuedInstantiation = true;
1404 }
1405 }
1406 }
1407 break;
1408 default:
Douglas Gregorb92ea592010-05-18 05:45:02 +00001409 if (const FunctionDecl *RPattern
Gabor Greifae849e42010-08-28 15:46:56 +00001410 = R->getTemplateInstantiationPattern())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00001411 if (RPattern->isDefined(RPattern)) {
Richard Smitha066ccf2011-10-19 00:54:10 +00001412 SemaRef.Diag(Function->getLocation(),
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001413 SemaRef.getLangOpts().CPlusPlus11 ?
Richard Smitha066ccf2011-10-19 00:54:10 +00001414 diag::warn_cxx98_compat_friend_redefinition :
1415 diag::err_redefinition)
Douglas Gregorb92ea592010-05-18 05:45:02 +00001416 << Function->getDeclName();
Gabor Greifae849e42010-08-28 15:46:56 +00001417 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001418 if (!SemaRef.getLangOpts().CPlusPlus11)
Richard Smitha066ccf2011-10-19 00:54:10 +00001419 Function->setInvalidDecl();
Douglas Gregorb92ea592010-05-18 05:45:02 +00001420 break;
1421 }
1422 }
1423 }
1424 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001425 }
1426
John McCallb9467b62010-04-24 01:30:58 +00001427 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1428 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1429 PrincipalDecl->setNonMemberOperator();
1430
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001431 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001432 return Function;
1433}
1434
Douglas Gregore704c9d2009-08-27 16:57:43 +00001435Decl *
1436TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001437 TemplateParameterList *TemplateParams,
1438 bool IsClassScopeSpecialization) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001439 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregore704c9d2009-08-27 16:57:43 +00001440 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001441 // We are creating a function template specialization from a function
1442 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001443 // specialization for this particular set of template arguments.
Richard Smith47752e42013-05-03 23:46:09 +00001444 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Mike Stump11289f42009-09-09 15:08:12 +00001445
Douglas Gregorce9978f2012-03-28 14:34:23 +00001446 void *InsertPos = 0;
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001447 FunctionDecl *SpecFunc
Richard Smith47752e42013-05-03 23:46:09 +00001448 = FunctionTemplate->findSpecialization(Innermost.begin(),
1449 Innermost.size(),
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001450 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001451
Douglas Gregor97628d62009-08-21 00:16:32 +00001452 // If we already have a function template specialization, return it.
Argyrios Kyrtzidisdde57902010-07-20 13:59:58 +00001453 if (SpecFunc)
1454 return SpecFunc;
Douglas Gregor97628d62009-08-21 00:16:32 +00001455 }
1456
John McCall2f88d7d2010-03-27 05:57:59 +00001457 bool isFriend;
1458 if (FunctionTemplate)
1459 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1460 else
1461 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1462
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001463 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001464 !(isa<Decl>(Owner) &&
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001465 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall19c1bfd2010-08-25 05:32:35 +00001466 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001467
John McCalld0e23ec2010-10-19 02:26:41 +00001468 // Instantiate enclosing template arguments for friends.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001469 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCalld0e23ec2010-10-19 02:26:41 +00001470 unsigned NumTempParamLists = 0;
1471 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1472 TempParamLists.set_size(NumTempParamLists);
1473 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1474 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1475 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1476 if (!InstParams)
1477 return NULL;
1478 TempParamLists[I] = InstParams;
1479 }
1480 }
1481
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001482 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramer1dd48bc2012-01-20 14:42:32 +00001483 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall58f10c32010-03-11 09:03:00 +00001484 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001485 return 0;
Douglas Gregor89f593a2012-09-13 21:56:43 +00001486 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001487
Douglas Gregor14454802011-02-25 02:25:35 +00001488 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1489 if (QualifierLoc) {
1490 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCall2f88d7d2010-03-27 05:57:59 +00001491 TemplateArgs);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001492 if (!QualifierLoc)
Douglas Gregor14454802011-02-25 02:25:35 +00001493 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001494 }
1495
1496 DeclContext *DC = Owner;
1497 if (isFriend) {
Douglas Gregor14454802011-02-25 02:25:35 +00001498 if (QualifierLoc) {
John McCall2f88d7d2010-03-27 05:57:59 +00001499 CXXScopeSpec SS;
Douglas Gregor14454802011-02-25 02:25:35 +00001500 SS.Adopt(QualifierLoc);
John McCall2f88d7d2010-03-27 05:57:59 +00001501 DC = SemaRef.computeDeclContext(SS);
John McCall1a1b53e2010-10-19 05:01:53 +00001502
1503 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1504 return 0;
John McCall2f88d7d2010-03-27 05:57:59 +00001505 } else {
1506 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1507 D->getDeclContext(),
1508 TemplateArgs);
1509 }
1510 if (!DC) return 0;
1511 }
1512
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001513 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001514 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001515 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001516
Abramo Bagnaradff19302011-03-08 08:55:46 +00001517 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001518 DeclarationNameInfo NameInfo
1519 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregore8394862009-08-21 22:43:28 +00001520 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001521 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001522 StartLoc, NameInfo, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001523 Constructor->isExplicit(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001524 Constructor->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001525 false, Constructor->isConstexpr());
Richard Smith4c163a02013-05-17 02:19:35 +00001526
Richard Smith185be182013-04-10 05:48:59 +00001527 // Claim that the instantiation of a constructor or constructor template
1528 // inherits the same constructor that the template does.
Richard Smith4c163a02013-05-17 02:19:35 +00001529 if (CXXConstructorDecl *Inh = const_cast<CXXConstructorDecl *>(
1530 Constructor->getInheritedConstructor())) {
1531 // If we're instantiating a specialization of a function template, our
1532 // "inherited constructor" will actually itself be a function template.
1533 // Instantiate a declaration of it, too.
1534 if (FunctionTemplate) {
1535 assert(!TemplateParams && Inh->getDescribedFunctionTemplate() &&
1536 !Inh->getParent()->isDependentContext() &&
1537 "inheriting constructor template in dependent context?");
1538 Sema::InstantiatingTemplate Inst(SemaRef, Constructor->getLocation(),
1539 Inh);
1540 if (Inst)
1541 return 0;
1542 Sema::ContextRAII SavedContext(SemaRef, Inh->getDeclContext());
1543 LocalInstantiationScope LocalScope(SemaRef);
1544
1545 // Use the same template arguments that we deduced for the inheriting
1546 // constructor. There's no way they could be deduced differently.
1547 MultiLevelTemplateArgumentList InheritedArgs;
1548 InheritedArgs.addOuterTemplateArguments(TemplateArgs.getInnermost());
1549 Inh = cast_or_null<CXXConstructorDecl>(
1550 SemaRef.SubstDecl(Inh, Inh->getDeclContext(), InheritedArgs));
1551 if (!Inh)
1552 return 0;
1553 }
Richard Smith185be182013-04-10 05:48:59 +00001554 cast<CXXConstructorDecl>(Method)->setInheritedConstructor(Inh);
Richard Smith4c163a02013-05-17 02:19:35 +00001555 }
Douglas Gregore8394862009-08-21 22:43:28 +00001556 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregore8394862009-08-21 22:43:28 +00001557 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001558 StartLoc, NameInfo, T, TInfo,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001559 Destructor->isInlineSpecified(),
Douglas Gregorc4df4072010-04-19 22:54:31 +00001560 false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001561 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001562 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001563 StartLoc, NameInfo, T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001564 Conversion->isInlineSpecified(),
Douglas Gregorf2f08062011-03-08 17:10:18 +00001565 Conversion->isExplicit(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001566 Conversion->isConstexpr(),
Richard Smitheb3c10c2011-10-01 02:31:28 +00001567 Conversion->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001568 } else {
Rafael Espindola29cda592013-04-15 12:38:20 +00001569 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001570 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001571 StartLoc, NameInfo, T, TInfo,
Rafael Espindola29cda592013-04-15 12:38:20 +00001572 SC, D->isInlineSpecified(),
Richard Smith3607ffe2012-02-13 03:54:03 +00001573 D->isConstexpr(), D->getLocEnd());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001574 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001575
Richard Smithf3814ad2013-01-25 00:08:28 +00001576 if (D->isInlined())
1577 Method->setImplicitlyInline();
1578
Douglas Gregor14454802011-02-25 02:25:35 +00001579 if (QualifierLoc)
1580 Method->setQualifierInfo(QualifierLoc);
John McCall3e11ebe2010-03-15 10:12:16 +00001581
Douglas Gregore704c9d2009-08-27 16:57:43 +00001582 if (TemplateParams) {
1583 // Our resulting instantiation is actually a function template, since we
1584 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001585 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001586 // template<typename T>
1587 // struct X {
1588 // template<typename U> void f(T, U);
1589 // };
1590 //
1591 // X<int> x;
1592 //
1593 // We are instantiating the member template "f" within X<int>, which means
1594 // substituting int for T, but leaving "f" as a member function template.
1595 // Build the function template itself.
1596 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1597 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001598 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001599 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001600 if (isFriend) {
1601 FunctionTemplate->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001602 FunctionTemplate->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001603 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001604 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001605 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001606 } else if (FunctionTemplate) {
1607 // Record this function template specialization.
Richard Smith47752e42013-05-03 23:46:09 +00001608 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
Douglas Gregord5058122010-02-11 01:19:42 +00001609 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00001610 TemplateArgumentList::CreateCopy(SemaRef.Context,
Richard Smith47752e42013-05-03 23:46:09 +00001611 Innermost.begin(),
1612 Innermost.size()),
Douglas Gregorce9978f2012-03-28 14:34:23 +00001613 /*InsertPos=*/0);
John McCall2f88d7d2010-03-27 05:57:59 +00001614 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001615 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001616 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001617 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001618
Mike Stump11289f42009-09-09 15:08:12 +00001619 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001620 // out-of-line, the instantiation will have the same lexical
1621 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001622 if (isFriend) {
John McCalld0e23ec2010-10-19 02:26:41 +00001623 if (NumTempParamLists)
1624 Method->setTemplateParameterListsInfo(SemaRef.Context,
1625 NumTempParamLists,
1626 TempParamLists.data());
1627
John McCall2f88d7d2010-03-27 05:57:59 +00001628 Method->setLexicalDeclContext(Owner);
Richard Smith64017682013-07-17 23:53:16 +00001629 Method->setObjectOfFriendDecl();
John McCall2f88d7d2010-03-27 05:57:59 +00001630 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001631 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001632
Douglas Gregor21342092009-03-24 00:38:23 +00001633 // Attach the parameters
1634 for (unsigned P = 0; P < Params.size(); ++P)
1635 Params[P]->setOwningFunction(Method);
David Blaikie9c70e042011-09-21 18:16:56 +00001636 Method->setParams(Params);
Douglas Gregor21342092009-03-24 00:38:23 +00001637
1638 if (InitMethodInstantiation(Method, D))
1639 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001640
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001641 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1642 Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001643
John McCall2f88d7d2010-03-27 05:57:59 +00001644 if (!FunctionTemplate || TemplateParams || isFriend) {
1645 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001646
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001647 // In C++, the previous declaration we find might be a tag type
1648 // (class or enum). In this case, the new declaration will hide the
1649 // tag type. Note that this does does not apply if we're declaring a
1650 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001651 if (Previous.isSingleTagDecl())
1652 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001653 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001654
Francois Pichet00c7e6c2011-08-14 03:52:19 +00001655 if (!IsClassScopeSpecialization)
Kaelyn Uhrain4dc695d2011-10-11 00:28:45 +00001656 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001657
Douglas Gregor21920e372009-12-01 17:24:26 +00001658 if (D->isPure())
1659 SemaRef.CheckPureMethod(Method, SourceRange());
1660
John McCalla0a96892012-08-10 03:15:35 +00001661 // Propagate access. For a non-friend declaration, the access is
1662 // whatever we're propagating from. For a friend, it should be the
1663 // previous declaration we just found.
1664 if (isFriend && Method->getPreviousDecl())
1665 Method->setAccess(Method->getPreviousDecl()->getAccess());
1666 else
1667 Method->setAccess(D->getAccess());
1668 if (FunctionTemplate)
1669 FunctionTemplate->setAccess(Method->getAccess());
John McCall401982f2010-01-20 21:53:11 +00001670
Anders Carlsson7c812f52011-01-20 06:52:44 +00001671 SemaRef.CheckOverrideControl(Method);
1672
Eli Friedman41340732011-11-15 22:39:08 +00001673 // If a function is defined as defaulted or deleted, mark it as such now.
Richard Smith92f241f2012-12-08 02:53:02 +00001674 if (D->isExplicitlyDefaulted())
1675 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001676 if (D->isDeletedAsWritten())
Richard Smith92f241f2012-12-08 02:53:02 +00001677 SemaRef.SetDeclDeleted(Method, Method->getLocation());
Eli Friedman41340732011-11-15 22:39:08 +00001678
John McCalla0a96892012-08-10 03:15:35 +00001679 // If there's a function template, let our caller handle it.
John McCall2f88d7d2010-03-27 05:57:59 +00001680 if (FunctionTemplate) {
John McCalla0a96892012-08-10 03:15:35 +00001681 // do nothing
1682
1683 // Don't hide a (potentially) valid declaration with an invalid one.
John McCall2f88d7d2010-03-27 05:57:59 +00001684 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCalla0a96892012-08-10 03:15:35 +00001685 // do nothing
1686
1687 // Otherwise, check access to friends and make them visible.
1688 } else if (isFriend) {
1689 // We only need to re-check access for methods which we didn't
1690 // manage to match during parsing.
1691 if (!D->getPreviousDecl())
1692 SemaRef.CheckFriendAccess(Method);
1693
1694 Record->makeDeclVisibleInContext(Method);
1695
1696 // Otherwise, add the declaration. We don't need to do this for
1697 // class-scope specializations because we'll have matched them with
1698 // the appropriate template.
1699 } else if (!IsClassScopeSpecialization) {
1700 Owner->addDecl(Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001701 }
Alexis Hunt1fb4e762011-05-23 21:07:59 +00001702
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001703 return Method;
1704}
1705
Douglas Gregor4044d992009-03-24 16:43:20 +00001706Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001707 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001708}
1709
Douglas Gregor654b07e2009-03-24 00:15:49 +00001710Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001711 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001712}
1713
Douglas Gregor1880ba52009-03-25 00:34:44 +00001714Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001715 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001716}
1717
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00001718Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
David Blaikie7a30dc52013-02-21 01:47:18 +00001719 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, None,
1720 /*ExpectParameterPack=*/ false);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001721}
1722
John McCall87a44eb2009-08-20 01:44:21 +00001723Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1724 TemplateTypeParmDecl *D) {
1725 // TODO: don't always clone when decls are refcounted.
Chandler Carruth08836322011-05-01 00:51:33 +00001726 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump11289f42009-09-09 15:08:12 +00001727
John McCall87a44eb2009-08-20 01:44:21 +00001728 TemplateTypeParmDecl *Inst =
Abramo Bagnarab3185b02011-03-06 15:48:19 +00001729 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1730 D->getLocStart(), D->getLocation(),
Chandler Carruth08836322011-05-01 00:51:33 +00001731 D->getDepth() - TemplateArgs.getNumLevels(),
1732 D->getIndex(), D->getIdentifier(),
John McCall87a44eb2009-08-20 01:44:21 +00001733 D->wasDeclaredWithTypename(),
1734 D->isParameterPack());
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001735 Inst->setAccess(AS_public);
John McCall87a44eb2009-08-20 01:44:21 +00001736
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001737 if (D->hasDefaultArgument())
1738 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1739
1740 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001741 // scope.
1742 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001743
John McCall87a44eb2009-08-20 01:44:21 +00001744 return Inst;
1745}
1746
Douglas Gregor6b815c82009-10-23 23:25:44 +00001747Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1748 NonTypeTemplateParmDecl *D) {
1749 // Substitute into the type of the non-type template parameter.
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001750 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001751 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1752 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001753 bool IsExpandedParameterPack = false;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001754 TypeSourceInfo *DI;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001755 QualType T;
Douglas Gregor6b815c82009-10-23 23:25:44 +00001756 bool Invalid = false;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001757
1758 if (D->isExpandedParameterPack()) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001759 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001760 // expansion of types. Substitute into each of the expanded types.
1761 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1762 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1763 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1764 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1765 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001766 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001767 D->getDeclName());
1768 if (!NewDI)
1769 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001770
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001771 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1772 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1773 D->getLocation());
1774 if (NewT.isNull())
1775 return 0;
1776 ExpandedParameterPackTypes.push_back(NewT);
1777 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001778
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001779 IsExpandedParameterPack = true;
1780 DI = D->getTypeSourceInfo();
1781 T = DI->getType();
Richard Smith1fde8ec2012-09-07 02:06:42 +00001782 } else if (D->isPackExpansion()) {
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001783 // The non-type template parameter pack's type is a pack expansion of types.
1784 // Determine whether we need to expand this parameter pack into separate
1785 // types.
David Blaikie6adc78e2013-02-18 22:06:02 +00001786 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001787 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001788 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001789 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001790
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001791 // Determine whether the set of unexpanded parameter packs can and should
1792 // be expanded.
1793 bool Expand = true;
1794 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001795 Optional<unsigned> OrigNumExpansions
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001796 = Expansion.getTypePtr()->getNumExpansions();
David Blaikie05785d12013-02-20 22:23:23 +00001797 Optional<unsigned> NumExpansions = OrigNumExpansions;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001798 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1799 Pattern.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001800 Unexpanded,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001801 TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001802 Expand, RetainExpansion,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001803 NumExpansions))
1804 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001805
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001806 if (Expand) {
1807 for (unsigned I = 0; I != *NumExpansions; ++I) {
1808 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1809 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001810 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001811 D->getDeclName());
1812 if (!NewDI)
1813 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001814
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001815 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1816 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1817 NewDI->getType(),
1818 D->getLocation());
1819 if (NewT.isNull())
1820 return 0;
1821 ExpandedParameterPackTypes.push_back(NewT);
1822 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001823
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001824 // Note that we have an expanded parameter pack. The "type" of this
1825 // expanded parameter pack is the original expansion type, but callers
1826 // will end up using the expanded parameter pack types for type-checking.
1827 IsExpandedParameterPack = true;
1828 DI = D->getTypeSourceInfo();
1829 T = DI->getType();
1830 } else {
1831 // We cannot fully expand the pack expansion now, so substitute into the
1832 // pattern and create a new pack expansion type.
1833 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1834 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001835 D->getLocation(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001836 D->getDeclName());
1837 if (!NewPattern)
1838 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001839
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001840 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1841 NumExpansions);
1842 if (!DI)
1843 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001844
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001845 T = DI->getType();
1846 }
1847 } else {
1848 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001849 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001850 D->getLocation(), D->getDeclName());
1851 if (!DI)
1852 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001853
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001854 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001855 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001856 D->getLocation());
1857 if (T.isNull()) {
1858 T = SemaRef.Context.IntTy;
1859 Invalid = true;
1860 }
Douglas Gregor6b815c82009-10-23 23:25:44 +00001861 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001862
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001863 NonTypeTemplateParmDecl *Param;
1864 if (IsExpandedParameterPack)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001865 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001866 D->getInnerLocStart(),
1867 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001868 D->getDepth() - TemplateArgs.getNumLevels(),
1869 D->getPosition(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001870 D->getIdentifier(), T,
1871 DI,
1872 ExpandedParameterPackTypes.data(),
1873 ExpandedParameterPackTypes.size(),
1874 ExpandedParameterPackTypesAsWritten.data());
1875 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001876 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001877 D->getInnerLocStart(),
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001878 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001879 D->getDepth() - TemplateArgs.getNumLevels(),
1880 D->getPosition(),
1881 D->getIdentifier(), T,
Douglas Gregor0231d8d2011-01-19 20:10:05 +00001882 D->isParameterPack(), DI);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001883
Douglas Gregorfd7c2252011-03-04 17:52:15 +00001884 Param->setAccess(AS_public);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001885 if (Invalid)
1886 Param->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001887
Abramo Bagnara656e3002010-06-09 09:26:05 +00001888 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001889
1890 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor954de172009-10-31 17:21:17 +00001891 // scope.
1892 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001893 return Param;
1894}
1895
Richard Smith1fde8ec2012-09-07 02:06:42 +00001896static void collectUnexpandedParameterPacks(
1897 Sema &S,
1898 TemplateParameterList *Params,
1899 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1900 for (TemplateParameterList::const_iterator I = Params->begin(),
1901 E = Params->end(); I != E; ++I) {
1902 if ((*I)->isTemplateParameterPack())
1903 continue;
1904 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1905 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1906 Unexpanded);
1907 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1908 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1909 Unexpanded);
1910 }
1911}
1912
Anders Carlsson4bd78752009-08-28 15:18:15 +00001913Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001914TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1915 TemplateTemplateParmDecl *D) {
1916 // Instantiate the template parameter list of the template template parameter.
1917 TemplateParameterList *TempParams = D->getTemplateParameters();
1918 TemplateParameterList *InstParams;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001919 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1920
1921 bool IsExpandedParameterPack = false;
1922
1923 if (D->isExpandedParameterPack()) {
1924 // The template template parameter pack is an already-expanded pack
1925 // expansion of template parameters. Substitute into each of the expanded
1926 // parameters.
1927 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1928 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1929 I != N; ++I) {
1930 LocalInstantiationScope Scope(SemaRef);
1931 TemplateParameterList *Expansion =
1932 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1933 if (!Expansion)
1934 return 0;
1935 ExpandedParams.push_back(Expansion);
1936 }
1937
1938 IsExpandedParameterPack = true;
1939 InstParams = TempParams;
1940 } else if (D->isPackExpansion()) {
1941 // The template template parameter pack expands to a pack of template
1942 // template parameters. Determine whether we need to expand this parameter
1943 // pack into separate parameters.
1944 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1945 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1946 Unexpanded);
1947
1948 // Determine whether the set of unexpanded parameter packs can and should
1949 // be expanded.
1950 bool Expand = true;
1951 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001952 Optional<unsigned> NumExpansions;
Richard Smith1fde8ec2012-09-07 02:06:42 +00001953 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1954 TempParams->getSourceRange(),
1955 Unexpanded,
1956 TemplateArgs,
1957 Expand, RetainExpansion,
1958 NumExpansions))
1959 return 0;
1960
1961 if (Expand) {
1962 for (unsigned I = 0; I != *NumExpansions; ++I) {
1963 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1964 LocalInstantiationScope Scope(SemaRef);
1965 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1966 if (!Expansion)
1967 return 0;
1968 ExpandedParams.push_back(Expansion);
1969 }
1970
1971 // Note that we have an expanded parameter pack. The "type" of this
1972 // expanded parameter pack is the original expansion type, but callers
1973 // will end up using the expanded parameter pack types for type-checking.
1974 IsExpandedParameterPack = true;
1975 InstParams = TempParams;
1976 } else {
1977 // We cannot fully expand the pack expansion now, so just substitute
1978 // into the pattern.
1979 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1980
1981 LocalInstantiationScope Scope(SemaRef);
1982 InstParams = SubstTemplateParams(TempParams);
1983 if (!InstParams)
1984 return 0;
1985 }
1986 } else {
Douglas Gregor38fee962009-11-11 16:58:32 +00001987 // Perform the actual substitution of template parameters within a new,
1988 // local instantiation scope.
John McCall19c1bfd2010-08-25 05:32:35 +00001989 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor38fee962009-11-11 16:58:32 +00001990 InstParams = SubstTemplateParams(TempParams);
1991 if (!InstParams)
Richard Smith1fde8ec2012-09-07 02:06:42 +00001992 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00001993 }
1994
Douglas Gregor38fee962009-11-11 16:58:32 +00001995 // Build the template template parameter.
Richard Smith1fde8ec2012-09-07 02:06:42 +00001996 TemplateTemplateParmDecl *Param;
1997 if (IsExpandedParameterPack)
1998 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1999 D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002000 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith1fde8ec2012-09-07 02:06:42 +00002001 D->getPosition(),
2002 D->getIdentifier(), InstParams,
2003 ExpandedParams);
2004 else
2005 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
2006 D->getLocation(),
2007 D->getDepth() - TemplateArgs.getNumLevels(),
2008 D->getPosition(),
2009 D->isParameterPack(),
2010 D->getIdentifier(), InstParams);
Abramo Bagnara656e3002010-06-09 09:26:05 +00002011 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregorfd7c2252011-03-04 17:52:15 +00002012 Param->setAccess(AS_public);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002013
2014 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor38fee962009-11-11 16:58:32 +00002015 // scope.
2016 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002017
Douglas Gregor38fee962009-11-11 16:58:32 +00002018 return Param;
2019}
2020
Douglas Gregore0b28662009-11-17 06:07:40 +00002021Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregor12441b32011-02-25 16:33:46 +00002022 // Using directives are never dependent (and never contain any types or
2023 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002024
Douglas Gregore0b28662009-11-17 06:07:40 +00002025 UsingDirectiveDecl *Inst
2026 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002027 D->getNamespaceKeyLocation(),
Douglas Gregor12441b32011-02-25 16:33:46 +00002028 D->getQualifierLoc(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002029 D->getIdentLocation(),
2030 D->getNominatedNamespace(),
Douglas Gregore0b28662009-11-17 06:07:40 +00002031 D->getCommonAncestor());
Abramo Bagnara8843f9f2012-09-05 09:55:10 +00002032
2033 // Add the using directive to its declaration context
2034 // only if this is not a function or method.
2035 if (!Owner->isFunctionOrMethod())
2036 Owner->addDecl(Inst);
2037
Douglas Gregore0b28662009-11-17 06:07:40 +00002038 return Inst;
2039}
2040
John McCallb96ec562009-12-04 22:46:56 +00002041Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorac2e4302010-09-29 17:58:28 +00002042
2043 // The nested name specifier may be dependent, for example
2044 // template <typename T> struct t {
2045 // struct s1 { T f1(); };
2046 // struct s2 : s1 { using s1::f1; };
2047 // };
2048 // template struct t<int>;
2049 // Here, in using s1::f1, s1 refers to t<T>::s1;
2050 // we need to substitute for t<int>::s1.
Douglas Gregor0499ab62011-02-25 15:54:31 +00002051 NestedNameSpecifierLoc QualifierLoc
2052 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
2053 TemplateArgs);
2054 if (!QualifierLoc)
Douglas Gregora9d87bc2011-02-25 00:36:19 +00002055 return 0;
Douglas Gregorac2e4302010-09-29 17:58:28 +00002056
2057 // The name info is non-dependent, so no transformation
2058 // is required.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002059 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCallb96ec562009-12-04 22:46:56 +00002060
John McCall84d87672009-12-10 09:41:52 +00002061 // We only need to do redeclaration lookups if we're in a class
2062 // scope (in fact, it's not really even possible in non-class
2063 // scopes).
2064 bool CheckRedeclaration = Owner->isRecord();
2065
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002066 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
2067 Sema::ForRedeclaration);
John McCall84d87672009-12-10 09:41:52 +00002068
John McCallb96ec562009-12-04 22:46:56 +00002069 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002070 D->getUsingLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002071 QualifierLoc,
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002072 NameInfo,
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002073 D->hasTypename());
John McCallb96ec562009-12-04 22:46:56 +00002074
Douglas Gregor0499ab62011-02-25 15:54:31 +00002075 CXXScopeSpec SS;
2076 SS.Adopt(QualifierLoc);
John McCall84d87672009-12-10 09:41:52 +00002077 if (CheckRedeclaration) {
2078 Prev.setHideTags(false);
2079 SemaRef.LookupQualifiedName(Prev, Owner);
2080
2081 // Check for invalid redeclarations.
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002082 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
2083 D->hasTypename(), SS,
John McCall84d87672009-12-10 09:41:52 +00002084 D->getLocation(), Prev))
2085 NewUD->setInvalidDecl();
2086
2087 }
2088
2089 if (!NewUD->isInvalidDecl() &&
Enea Zaffanellae05a3cf2013-07-22 10:54:09 +00002090 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), SS,
John McCallb96ec562009-12-04 22:46:56 +00002091 D->getLocation()))
2092 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00002093
John McCallb96ec562009-12-04 22:46:56 +00002094 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2095 NewUD->setAccess(D->getAccess());
2096 Owner->addDecl(NewUD);
2097
John McCall84d87672009-12-10 09:41:52 +00002098 // Don't process the shadow decls for an invalid decl.
2099 if (NewUD->isInvalidDecl())
2100 return NewUD;
2101
Richard Smith23d55872012-04-02 01:30:27 +00002102 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2103 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2104 NewUD->setInvalidDecl();
2105 return NewUD;
2106 }
2107
John McCalla1d85502009-12-22 22:26:37 +00002108 bool isFunctionScope = Owner->isFunctionOrMethod();
2109
John McCall84d87672009-12-10 09:41:52 +00002110 // Process the shadow decls.
2111 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2112 I != E; ++I) {
2113 UsingShadowDecl *Shadow = *I;
2114 NamedDecl *InstTarget =
Douglas Gregor55e6b312011-03-04 19:46:35 +00002115 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2116 Shadow->getLocation(),
2117 Shadow->getTargetDecl(),
2118 TemplateArgs));
2119 if (!InstTarget)
2120 return 0;
John McCall84d87672009-12-10 09:41:52 +00002121
2122 if (CheckRedeclaration &&
2123 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2124 continue;
2125
2126 UsingShadowDecl *InstShadow
2127 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2128 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00002129
2130 if (isFunctionScope)
2131 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00002132 }
John McCallb96ec562009-12-04 22:46:56 +00002133
2134 return NewUD;
2135}
2136
2137Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00002138 // Ignore these; we handle them in bulk when processing the UsingDecl.
2139 return 0;
John McCallb96ec562009-12-04 22:46:56 +00002140}
2141
John McCalle61f2ba2009-11-18 02:36:19 +00002142Decl * TemplateDeclInstantiator
2143 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002144 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002145 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor0499ab62011-02-25 15:54:31 +00002146 TemplateArgs);
2147 if (!QualifierLoc)
Anders Carlsson4bd78752009-08-28 15:18:15 +00002148 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002149
Anders Carlsson4bd78752009-08-28 15:18:15 +00002150 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002151 SS.Adopt(QualifierLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002152
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002153 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Kramerd81108f2012-11-14 15:08:31 +00002154 // Hence, no transformation is required for it.
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002155 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002156 NamedDecl *UD =
John McCall3f746822009-11-17 05:59:44 +00002157 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002158 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002159 /*instantiation*/ true,
2160 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor6044d692010-05-19 17:02:24 +00002161 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002162 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2163
John McCalle61f2ba2009-11-18 02:36:19 +00002164 return UD;
2165}
2166
2167Decl * TemplateDeclInstantiator
2168 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor0499ab62011-02-25 15:54:31 +00002169 NestedNameSpecifierLoc QualifierLoc
2170 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2171 if (!QualifierLoc)
John McCalle61f2ba2009-11-18 02:36:19 +00002172 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002173
John McCalle61f2ba2009-11-18 02:36:19 +00002174 CXXScopeSpec SS;
Douglas Gregor0499ab62011-02-25 15:54:31 +00002175 SS.Adopt(QualifierLoc);
John McCalle61f2ba2009-11-18 02:36:19 +00002176
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002177 DeclarationNameInfo NameInfo
2178 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2179
John McCalle61f2ba2009-11-18 02:36:19 +00002180 NamedDecl *UD =
2181 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnara8de74e92010-08-12 11:46:03 +00002182 D->getUsingLoc(), SS, NameInfo, 0,
John McCalle61f2ba2009-11-18 02:36:19 +00002183 /*instantiation*/ true,
2184 /*typename*/ false, SourceLocation());
Douglas Gregor6044d692010-05-19 17:02:24 +00002185 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00002186 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2187
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002188 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00002189}
2190
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002191
2192Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2193 ClassScopeFunctionSpecializationDecl *Decl) {
2194 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber7b5a7162012-06-25 17:21:05 +00002195 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2196 0, true));
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002197
2198 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2199 Sema::ForRedeclaration);
2200
Nico Weber7b5a7162012-06-25 17:21:05 +00002201 TemplateArgumentListInfo TemplateArgs;
2202 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2203 if (Decl->hasExplicitTemplateArgs()) {
2204 TemplateArgs = Decl->templateArgs();
2205 TemplateArgsPtr = &TemplateArgs;
2206 }
2207
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002208 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber7b5a7162012-06-25 17:21:05 +00002209 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2210 Previous)) {
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002211 NewFD->setInvalidDecl();
2212 return NewFD;
2213 }
2214
2215 // Associate the specialization with the pattern.
2216 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2217 assert(Specialization && "Class scope Specialization is null");
2218 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2219
2220 return NewFD;
2221}
2222
Alexey Bataeva769e072013-03-22 06:34:35 +00002223Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
2224 OMPThreadPrivateDecl *D) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002225 SmallVector<Expr *, 5> Vars;
2226 for (ArrayRef<Expr *>::iterator I = D->varlist_begin(),
2227 E = D->varlist_end();
Alexey Bataeva769e072013-03-22 06:34:35 +00002228 I != E; ++I) {
2229 Expr *Var = SemaRef.SubstExpr(*I, TemplateArgs).take();
2230 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr");
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002231 Vars.push_back(Var);
Alexey Bataeva769e072013-03-22 06:34:35 +00002232 }
2233
2234 OMPThreadPrivateDecl *TD =
2235 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
2236
2237 return TD;
2238}
2239
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002240Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
2241 return VisitFunctionDecl(D, 0);
2242}
2243
2244Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
2245 return VisitCXXMethodDecl(D, 0);
2246}
2247
2248Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
2249 llvm_unreachable("There are only CXXRecordDecls in C++");
2250}
2251
2252Decl *
2253TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
2254 ClassTemplateSpecializationDecl *D) {
2255 llvm_unreachable("Only ClassTemplatePartialSpecializationDecls occur"
2256 "inside templates");
2257}
2258
2259Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
2260 llvm_unreachable("@defs is not supported in Objective-C++");
2261}
2262
2263Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2264 // FIXME: We need to be able to instantiate FriendTemplateDecls.
2265 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
2266 DiagnosticsEngine::Error,
2267 "cannot instantiate %0 yet");
2268 SemaRef.Diag(D->getLocation(), DiagID)
2269 << D->getDeclKindName();
2270
2271 return 0;
2272}
2273
2274Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
2275 llvm_unreachable("Unexpected decl");
2276}
2277
John McCall76d824f2009-08-25 22:02:44 +00002278Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002279 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00002280 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00002281 if (D->isInvalidDecl())
2282 return 0;
2283
Douglas Gregord7e7a512009-03-17 21:15:40 +00002284 return Instantiator.Visit(D);
2285}
2286
John McCall87a44eb2009-08-20 01:44:21 +00002287/// \brief Instantiates a nested template parameter list in the current
2288/// instantiation context.
2289///
2290/// \param L The parameter list to instantiate
2291///
2292/// \returns NULL if there was an error
2293TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00002294TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00002295 // Get errors for all the parameters before bailing out.
2296 bool Invalid = false;
2297
2298 unsigned N = L->size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002299 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00002300 ParamVector Params;
2301 Params.reserve(N);
2302 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2303 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002304 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00002305 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00002306 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00002307 }
2308
2309 // Clean up if we had an error.
Douglas Gregorb412e172010-07-25 18:17:45 +00002310 if (Invalid)
John McCall87a44eb2009-08-20 01:44:21 +00002311 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +00002312
2313 TemplateParameterList *InstL
2314 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2315 L->getLAngleLoc(), &Params.front(), N,
2316 L->getRAngleLoc());
2317 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00002318}
John McCall87a44eb2009-08-20 01:44:21 +00002319
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002320/// \brief Instantiate the declaration of a class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002321/// specialization.
2322///
2323/// \param ClassTemplate the (instantiated) class template that is partially
2324// specialized by the instantiation of \p PartialSpec.
2325///
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002326/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregor21610382009-10-29 00:04:11 +00002327/// specialization that we are instantiating.
2328///
Douglas Gregor869853e2010-11-10 19:44:59 +00002329/// \returns The instantiated partial specialization, if successful; otherwise,
2330/// NULL to indicate an error.
2331ClassTemplatePartialSpecializationDecl *
Douglas Gregor21610382009-10-29 00:04:11 +00002332TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2333 ClassTemplateDecl *ClassTemplate,
2334 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00002335 // Create a local instantiation scope for this class template partial
2336 // specialization, which will contain the instantiations of the template
2337 // parameters.
John McCall19c1bfd2010-08-25 05:32:35 +00002338 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002339
Douglas Gregor21610382009-10-29 00:04:11 +00002340 // Substitute into the template parameters of the class template partial
2341 // specialization.
2342 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2343 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2344 if (!InstParams)
Douglas Gregor869853e2010-11-10 19:44:59 +00002345 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002346
Douglas Gregor21610382009-10-29 00:04:11 +00002347 // Substitute into the template arguments of the class template partial
2348 // specialization.
John McCall6b51f282009-11-23 01:53:49 +00002349 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002350 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2351 PartialSpec->getNumTemplateArgsAsWritten(),
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002352 InstTemplateArgs, TemplateArgs))
2353 return 0;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002354
Douglas Gregor21610382009-10-29 00:04:11 +00002355 // Check that the template argument list is well-formed for this
2356 // class template.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002357 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002358 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregor21610382009-10-29 00:04:11 +00002359 PartialSpec->getLocation(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002360 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002361 false,
2362 Converted))
Douglas Gregor869853e2010-11-10 19:44:59 +00002363 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002364
2365 // Figure out where to insert this class template partial specialization
2366 // in the member template's set of class template partial specializations.
Douglas Gregor21610382009-10-29 00:04:11 +00002367 void *InsertPos = 0;
2368 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002369 = ClassTemplate->findPartialSpecialization(Converted.data(),
2370 Converted.size(), InsertPos);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002371
Douglas Gregor21610382009-10-29 00:04:11 +00002372 // Build the canonical type that describes the converted template
2373 // arguments of the class template partial specialization.
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002374 QualType CanonType
Douglas Gregor21610382009-10-29 00:04:11 +00002375 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002376 Converted.data(),
2377 Converted.size());
Douglas Gregor21610382009-10-29 00:04:11 +00002378
2379 // Build the fully-sugared type for this class template
2380 // specialization as the user wrote in the specialization
2381 // itself. This means that we'll pretty-print the type retrieved
2382 // from the specialization's declaration the way that the user
2383 // actually wrote the specialization, rather than formatting the
2384 // name based on the "canonical" representation used to store the
2385 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00002386 TypeSourceInfo *WrittenTy
2387 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2388 TemplateName(ClassTemplate),
2389 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00002390 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00002391 CanonType);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002392
Douglas Gregor21610382009-10-29 00:04:11 +00002393 if (PrevDecl) {
2394 // We've already seen a partial specialization with the same template
2395 // parameters and template arguments. This can happen, for example, when
2396 // substituting the outer template arguments ends up causing two
2397 // class template partial specializations of a member class template
2398 // to have identical forms, e.g.,
2399 //
2400 // template<typename T, typename U>
2401 // struct Outer {
2402 // template<typename X, typename Y> struct Inner;
2403 // template<typename Y> struct Inner<T, Y>;
2404 // template<typename Y> struct Inner<U, Y>;
2405 // };
2406 //
2407 // Outer<int, int> outer; // error: the partial specializations of Inner
2408 // // have the same signature.
2409 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregor869853e2010-11-10 19:44:59 +00002410 << WrittenTy->getType();
Douglas Gregor21610382009-10-29 00:04:11 +00002411 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2412 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregor869853e2010-11-10 19:44:59 +00002413 return 0;
Douglas Gregor21610382009-10-29 00:04:11 +00002414 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002415
2416
Douglas Gregor21610382009-10-29 00:04:11 +00002417 // Create the class template partial specialization declaration.
2418 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002419 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregore9029562010-05-06 00:28:52 +00002420 PartialSpec->getTagKind(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002421 Owner,
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002422 PartialSpec->getLocStart(),
2423 PartialSpec->getLocation(),
Douglas Gregor21610382009-10-29 00:04:11 +00002424 InstParams,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002425 ClassTemplate,
Douglas Gregor1ccc8412010-11-07 23:05:16 +00002426 Converted.data(),
2427 Converted.size(),
John McCall6b51f282009-11-23 01:53:49 +00002428 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00002429 CanonType,
Douglas Gregor407e9612010-04-30 05:56:50 +00002430 0,
Argyrios Kyrtzidis47470f22010-07-20 13:59:28 +00002431 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCall3e11ebe2010-03-15 10:12:16 +00002432 // Substitute the nested name specifier, if any.
2433 if (SubstQualifier(PartialSpec, InstPartialSpec))
2434 return 0;
2435
Douglas Gregor21610382009-10-29 00:04:11 +00002436 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor6044d692010-05-19 17:02:24 +00002437 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002438
Douglas Gregor21610382009-10-29 00:04:11 +00002439 // Add this partial specialization to the set of class template partial
2440 // specializations.
Douglas Gregorce9978f2012-03-28 14:34:23 +00002441 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregor869853e2010-11-10 19:44:59 +00002442 return InstPartialSpec;
Douglas Gregor21610382009-10-29 00:04:11 +00002443}
2444
John McCall58f10c32010-03-11 09:03:00 +00002445TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00002446TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002447 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00002448 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2449 assert(OldTInfo && "substituting function without type source info");
2450 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregor3024f072012-04-16 07:05:22 +00002451
2452 CXXRecordDecl *ThisContext = 0;
2453 unsigned ThisTypeQuals = 0;
2454 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002455 ThisContext = cast<CXXRecordDecl>(Owner);
Douglas Gregor3024f072012-04-16 07:05:22 +00002456 ThisTypeQuals = Method->getTypeQualifiers();
2457 }
2458
John McCallb29f78f2010-04-09 17:38:44 +00002459 TypeSourceInfo *NewTInfo
2460 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2461 D->getTypeSpecStartLoc(),
Douglas Gregor3024f072012-04-16 07:05:22 +00002462 D->getDeclName(),
2463 ThisContext, ThisTypeQuals);
John McCall58f10c32010-03-11 09:03:00 +00002464 if (!NewTInfo)
2465 return 0;
Douglas Gregor21342092009-03-24 00:38:23 +00002466
Reid Klecknera09e44c2013-07-31 21:00:18 +00002467 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
2468 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
2469 if (NewTInfo != OldTInfo) {
2470 // Get parameters from the new type info.
Abramo Bagnaraa44c9022010-12-13 22:27:55 +00002471 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00002472 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
Richard Smith198223b2012-07-18 01:29:05 +00002473 unsigned NewIdx = 0;
David Blaikie6adc78e2013-02-18 22:06:02 +00002474 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumArgs();
Douglas Gregorf3010112011-01-07 16:43:16 +00002475 OldIdx != NumOldParams; ++OldIdx) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002476 ParmVarDecl *OldParam = OldProtoLoc.getArg(OldIdx);
Richard Smith198223b2012-07-18 01:29:05 +00002477 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2478
David Blaikie05785d12013-02-20 22:23:23 +00002479 Optional<unsigned> NumArgumentsInExpansion;
Richard Smith198223b2012-07-18 01:29:05 +00002480 if (OldParam->isParameterPack())
2481 NumArgumentsInExpansion =
2482 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2483 TemplateArgs);
2484 if (!NumArgumentsInExpansion) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002485 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregorf3010112011-01-07 16:43:16 +00002486 // instantiated to a (still-dependent) parameter pack.
David Blaikie6adc78e2013-02-18 22:06:02 +00002487 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Douglas Gregorf3010112011-01-07 16:43:16 +00002488 Params.push_back(NewParam);
Richard Smith198223b2012-07-18 01:29:05 +00002489 Scope->InstantiatedLocal(OldParam, NewParam);
2490 } else {
2491 // Parameter pack expansion: make the instantiation an argument pack.
2492 Scope->MakeInstantiatedLocalArgPack(OldParam);
2493 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
David Blaikie6adc78e2013-02-18 22:06:02 +00002494 ParmVarDecl *NewParam = NewProtoLoc.getArg(NewIdx++);
Richard Smith198223b2012-07-18 01:29:05 +00002495 Params.push_back(NewParam);
2496 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2497 }
Douglas Gregorf3010112011-01-07 16:43:16 +00002498 }
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002499 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002500 } else {
2501 // The function type itself was not dependent and therefore no
2502 // substitution occurred. However, we still need to instantiate
2503 // the function parameters themselves.
2504 const FunctionProtoType *OldProto =
2505 cast<FunctionProtoType>(OldProtoLoc.getType());
David Blaikie6adc78e2013-02-18 22:06:02 +00002506 for (unsigned i = 0, i_end = OldProtoLoc.getNumArgs(); i != i_end; ++i) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00002507 ParmVarDecl *OldParam = OldProtoLoc.getArg(i);
2508 if (!OldParam) {
2509 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
2510 D, D->getLocation(), OldProto->getArgType(i)));
2511 continue;
2512 }
2513
Eli Friedmancb9cd6c2013-06-27 23:21:55 +00002514 ParmVarDecl *Parm =
Reid Klecknera09e44c2013-07-31 21:00:18 +00002515 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
Douglas Gregor95c70ec2010-05-03 15:32:18 +00002516 if (!Parm)
2517 return 0;
2518 Params.push_back(Parm);
2519 }
Douglas Gregor940bca72010-04-12 07:48:19 +00002520 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002521 } else {
2522 // If the type of this function, after ignoring parentheses, is not
2523 // *directly* a function type, then we're instantiating a function that
2524 // was declared via a typedef or with attributes, e.g.,
2525 //
2526 // typedef int functype(int, int);
2527 // functype func;
2528 // int __cdecl meth(int, int);
2529 //
2530 // In this case, we'll just go instantiate the ParmVarDecls that we
2531 // synthesized in the method declaration.
2532 SmallVector<QualType, 4> ParamTypes;
2533 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
2534 D->getNumParams(), TemplateArgs, ParamTypes,
2535 &Params))
2536 return 0;
Douglas Gregor940bca72010-04-12 07:48:19 +00002537 }
Reid Klecknera09e44c2013-07-31 21:00:18 +00002538
John McCall58f10c32010-03-11 09:03:00 +00002539 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00002540}
2541
Richard Smithf623c962012-04-17 00:58:00 +00002542/// Introduce the instantiated function parameters into the local
2543/// instantiation scope, and set the parameter names to those used
2544/// in the template.
2545static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2546 const FunctionDecl *PatternDecl,
2547 LocalInstantiationScope &Scope,
2548 const MultiLevelTemplateArgumentList &TemplateArgs) {
2549 unsigned FParamIdx = 0;
2550 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2551 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2552 if (!PatternParam->isParameterPack()) {
2553 // Simple case: not a parameter pack.
2554 assert(FParamIdx < Function->getNumParams());
2555 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2556 FunctionParam->setDeclName(PatternParam->getDeclName());
2557 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2558 ++FParamIdx;
2559 continue;
2560 }
2561
2562 // Expand the parameter pack.
2563 Scope.MakeInstantiatedLocalArgPack(PatternParam);
David Blaikie05785d12013-02-20 22:23:23 +00002564 Optional<unsigned> NumArgumentsInExpansion
Richard Smithf623c962012-04-17 00:58:00 +00002565 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith198223b2012-07-18 01:29:05 +00002566 assert(NumArgumentsInExpansion &&
2567 "should only be called when all template arguments are known");
2568 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithf623c962012-04-17 00:58:00 +00002569 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2570 FunctionParam->setDeclName(PatternParam->getDeclName());
2571 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2572 ++FParamIdx;
2573 }
2574 }
2575}
2576
2577static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2578 const FunctionProtoType *Proto,
2579 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smithd3729422012-04-19 00:08:28 +00002580 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2581
Richard Smithf623c962012-04-17 00:58:00 +00002582 // C++11 [expr.prim.general]p3:
2583 // If a declaration declares a member function or member function
2584 // template of a class X, the expression this is a prvalue of type
2585 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2586 // and the end of the function-definition, member-declarator, or
2587 // declarator.
2588 CXXRecordDecl *ThisContext = 0;
2589 unsigned ThisTypeQuals = 0;
2590 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2591 ThisContext = Method->getParent();
2592 ThisTypeQuals = Method->getTypeQualifiers();
2593 }
2594 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002595 SemaRef.getLangOpts().CPlusPlus11);
Richard Smithf623c962012-04-17 00:58:00 +00002596
2597 // The function has an exception specification or a "noreturn"
2598 // attribute. Substitute into each of the exception types.
2599 SmallVector<QualType, 4> Exceptions;
2600 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2601 // FIXME: Poor location information!
2602 if (const PackExpansionType *PackExpansion
2603 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2604 // We have a pack expansion. Instantiate it.
2605 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2606 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2607 Unexpanded);
2608 assert(!Unexpanded.empty() &&
2609 "Pack expansion without parameter packs?");
2610
2611 bool Expand = false;
2612 bool RetainExpansion = false;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002613 Optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
Richard Smithf623c962012-04-17 00:58:00 +00002614 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2615 SourceRange(),
2616 Unexpanded,
2617 TemplateArgs,
2618 Expand,
2619 RetainExpansion,
2620 NumExpansions))
2621 break;
2622
2623 if (!Expand) {
2624 // We can't expand this pack expansion into separate arguments yet;
2625 // just substitute into the pattern and create a new pack expansion
2626 // type.
2627 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2628 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2629 TemplateArgs,
2630 New->getLocation(), New->getDeclName());
2631 if (T.isNull())
2632 break;
2633
2634 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2635 Exceptions.push_back(T);
2636 continue;
2637 }
2638
2639 // Substitute into the pack expansion pattern for each template
2640 bool Invalid = false;
2641 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2642 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2643
2644 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2645 TemplateArgs,
2646 New->getLocation(), New->getDeclName());
2647 if (T.isNull()) {
2648 Invalid = true;
2649 break;
2650 }
2651
2652 Exceptions.push_back(T);
2653 }
2654
2655 if (Invalid)
2656 break;
2657
2658 continue;
2659 }
2660
2661 QualType T
2662 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2663 New->getLocation(), New->getDeclName());
2664 if (T.isNull() ||
2665 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2666 continue;
2667
2668 Exceptions.push_back(T);
2669 }
2670 Expr *NoexceptExpr = 0;
2671 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2672 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2673 Sema::ConstantEvaluated);
2674 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2675 if (E.isUsable())
2676 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2677
2678 if (E.isUsable()) {
2679 NoexceptExpr = E.take();
2680 if (!NoexceptExpr->isTypeDependent() &&
2681 !NoexceptExpr->isValueDependent())
Douglas Gregore2b37442012-05-04 22:38:52 +00002682 NoexceptExpr
2683 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2684 0, diag::err_noexcept_needs_constant_expression,
2685 /*AllowFold*/ false).take();
Richard Smithf623c962012-04-17 00:58:00 +00002686 }
2687 }
2688
2689 // Rebuild the function type
2690 const FunctionProtoType *NewProto
2691 = New->getType()->getAs<FunctionProtoType>();
2692 assert(NewProto && "Template instantiation without function prototype?");
2693
2694 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2695 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2696 EPI.NumExceptions = Exceptions.size();
2697 EPI.Exceptions = Exceptions.data();
2698 EPI.NoexceptExpr = NoexceptExpr;
2699
2700 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00002701 NewProto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00002702}
2703
2704void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2705 FunctionDecl *Decl) {
Richard Smithd3729422012-04-19 00:08:28 +00002706 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2707 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00002708 return;
2709
2710 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2711 InstantiatingTemplate::ExceptionSpecification());
Richard Smithd3b5c9082012-07-27 04:22:15 +00002712 if (Inst) {
2713 // We hit the instantiation depth limit. Clear the exception specification
2714 // so that our callers don't have to cope with EST_Uninstantiated.
2715 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2716 EPI.ExceptionSpecType = EST_None;
2717 Decl->setType(Context.getFunctionType(Proto->getResultType(),
Reid Kleckner896b32f2013-06-10 20:51:09 +00002718 Proto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00002719 return;
Richard Smithd3b5c9082012-07-27 04:22:15 +00002720 }
Richard Smithf623c962012-04-17 00:58:00 +00002721
2722 // Enter the scope of this instantiation. We don't use
2723 // PushDeclContext because we don't have a scope.
2724 Sema::ContextRAII savedContext(*this, Decl);
2725 LocalInstantiationScope Scope(*this);
2726
2727 MultiLevelTemplateArgumentList TemplateArgs =
2728 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2729
Richard Smithd3729422012-04-19 00:08:28 +00002730 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2731 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00002732
Richard Smithd3729422012-04-19 00:08:28 +00002733 ::InstantiateExceptionSpec(*this, Decl,
2734 Template->getType()->castAs<FunctionProtoType>(),
2735 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +00002736}
2737
Mike Stump11289f42009-09-09 15:08:12 +00002738/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002739/// declaration (New) from the corresponding fields of its template (Tmpl).
2740///
2741/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00002742bool
2743TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002744 FunctionDecl *Tmpl) {
David Blaikie5a0956e2012-07-16 18:50:45 +00002745 if (Tmpl->isDeleted())
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002746 New->setDeletedAsWritten();
Mike Stump11289f42009-09-09 15:08:12 +00002747
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00002748 // If we are performing substituting explicitly-specified template arguments
2749 // or deduced template arguments into a function template and we reach this
2750 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00002751 // to keeping the new function template specialization. We therefore
2752 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00002753 // into a template instantiation for this specific function template
2754 // specialization, which is not a SFINAE context, so that we diagnose any
2755 // further errors in the declaration itself.
2756 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2757 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2758 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2759 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00002760 if (FunctionTemplateDecl *FunTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +00002761 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00002762 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00002763 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00002764 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00002765 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +00002766 ActiveInst.Entity = New;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00002767 }
2768 }
Mike Stump11289f42009-09-09 15:08:12 +00002769
Douglas Gregor049bdca2009-12-08 17:45:32 +00002770 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2771 assert(Proto && "Function template without prototype?");
2772
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002773 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalldb40c7f2010-12-14 08:05:40 +00002774 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalldb40c7f2010-12-14 08:05:40 +00002775
Richard Smithf623c962012-04-17 00:58:00 +00002776 // DR1330: In C++11, defer instantiation of a non-trivial
2777 // exception specification.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002778 if (SemaRef.getLangOpts().CPlusPlus11 &&
Richard Smithf623c962012-04-17 00:58:00 +00002779 EPI.ExceptionSpecType != EST_None &&
2780 EPI.ExceptionSpecType != EST_DynamicNone &&
2781 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smithd3729422012-04-19 00:08:28 +00002782 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2783 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2784 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smith185be182013-04-10 05:48:59 +00002785 ExceptionSpecificationType NewEST = EST_Uninstantiated;
2786 if (EPI.ExceptionSpecType == EST_Unevaluated)
2787 NewEST = EST_Unevaluated;
Richard Smithd3729422012-04-19 00:08:28 +00002788
Richard Smithf623c962012-04-17 00:58:00 +00002789 // Mark the function has having an uninstantiated exception specification.
2790 const FunctionProtoType *NewProto
2791 = New->getType()->getAs<FunctionProtoType>();
2792 assert(NewProto && "Template instantiation without function prototype?");
2793 EPI = NewProto->getExtProtoInfo();
Richard Smith185be182013-04-10 05:48:59 +00002794 EPI.ExceptionSpecType = NewEST;
Richard Smithf623c962012-04-17 00:58:00 +00002795 EPI.ExceptionSpecDecl = New;
Richard Smithd3729422012-04-19 00:08:28 +00002796 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Reid Kleckner896b32f2013-06-10 20:51:09 +00002797 New->setType(SemaRef.Context.getFunctionType(
2798 NewProto->getResultType(), NewProto->getArgTypes(), EPI));
Richard Smithf623c962012-04-17 00:58:00 +00002799 } else {
2800 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2801 }
Douglas Gregor049bdca2009-12-08 17:45:32 +00002802 }
2803
Rafael Espindolaba195cf2011-07-06 15:46:09 +00002804 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithf623c962012-04-17 00:58:00 +00002805 const FunctionDecl *Definition = Tmpl;
Rafael Espindolaba195cf2011-07-06 15:46:09 +00002806 Tmpl->isDefined(Definition);
2807
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002808 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2809 LateAttrs, StartingScope);
Douglas Gregor08329632010-06-15 17:05:35 +00002810
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002811 return false;
2812}
2813
Douglas Gregor21342092009-03-24 00:38:23 +00002814/// \brief Initializes common fields of an instantiated method
2815/// declaration (New) from the corresponding fields of its template
2816/// (Tmpl).
2817///
2818/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00002819bool
2820TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00002821 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002822 if (InitFunctionInstantiation(New, Tmpl))
2823 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002824
Douglas Gregor21342092009-03-24 00:38:23 +00002825 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00002826 if (Tmpl->isVirtualAsWritten())
Douglas Gregor11c024b2010-09-28 20:50:54 +00002827 New->setVirtualAsWritten(true);
Douglas Gregor21342092009-03-24 00:38:23 +00002828
Douglas Gregor21342092009-03-24 00:38:23 +00002829 // FIXME: New needs a pointer to Tmpl
2830 return false;
2831}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002832
2833/// \brief Instantiate the definition of the given function from its
2834/// template.
2835///
Douglas Gregordda7ced2009-06-30 17:20:14 +00002836/// \param PointOfInstantiation the point at which the instantiation was
2837/// required. Note that this is not precisely a "point of instantiation"
2838/// for the function, but it's close.
2839///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002840/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00002841/// function template specialization or member function of a class template
2842/// specialization.
2843///
2844/// \param Recursive if true, recursively instantiates any functions that
2845/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00002846///
2847/// \param DefinitionRequired if true, then we are performing an explicit
2848/// instantiation where the body of the function is required. Complain if
2849/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00002850void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00002851 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00002852 bool Recursive,
2853 bool DefinitionRequired) {
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002854 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregorb4850462009-05-14 23:26:13 +00002855 return;
2856
Francois Pichet00c7e6c2011-08-14 03:52:19 +00002857 // Never instantiate an explicit specialization except if it is a class scope
2858 // explicit specialization.
2859 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2860 !Function->getClassScopeSpecializationPattern())
Douglas Gregor86d142a2009-10-08 07:24:58 +00002861 return;
Douglas Gregor69f6a362010-05-17 17:34:56 +00002862
Douglas Gregor24c332b2009-05-14 21:06:31 +00002863 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00002864 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Alexis Hunt23f6b832011-05-27 20:00:14 +00002865 assert(PatternDecl && "instantiating a non-template");
2866
2867 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2868 assert(PatternDecl && "template definition is not a template");
2869 if (!Pattern) {
2870 // Try to find a defaulted definition
2871 PatternDecl->isDefined(PatternDecl);
Alexis Hunt92a0adf2011-05-25 22:02:25 +00002872 }
Alexis Hunt23f6b832011-05-27 20:00:14 +00002873 assert(PatternDecl && "template definition is not a template");
Douglas Gregor24c332b2009-05-14 21:06:31 +00002874
Francois Pichet1c229c02011-04-22 22:18:13 +00002875 // Postpone late parsed template instantiations.
Alexis Hunt23f6b832011-05-27 20:00:14 +00002876 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky610128e2011-05-12 03:51:24 +00002877 !LateTemplateParser) {
Francois Pichet1c229c02011-04-22 22:18:13 +00002878 PendingInstantiations.push_back(
2879 std::make_pair(Function, PointOfInstantiation));
2880 return;
2881 }
2882
2883 // Call the LateTemplateParser callback if there a need to late parse
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002884 // a templated function definition.
Alexis Hunt23f6b832011-05-27 20:00:14 +00002885 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet1c229c02011-04-22 22:18:13 +00002886 LateTemplateParser) {
Francois Picheta7d337d2011-04-23 11:52:20 +00002887 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet1c229c02011-04-22 22:18:13 +00002888 Pattern = PatternDecl->getBody(PatternDecl);
2889 }
2890
Alexis Hunt23f6b832011-05-27 20:00:14 +00002891 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregora8b89d22009-10-15 14:05:49 +00002892 if (DefinitionRequired) {
2893 if (Function->getPrimaryTemplate())
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002894 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00002895 diag::err_explicit_instantiation_undefined_func_template)
2896 << Function->getPrimaryTemplate();
2897 else
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002898 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00002899 diag::err_explicit_instantiation_undefined_member)
2900 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002901
Douglas Gregora8b89d22009-10-15 14:05:49 +00002902 if (PatternDecl)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002903 Diag(PatternDecl->getLocation(),
Douglas Gregora8b89d22009-10-15 14:05:49 +00002904 diag::note_explicit_instantiation_here);
Douglas Gregorfd7224f2010-05-17 17:57:54 +00002905 Function->setInvalidDecl();
Chandler Carruthcfe41db2010-08-25 08:27:02 +00002906 } else if (Function->getTemplateSpecializationKind()
2907 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00002908 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00002909 std::make_pair(Function, PointOfInstantiation));
Douglas Gregora8b89d22009-10-15 14:05:49 +00002910 }
Chandler Carruthcfe41db2010-08-25 08:27:02 +00002911
Douglas Gregor24c332b2009-05-14 21:06:31 +00002912 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00002913 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00002914
Richard Smith2a7d4812013-05-04 07:00:32 +00002915 // C++1y [temp.explicit]p10:
2916 // Except for inline functions, declarations with types deduced from their
2917 // initializer or return value, and class template specializations, other
2918 // explicit instantiation declarations have the effect of suppressing the
2919 // implicit instantiation of the entity to which they refer.
Mike Stump11289f42009-09-09 15:08:12 +00002920 if (Function->getTemplateSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002921 == TSK_ExplicitInstantiationDeclaration &&
Richard Smith2a7d4812013-05-04 07:00:32 +00002922 !PatternDecl->isInlined() &&
2923 !PatternDecl->getResultType()->isUndeducedType())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002924 return;
Mike Stump11289f42009-09-09 15:08:12 +00002925
Richard Smithf3814ad2013-01-25 00:08:28 +00002926 if (PatternDecl->isInlined())
2927 Function->setImplicitlyInline();
2928
Douglas Gregor85673582009-05-18 17:01:57 +00002929 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2930 if (Inst)
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002931 return;
2932
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002933 // Copy the inner loc start from the pattern.
2934 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2935
Douglas Gregordda7ced2009-06-30 17:20:14 +00002936 // If we're performing recursive template instantiation, create our own
2937 // queue of pending implicit instantiations that we will instantiate later,
2938 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002939 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00002940 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Faisal Vali18d35982013-06-26 02:34:24 +00002941 std::deque<PendingImplicitInstantiation>
2942 SavedPendingLocalImplicitInstantiations;
2943 SavedPendingLocalImplicitInstantiations.swap(
2944 PendingLocalImplicitInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00002945 if (Recursive) {
2946 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00002947 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewyckyef4f4562010-11-25 00:35:20 +00002948 }
Mike Stump11289f42009-09-09 15:08:12 +00002949
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002950 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00002951 Sema::PotentiallyEvaluated);
Douglas Gregor67da0d92009-05-15 17:59:04 +00002952
Douglas Gregorb4850462009-05-14 23:26:13 +00002953 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00002954 // recorded, unless we're actually a member function within a local
2955 // class, in which case we need to merge our results with the parent
2956 // scope (of the enclosing function).
2957 bool MergeWithParentScope = false;
2958 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2959 MergeWithParentScope = Rec->isLocalClass();
2960
2961 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00002962
Richard Smithbd305122012-12-11 01:14:52 +00002963 if (PatternDecl->isDefaulted())
Alexis Hunt61ae8d32011-05-23 23:14:04 +00002964 SetDeclDefaulted(Function, PatternDecl->getLocation());
Richard Smithbd305122012-12-11 01:14:52 +00002965 else {
2966 ActOnStartOfFunctionDef(0, Function);
2967
2968 // Enter the scope of this instantiation. We don't use
2969 // PushDeclContext because we don't have a scope.
2970 Sema::ContextRAII savedContext(*this, Function);
2971
2972 MultiLevelTemplateArgumentList TemplateArgs =
2973 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2974
2975 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2976 TemplateArgs);
2977
Alexis Hunt61ae8d32011-05-23 23:14:04 +00002978 // If this is a constructor, instantiate the member initializers.
2979 if (const CXXConstructorDecl *Ctor =
2980 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2981 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2982 TemplateArgs);
2983 }
2984
2985 // Instantiate the function body.
2986 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2987
2988 if (Body.isInvalid())
2989 Function->setInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00002990
Alexis Hunt61ae8d32011-05-23 23:14:04 +00002991 ActOnFinishFunctionBody(Function, Body.get(),
2992 /*IsInstantiation=*/true);
Richard Smithbd305122012-12-11 01:14:52 +00002993
2994 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2995
2996 savedContext.pop();
Mike Stump11289f42009-09-09 15:08:12 +00002997 }
2998
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002999 DeclGroupRef DG(Function);
3000 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00003001
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003002 // This class may have local implicit instantiations that need to be
3003 // instantiation within this scope.
Chandler Carruth54080172010-08-25 08:44:16 +00003004 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003005 Scope.Exit();
3006
Douglas Gregordda7ced2009-06-30 17:20:14 +00003007 if (Recursive) {
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003008 // Define any pending vtables.
3009 DefineUsedVTables();
3010
Douglas Gregordda7ced2009-06-30 17:20:14 +00003011 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003012 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003013 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003014
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003015 // Restore the set of pending vtables.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003016 assert(VTableUses.empty() &&
3017 "VTableUses should be empty before it is discarded.");
Nick Lewyckyef4f4562010-11-25 00:35:20 +00003018 VTableUses.swap(SavedVTableUses);
3019
Douglas Gregordda7ced2009-06-30 17:20:14 +00003020 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003021 assert(PendingInstantiations.empty() &&
3022 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth54080172010-08-25 08:44:16 +00003023 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregordda7ced2009-06-30 17:20:14 +00003024 }
Faisal Vali18d35982013-06-26 02:34:24 +00003025 SavedPendingLocalImplicitInstantiations.swap(
3026 PendingLocalImplicitInstantiations);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003027}
3028
3029/// \brief Instantiate the definition of the given variable from its
3030/// template.
3031///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003032/// \param PointOfInstantiation the point at which the instantiation was
3033/// required. Note that this is not precisely a "point of instantiation"
3034/// for the function, but it's close.
3035///
3036/// \param Var the already-instantiated declaration of a static member
3037/// variable of a class template specialization.
3038///
3039/// \param Recursive if true, recursively instantiates any functions that
3040/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003041///
3042/// \param DefinitionRequired if true, then we are performing an explicit
3043/// instantiation where an out-of-line definition of the member variable
3044/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003045void Sema::InstantiateStaticDataMemberDefinition(
3046 SourceLocation PointOfInstantiation,
3047 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003048 bool Recursive,
3049 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003050 if (Var->isInvalidDecl())
3051 return;
Mike Stump11289f42009-09-09 15:08:12 +00003052
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003053 // Find the out-of-line definition of this static data member.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003054 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003055 assert(Def && "This data member was not instantiated from a template?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003056 assert(Def->isStaticDataMember() && "Not a static data member?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00003057 Def = Def->getOutOfLineDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00003058
Douglas Gregor1d957a32009-10-27 18:42:08 +00003059 if (!Def) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003060 // We did not find an out-of-line definition of this static data member,
3061 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump11289f42009-09-09 15:08:12 +00003062 // instantiate this definition (or provide a specialization for it) in
3063 // another translation unit.
Douglas Gregora8b89d22009-10-15 14:05:49 +00003064 if (DefinitionRequired) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00003065 Def = Var->getInstantiatedFromStaticDataMember();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003066 Diag(PointOfInstantiation,
Douglas Gregora8b89d22009-10-15 14:05:49 +00003067 diag::err_explicit_instantiation_undefined_member)
3068 << 2 << Var->getDeclName() << Var->getDeclContext();
3069 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003070 } else if (Var->getTemplateSpecializationKind()
3071 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth54080172010-08-25 08:44:16 +00003072 PendingInstantiations.push_back(
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003073 std::make_pair(Var, PointOfInstantiation));
3074 }
3075
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003076 return;
3077 }
3078
Rafael Espindola189fa742012-03-05 10:54:55 +00003079 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
3080
Douglas Gregor86d142a2009-10-08 07:24:58 +00003081 // Never instantiate an explicit specialization.
Rafael Espindola189fa742012-03-05 10:54:55 +00003082 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003083 return;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003084
Douglas Gregor86d142a2009-10-08 07:24:58 +00003085 // C++0x [temp.explicit]p9:
3086 // Except for inline functions, other explicit instantiation declarations
3087 // have the effect of suppressing the implicit instantiation of the entity
3088 // to which they refer.
Rafael Espindola189fa742012-03-05 10:54:55 +00003089 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor86d142a2009-10-08 07:24:58 +00003090 return;
Mike Stump11289f42009-09-09 15:08:12 +00003091
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003092 // Make sure to pass the instantiated variable to the consumer at the end.
3093 struct PassToConsumerRAII {
3094 ASTConsumer &Consumer;
3095 VarDecl *Var;
3096
3097 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
3098 : Consumer(Consumer), Var(Var) { }
3099
3100 ~PassToConsumerRAII() {
3101 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
3102 }
3103 } PassToConsumerRAII(Consumer, Var);
Rafael Espindoladf88f6f2012-03-08 15:51:03 +00003104
Douglas Gregor57d4f972011-06-03 03:35:07 +00003105 // If we already have a definition, we're done.
Nick Lewyckya995a472012-04-04 02:38:36 +00003106 if (VarDecl *Def = Var->getDefinition()) {
3107 // We may be explicitly instantiating something we've already implicitly
3108 // instantiated.
3109 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
3110 PointOfInstantiation);
Douglas Gregor57d4f972011-06-03 03:35:07 +00003111 return;
Nick Lewyckya995a472012-04-04 02:38:36 +00003112 }
Douglas Gregor57d4f972011-06-03 03:35:07 +00003113
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003114 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
3115 if (Inst)
3116 return;
Mike Stump11289f42009-09-09 15:08:12 +00003117
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003118 // If we're performing recursive template instantiation, create our own
3119 // queue of pending implicit instantiations that we will instantiate later,
3120 // while we're still within our own instantiation context.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003121 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth54080172010-08-25 08:44:16 +00003122 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003123 if (Recursive) {
3124 VTableUses.swap(SavedVTableUses);
Chandler Carruth54080172010-08-25 08:44:16 +00003125 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003126 }
Mike Stump11289f42009-09-09 15:08:12 +00003127
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003128 // Enter the scope of this instantiation. We don't use
3129 // PushDeclContext because we don't have a scope.
John McCall2957e3e2011-02-14 20:37:25 +00003130 ContextRAII previousContext(*this, Var->getDeclContext());
Douglas Gregora86bc002012-02-16 21:36:18 +00003131 LocalInstantiationScope Local(*this);
3132
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00003133 VarDecl *OldVar = Var;
John McCall76d824f2009-08-25 22:02:44 +00003134 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber20c9f1d2010-11-28 22:53:37 +00003135 getTemplateInstantiationArgs(Var)));
John McCall2957e3e2011-02-14 20:37:25 +00003136
3137 previousContext.pop();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003138
3139 if (Var) {
Argyrios Kyrtzidis8a27b2b2013-02-24 00:05:01 +00003140 PassToConsumerRAII.Var = Var;
Douglas Gregor8f003d02009-10-15 18:07:02 +00003141 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
3142 assert(MSInfo && "Missing member specialization information?");
3143 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
3144 MSInfo->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003145 }
Douglas Gregora86bc002012-02-16 21:36:18 +00003146 Local.Exit();
3147
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003148 if (Recursive) {
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003149 // Define any newly required vtables.
3150 DefineUsedVTables();
3151
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003152 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00003153 // instantiation of this template.
Chandler Carruth54080172010-08-25 08:44:16 +00003154 PerformPendingInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00003155
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003156 // Restore the set of pending vtables.
3157 assert(VTableUses.empty() &&
3158 "VTableUses should be empty before it is discarded, "
3159 "while instantiating static data member.");
3160 VTableUses.swap(SavedVTableUses);
3161
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003162 // Restore the set of pending implicit instantiations.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003163 assert(PendingInstantiations.empty() &&
3164 "PendingInstantiations should be empty before it is discarded, "
3165 "while instantiating static data member.");
Chandler Carruth54080172010-08-25 08:44:16 +00003166 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00003167 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00003168}
Douglas Gregor51783312009-05-27 05:35:12 +00003169
Anders Carlsson70553942009-08-29 05:16:22 +00003170void
3171Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3172 const CXXConstructorDecl *Tmpl,
3173 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00003174
Richard Trieu9becef62011-09-09 03:18:59 +00003175 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith60f2e1e2012-09-25 00:23:05 +00003176 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003177
Anders Carlsson70553942009-08-29 05:16:22 +00003178 // Instantiate all the initializers.
3179 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregora3a3f6f2009-09-01 21:04:42 +00003180 InitsEnd = Tmpl->init_end();
3181 Inits != InitsEnd; ++Inits) {
Alexis Hunt1d792652011-01-08 20:30:50 +00003182 CXXCtorInitializer *Init = *Inits;
Anders Carlsson70553942009-08-29 05:16:22 +00003183
Chandler Carruthf92bd8c2010-09-03 21:54:20 +00003184 // Only instantiate written initializers, let Sema re-construct implicit
3185 // ones.
3186 if (!Init->isWritten())
3187 continue;
3188
Douglas Gregor44e7df62011-01-04 00:32:56 +00003189 SourceLocation EllipsisLoc;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003190
Douglas Gregor44e7df62011-01-04 00:32:56 +00003191 if (Init->isPackExpansion()) {
3192 // This is a pack expansion. We should expand it now.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003193 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Nick Lewycky2c308502013-06-13 00:45:47 +00003194 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
Douglas Gregor44e7df62011-01-04 00:32:56 +00003195 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
Nick Lewycky2c308502013-06-13 00:45:47 +00003196 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
Douglas Gregor44e7df62011-01-04 00:32:56 +00003197 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003198 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00003199 Optional<unsigned> NumExpansions;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003200 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003201 BaseTL.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00003202 Unexpanded,
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003203 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003204 RetainExpansion,
Douglas Gregor44e7df62011-01-04 00:32:56 +00003205 NumExpansions)) {
3206 AnyErrors = true;
3207 New->setInvalidDecl();
3208 continue;
3209 }
3210 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003211
3212 // Loop over all of the arguments in the argument pack(s),
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00003213 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003214 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3215
3216 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00003217 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3218 /*CXXDirectInit=*/true);
3219 if (TempInit.isInvalid()) {
Douglas Gregor44e7df62011-01-04 00:32:56 +00003220 AnyErrors = true;
3221 break;
3222 }
3223
3224 // Instantiate the base type.
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003225 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003226 TemplateArgs,
3227 Init->getSourceLocation(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003228 New->getDeclName());
3229 if (!BaseTInfo) {
3230 AnyErrors = true;
3231 break;
3232 }
3233
3234 // Build the initializer.
Sebastian Redla74948d2011-09-24 17:48:25 +00003235 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redla9351792012-02-11 23:51:47 +00003236 BaseTInfo, TempInit.take(),
Douglas Gregor44e7df62011-01-04 00:32:56 +00003237 New->getParent(),
3238 SourceLocation());
3239 if (NewInit.isInvalid()) {
3240 AnyErrors = true;
3241 break;
3242 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003243
Douglas Gregor44e7df62011-01-04 00:32:56 +00003244 NewInits.push_back(NewInit.get());
Douglas Gregor44e7df62011-01-04 00:32:56 +00003245 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003246
Douglas Gregor44e7df62011-01-04 00:32:56 +00003247 continue;
3248 }
3249
Douglas Gregorb30f22b2010-03-02 07:38:39 +00003250 // Instantiate the initializer.
Sebastian Redla9351792012-02-11 23:51:47 +00003251 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3252 /*CXXDirectInit=*/true);
3253 if (TempInit.isInvalid()) {
Douglas Gregorb30f22b2010-03-02 07:38:39 +00003254 AnyErrors = true;
3255 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00003256 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003257
Anders Carlsson70553942009-08-29 05:16:22 +00003258 MemInitResult NewInit;
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003259 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3260 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3261 TemplateArgs,
3262 Init->getSourceLocation(),
3263 New->getDeclName());
3264 if (!TInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003265 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00003266 New->setInvalidDecl();
3267 continue;
3268 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003269
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003270 if (Init->isBaseInitializer())
Sebastian Redla9351792012-02-11 23:51:47 +00003271 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003272 New->getParent(), EllipsisLoc);
3273 else
Sebastian Redla9351792012-02-11 23:51:47 +00003274 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregord73f3dd2011-11-01 01:16:03 +00003275 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson70553942009-08-29 05:16:22 +00003276 } else if (Init->isMemberInitializer()) {
Douglas Gregor55e6b312011-03-04 19:46:35 +00003277 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00003278 Init->getMemberLocation(),
3279 Init->getMember(),
3280 TemplateArgs));
Douglas Gregor55e6b312011-03-04 19:46:35 +00003281 if (!Member) {
3282 AnyErrors = true;
3283 New->setInvalidDecl();
3284 continue;
3285 }
Mike Stump11289f42009-09-09 15:08:12 +00003286
Sebastian Redla9351792012-02-11 23:51:47 +00003287 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00003288 Init->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +00003289 } else if (Init->isIndirectMemberInitializer()) {
3290 IndirectFieldDecl *IndirectMember =
Douglas Gregor55e6b312011-03-04 19:46:35 +00003291 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichetd583da02010-12-04 09:14:42 +00003292 Init->getMemberLocation(),
3293 Init->getIndirectMember(), TemplateArgs));
3294
Douglas Gregor55e6b312011-03-04 19:46:35 +00003295 if (!IndirectMember) {
3296 AnyErrors = true;
3297 New->setInvalidDecl();
Sebastian Redla74948d2011-09-24 17:48:25 +00003298 continue;
Douglas Gregor55e6b312011-03-04 19:46:35 +00003299 }
Sebastian Redla74948d2011-09-24 17:48:25 +00003300
Sebastian Redla9351792012-02-11 23:51:47 +00003301 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redla74948d2011-09-24 17:48:25 +00003302 Init->getSourceLocation());
Anders Carlsson70553942009-08-29 05:16:22 +00003303 }
3304
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003305 if (NewInit.isInvalid()) {
3306 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00003307 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003308 } else {
Richard Trieu9becef62011-09-09 03:18:59 +00003309 NewInits.push_back(NewInit.get());
Anders Carlsson70553942009-08-29 05:16:22 +00003310 }
3311 }
Mike Stump11289f42009-09-09 15:08:12 +00003312
Anders Carlsson70553942009-08-29 05:16:22 +00003313 // Assign all the initializers to the new constructor.
John McCall48871652010-08-21 09:40:31 +00003314 ActOnMemInitializers(New,
Anders Carlsson70553942009-08-29 05:16:22 +00003315 /*FIXME: ColonLoc */
3316 SourceLocation(),
David Blaikie3fc2f912013-01-17 05:26:25 +00003317 NewInits,
Douglas Gregor7ae2d772010-01-31 09:12:51 +00003318 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00003319}
3320
John McCall59660882009-08-29 08:11:13 +00003321// TODO: this could be templated if the various decl types used the
3322// same method name.
3323static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3324 ClassTemplateDecl *Instance) {
3325 Pattern = Pattern->getCanonicalDecl();
3326
3327 do {
3328 Instance = Instance->getCanonicalDecl();
3329 if (Pattern == Instance) return true;
3330 Instance = Instance->getInstantiatedFromMemberTemplate();
3331 } while (Instance);
3332
3333 return false;
3334}
3335
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003336static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3337 FunctionTemplateDecl *Instance) {
3338 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003339
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003340 do {
3341 Instance = Instance->getCanonicalDecl();
3342 if (Pattern == Instance) return true;
3343 Instance = Instance->getInstantiatedFromMemberTemplate();
3344 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003345
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003346 return false;
3347}
3348
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003349static bool
Douglas Gregor21610382009-10-29 00:04:11 +00003350isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3351 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003352 Pattern
Douglas Gregor21610382009-10-29 00:04:11 +00003353 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3354 do {
3355 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3356 Instance->getCanonicalDecl());
3357 if (Pattern == Instance)
3358 return true;
3359 Instance = Instance->getInstantiatedFromMember();
3360 } while (Instance);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003361
Douglas Gregor21610382009-10-29 00:04:11 +00003362 return false;
3363}
3364
John McCall59660882009-08-29 08:11:13 +00003365static bool isInstantiationOf(CXXRecordDecl *Pattern,
3366 CXXRecordDecl *Instance) {
3367 Pattern = Pattern->getCanonicalDecl();
3368
3369 do {
3370 Instance = Instance->getCanonicalDecl();
3371 if (Pattern == Instance) return true;
3372 Instance = Instance->getInstantiatedFromMemberClass();
3373 } while (Instance);
3374
3375 return false;
3376}
3377
3378static bool isInstantiationOf(FunctionDecl *Pattern,
3379 FunctionDecl *Instance) {
3380 Pattern = Pattern->getCanonicalDecl();
3381
3382 do {
3383 Instance = Instance->getCanonicalDecl();
3384 if (Pattern == Instance) return true;
3385 Instance = Instance->getInstantiatedFromMemberFunction();
3386 } while (Instance);
3387
3388 return false;
3389}
3390
3391static bool isInstantiationOf(EnumDecl *Pattern,
3392 EnumDecl *Instance) {
3393 Pattern = Pattern->getCanonicalDecl();
3394
3395 do {
3396 Instance = Instance->getCanonicalDecl();
3397 if (Pattern == Instance) return true;
3398 Instance = Instance->getInstantiatedFromMemberEnum();
3399 } while (Instance);
3400
3401 return false;
3402}
3403
John McCallb96ec562009-12-04 22:46:56 +00003404static bool isInstantiationOf(UsingShadowDecl *Pattern,
3405 UsingShadowDecl *Instance,
3406 ASTContext &C) {
3407 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3408}
3409
3410static bool isInstantiationOf(UsingDecl *Pattern,
3411 UsingDecl *Instance,
3412 ASTContext &C) {
3413 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3414}
3415
John McCalle61f2ba2009-11-18 02:36:19 +00003416static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3417 UsingDecl *Instance,
3418 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00003419 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00003420}
3421
3422static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00003423 UsingDecl *Instance,
3424 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00003425 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00003426}
3427
John McCall59660882009-08-29 08:11:13 +00003428static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3429 VarDecl *Instance) {
3430 assert(Instance->isStaticDataMember());
3431
3432 Pattern = Pattern->getCanonicalDecl();
3433
3434 do {
3435 Instance = Instance->getCanonicalDecl();
3436 if (Pattern == Instance) return true;
3437 Instance = Instance->getInstantiatedFromStaticDataMember();
3438 } while (Instance);
3439
3440 return false;
3441}
3442
John McCallb96ec562009-12-04 22:46:56 +00003443// Other is the prospective instantiation
3444// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00003445static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00003446 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00003447 if (UnresolvedUsingTypenameDecl *UUD
3448 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3449 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3450 return isInstantiationOf(UUD, UD, Ctx);
3451 }
3452 }
3453
3454 if (UnresolvedUsingValueDecl *UUD
3455 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00003456 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3457 return isInstantiationOf(UUD, UD, Ctx);
3458 }
3459 }
Douglas Gregor51783312009-05-27 05:35:12 +00003460
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00003461 return false;
3462 }
Mike Stump11289f42009-09-09 15:08:12 +00003463
John McCall59660882009-08-29 08:11:13 +00003464 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3465 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00003466
John McCall59660882009-08-29 08:11:13 +00003467 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3468 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00003469
John McCall59660882009-08-29 08:11:13 +00003470 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3471 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00003472
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003473 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00003474 if (Var->isStaticDataMember())
3475 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3476
3477 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3478 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00003479
Douglas Gregor14d1bf42009-09-28 06:34:35 +00003480 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3481 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3482
Douglas Gregor21610382009-10-29 00:04:11 +00003483 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3484 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3485 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3486 PartialSpec);
3487
Anders Carlsson5da84842009-09-01 04:26:58 +00003488 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3489 if (!Field->getDeclName()) {
3490 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00003491 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00003492 cast<FieldDecl>(D);
3493 }
3494 }
Mike Stump11289f42009-09-09 15:08:12 +00003495
John McCallb96ec562009-12-04 22:46:56 +00003496 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3497 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3498
3499 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3500 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3501
Douglas Gregor51783312009-05-27 05:35:12 +00003502 return D->getDeclName() && isa<NamedDecl>(Other) &&
3503 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3504}
3505
3506template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00003507static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00003508 NamedDecl *D,
3509 ForwardIterator first,
3510 ForwardIterator last) {
3511 for (; first != last; ++first)
3512 if (isInstantiationOf(Ctx, D, *first))
3513 return cast<NamedDecl>(*first);
3514
3515 return 0;
3516}
3517
John McCallaa74a0c2009-08-28 07:59:38 +00003518/// \brief Finds the instantiation of the given declaration context
3519/// within the current instantiation.
3520///
3521/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00003522DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00003523 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00003524 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00003525 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00003526 return cast_or_null<DeclContext>(ID);
3527 } else return DC;
3528}
3529
Douglas Gregorcd3a0972009-05-27 17:54:46 +00003530/// \brief Find the instantiation of the given declaration within the
3531/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00003532///
3533/// This routine is intended to be used when \p D is a declaration
3534/// referenced from within a template, that needs to mapped into the
3535/// corresponding declaration within an instantiation. For example,
3536/// given:
3537///
3538/// \code
3539/// template<typename T>
3540/// struct X {
3541/// enum Kind {
3542/// KnownValue = sizeof(T)
3543/// };
3544///
3545/// bool getKind() const { return KnownValue; }
3546/// };
3547///
3548/// template struct X<int>;
3549/// \endcode
3550///
Serge Pavloved5fe902013-07-10 04:59:14 +00003551/// In the instantiation of <tt>X<int>::getKind()</tt>, we need to map the
3552/// \p EnumConstantDecl for \p KnownValue (which refers to
3553/// <tt>X<T>::<Kind>::KnownValue</tt>) to its instantiation
3554/// (<tt>X<int>::<Kind>::KnownValue</tt>). \p FindInstantiatedDecl performs
3555/// this mapping from within the instantiation of <tt>X<int></tt>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00003556NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00003557 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00003558 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor954de172009-10-31 17:21:17 +00003559 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00003560 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregora86bc002012-02-16 21:36:18 +00003561 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3562 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00003563 // D is a local of some kind. Look into the map of local
3564 // declarations to their instantiations.
Chris Lattner50c3c132011-02-17 19:47:42 +00003565 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3566 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3567 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003568
Chris Lattnercab02a62011-02-17 20:34:02 +00003569 if (Found) {
3570 if (Decl *FD = Found->dyn_cast<Decl *>())
3571 return cast<NamedDecl>(FD);
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003572
Richard Smithb15fe3a2012-09-12 00:56:43 +00003573 int PackIdx = ArgumentPackSubstitutionIndex;
3574 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattnercab02a62011-02-17 20:34:02 +00003575 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3576 }
3577
Serge Pavlov7cd8f602013-07-15 06:14:07 +00003578 // If we're performing a partial substitution during template argument
3579 // deduction, we may not have values for template parameters yet. They
3580 // just map to themselves.
3581 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
3582 isa<TemplateTemplateParmDecl>(D))
3583 return D;
3584
Chris Lattnercab02a62011-02-17 20:34:02 +00003585 // If we didn't find the decl, then we must have a label decl that hasn't
3586 // been found yet. Lazily instantiate it and return it now.
3587 assert(isa<LabelDecl>(D));
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003588
Chris Lattnercab02a62011-02-17 20:34:02 +00003589 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3590 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003591
Chris Lattnercab02a62011-02-17 20:34:02 +00003592 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3593 return cast<LabelDecl>(Inst);
Douglas Gregorf98d9b62009-05-27 17:07:49 +00003594 }
Douglas Gregor51783312009-05-27 05:35:12 +00003595
Douglas Gregor64621e62009-09-16 18:34:49 +00003596 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3597 if (!Record->isDependentContext())
3598 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003599
Douglas Gregor4109afa2011-11-07 17:43:18 +00003600 // Determine whether this record is the "templated" declaration describing
3601 // a class template or class template partial specialization.
Douglas Gregor64621e62009-09-16 18:34:49 +00003602 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor4109afa2011-11-07 17:43:18 +00003603 if (ClassTemplate)
3604 ClassTemplate = ClassTemplate->getCanonicalDecl();
3605 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3606 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3607 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3608
3609 // Walk the current context to find either the record or an instantiation of
3610 // it.
3611 DeclContext *DC = CurContext;
3612 while (!DC->isFileContext()) {
3613 // If we're performing substitution while we're inside the template
3614 // definition, we'll find our own context. We're done.
3615 if (DC->Equals(Record))
3616 return Record;
3617
3618 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3619 // Check whether we're in the process of instantiating a class template
3620 // specialization of the template we're mapping.
3621 if (ClassTemplateSpecializationDecl *InstSpec
3622 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3623 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3624 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3625 return InstRecord;
3626 }
3627
3628 // Check whether we're in the process of instantiating a member class.
3629 if (isInstantiationOf(Record, InstRecord))
3630 return InstRecord;
Douglas Gregor64621e62009-09-16 18:34:49 +00003631 }
Douglas Gregor4109afa2011-11-07 17:43:18 +00003632
3633
3634 // Move to the outer template scope.
3635 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3636 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3637 DC = FD->getLexicalDeclContext();
3638 continue;
3639 }
John McCall59660882009-08-29 08:11:13 +00003640 }
Douglas Gregor4109afa2011-11-07 17:43:18 +00003641
3642 DC = DC->getParent();
John McCall59660882009-08-29 08:11:13 +00003643 }
Douglas Gregord225fa02010-02-05 22:40:03 +00003644
Douglas Gregor64621e62009-09-16 18:34:49 +00003645 // Fall through to deal with other dependent record types (e.g.,
3646 // anonymous unions in class templates).
3647 }
John McCall59660882009-08-29 08:11:13 +00003648
Douglas Gregor64621e62009-09-16 18:34:49 +00003649 if (!ParentDC->isDependentContext())
3650 return D;
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003651
Douglas Gregora04f2ca2010-03-01 15:56:25 +00003652 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003653 if (!ParentDC)
Douglas Gregor2ffd9652009-09-01 17:53:10 +00003654 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00003655
Douglas Gregor51783312009-05-27 05:35:12 +00003656 if (ParentDC != D->getDeclContext()) {
3657 // We performed some kind of instantiation in the parent context,
3658 // so now we need to look into the instantiated parent context to
3659 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00003660
John McCalle78aac42010-03-10 03:28:59 +00003661 // If our context used to be dependent, we may need to instantiate
3662 // it before performing lookup into that context.
Douglas Gregor528ad932011-03-06 20:12:45 +00003663 bool IsBeingInstantiated = false;
John McCalle78aac42010-03-10 03:28:59 +00003664 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00003665 if (!Spec->isDependentContext()) {
3666 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00003667 const RecordType *Tag = T->getAs<RecordType>();
3668 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregor528ad932011-03-06 20:12:45 +00003669 if (Tag->isBeingDefined())
3670 IsBeingInstantiated = true;
John McCalle78aac42010-03-10 03:28:59 +00003671 if (!Tag->isBeingDefined() &&
3672 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3673 return 0;
Douglas Gregor25edf432010-11-05 23:22:45 +00003674
3675 ParentDC = Tag->getDecl();
Douglas Gregora04f2ca2010-03-01 15:56:25 +00003676 }
3677 }
3678
Douglas Gregor51783312009-05-27 05:35:12 +00003679 NamedDecl *Result = 0;
3680 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003681 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
David Blaikieff7d47a2012-12-19 00:45:41 +00003682 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
Douglas Gregor51783312009-05-27 05:35:12 +00003683 } else {
3684 // Since we don't have a name for the entity we're looking for,
3685 // our only option is to walk through all of the declarations to
3686 // find that name. This will occur in a few cases:
3687 //
3688 // - anonymous struct/union within a template
3689 // - unnamed class/struct/union/enum within a template
3690 //
3691 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00003692 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003693 ParentDC->decls_begin(),
3694 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00003695 }
Mike Stump11289f42009-09-09 15:08:12 +00003696
Douglas Gregor528ad932011-03-06 20:12:45 +00003697 if (!Result) {
3698 if (isa<UsingShadowDecl>(D)) {
3699 // UsingShadowDecls can instantiate to nothing because of using hiding.
3700 } else if (Diags.hasErrorOccurred()) {
3701 // We've already complained about something, so most likely this
3702 // declaration failed to instantiate. There's no point in complaining
3703 // further, since this is normal in invalid code.
3704 } else if (IsBeingInstantiated) {
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003705 // The class in which this member exists is currently being
Douglas Gregor528ad932011-03-06 20:12:45 +00003706 // instantiated, and we haven't gotten around to instantiating this
3707 // member yet. This can happen when the code uses forward declarations
3708 // of member classes, and introduces ordering dependencies via
3709 // template instantiation.
3710 Diag(Loc, diag::err_member_not_yet_instantiated)
3711 << D->getDeclName()
3712 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3713 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith169f2192012-03-26 20:28:16 +00003714 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3715 // This enumeration constant was found when the template was defined,
3716 // but can't be found in the instantiation. This can happen if an
3717 // unscoped enumeration member is explicitly specialized.
3718 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3719 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3720 TemplateArgs));
3721 assert(Spec->getTemplateSpecializationKind() ==
3722 TSK_ExplicitSpecialization);
3723 Diag(Loc, diag::err_enumerator_does_not_exist)
3724 << D->getDeclName()
3725 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3726 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3727 << Context.getTypeDeclType(Spec);
Douglas Gregor528ad932011-03-06 20:12:45 +00003728 } else {
3729 // We should have found something, but didn't.
3730 llvm_unreachable("Unable to find instantiation of declaration!");
3731 }
3732 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003733
Douglas Gregor51783312009-05-27 05:35:12 +00003734 D = Result;
3735 }
3736
Douglas Gregor51783312009-05-27 05:35:12 +00003737 return D;
3738}
Douglas Gregor77b50e12009-06-22 23:06:13 +00003739
Mike Stump11289f42009-09-09 15:08:12 +00003740/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00003741/// instantiations we have seen until this point.
Nick Lewycky67c4d0f2011-05-31 07:58:42 +00003742void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregore39f97c2011-07-28 19:49:54 +00003743 // Load pending instantiations from the external source.
3744 if (!LocalOnly && ExternalSource) {
Richard Smithd3b5c9082012-07-27 04:22:15 +00003745 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregore39f97c2011-07-28 19:49:54 +00003746 ExternalSource->ReadPendingInstantiations(Pending);
3747 PendingInstantiations.insert(PendingInstantiations.begin(),
3748 Pending.begin(), Pending.end());
3749 }
NAKAMURA Takumi82a35112011-10-08 11:31:46 +00003750
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003751 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth54080172010-08-25 08:44:16 +00003752 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003753 PendingImplicitInstantiation Inst;
3754
3755 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth54080172010-08-25 08:44:16 +00003756 Inst = PendingInstantiations.front();
3757 PendingInstantiations.pop_front();
Douglas Gregor7f792cf2010-01-16 22:29:39 +00003758 } else {
3759 Inst = PendingLocalImplicitInstantiations.front();
3760 PendingLocalImplicitInstantiations.pop_front();
3761 }
Mike Stump11289f42009-09-09 15:08:12 +00003762
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003763 // Instantiate function definitions
3764 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallfaf5fb42010-08-26 23:41:50 +00003765 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3766 "instantiating function definition");
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003767 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3768 TSK_ExplicitInstantiationDefinition;
3769 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3770 DefinitionRequired);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003771 continue;
3772 }
Mike Stump11289f42009-09-09 15:08:12 +00003773
Douglas Gregora6ef8f02009-07-24 20:34:43 +00003774 // Instantiate static data member definitions.
3775 VarDecl *Var = cast<VarDecl>(Inst.first);
3776 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlsson62215c42009-09-01 05:12:24 +00003777
Chandler Carruth6b4756a2010-02-13 10:17:50 +00003778 // Don't try to instantiate declarations if the most recent redeclaration
3779 // is invalid.
Douglas Gregorec9fd132012-01-14 16:38:05 +00003780 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth6b4756a2010-02-13 10:17:50 +00003781 continue;
3782
3783 // Check if the most recent declaration has changed the specialization kind
3784 // and removed the need for implicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00003785 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth6b4756a2010-02-13 10:17:50 +00003786 case TSK_Undeclared:
David Blaikie83d382b2011-09-23 05:06:16 +00003787 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth6b4756a2010-02-13 10:17:50 +00003788 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth6b4756a2010-02-13 10:17:50 +00003789 case TSK_ExplicitSpecialization:
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003790 continue; // No longer need to instantiate this type.
3791 case TSK_ExplicitInstantiationDefinition:
3792 // We only need an instantiation if the pending instantiation *is* the
3793 // explicit instantiation.
Douglas Gregorec9fd132012-01-14 16:38:05 +00003794 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth6b4756a2010-02-13 10:17:50 +00003795 case TSK_ImplicitInstantiation:
3796 break;
3797 }
3798
John McCallfaf5fb42010-08-26 23:41:50 +00003799 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3800 "instantiating static data member "
3801 "definition");
Mike Stump11289f42009-09-09 15:08:12 +00003802
Chandler Carruthcfe41db2010-08-25 08:27:02 +00003803 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3804 TSK_ExplicitInstantiationDefinition;
3805 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3806 DefinitionRequired);
Douglas Gregor77b50e12009-06-22 23:06:13 +00003807 }
3808}
John McCallc62bb642010-03-24 05:22:00 +00003809
3810void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3811 const MultiLevelTemplateArgumentList &TemplateArgs) {
3812 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3813 E = Pattern->ddiag_end(); I != E; ++I) {
3814 DependentDiagnostic *DD = *I;
3815
3816 switch (DD->getKind()) {
3817 case DependentDiagnostic::Access:
3818 HandleDependentAccessCheck(*DD, TemplateArgs);
3819 break;
3820 }
3821 }
3822}