blob: 2355544ca849b1e815d371b9f73f28dc4c189bd1 [file] [log] [blame]
Douglas Gregor8dbc2692009-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 McCall2d887082010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000013#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000014#include "clang/AST/ASTContext.h"
15#include "clang/AST/DeclTemplate.h"
16#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000017#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000018#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000019#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000020#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000021#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/PrettyDeclStackTrace.h"
24#include "clang/Sema/Template.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000025
26using namespace clang;
27
John McCallb6217662010-03-15 10:12:16 +000028bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
29 DeclaratorDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000030 if (!OldDecl->getQualifierLoc())
31 return false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000032
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000033 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000034 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000035 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000036
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000037 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000038 return true;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000039
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000040 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000041 return false;
42}
43
44bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
45 TagDecl *NewDecl) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000046 if (!OldDecl->getQualifierLoc())
47 return false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000048
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000049 NestedNameSpecifierLoc NewQualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000050 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000051 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000052
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000053 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000054 return true;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000055
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000056 NewDecl->setQualifierInfo(NewQualifierLoc);
John McCallb6217662010-03-15 10:12:16 +000057 return false;
58}
59
DeLesley Hutchins7b9ff0c2012-01-20 22:37:06 +000060// Include attribute instantiation code.
61#include "clang/Sema/AttrTemplateInstantiate.inc"
62
John McCall1d8d1cc2010-08-01 02:01:53 +000063void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
DeLesley Hutchins23323e02012-01-20 22:50:54 +000064 const Decl *Tmpl, Decl *New,
65 LateInstantiatedAttrVec *LateAttrs,
66 LocalInstantiationScope *OuterMostScope) {
Sean Huntcf807c42010-08-18 23:23:40 +000067 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
68 i != e; ++i) {
69 const Attr *TmplAttr = *i;
DeLesley Hutchins23323e02012-01-20 22:50:54 +000070
Chandler Carruth4ced79f2010-06-25 03:22:07 +000071 // FIXME: This should be generalized to more than just the AlignedAttr.
72 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +000073 if (Aligned->isAlignmentDependent()) {
Sean Huntcf807c42010-08-18 23:23:40 +000074 if (Aligned->isAlignmentExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +000075 // The alignment expression is a constant expression.
76 EnterExpressionEvaluationContext Unevaluated(*this,
77 Sema::ConstantEvaluated);
78
John McCall60d7b3a2010-08-24 06:29:42 +000079 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
Nick Lewycky7663f392010-11-20 01:29:55 +000080 TemplateArgs);
Sean Huntcf807c42010-08-18 23:23:40 +000081 if (!Result.isInvalid())
Aaron Ballmanfc685ac2012-06-19 22:09:27 +000082 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>(),
83 Aligned->getIsMSDeclSpec());
Richard Smithf6702a32011-12-20 02:08:33 +000084 } else {
Sean Huntcf807c42010-08-18 23:23:40 +000085 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
Nick Lewycky7663f392010-11-20 01:29:55 +000086 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000087 Aligned->getLocation(),
Nick Lewycky7663f392010-11-20 01:29:55 +000088 DeclarationName());
Sean Huntcf807c42010-08-18 23:23:40 +000089 if (Result)
Aaron Ballmanfc685ac2012-06-19 22:09:27 +000090 AddAlignedAttr(Aligned->getLocation(), New, Result,
91 Aligned->getIsMSDeclSpec());
Sean Huntcf807c42010-08-18 23:23:40 +000092 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +000093 continue;
94 }
95 }
96
DeLesley Hutchins23323e02012-01-20 22:50:54 +000097 if (TmplAttr->isLateParsed() && LateAttrs) {
98 // Late parsed attributes must be instantiated and attached after the
99 // enclosing class has been instantiated. See Sema::InstantiateClass.
100 LocalInstantiationScope *Saved = 0;
101 if (CurrentInstantiationScope)
102 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
103 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
104 } else {
Benjamin Kramer5bbc3852012-02-06 11:13:08 +0000105 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
106 *this, TemplateArgs);
Rafael Espindola31c195a2012-05-15 14:09:55 +0000107 if (NewAttr)
108 New->addAttr(NewAttr);
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000109 }
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000110 }
111}
112
Douglas Gregor4f722be2009-03-25 15:45:12 +0000113Decl *
114TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000115 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000116}
117
118Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000119TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
120 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
121 D->getIdentifier());
122 Owner->addDecl(Inst);
123 return Inst;
124}
125
126Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000127TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000128 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000129}
130
John McCall3dbd3d52010-02-16 06:53:13 +0000131Decl *
132TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
133 NamespaceAliasDecl *Inst
134 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
135 D->getNamespaceLoc(),
136 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000137 D->getIdentifier(),
138 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000139 D->getTargetNameLoc(),
140 D->getNamespace());
141 Owner->addDecl(Inst);
142 return Inst;
143}
144
Richard Smith3e4c6c42011-05-05 21:57:07 +0000145Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
146 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000147 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000148 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000149 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000150 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000151 DI = SemaRef.SubstType(DI, TemplateArgs,
152 D->getLocation(), D->getDeclName());
153 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000154 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000155 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000156 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000157 } else {
158 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000159 }
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Richard Smithb5b37d12012-10-23 00:32:41 +0000161 // HACK: g++ has a bug where it gets the value kind of ?: wrong.
162 // libstdc++ relies upon this bug in its implementation of common_type.
163 // If we happen to be processing that implementation, fake up the g++ ?:
164 // semantics. See LWG issue 2141 for more information on the bug.
165 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
166 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
167 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
168 DT->isReferenceType() &&
169 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
170 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
171 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
172 SemaRef.getSourceManager().isInSystemHeader(D->getLocStart()))
173 // Fold it to the (non-reference) type which g++ would have produced.
174 DI = SemaRef.Context.getTrivialTypeSourceInfo(
175 DI->getType().getNonReferenceType());
176
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000177 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000178 TypedefNameDecl *Typedef;
179 if (IsTypeAlias)
180 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
181 D->getLocation(), D->getIdentifier(), DI);
182 else
183 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
184 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000185 if (Invalid)
186 Typedef->setInvalidDecl();
187
John McCallcde5a402011-02-01 08:20:08 +0000188 // If the old typedef was the name for linkage purposes of an anonymous
189 // tag decl, re-establish that relationship for the new typedef.
190 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
191 TagDecl *oldTag = oldTagType->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000192 if (oldTag->getTypedefNameForAnonDecl() == D) {
John McCallcde5a402011-02-01 08:20:08 +0000193 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000194 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
195 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000196 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000197 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000198
Douglas Gregoref96ee02012-01-14 16:38:05 +0000199 if (TypedefNameDecl *Prev = D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000200 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
201 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000202 if (!InstPrev)
203 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000204
Rafael Espindola5df37bd2011-12-26 22:42:47 +0000205 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
206
207 // If the typedef types are not identical, reject them.
208 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
209
210 Typedef->setPreviousDeclaration(InstPrevTypedef);
John McCall5126fd02009-12-30 00:31:22 +0000211 }
212
John McCall1d8d1cc2010-08-01 02:01:53 +0000213 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000214
John McCall46460a62010-01-20 21:53:11 +0000215 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000217 return Typedef;
218}
219
Richard Smith162e1c12011-04-15 14:24:37 +0000220Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000221 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
222 Owner->addDecl(Typedef);
223 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000224}
225
226Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000227 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
228 Owner->addDecl(Typedef);
229 return Typedef;
230}
231
232Decl *
233TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
234 // Create a local instantiation scope for this type alias template, which
235 // will contain the instantiations of the template parameters.
236 LocalInstantiationScope Scope(SemaRef);
237
238 TemplateParameterList *TempParams = D->getTemplateParameters();
239 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
240 if (!InstParams)
241 return 0;
242
243 TypeAliasDecl *Pattern = D->getTemplatedDecl();
244
245 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
Douglas Gregoref96ee02012-01-14 16:38:05 +0000246 if (Pattern->getPreviousDecl()) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000247 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
248 if (Found.first != Found.second) {
249 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
250 }
251 }
252
253 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
254 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
255 if (!AliasInst)
256 return 0;
257
258 TypeAliasTemplateDecl *Inst
259 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
260 D->getDeclName(), InstParams, AliasInst);
261 if (PrevAliasTemplate)
262 Inst->setPreviousDeclaration(PrevAliasTemplate);
263
264 Inst->setAccess(D->getAccess());
265
266 if (!PrevAliasTemplate)
267 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000268
Richard Smith3e4c6c42011-05-05 21:57:07 +0000269 Owner->addDecl(Inst);
270
271 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000272}
273
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000274Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000275 // If this is the variable for an anonymous struct or union,
276 // instantiate the anonymous struct/union type first.
277 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
278 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
279 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
280 return 0;
281
John McCallce3ff2b2009-08-25 22:02:44 +0000282 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000283 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000284 TemplateArgs,
285 D->getTypeSpecStartLoc(),
286 D->getDeclName());
287 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000288 return 0;
289
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000290 if (DI->getType()->isFunctionType()) {
291 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
292 << D->isStaticDataMember() << DI->getType();
293 return 0;
294 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000295
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000296 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000297 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000298 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000299 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000300 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000301 D->getStorageClass(),
302 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000303 Var->setThreadSpecified(D->isThreadSpecified());
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000304 Var->setInitStyle(D->getInitStyle());
Richard Smithad762fc2011-04-14 22:09:26 +0000305 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Richard Smith796c1a12012-01-19 22:46:17 +0000306 Var->setConstexpr(D->isConstexpr());
Mike Stump1eb44332009-09-09 15:08:12 +0000307
John McCallb6217662010-03-15 10:12:16 +0000308 // Substitute the nested name specifier, if any.
309 if (SubstQualifier(D, Var))
310 return 0;
311
Mike Stump1eb44332009-09-09 15:08:12 +0000312 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000313 // out-of-line, the instantiation will have the same lexical
314 // context (which will be a namespace scope) as the template.
315 if (D->isOutOfLine())
316 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000317
John McCall46460a62010-01-20 21:53:11 +0000318 Var->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000319
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000320 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000321 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000322 Var->setReferenced(D->isReferenced());
323 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000324
Mike Stump390b4cc2009-05-16 07:39:55 +0000325 // FIXME: In theory, we could have a previous declaration for variables that
326 // are not static data members.
John McCall68263142009-11-18 22:49:29 +0000327 // FIXME: having to fake up a LookupResult is dumb.
328 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000329 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000330 if (D->isStaticDataMember())
331 SemaRef.LookupQualifiedName(Previous, Owner, false);
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000332
333 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000334 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000335 SemaRef.inferObjCARCLifetime(Var))
336 Var->setInvalidDecl();
337
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +0000338 SemaRef.CheckVariableDeclaration(Var, Previous);
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregor7caa6822009-07-24 20:34:43 +0000340 if (D->isOutOfLine()) {
Richard Smith3e9ea0b2011-12-21 00:25:33 +0000341 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000342 Owner->makeDeclVisibleInContext(Var);
343 } else {
344 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000345 if (Owner->isFunctionOrMethod())
346 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000347 }
DeLesley Hutchinsdd5756c2012-02-16 17:30:51 +0000348 SemaRef.InstantiateAttrs(TemplateArgs, D, Var, LateAttrs, StartingScope);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000349
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000350 // Link instantiations of static data members back to the template from
351 // which they were instantiated.
352 if (Var->isStaticDataMember())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000353 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000354 TSK_ImplicitInstantiation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000355
Douglas Gregor60c93c92010-02-09 07:26:29 +0000356 if (Var->getAnyInitializer()) {
357 // We already have an initializer in the class.
358 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000359 if (Var->isStaticDataMember() && !D->isOutOfLine())
Richard Smithadb1d4c2012-07-22 23:45:10 +0000360 SemaRef.PushExpressionEvaluationContext(Sema::ConstantEvaluated, D);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000361 else
Richard Smithadb1d4c2012-07-22 23:45:10 +0000362 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated, D);
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000363
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000364 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000365 ExprResult Init = SemaRef.SubstInitializer(D->getInit(), TemplateArgs,
366 D->getInitStyle() == VarDecl::CallInit);
367 if (!Init.isInvalid()) {
Richard Smith34b41d92011-02-20 03:19:35 +0000368 bool TypeMayContainAuto = true;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +0000369 if (Init.get()) {
370 bool DirectInit = D->isDirectInit();
371 SemaRef.AddInitializerToDecl(Var, Init.take(), DirectInit,
372 TypeMayContainAuto);
373 } else
Eli Friedman6aeaa602012-01-05 22:34:08 +0000374 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000375 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000376 // FIXME: Not too happy about invalidating the declaration
377 // because of a bogus initializer.
378 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000379 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000380
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000381 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000382 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
383 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000384 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000385
Richard Smithe3499ca2011-06-21 23:42:09 +0000386 // Diagnose unused local variables with dependent types, where the diagnostic
387 // will have been deferred.
388 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
389 D->getType()->isDependentType())
Douglas Gregor5764f612010-05-08 23:05:03 +0000390 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000391
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000392 return Var;
393}
394
Abramo Bagnara6206d532010-06-05 05:09:32 +0000395Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
396 AccessSpecDecl* AD
397 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
398 D->getAccessSpecifierLoc(), D->getColonLoc());
399 Owner->addHiddenDecl(AD);
400 return AD;
401}
402
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000403Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
404 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000405 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000406 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000407 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000408 DI = SemaRef.SubstType(DI, TemplateArgs,
409 D->getLocation(), D->getDeclName());
410 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000411 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000412 Invalid = true;
413 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000414 // C++ [temp.arg.type]p3:
415 // If a declaration acquires a function type through a type
416 // dependent on a template-parameter and this causes a
417 // declaration that does not use the syntactic form of a
418 // function declarator to have function type, the program is
419 // ill-formed.
420 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000421 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000422 Invalid = true;
423 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000424 } else {
425 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000426 }
427
428 Expr *BitWidth = D->getBitWidth();
429 if (Invalid)
430 BitWidth = 0;
431 else if (BitWidth) {
Richard Smithf6702a32011-12-20 02:08:33 +0000432 // The bit-width expression is a constant expression.
433 EnterExpressionEvaluationContext Unevaluated(SemaRef,
434 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000435
John McCall60d7b3a2010-08-24 06:29:42 +0000436 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000437 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000438 if (InstantiatedBitWidth.isInvalid()) {
439 Invalid = true;
440 BitWidth = 0;
441 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000442 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000443 }
444
John McCall07fb6be2009-10-22 23:33:21 +0000445 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
446 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000447 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000448 D->getLocation(),
449 D->isMutable(),
450 BitWidth,
Richard Smithca523302012-06-10 03:12:00 +0000451 D->getInClassInitStyle(),
Richard Smith703b6012012-05-23 04:22:22 +0000452 D->getInnerLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000453 D->getAccess(),
454 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000455 if (!Field) {
456 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000457 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000458 }
Mike Stump1eb44332009-09-09 15:08:12 +0000459
DeLesley Hutchins23323e02012-01-20 22:50:54 +0000460 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000461
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000462 if (Invalid)
463 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000465 if (!Field->getDeclName()) {
466 // Keep track of where this decl came from.
467 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000468 }
Douglas Gregor9901c572010-05-21 00:31:19 +0000469 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
470 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000471 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000472 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000473 }
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000475 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000476 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000477 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000478
479 return Field;
480}
481
Francois Pichet87c2e122010-11-21 06:08:52 +0000482Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
483 NamedDecl **NamedChain =
484 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
485
486 int i = 0;
487 for (IndirectFieldDecl::chain_iterator PI =
488 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000489 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000490 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000491 TemplateArgs);
492 if (!Next)
493 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000494
Douglas Gregorb7107222011-03-04 19:46:35 +0000495 NamedChain[i++] = Next;
496 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000497
Francois Pichet40e17752010-12-09 10:07:54 +0000498 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000499 IndirectFieldDecl* IndirectField
500 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000501 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000502 NamedChain, D->getChainingSize());
503
504
505 IndirectField->setImplicit(D->isImplicit());
506 IndirectField->setAccess(D->getAccess());
507 Owner->addDecl(IndirectField);
508 return IndirectField;
509}
510
John McCall02cace72009-08-28 07:59:38 +0000511Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000512 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000513 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000514 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000515 TypeSourceInfo *InstTy;
516 // If this is an unsupported friend, don't bother substituting template
517 // arguments into it. The actual type referred to won't be used by any
518 // parts of Clang, and may not be valid for instantiating. Just use the
519 // same info for the instantiated friend.
520 if (D->isUnsupportedFriend()) {
521 InstTy = Ty;
522 } else {
523 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
524 D->getLocation(), DeclarationName());
525 }
526 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000527 return 0;
John McCall02cace72009-08-28 07:59:38 +0000528
Richard Smithd6f80da2012-09-20 01:31:00 +0000529 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocStart(),
Abramo Bagnara0216df82011-10-29 20:52:52 +0000530 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000531 if (!FD)
532 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000533
Douglas Gregor06245bf2010-04-07 17:57:12 +0000534 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000535 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000536 Owner->addDecl(FD);
537 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000538 }
539
Douglas Gregor06245bf2010-04-07 17:57:12 +0000540 NamedDecl *ND = D->getFriendDecl();
541 assert(ND && "friend decl must be a decl or a type!");
542
John McCallaf2094e2010-04-08 09:05:18 +0000543 // All of the Visit implementations for the various potential friend
544 // declarations have to be carefully written to work for friend
545 // objects, with the most important detail being that the target
546 // decl should almost certainly not be placed in Owner.
547 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000548 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000549
John McCall02cace72009-08-28 07:59:38 +0000550 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000551 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000552 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000553 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000554 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000555 Owner->addDecl(FD);
556 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000557}
558
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000559Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
560 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Richard Smithf6702a32011-12-20 02:08:33 +0000562 // The expression in a static assertion is a constant expression.
563 EnterExpressionEvaluationContext Unevaluated(SemaRef,
564 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000565
John McCall60d7b3a2010-08-24 06:29:42 +0000566 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000567 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000568 if (InstantiatedAssertExpr.isInvalid())
569 return 0;
570
Richard Smithe3f470a2012-07-11 22:37:56 +0000571 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000572 InstantiatedAssertExpr.get(),
Richard Smithe3f470a2012-07-11 22:37:56 +0000573 D->getMessage(),
574 D->getRParenLoc(),
575 D->isFailed());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000576}
577
578Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Richard Smith38f0df32012-03-26 04:58:10 +0000579 EnumDecl *PrevDecl = 0;
580 if (D->getPreviousDecl()) {
581 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
582 D->getPreviousDecl(),
583 TemplateArgs);
584 if (!Prev) return 0;
585 PrevDecl = cast<EnumDecl>(Prev);
586 }
587
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000588 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000589 D->getLocation(), D->getIdentifier(),
Richard Smith38f0df32012-03-26 04:58:10 +0000590 PrevDecl, D->isScoped(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000591 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000592 if (D->isFixed()) {
Richard Smithf1c66b42012-03-14 23:13:10 +0000593 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000594 // If we have type source information for the underlying type, it means it
595 // has been explicitly set by the user. Perform substitution on it before
596 // moving on.
597 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
Richard Smithf1c66b42012-03-14 23:13:10 +0000598 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
599 DeclarationName());
600 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000601 Enum->setIntegerType(SemaRef.Context.IntTy);
Richard Smithf1c66b42012-03-14 23:13:10 +0000602 else
603 Enum->setIntegerTypeSourceInfo(NewTI);
604 } else {
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000605 assert(!D->getIntegerType()->isDependentType()
606 && "Dependent type without type source info");
607 Enum->setIntegerType(D->getIntegerType());
608 }
609 }
610
John McCall5b629aa2010-10-22 23:36:17 +0000611 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
612
Richard Smithf1c66b42012-03-14 23:13:10 +0000613 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000614 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000615 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000616 Owner->addDecl(Enum);
Richard Smithf1c66b42012-03-14 23:13:10 +0000617
Richard Smith4ca93d92012-03-26 04:08:46 +0000618 EnumDecl *Def = D->getDefinition();
619 if (Def && Def != D) {
620 // If this is an out-of-line definition of an enum member template, check
621 // that the underlying types match in the instantiation of both
622 // declarations.
623 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
624 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
625 QualType DefnUnderlying =
626 SemaRef.SubstType(TI->getType(), TemplateArgs,
627 UnderlyingLoc, DeclarationName());
628 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
629 DefnUnderlying, Enum);
630 }
631 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000632
Douglas Gregor96084f12010-03-01 19:00:07 +0000633 if (D->getDeclContext()->isFunctionOrMethod())
634 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000635
Richard Smithf1c66b42012-03-14 23:13:10 +0000636 // C++11 [temp.inst]p1: The implicit instantiation of a class template
637 // specialization causes the implicit instantiation of the declarations, but
638 // not the definitions of scoped member enumerations.
639 // FIXME: There appears to be no wording for what happens for an enum defined
Richard Smith38f0df32012-03-26 04:58:10 +0000640 // within a block scope, but we treat that much like a member template. Only
641 // instantiate the definition when visiting the definition in that case, since
642 // we will visit all redeclarations.
643 if (!Enum->isScoped() && Def &&
644 (!D->getDeclContext()->isFunctionOrMethod() || D->isCompleteDefinition()))
Richard Smith4ca93d92012-03-26 04:08:46 +0000645 InstantiateEnumDefinition(Enum, Def);
Richard Smithf1c66b42012-03-14 23:13:10 +0000646
647 return Enum;
648}
649
650void TemplateDeclInstantiator::InstantiateEnumDefinition(
651 EnumDecl *Enum, EnumDecl *Pattern) {
652 Enum->startDefinition();
653
Richard Smith1af83c42012-03-23 03:33:32 +0000654 // Update the location to refer to the definition.
655 Enum->setLocation(Pattern->getLocation());
656
Chris Lattner5f9e2722011-07-23 10:55:15 +0000657 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000658
659 EnumConstantDecl *LastEnumConst = 0;
Richard Smithf1c66b42012-03-14 23:13:10 +0000660 for (EnumDecl::enumerator_iterator EC = Pattern->enumerator_begin(),
661 ECEnd = Pattern->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000662 EC != ECEnd; ++EC) {
663 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000664 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000665 if (Expr *UninstValue = EC->getInitExpr()) {
Richard Smithf6702a32011-12-20 02:08:33 +0000666 // The enumerator's value expression is a constant expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000667 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Richard Smithf6702a32011-12-20 02:08:33 +0000668 Sema::ConstantEvaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000669
John McCallce3ff2b2009-08-25 22:02:44 +0000670 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000671 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000672
673 // Drop the initial value and continue.
674 bool isInvalid = false;
675 if (Value.isInvalid()) {
676 Value = SemaRef.Owned((Expr *)0);
677 isInvalid = true;
678 }
679
Mike Stump1eb44332009-09-09 15:08:12 +0000680 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000681 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
682 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000683 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000684
685 if (isInvalid) {
686 if (EnumConst)
687 EnumConst->setInvalidDecl();
688 Enum->setInvalidDecl();
689 }
690
691 if (EnumConst) {
David Blaikie581deb32012-06-06 20:45:41 +0000692 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
John McCall5b629aa2010-10-22 23:36:17 +0000693
John McCall3b85ecf2010-01-23 22:37:59 +0000694 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000695 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000696 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000697 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000698
Richard Smithf1c66b42012-03-14 23:13:10 +0000699 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
700 !Enum->isScoped()) {
Douglas Gregor96084f12010-03-01 19:00:07 +0000701 // If the enumeration is within a function or method, record the enum
702 // constant as a local.
David Blaikie581deb32012-06-06 20:45:41 +0000703 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
Douglas Gregor96084f12010-03-01 19:00:07 +0000704 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000705 }
706 }
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Richard Smithf1c66b42012-03-14 23:13:10 +0000708 // FIXME: Fixup LBraceLoc
709 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(),
710 Enum->getRBraceLoc(), Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000711 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000712 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000713}
714
Douglas Gregor6477b692009-03-25 15:04:13 +0000715Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000716 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000717}
718
John McCalle29ba202009-08-20 01:44:21 +0000719Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000720 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
721
Douglas Gregor550d9b22009-10-31 17:21:17 +0000722 // Create a local instantiation scope for this class template, which
723 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000724 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000725 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000726 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000727 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000728 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000729
730 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000731
732 // Instantiate the qualifier. We have to do this first in case
733 // we're a friend declaration, because if we are then we need to put
734 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000735 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
736 if (QualifierLoc) {
737 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
738 TemplateArgs);
739 if (!QualifierLoc)
740 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000741 }
742
743 CXXRecordDecl *PrevDecl = 0;
744 ClassTemplateDecl *PrevClassTemplate = 0;
745
Douglas Gregoref96ee02012-01-14 16:38:05 +0000746 if (!isFriend && Pattern->getPreviousDecl()) {
Nick Lewycky37574f52010-11-08 23:29:42 +0000747 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
748 if (Found.first != Found.second) {
749 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
750 if (PrevClassTemplate)
751 PrevDecl = PrevClassTemplate->getTemplatedDecl();
752 }
753 }
754
John McCall93ba8572010-03-25 06:39:04 +0000755 // If this isn't a friend, then it's a member template, in which
756 // case we just want to build the instantiation in the
757 // specialization. If it is a friend, we want to build it in
758 // the appropriate context.
759 DeclContext *DC = Owner;
760 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000761 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000762 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000763 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000764 DC = SemaRef.computeDeclContext(SS);
765 if (!DC) return 0;
766 } else {
767 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
768 Pattern->getDeclContext(),
769 TemplateArgs);
770 }
771
772 // Look for a previous declaration of the template in the owning
773 // context.
774 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
775 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
776 SemaRef.LookupQualifiedName(R, DC);
777
778 if (R.isSingleResult()) {
779 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
780 if (PrevClassTemplate)
781 PrevDecl = PrevClassTemplate->getTemplatedDecl();
782 }
783
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000784 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000785 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000786 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000787 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000788 return 0;
789 }
790
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000791 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000792 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000793 bool Complain = true;
794
795 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
796 // template for struct std::tr1::__detail::_Map_base, where the
797 // template parameters of the friend declaration don't match the
798 // template parameters of the original declaration. In this one
799 // case, we don't complain about the ill-formed friend
800 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000801 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000802 Pattern->getIdentifier()->isStr("_Map_base") &&
803 DC->isNamespace() &&
804 cast<NamespaceDecl>(DC)->getIdentifier() &&
805 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
806 DeclContext *DCParent = DC->getParent();
807 if (DCParent->isNamespace() &&
808 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
809 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
810 DeclContext *DCParent2 = DCParent->getParent();
811 if (DCParent2->isNamespace() &&
812 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
813 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
814 DCParent2->getParent()->isTranslationUnit())
815 Complain = false;
816 }
817 }
818
John McCall93ba8572010-03-25 06:39:04 +0000819 TemplateParameterList *PrevParams
820 = PrevClassTemplate->getTemplateParameters();
821
822 // Make sure the parameter lists match.
823 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000824 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000825 Sema::TPL_TemplateMatch)) {
826 if (Complain)
827 return 0;
828
829 AdoptedPreviousTemplateParams = true;
830 InstParams = PrevParams;
831 }
John McCall93ba8572010-03-25 06:39:04 +0000832
833 // Do some additional validation, then merge default arguments
834 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000835 if (!AdoptedPreviousTemplateParams &&
836 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000837 Sema::TPC_ClassTemplate))
838 return 0;
839 }
840 }
841
John McCalle29ba202009-08-20 01:44:21 +0000842 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000843 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000844 Pattern->getLocStart(), Pattern->getLocation(),
845 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000846 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000847
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000848 if (QualifierLoc)
849 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000850
John McCalle29ba202009-08-20 01:44:21 +0000851 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000852 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
853 D->getIdentifier(), InstParams, RecordInst,
854 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000855 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000856
John McCall93ba8572010-03-25 06:39:04 +0000857 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000858 if (PrevClassTemplate)
859 Inst->setAccess(PrevClassTemplate->getAccess());
860 else
861 Inst->setAccess(D->getAccess());
862
John McCall93ba8572010-03-25 06:39:04 +0000863 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
864 // TODO: do we want to track the instantiation progeny of this
865 // friend target decl?
866 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000867 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000868 if (!PrevClassTemplate)
869 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000870 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000871
Douglas Gregorf0510d42009-10-12 23:11:44 +0000872 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000873 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000874 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000875
Douglas Gregor259571e2009-10-30 22:42:42 +0000876 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000877 if (isFriend) {
Richard Smith1b7f9cb2012-03-13 03:12:56 +0000878 DC->makeDeclVisibleInContext(Inst);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000879 Inst->setLexicalDeclContext(Owner);
880 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000881 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000882 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000883
Abramo Bagnara4c515482011-11-26 13:33:46 +0000884 if (D->isOutOfLine()) {
885 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
886 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
887 }
888
John McCalle29ba202009-08-20 01:44:21 +0000889 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000890
891 if (!PrevClassTemplate) {
892 // Queue up any out-of-line partial specializations of this member
893 // class template; the client will force their instantiation once
894 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000895 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000896 D->getPartialSpecializations(PartialSpecs);
897 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
898 if (PartialSpecs[I]->isOutOfLine())
899 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
900 }
901
John McCalle29ba202009-08-20 01:44:21 +0000902 return Inst;
903}
904
Douglas Gregord60e1052009-08-27 16:57:43 +0000905Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000906TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
907 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000908 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000909
Douglas Gregored9c0f92009-10-29 00:04:11 +0000910 // Lookup the already-instantiated declaration in the instantiation
911 // of the class template and return that.
912 DeclContext::lookup_result Found
913 = Owner->lookup(ClassTemplate->getDeclName());
914 if (Found.first == Found.second)
915 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000916
Douglas Gregored9c0f92009-10-29 00:04:11 +0000917 ClassTemplateDecl *InstClassTemplate
918 = dyn_cast<ClassTemplateDecl>(*Found.first);
919 if (!InstClassTemplate)
920 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000921
Douglas Gregord65587f2010-11-10 19:44:59 +0000922 if (ClassTemplatePartialSpecializationDecl *Result
923 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
924 return Result;
925
926 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000927}
928
929Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000930TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000931 // Create a local instantiation scope for this function template, which
932 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000933 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +0000934 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000935 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000936
Douglas Gregord60e1052009-08-27 16:57:43 +0000937 TemplateParameterList *TempParams = D->getTemplateParameters();
938 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000939 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000940 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000941
Douglas Gregora735b202009-10-13 14:39:41 +0000942 FunctionDecl *Instantiated = 0;
943 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000944 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +0000945 InstParams));
946 else
947 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000948 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +0000949 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000950
Douglas Gregora735b202009-10-13 14:39:41 +0000951 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000952 return 0;
953
Mike Stump1eb44332009-09-09 15:08:12 +0000954 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000955 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000956 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000957 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000958 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000959 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +0000960 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000961
John McCallb1a56e72010-03-26 23:10:15 +0000962 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
963
John McCalle976ffe2009-12-14 23:19:40 +0000964 // Link the instantiation back to the pattern *unless* this is a
965 // non-definition friend declaration.
966 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000967 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000968 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000969
John McCallb1a56e72010-03-26 23:10:15 +0000970 // Make declarations visible in the appropriate context.
John McCall1f2e1a92012-08-10 03:15:35 +0000971 if (!isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +0000972 Owner->addDecl(InstTemplate);
John McCall1f2e1a92012-08-10 03:15:35 +0000973 } else if (InstTemplate->getDeclContext()->isRecord() &&
974 !D->getPreviousDecl()) {
975 SemaRef.CheckFriendAccess(InstTemplate);
976 }
John McCallb1a56e72010-03-26 23:10:15 +0000977
Douglas Gregord60e1052009-08-27 16:57:43 +0000978 return InstTemplate;
979}
980
Douglas Gregord475b8d2009-03-25 21:17:03 +0000981Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
982 CXXRecordDecl *PrevDecl = 0;
983 if (D->isInjectedClassName())
984 PrevDecl = cast<CXXRecordDecl>(Owner);
Douglas Gregoref96ee02012-01-14 16:38:05 +0000985 else if (D->getPreviousDecl()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000986 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
Douglas Gregoref96ee02012-01-14 16:38:05 +0000987 D->getPreviousDecl(),
John McCall6c1c1b82009-12-15 22:29:06 +0000988 TemplateArgs);
989 if (!Prev) return 0;
990 PrevDecl = cast<CXXRecordDecl>(Prev);
991 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000992
993 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000994 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000995 D->getLocStart(), D->getLocation(),
996 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000997
998 // Substitute the nested name specifier, if any.
999 if (SubstQualifier(D, Record))
1000 return 0;
1001
Douglas Gregord475b8d2009-03-25 21:17:03 +00001002 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +00001003 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1004 // the tag decls introduced by friend class declarations don't have an access
1005 // specifier. Remove once this area of the code gets sorted out.
1006 if (D->getAccess() != AS_none)
1007 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001008 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +00001009 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001010
John McCall02cace72009-08-28 07:59:38 +00001011 // If the original function was part of a friend declaration,
1012 // inherit its namespace state.
1013 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1014 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1015
Douglas Gregor9901c572010-05-21 00:31:19 +00001016 // Make sure that anonymous structs and unions are recorded.
1017 if (D->isAnonymousStructOrUnion()) {
1018 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001019 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001020 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1021 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001022
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001023 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001024 return Record;
1025}
1026
Douglas Gregor71074fd2012-09-13 21:56:43 +00001027/// \brief Adjust the given function type for an instantiation of the
1028/// given declaration, to cope with modifications to the function's type that
1029/// aren't reflected in the type-source information.
1030///
1031/// \param D The declaration we're instantiating.
1032/// \param TInfo The already-instantiated type.
1033static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
1034 FunctionDecl *D,
1035 TypeSourceInfo *TInfo) {
Douglas Gregorbed51fe2012-09-13 22:01:49 +00001036 const FunctionProtoType *OrigFunc
1037 = D->getType()->castAs<FunctionProtoType>();
1038 const FunctionProtoType *NewFunc
1039 = TInfo->getType()->castAs<FunctionProtoType>();
1040 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
1041 return TInfo->getType();
1042
1043 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
1044 NewEPI.ExtInfo = OrigFunc->getExtInfo();
1045 return Context.getFunctionType(NewFunc->getResultType(),
1046 NewFunc->arg_type_begin(),
1047 NewFunc->getNumArgs(),
1048 NewEPI);
Douglas Gregor71074fd2012-09-13 21:56:43 +00001049}
1050
John McCall02cace72009-08-28 07:59:38 +00001051/// Normal class members are of more specific types and therefore
1052/// don't make it here. This function serves two purposes:
1053/// 1) instantiating function templates
1054/// 2) substituting friend declarations
1055/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001056Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001057 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001058 // Check whether there is already a function template specialization for
1059 // this declaration.
1060 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
John McCallb0cb0222010-03-27 05:57:59 +00001061 if (FunctionTemplate && !TemplateParams) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001062 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001063 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001065 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001066 FunctionDecl *SpecFunc
1067 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1068 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Douglas Gregor127102b2009-06-29 20:59:39 +00001070 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001071 if (SpecFunc)
1072 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001073 }
Mike Stump1eb44332009-09-09 15:08:12 +00001074
John McCallb0cb0222010-03-27 05:57:59 +00001075 bool isFriend;
1076 if (FunctionTemplate)
1077 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1078 else
1079 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1080
Douglas Gregor79c22782010-01-16 20:21:20 +00001081 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001082 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001083 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001084 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001085 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001086
Chris Lattner5f9e2722011-07-23 10:55:15 +00001087 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001088 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001089 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001090 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001091 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
John McCallfd810b12009-08-14 02:03:10 +00001092
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001093 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1094 if (QualifierLoc) {
1095 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1096 TemplateArgs);
1097 if (!QualifierLoc)
1098 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001099 }
1100
John McCall68b6b872010-02-06 01:50:47 +00001101 // If we're instantiating a local function declaration, put the result
1102 // in the owner; otherwise we need to find the instantiated context.
1103 DeclContext *DC;
1104 if (D->getDeclContext()->isFunctionOrMethod())
1105 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001106 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001107 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001108 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001109 DC = SemaRef.computeDeclContext(SS);
1110 if (!DC) return 0;
1111 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001112 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001113 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001114 }
John McCall68b6b872010-02-06 01:50:47 +00001115
John McCall02cace72009-08-28 07:59:38 +00001116 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001117 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
Abramo Bagnara635311f2012-10-04 21:40:42 +00001118 D->getNameInfo(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001119 D->getStorageClass(), D->getStorageClassAsWritten(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001120 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001121 D->isConstexpr());
John McCallb6217662010-03-15 10:12:16 +00001122
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001123 if (QualifierLoc)
1124 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001125
John McCallb1a56e72010-03-26 23:10:15 +00001126 DeclContext *LexicalDC = Owner;
1127 if (!isFriend && D->isOutOfLine()) {
1128 assert(D->getDeclContext()->isFileContext());
1129 LexicalDC = D->getDeclContext();
1130 }
1131
1132 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001133
Douglas Gregore53060f2009-06-25 22:08:12 +00001134 // Attach the parameters
Douglas Gregor5cbe1012011-07-05 18:30:26 +00001135 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
Douglas Gregor1d441ee2011-06-22 18:16:25 +00001136 // Adopt the already-instantiated parameters into our own context.
1137 for (unsigned P = 0; P < Params.size(); ++P)
1138 if (Params[P])
1139 Params[P]->setOwningFunction(Function);
1140 } else {
1141 // Since we were instantiated via a typedef of a function type, create
1142 // new parameters.
1143 const FunctionProtoType *Proto
1144 = Function->getType()->getAs<FunctionProtoType>();
1145 assert(Proto && "No function prototype in template instantiation?");
1146 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1147 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1148 ParmVarDecl *Param
1149 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1150 *AI);
1151 Param->setScopeInfo(0, Params.size());
1152 Params.push_back(Param);
1153 }
1154 }
David Blaikie4278c652011-09-21 18:16:56 +00001155 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001156
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001157 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001158 if (TemplateParams) {
1159 // Our resulting instantiation is actually a function template, since we
1160 // are substituting only the outer template parameters. For example, given
1161 //
1162 // template<typename T>
1163 // struct X {
1164 // template<typename U> friend void f(T, U);
1165 // };
1166 //
1167 // X<int> x;
1168 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001169 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001170 // which means substituting int for T, but leaving "f" as a friend function
1171 // template.
1172 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001173 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001174 Function->getLocation(),
1175 Function->getDeclName(),
1176 TemplateParams, Function);
1177 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001178
1179 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001180
1181 if (isFriend && D->isThisDeclarationADefinition()) {
1182 // TODO: should we remember this connection regardless of whether
1183 // the friend declaration provided a body?
1184 FunctionTemplate->setInstantiatedFromMemberTemplate(
1185 D->getDescribedFunctionTemplate());
1186 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001187 } else if (FunctionTemplate) {
1188 // Record this function template specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001189 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001190 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001191 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001192 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001193 Innermost.first,
1194 Innermost.second),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001195 /*InsertPos=*/0);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001196 } else if (isFriend) {
1197 // Note, we need this connection even if the friend doesn't have a body.
1198 // Its body may exist but not have been attached yet due to deferred
1199 // parsing.
1200 // FIXME: It might be cleaner to set this when attaching the body to the
1201 // friend function declaration, however that would require finding all the
1202 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001203 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001204 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001205
Douglas Gregore53060f2009-06-25 22:08:12 +00001206 if (InitFunctionInstantiation(Function, D))
1207 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001208
John McCallaf2094e2010-04-08 09:05:18 +00001209 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001210
John McCall68263142009-11-18 22:49:29 +00001211 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1212 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1213
John McCallaf2094e2010-04-08 09:05:18 +00001214 if (DependentFunctionTemplateSpecializationInfo *Info
1215 = D->getDependentSpecializationInfo()) {
1216 assert(isFriend && "non-friend has dependent specialization info?");
1217
1218 // This needs to be set now for future sanity.
1219 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1220
1221 // Instantiate the explicit template arguments.
1222 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1223 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001224 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1225 ExplicitArgs, TemplateArgs))
1226 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001227
1228 // Map the candidate templates to their instantiations.
1229 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1230 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1231 Info->getTemplate(I),
1232 TemplateArgs);
1233 if (!Temp) return 0;
1234
1235 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1236 }
1237
1238 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1239 &ExplicitArgs,
1240 Previous))
1241 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001242
John McCallaf2094e2010-04-08 09:05:18 +00001243 isExplicitSpecialization = true;
1244
1245 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001246 // Look only into the namespace where the friend would be declared to
1247 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001248 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001249 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001250
Douglas Gregora735b202009-10-13 14:39:41 +00001251 // In C++, the previous declaration we find might be a tag type
1252 // (class or enum). In this case, the new declaration will hide the
1253 // tag type. Note that this does does not apply if we're declaring a
1254 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001255 if (Previous.isSingleTagDecl())
1256 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001257 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001258
John McCall9f54ad42009-12-10 09:41:52 +00001259 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001260 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001261
John McCall76d32642010-04-24 01:30:58 +00001262 NamedDecl *PrincipalDecl = (TemplateParams
1263 ? cast<NamedDecl>(FunctionTemplate)
1264 : Function);
1265
Douglas Gregora735b202009-10-13 14:39:41 +00001266 // If the original function was part of a friend declaration,
1267 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001268 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001269 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001270 if (TemplateParams)
Douglas Gregoref96ee02012-01-14 16:38:05 +00001271 PrevDecl = FunctionTemplate->getPreviousDecl();
John McCall76d32642010-04-24 01:30:58 +00001272 else
Douglas Gregoref96ee02012-01-14 16:38:05 +00001273 PrevDecl = Function->getPreviousDecl();
John McCall76d32642010-04-24 01:30:58 +00001274
1275 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001276 DC->makeDeclVisibleInContext(PrincipalDecl);
Gabor Greifab297ac2010-08-30 21:10:05 +00001277
Gabor Greif77535df2010-08-30 22:25:56 +00001278 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001279
Richard Smith53e53512011-10-19 00:54:10 +00001280 // C++98 [temp.friend]p5: When a function is defined in a friend function
1281 // declaration in a class template, the function is defined at each
1282 // instantiation of the class template. The function is defined even if it
1283 // is never used.
1284 // C++11 [temp.friend]p4: When a function is defined in a friend function
1285 // declaration in a class template, the function is instantiated when the
1286 // function is odr-used.
1287 //
1288 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1289 // redefinition, but don't instantiate the function.
David Blaikie4e4d0842012-03-11 07:00:24 +00001290 if ((!SemaRef.getLangOpts().CPlusPlus0x ||
Richard Smith53e53512011-10-19 00:54:10 +00001291 SemaRef.Diags.getDiagnosticLevel(
1292 diag::warn_cxx98_compat_friend_redefinition,
1293 Function->getLocation())
1294 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001295 D->isThisDeclarationADefinition()) {
1296 // Check for a function body.
1297 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001298 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001299 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001300 SemaRef.Diag(Function->getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001301 SemaRef.getLangOpts().CPlusPlus0x ?
Richard Smith53e53512011-10-19 00:54:10 +00001302 diag::warn_cxx98_compat_friend_redefinition :
1303 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001304 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
David Blaikie4e4d0842012-03-11 07:00:24 +00001305 if (!SemaRef.getLangOpts().CPlusPlus0x)
Richard Smith53e53512011-10-19 00:54:10 +00001306 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001307 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001308 // Check for redefinitions due to other instantiations of this or
1309 // a similar friend function.
1310 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1311 REnd = Function->redecls_end();
1312 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001313 if (*R == Function)
1314 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001315 switch (R->getFriendObjectKind()) {
1316 case Decl::FOK_None:
David Blaikie4e4d0842012-03-11 07:00:24 +00001317 if (!SemaRef.getLangOpts().CPlusPlus0x &&
Richard Smith53e53512011-10-19 00:54:10 +00001318 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001319 if (MemberSpecializationInfo *MSInfo
1320 = Function->getMemberSpecializationInfo()) {
1321 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1322 SourceLocation Loc = R->getLocation(); // FIXME
1323 MSInfo->setPointOfInstantiation(Loc);
1324 SemaRef.PendingLocalImplicitInstantiations.push_back(
1325 std::make_pair(Function, Loc));
1326 queuedInstantiation = true;
1327 }
1328 }
1329 }
1330 break;
1331 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001332 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001333 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001334 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001335 SemaRef.Diag(Function->getLocation(),
David Blaikie4e4d0842012-03-11 07:00:24 +00001336 SemaRef.getLangOpts().CPlusPlus0x ?
Richard Smith53e53512011-10-19 00:54:10 +00001337 diag::warn_cxx98_compat_friend_redefinition :
1338 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001339 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001340 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
David Blaikie4e4d0842012-03-11 07:00:24 +00001341 if (!SemaRef.getLangOpts().CPlusPlus0x)
Richard Smith53e53512011-10-19 00:54:10 +00001342 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001343 break;
1344 }
1345 }
1346 }
1347 }
Douglas Gregora735b202009-10-13 14:39:41 +00001348 }
1349
John McCall76d32642010-04-24 01:30:58 +00001350 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1351 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1352 PrincipalDecl->setNonMemberOperator();
1353
Sean Hunteb88ae52011-05-23 21:07:59 +00001354 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001355 return Function;
1356}
1357
Douglas Gregord60e1052009-08-27 16:57:43 +00001358Decl *
1359TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001360 TemplateParameterList *TemplateParams,
1361 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001362 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
Douglas Gregord60e1052009-08-27 16:57:43 +00001363 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001364 // We are creating a function template specialization from a function
1365 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001366 // specialization for this particular set of template arguments.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001367 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001368 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001369
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001370 void *InsertPos = 0;
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001371 FunctionDecl *SpecFunc
1372 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1373 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Douglas Gregor6b906862009-08-21 00:16:32 +00001375 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001376 if (SpecFunc)
1377 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001378 }
1379
John McCallb0cb0222010-03-27 05:57:59 +00001380 bool isFriend;
1381 if (FunctionTemplate)
1382 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1383 else
1384 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1385
Douglas Gregor79c22782010-01-16 20:21:20 +00001386 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001387 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001388 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001389 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001390
John McCall4eab39f2010-10-19 02:26:41 +00001391 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001392 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001393 unsigned NumTempParamLists = 0;
1394 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1395 TempParamLists.set_size(NumTempParamLists);
1396 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1397 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1398 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1399 if (!InstParams)
1400 return NULL;
1401 TempParamLists[I] = InstParams;
1402 }
1403 }
1404
Chris Lattner5f9e2722011-07-23 10:55:15 +00001405 SmallVector<ParmVarDecl *, 4> Params;
Benjamin Kramerdc370c12012-01-20 14:42:32 +00001406 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001407 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001408 return 0;
Douglas Gregor71074fd2012-09-13 21:56:43 +00001409 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001410
Abramo Bagnara723df242010-12-14 22:11:44 +00001411 // \brief If the type of this function, after ignoring parentheses,
1412 // is not *directly* a function type, then we're instantiating a function
1413 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001414 //
1415 // typedef int functype(int, int);
1416 // functype func;
1417 //
1418 // In this case, we'll just go instantiate the ParmVarDecls that we
1419 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001420 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001421 assert(!Params.size() && "Instantiating type could not yield parameters");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001422 SmallVector<QualType, 4> ParamTypes;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001423 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1424 D->getNumParams(), TemplateArgs, ParamTypes,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001425 &Params))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001426 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001427 }
1428
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001429 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1430 if (QualifierLoc) {
1431 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001432 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001433 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001434 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001435 }
1436
1437 DeclContext *DC = Owner;
1438 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001439 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001440 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001441 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001442 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001443
1444 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1445 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001446 } else {
1447 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1448 D->getDeclContext(),
1449 TemplateArgs);
1450 }
1451 if (!DC) return 0;
1452 }
1453
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001454 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001455 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001456 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001457
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001458 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001459 DeclarationNameInfo NameInfo
1460 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001461 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001462 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001463 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001464 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001465 Constructor->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001466 false, Constructor->isConstexpr());
Douglas Gregor17e32f32009-08-21 22:43:28 +00001467 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001468 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001469 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001470 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001471 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001472 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001473 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001474 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001475 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001476 Conversion->isExplicit(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001477 Conversion->isConstexpr(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001478 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001479 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001480 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001481 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001482 D->isStatic(),
1483 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001484 D->isInlineSpecified(),
Richard Smith86c3ae42012-02-13 03:54:03 +00001485 D->isConstexpr(), D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001486 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001487
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001488 if (QualifierLoc)
1489 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001490
Douglas Gregord60e1052009-08-27 16:57:43 +00001491 if (TemplateParams) {
1492 // Our resulting instantiation is actually a function template, since we
1493 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001494 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001495 // template<typename T>
1496 // struct X {
1497 // template<typename U> void f(T, U);
1498 // };
1499 //
1500 // X<int> x;
1501 //
1502 // We are instantiating the member template "f" within X<int>, which means
1503 // substituting int for T, but leaving "f" as a member function template.
1504 // Build the function template itself.
1505 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1506 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001507 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001508 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001509 if (isFriend) {
1510 FunctionTemplate->setLexicalDeclContext(Owner);
1511 FunctionTemplate->setObjectOfFriendDecl(true);
1512 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001513 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001514 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001515 } else if (FunctionTemplate) {
1516 // Record this function template specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001517 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001518 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001519 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001520 TemplateArgumentList::CreateCopy(SemaRef.Context,
1521 Innermost.first,
1522 Innermost.second),
Douglas Gregor1e1e9722012-03-28 14:34:23 +00001523 /*InsertPos=*/0);
John McCallb0cb0222010-03-27 05:57:59 +00001524 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001525 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001526 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001527 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001528
Mike Stump1eb44332009-09-09 15:08:12 +00001529 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001530 // out-of-line, the instantiation will have the same lexical
1531 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001532 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001533 if (NumTempParamLists)
1534 Method->setTemplateParameterListsInfo(SemaRef.Context,
1535 NumTempParamLists,
1536 TempParamLists.data());
1537
John McCallb0cb0222010-03-27 05:57:59 +00001538 Method->setLexicalDeclContext(Owner);
1539 Method->setObjectOfFriendDecl(true);
1540 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001541 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001542
Douglas Gregor5545e162009-03-24 00:38:23 +00001543 // Attach the parameters
1544 for (unsigned P = 0; P < Params.size(); ++P)
1545 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001546 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001547
1548 if (InitMethodInstantiation(Method, D))
1549 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001550
Abramo Bagnara25777432010-08-11 22:01:17 +00001551 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1552 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001553
John McCallb0cb0222010-03-27 05:57:59 +00001554 if (!FunctionTemplate || TemplateParams || isFriend) {
1555 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001556
Douglas Gregordec06662009-08-21 18:42:58 +00001557 // In C++, the previous declaration we find might be a tag type
1558 // (class or enum). In this case, the new declaration will hide the
1559 // tag type. Note that this does does not apply if we're declaring a
1560 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001561 if (Previous.isSingleTagDecl())
1562 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001563 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001564
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001565 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001566 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001567
Douglas Gregor4ba31362009-12-01 17:24:26 +00001568 if (D->isPure())
1569 SemaRef.CheckPureMethod(Method, SourceRange());
1570
John McCall1f2e1a92012-08-10 03:15:35 +00001571 // Propagate access. For a non-friend declaration, the access is
1572 // whatever we're propagating from. For a friend, it should be the
1573 // previous declaration we just found.
1574 if (isFriend && Method->getPreviousDecl())
1575 Method->setAccess(Method->getPreviousDecl()->getAccess());
1576 else
1577 Method->setAccess(D->getAccess());
1578 if (FunctionTemplate)
1579 FunctionTemplate->setAccess(Method->getAccess());
John McCall46460a62010-01-20 21:53:11 +00001580
Anders Carlsson9eefa222011-01-20 06:52:44 +00001581 SemaRef.CheckOverrideControl(Method);
1582
Eli Friedman3bc45152011-11-15 22:39:08 +00001583 // If a function is defined as defaulted or deleted, mark it as such now.
1584 if (D->isDefaulted())
1585 Method->setDefaulted();
1586 if (D->isDeletedAsWritten())
1587 Method->setDeletedAsWritten();
1588
John McCall1f2e1a92012-08-10 03:15:35 +00001589 // If there's a function template, let our caller handle it.
John McCallb0cb0222010-03-27 05:57:59 +00001590 if (FunctionTemplate) {
John McCall1f2e1a92012-08-10 03:15:35 +00001591 // do nothing
1592
1593 // Don't hide a (potentially) valid declaration with an invalid one.
John McCallb0cb0222010-03-27 05:57:59 +00001594 } else if (Method->isInvalidDecl() && !Previous.empty()) {
John McCall1f2e1a92012-08-10 03:15:35 +00001595 // do nothing
1596
1597 // Otherwise, check access to friends and make them visible.
1598 } else if (isFriend) {
1599 // We only need to re-check access for methods which we didn't
1600 // manage to match during parsing.
1601 if (!D->getPreviousDecl())
1602 SemaRef.CheckFriendAccess(Method);
1603
1604 Record->makeDeclVisibleInContext(Method);
1605
1606 // Otherwise, add the declaration. We don't need to do this for
1607 // class-scope specializations because we'll have matched them with
1608 // the appropriate template.
1609 } else if (!IsClassScopeSpecialization) {
1610 Owner->addDecl(Method);
John McCallb0cb0222010-03-27 05:57:59 +00001611 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001612
1613 if (D->isExplicitlyDefaulted()) {
1614 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1615 } else {
1616 assert(!D->isDefaulted() &&
1617 "should not implicitly default uninstantiated function");
1618 }
1619
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001620 return Method;
1621}
1622
Douglas Gregor615c5d42009-03-24 16:43:20 +00001623Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001624 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001625}
1626
Douglas Gregor03b2b072009-03-24 00:15:49 +00001627Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001628 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001629}
1630
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001631Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001632 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001633}
1634
Douglas Gregor6477b692009-03-25 15:04:13 +00001635ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallfb44de92011-05-01 22:35:37 +00001636 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001637 llvm::Optional<unsigned>(),
1638 /*ExpectParameterPack=*/false);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001639}
1640
John McCalle29ba202009-08-20 01:44:21 +00001641Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1642 TemplateTypeParmDecl *D) {
1643 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001644 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001645
John McCalle29ba202009-08-20 01:44:21 +00001646 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001647 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1648 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001649 D->getDepth() - TemplateArgs.getNumLevels(),
1650 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001651 D->wasDeclaredWithTypename(),
1652 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001653 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001654
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001655 if (D->hasDefaultArgument())
1656 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1657
1658 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001659 // scope.
1660 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001661
John McCalle29ba202009-08-20 01:44:21 +00001662 return Inst;
1663}
1664
Douglas Gregor33642df2009-10-23 23:25:44 +00001665Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1666 NonTypeTemplateParmDecl *D) {
1667 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001668 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001669 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1670 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001671 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001672 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001673 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001674 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001675
1676 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001677 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001678 // expansion of types. Substitute into each of the expanded types.
1679 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1680 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1681 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1682 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1683 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001684 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001685 D->getDeclName());
1686 if (!NewDI)
1687 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001688
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001689 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1690 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1691 D->getLocation());
1692 if (NewT.isNull())
1693 return 0;
1694 ExpandedParameterPackTypes.push_back(NewT);
1695 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001696
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001697 IsExpandedParameterPack = true;
1698 DI = D->getTypeSourceInfo();
1699 T = DI->getType();
Richard Smith6964b3f2012-09-07 02:06:42 +00001700 } else if (D->isPackExpansion()) {
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001701 // The non-type template parameter pack's type is a pack expansion of types.
1702 // Determine whether we need to expand this parameter pack into separate
1703 // types.
1704 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1705 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001706 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001707 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001708
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001709 // Determine whether the set of unexpanded parameter packs can and should
1710 // be expanded.
1711 bool Expand = true;
1712 bool RetainExpansion = false;
1713 llvm::Optional<unsigned> OrigNumExpansions
1714 = Expansion.getTypePtr()->getNumExpansions();
1715 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1716 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1717 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001718 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001719 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001720 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001721 NumExpansions))
1722 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001723
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001724 if (Expand) {
1725 for (unsigned I = 0; I != *NumExpansions; ++I) {
1726 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1727 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001728 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001729 D->getDeclName());
1730 if (!NewDI)
1731 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001732
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001733 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1734 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1735 NewDI->getType(),
1736 D->getLocation());
1737 if (NewT.isNull())
1738 return 0;
1739 ExpandedParameterPackTypes.push_back(NewT);
1740 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001741
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001742 // Note that we have an expanded parameter pack. The "type" of this
1743 // expanded parameter pack is the original expansion type, but callers
1744 // will end up using the expanded parameter pack types for type-checking.
1745 IsExpandedParameterPack = true;
1746 DI = D->getTypeSourceInfo();
1747 T = DI->getType();
1748 } else {
1749 // We cannot fully expand the pack expansion now, so substitute into the
1750 // pattern and create a new pack expansion type.
1751 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1752 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001753 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001754 D->getDeclName());
1755 if (!NewPattern)
1756 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001757
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001758 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1759 NumExpansions);
1760 if (!DI)
1761 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001762
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001763 T = DI->getType();
1764 }
1765 } else {
1766 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001767 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001768 D->getLocation(), D->getDeclName());
1769 if (!DI)
1770 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001771
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001772 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001773 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001774 D->getLocation());
1775 if (T.isNull()) {
1776 T = SemaRef.Context.IntTy;
1777 Invalid = true;
1778 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001779 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001780
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001781 NonTypeTemplateParmDecl *Param;
1782 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001783 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001784 D->getInnerLocStart(),
1785 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001786 D->getDepth() - TemplateArgs.getNumLevels(),
1787 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001788 D->getIdentifier(), T,
1789 DI,
1790 ExpandedParameterPackTypes.data(),
1791 ExpandedParameterPackTypes.size(),
1792 ExpandedParameterPackTypesAsWritten.data());
1793 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001794 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001795 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001796 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001797 D->getDepth() - TemplateArgs.getNumLevels(),
1798 D->getPosition(),
1799 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001800 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001801
Douglas Gregor9a299e02011-03-04 17:52:15 +00001802 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001803 if (Invalid)
1804 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001805
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001806 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001807
1808 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001809 // scope.
1810 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001811 return Param;
1812}
1813
Richard Smith6964b3f2012-09-07 02:06:42 +00001814static void collectUnexpandedParameterPacks(
1815 Sema &S,
1816 TemplateParameterList *Params,
1817 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
1818 for (TemplateParameterList::const_iterator I = Params->begin(),
1819 E = Params->end(); I != E; ++I) {
1820 if ((*I)->isTemplateParameterPack())
1821 continue;
1822 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*I))
1823 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
1824 Unexpanded);
1825 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(*I))
1826 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
1827 Unexpanded);
1828 }
1829}
1830
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001831Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001832TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1833 TemplateTemplateParmDecl *D) {
1834 // Instantiate the template parameter list of the template template parameter.
1835 TemplateParameterList *TempParams = D->getTemplateParameters();
1836 TemplateParameterList *InstParams;
Richard Smith6964b3f2012-09-07 02:06:42 +00001837 SmallVector<TemplateParameterList*, 8> ExpandedParams;
1838
1839 bool IsExpandedParameterPack = false;
1840
1841 if (D->isExpandedParameterPack()) {
1842 // The template template parameter pack is an already-expanded pack
1843 // expansion of template parameters. Substitute into each of the expanded
1844 // parameters.
1845 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
1846 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1847 I != N; ++I) {
1848 LocalInstantiationScope Scope(SemaRef);
1849 TemplateParameterList *Expansion =
1850 SubstTemplateParams(D->getExpansionTemplateParameters(I));
1851 if (!Expansion)
1852 return 0;
1853 ExpandedParams.push_back(Expansion);
1854 }
1855
1856 IsExpandedParameterPack = true;
1857 InstParams = TempParams;
1858 } else if (D->isPackExpansion()) {
1859 // The template template parameter pack expands to a pack of template
1860 // template parameters. Determine whether we need to expand this parameter
1861 // pack into separate parameters.
1862 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1863 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
1864 Unexpanded);
1865
1866 // Determine whether the set of unexpanded parameter packs can and should
1867 // be expanded.
1868 bool Expand = true;
1869 bool RetainExpansion = false;
1870 llvm::Optional<unsigned> NumExpansions;
1871 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
1872 TempParams->getSourceRange(),
1873 Unexpanded,
1874 TemplateArgs,
1875 Expand, RetainExpansion,
1876 NumExpansions))
1877 return 0;
1878
1879 if (Expand) {
1880 for (unsigned I = 0; I != *NumExpansions; ++I) {
1881 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1882 LocalInstantiationScope Scope(SemaRef);
1883 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
1884 if (!Expansion)
1885 return 0;
1886 ExpandedParams.push_back(Expansion);
1887 }
1888
1889 // Note that we have an expanded parameter pack. The "type" of this
1890 // expanded parameter pack is the original expansion type, but callers
1891 // will end up using the expanded parameter pack types for type-checking.
1892 IsExpandedParameterPack = true;
1893 InstParams = TempParams;
1894 } else {
1895 // We cannot fully expand the pack expansion now, so just substitute
1896 // into the pattern.
1897 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1898
1899 LocalInstantiationScope Scope(SemaRef);
1900 InstParams = SubstTemplateParams(TempParams);
1901 if (!InstParams)
1902 return 0;
1903 }
1904 } else {
Douglas Gregor9106ef72009-11-11 16:58:32 +00001905 // Perform the actual substitution of template parameters within a new,
1906 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001907 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001908 InstParams = SubstTemplateParams(TempParams);
1909 if (!InstParams)
Richard Smith6964b3f2012-09-07 02:06:42 +00001910 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001911 }
1912
Douglas Gregor9106ef72009-11-11 16:58:32 +00001913 // Build the template template parameter.
Richard Smith6964b3f2012-09-07 02:06:42 +00001914 TemplateTemplateParmDecl *Param;
1915 if (IsExpandedParameterPack)
1916 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1917 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001918 D->getDepth() - TemplateArgs.getNumLevels(),
Richard Smith6964b3f2012-09-07 02:06:42 +00001919 D->getPosition(),
1920 D->getIdentifier(), InstParams,
1921 ExpandedParams);
1922 else
1923 Param = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner,
1924 D->getLocation(),
1925 D->getDepth() - TemplateArgs.getNumLevels(),
1926 D->getPosition(),
1927 D->isParameterPack(),
1928 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001929 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001930 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001931
1932 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00001933 // scope.
1934 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001935
Douglas Gregor9106ef72009-11-11 16:58:32 +00001936 return Param;
1937}
1938
Douglas Gregor48c32a72009-11-17 06:07:40 +00001939Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001940 // Using directives are never dependent (and never contain any types or
1941 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001942
Douglas Gregor48c32a72009-11-17 06:07:40 +00001943 UsingDirectiveDecl *Inst
1944 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001945 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001946 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001947 D->getIdentLocation(),
1948 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001949 D->getCommonAncestor());
Abramo Bagnara536afbe2012-09-05 09:55:10 +00001950
1951 // Add the using directive to its declaration context
1952 // only if this is not a function or method.
1953 if (!Owner->isFunctionOrMethod())
1954 Owner->addDecl(Inst);
1955
Douglas Gregor48c32a72009-11-17 06:07:40 +00001956 return Inst;
1957}
1958
John McCalled976492009-12-04 22:46:56 +00001959Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001960
1961 // The nested name specifier may be dependent, for example
1962 // template <typename T> struct t {
1963 // struct s1 { T f1(); };
1964 // struct s2 : s1 { using s1::f1; };
1965 // };
1966 // template struct t<int>;
1967 // Here, in using s1::f1, s1 refers to t<T>::s1;
1968 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001969 NestedNameSpecifierLoc QualifierLoc
1970 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1971 TemplateArgs);
1972 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001973 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001974
1975 // The name info is non-dependent, so no transformation
1976 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001977 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001978
John McCall9f54ad42009-12-10 09:41:52 +00001979 // We only need to do redeclaration lookups if we're in a class
1980 // scope (in fact, it's not really even possible in non-class
1981 // scopes).
1982 bool CheckRedeclaration = Owner->isRecord();
1983
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001984 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1985 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001986
John McCalled976492009-12-04 22:46:56 +00001987 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001988 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001989 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001990 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001991 D->isTypeName());
1992
Douglas Gregor5149f372011-02-25 15:54:31 +00001993 CXXScopeSpec SS;
1994 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001995 if (CheckRedeclaration) {
1996 Prev.setHideTags(false);
1997 SemaRef.LookupQualifiedName(Prev, Owner);
1998
1999 // Check for invalid redeclarations.
2000 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
2001 D->isTypeName(), SS,
2002 D->getLocation(), Prev))
2003 NewUD->setInvalidDecl();
2004
2005 }
2006
2007 if (!NewUD->isInvalidDecl() &&
2008 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00002009 D->getLocation()))
2010 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00002011
John McCalled976492009-12-04 22:46:56 +00002012 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
2013 NewUD->setAccess(D->getAccess());
2014 Owner->addDecl(NewUD);
2015
John McCall9f54ad42009-12-10 09:41:52 +00002016 // Don't process the shadow decls for an invalid decl.
2017 if (NewUD->isInvalidDecl())
2018 return NewUD;
2019
Richard Smithc5a89a12012-04-02 01:30:27 +00002020 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) {
2021 if (SemaRef.CheckInheritingConstructorUsingDecl(NewUD))
2022 NewUD->setInvalidDecl();
2023 return NewUD;
2024 }
2025
John McCall323c3102009-12-22 22:26:37 +00002026 bool isFunctionScope = Owner->isFunctionOrMethod();
2027
John McCall9f54ad42009-12-10 09:41:52 +00002028 // Process the shadow decls.
2029 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
2030 I != E; ++I) {
2031 UsingShadowDecl *Shadow = *I;
2032 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00002033 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
2034 Shadow->getLocation(),
2035 Shadow->getTargetDecl(),
2036 TemplateArgs));
2037 if (!InstTarget)
2038 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00002039
2040 if (CheckRedeclaration &&
2041 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
2042 continue;
2043
2044 UsingShadowDecl *InstShadow
2045 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
2046 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00002047
2048 if (isFunctionScope)
2049 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00002050 }
John McCalled976492009-12-04 22:46:56 +00002051
2052 return NewUD;
2053}
2054
2055Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00002056 // Ignore these; we handle them in bulk when processing the UsingDecl.
2057 return 0;
John McCalled976492009-12-04 22:46:56 +00002058}
2059
John McCall7ba107a2009-11-18 02:36:19 +00002060Decl * TemplateDeclInstantiator
2061 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002062 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002063 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00002064 TemplateArgs);
2065 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002066 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002067
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002068 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002069 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002070
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002071 // Since NameInfo refers to a typename, it cannot be a C++ special name.
Benjamin Krameraccaf192012-11-14 15:08:31 +00002072 // Hence, no transformation is required for it.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002073 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002074 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00002075 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002076 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002077 /*instantiation*/ true,
2078 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002079 if (UD)
John McCalled976492009-12-04 22:46:56 +00002080 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2081
John McCall7ba107a2009-11-18 02:36:19 +00002082 return UD;
2083}
2084
2085Decl * TemplateDeclInstantiator
2086 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00002087 NestedNameSpecifierLoc QualifierLoc
2088 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
2089 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00002090 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002091
John McCall7ba107a2009-11-18 02:36:19 +00002092 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00002093 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00002094
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002095 DeclarationNameInfo NameInfo
2096 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2097
John McCall7ba107a2009-11-18 02:36:19 +00002098 NamedDecl *UD =
2099 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00002100 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00002101 /*instantiation*/ true,
2102 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002103 if (UD)
John McCalled976492009-12-04 22:46:56 +00002104 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
2105
Anders Carlsson0d8df782009-08-29 19:37:28 +00002106 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00002107}
2108
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002109
2110Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
2111 ClassScopeFunctionSpecializationDecl *Decl) {
2112 CXXMethodDecl *OldFD = Decl->getSpecialization();
Nico Weber6b020092012-06-25 17:21:05 +00002113 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD,
2114 0, true));
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002115
2116 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
2117 Sema::ForRedeclaration);
2118
Nico Weber6b020092012-06-25 17:21:05 +00002119 TemplateArgumentListInfo TemplateArgs;
2120 TemplateArgumentListInfo* TemplateArgsPtr = 0;
2121 if (Decl->hasExplicitTemplateArgs()) {
2122 TemplateArgs = Decl->templateArgs();
2123 TemplateArgsPtr = &TemplateArgs;
2124 }
2125
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002126 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
Nico Weber6b020092012-06-25 17:21:05 +00002127 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, TemplateArgsPtr,
2128 Previous)) {
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002129 NewFD->setInvalidDecl();
2130 return NewFD;
2131 }
2132
2133 // Associate the specialization with the pattern.
2134 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
2135 assert(Specialization && "Class scope Specialization is null");
2136 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
2137
2138 return NewFD;
2139}
2140
John McCallce3ff2b2009-08-25 22:02:44 +00002141Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002142 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00002143 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00002144 if (D->isInvalidDecl())
2145 return 0;
2146
Douglas Gregor8dbc2692009-03-17 21:15:40 +00002147 return Instantiator.Visit(D);
2148}
2149
John McCalle29ba202009-08-20 01:44:21 +00002150/// \brief Instantiates a nested template parameter list in the current
2151/// instantiation context.
2152///
2153/// \param L The parameter list to instantiate
2154///
2155/// \returns NULL if there was an error
2156TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00002157TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00002158 // Get errors for all the parameters before bailing out.
2159 bool Invalid = false;
2160
2161 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002162 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00002163 ParamVector Params;
2164 Params.reserve(N);
2165 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2166 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002167 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002168 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002169 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002170 }
2171
2172 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002173 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002174 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002175
2176 TemplateParameterList *InstL
2177 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2178 L->getLAngleLoc(), &Params.front(), N,
2179 L->getRAngleLoc());
2180 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002181}
John McCalle29ba202009-08-20 01:44:21 +00002182
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002183/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002184/// specialization.
2185///
2186/// \param ClassTemplate the (instantiated) class template that is partially
2187// specialized by the instantiation of \p PartialSpec.
2188///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002189/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002190/// specialization that we are instantiating.
2191///
Douglas Gregord65587f2010-11-10 19:44:59 +00002192/// \returns The instantiated partial specialization, if successful; otherwise,
2193/// NULL to indicate an error.
2194ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002195TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2196 ClassTemplateDecl *ClassTemplate,
2197 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002198 // Create a local instantiation scope for this class template partial
2199 // specialization, which will contain the instantiations of the template
2200 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002201 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002202
Douglas Gregored9c0f92009-10-29 00:04:11 +00002203 // Substitute into the template parameters of the class template partial
2204 // specialization.
2205 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2206 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2207 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002208 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002209
Douglas Gregored9c0f92009-10-29 00:04:11 +00002210 // Substitute into the template arguments of the class template partial
2211 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00002212 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002213 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2214 PartialSpec->getNumTemplateArgsAsWritten(),
Douglas Gregore02e2622010-12-22 21:19:48 +00002215 InstTemplateArgs, TemplateArgs))
2216 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002217
Douglas Gregored9c0f92009-10-29 00:04:11 +00002218 // Check that the template argument list is well-formed for this
2219 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002220 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002221 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002222 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002223 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002224 false,
2225 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002226 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002227
2228 // Figure out where to insert this class template partial specialization
2229 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002230 void *InsertPos = 0;
2231 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002232 = ClassTemplate->findPartialSpecialization(Converted.data(),
2233 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002234
Douglas Gregored9c0f92009-10-29 00:04:11 +00002235 // Build the canonical type that describes the converted template
2236 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002237 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002238 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002239 Converted.data(),
2240 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002241
2242 // Build the fully-sugared type for this class template
2243 // specialization as the user wrote in the specialization
2244 // itself. This means that we'll pretty-print the type retrieved
2245 // from the specialization's declaration the way that the user
2246 // actually wrote the specialization, rather than formatting the
2247 // name based on the "canonical" representation used to store the
2248 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002249 TypeSourceInfo *WrittenTy
2250 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2251 TemplateName(ClassTemplate),
2252 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002253 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002254 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002255
Douglas Gregored9c0f92009-10-29 00:04:11 +00002256 if (PrevDecl) {
2257 // We've already seen a partial specialization with the same template
2258 // parameters and template arguments. This can happen, for example, when
2259 // substituting the outer template arguments ends up causing two
2260 // class template partial specializations of a member class template
2261 // to have identical forms, e.g.,
2262 //
2263 // template<typename T, typename U>
2264 // struct Outer {
2265 // template<typename X, typename Y> struct Inner;
2266 // template<typename Y> struct Inner<T, Y>;
2267 // template<typename Y> struct Inner<U, Y>;
2268 // };
2269 //
2270 // Outer<int, int> outer; // error: the partial specializations of Inner
2271 // // have the same signature.
2272 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002273 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002274 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2275 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002276 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002277 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002278
2279
Douglas Gregored9c0f92009-10-29 00:04:11 +00002280 // Create the class template partial specialization declaration.
2281 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002282 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002283 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002284 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002285 PartialSpec->getLocStart(),
2286 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002287 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002288 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002289 Converted.data(),
2290 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002291 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002292 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002293 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002294 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002295 // Substitute the nested name specifier, if any.
2296 if (SubstQualifier(PartialSpec, InstPartialSpec))
2297 return 0;
2298
Douglas Gregored9c0f92009-10-29 00:04:11 +00002299 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002300 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002301
Douglas Gregored9c0f92009-10-29 00:04:11 +00002302 // Add this partial specialization to the set of class template partial
2303 // specializations.
Douglas Gregor1e1e9722012-03-28 14:34:23 +00002304 ClassTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/0);
Douglas Gregord65587f2010-11-10 19:44:59 +00002305 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002306}
2307
John McCall21ef0fa2010-03-11 09:03:00 +00002308TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002309TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002310 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002311 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2312 assert(OldTInfo && "substituting function without type source info");
2313 assert(Params.empty() && "parameter vector is non-empty at start");
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002314
2315 CXXRecordDecl *ThisContext = 0;
2316 unsigned ThisTypeQuals = 0;
2317 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2318 ThisContext = Method->getParent();
2319 ThisTypeQuals = Method->getTypeQualifiers();
2320 }
2321
John McCall6cd3b9f2010-04-09 17:38:44 +00002322 TypeSourceInfo *NewTInfo
2323 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2324 D->getTypeSpecStartLoc(),
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002325 D->getDeclName(),
2326 ThisContext, ThisTypeQuals);
John McCall21ef0fa2010-03-11 09:03:00 +00002327 if (!NewTInfo)
2328 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002329
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002330 if (NewTInfo != OldTInfo) {
2331 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002332 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002333 if (FunctionProtoTypeLoc *OldProtoLoc
2334 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002335 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002336 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2337 assert(NewProtoLoc && "Missing prototype?");
Richard Smith500d7292012-07-18 01:29:05 +00002338 unsigned NewIdx = 0;
Douglas Gregor12c9c002011-01-07 16:43:16 +00002339 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2340 OldIdx != NumOldParams; ++OldIdx) {
2341 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
Richard Smith500d7292012-07-18 01:29:05 +00002342 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
2343
2344 llvm::Optional<unsigned> NumArgumentsInExpansion;
2345 if (OldParam->isParameterPack())
2346 NumArgumentsInExpansion =
2347 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2348 TemplateArgs);
2349 if (!NumArgumentsInExpansion) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002350 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002351 // instantiated to a (still-dependent) parameter pack.
2352 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2353 Params.push_back(NewParam);
Richard Smith500d7292012-07-18 01:29:05 +00002354 Scope->InstantiatedLocal(OldParam, NewParam);
2355 } else {
2356 // Parameter pack expansion: make the instantiation an argument pack.
2357 Scope->MakeInstantiatedLocalArgPack(OldParam);
2358 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
2359 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2360 Params.push_back(NewParam);
2361 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
2362 }
Douglas Gregor12c9c002011-01-07 16:43:16 +00002363 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002364 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002365 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002366 } else {
2367 // The function type itself was not dependent and therefore no
2368 // substitution occurred. However, we still need to instantiate
2369 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002370 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002371 if (FunctionProtoTypeLoc *OldProtoLoc
2372 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2373 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2374 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2375 if (!Parm)
2376 return 0;
2377 Params.push_back(Parm);
2378 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002379 }
2380 }
John McCall21ef0fa2010-03-11 09:03:00 +00002381 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002382}
2383
Richard Smithe6975e92012-04-17 00:58:00 +00002384/// Introduce the instantiated function parameters into the local
2385/// instantiation scope, and set the parameter names to those used
2386/// in the template.
2387static void addInstantiatedParametersToScope(Sema &S, FunctionDecl *Function,
2388 const FunctionDecl *PatternDecl,
2389 LocalInstantiationScope &Scope,
2390 const MultiLevelTemplateArgumentList &TemplateArgs) {
2391 unsigned FParamIdx = 0;
2392 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2393 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
2394 if (!PatternParam->isParameterPack()) {
2395 // Simple case: not a parameter pack.
2396 assert(FParamIdx < Function->getNumParams());
2397 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2398 FunctionParam->setDeclName(PatternParam->getDeclName());
2399 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2400 ++FParamIdx;
2401 continue;
2402 }
2403
2404 // Expand the parameter pack.
2405 Scope.MakeInstantiatedLocalArgPack(PatternParam);
Richard Smith500d7292012-07-18 01:29:05 +00002406 llvm::Optional<unsigned> NumArgumentsInExpansion
Richard Smithe6975e92012-04-17 00:58:00 +00002407 = S.getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
Richard Smith500d7292012-07-18 01:29:05 +00002408 assert(NumArgumentsInExpansion &&
2409 "should only be called when all template arguments are known");
2410 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
Richard Smithe6975e92012-04-17 00:58:00 +00002411 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2412 FunctionParam->setDeclName(PatternParam->getDeclName());
2413 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2414 ++FParamIdx;
2415 }
2416 }
2417}
2418
2419static void InstantiateExceptionSpec(Sema &SemaRef, FunctionDecl *New,
2420 const FunctionProtoType *Proto,
2421 const MultiLevelTemplateArgumentList &TemplateArgs) {
Richard Smith13bffc52012-04-19 00:08:28 +00002422 assert(Proto->getExceptionSpecType() != EST_Uninstantiated);
2423
Richard Smithe6975e92012-04-17 00:58:00 +00002424 // C++11 [expr.prim.general]p3:
2425 // If a declaration declares a member function or member function
2426 // template of a class X, the expression this is a prvalue of type
2427 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
2428 // and the end of the function-definition, member-declarator, or
2429 // declarator.
2430 CXXRecordDecl *ThisContext = 0;
2431 unsigned ThisTypeQuals = 0;
2432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(New)) {
2433 ThisContext = Method->getParent();
2434 ThisTypeQuals = Method->getTypeQualifiers();
2435 }
2436 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals,
2437 SemaRef.getLangOpts().CPlusPlus0x);
2438
2439 // The function has an exception specification or a "noreturn"
2440 // attribute. Substitute into each of the exception types.
2441 SmallVector<QualType, 4> Exceptions;
2442 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2443 // FIXME: Poor location information!
2444 if (const PackExpansionType *PackExpansion
2445 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2446 // We have a pack expansion. Instantiate it.
2447 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2448 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2449 Unexpanded);
2450 assert(!Unexpanded.empty() &&
2451 "Pack expansion without parameter packs?");
2452
2453 bool Expand = false;
2454 bool RetainExpansion = false;
2455 llvm::Optional<unsigned> NumExpansions
2456 = PackExpansion->getNumExpansions();
2457 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2458 SourceRange(),
2459 Unexpanded,
2460 TemplateArgs,
2461 Expand,
2462 RetainExpansion,
2463 NumExpansions))
2464 break;
2465
2466 if (!Expand) {
2467 // We can't expand this pack expansion into separate arguments yet;
2468 // just substitute into the pattern and create a new pack expansion
2469 // type.
2470 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2471 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2472 TemplateArgs,
2473 New->getLocation(), New->getDeclName());
2474 if (T.isNull())
2475 break;
2476
2477 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
2478 Exceptions.push_back(T);
2479 continue;
2480 }
2481
2482 // Substitute into the pack expansion pattern for each template
2483 bool Invalid = false;
2484 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
2485 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2486
2487 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2488 TemplateArgs,
2489 New->getLocation(), New->getDeclName());
2490 if (T.isNull()) {
2491 Invalid = true;
2492 break;
2493 }
2494
2495 Exceptions.push_back(T);
2496 }
2497
2498 if (Invalid)
2499 break;
2500
2501 continue;
2502 }
2503
2504 QualType T
2505 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2506 New->getLocation(), New->getDeclName());
2507 if (T.isNull() ||
2508 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2509 continue;
2510
2511 Exceptions.push_back(T);
2512 }
2513 Expr *NoexceptExpr = 0;
2514 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2515 EnterExpressionEvaluationContext Unevaluated(SemaRef,
2516 Sema::ConstantEvaluated);
2517 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2518 if (E.isUsable())
2519 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2520
2521 if (E.isUsable()) {
2522 NoexceptExpr = E.take();
2523 if (!NoexceptExpr->isTypeDependent() &&
2524 !NoexceptExpr->isValueDependent())
Douglas Gregorab41fe92012-05-04 22:38:52 +00002525 NoexceptExpr
2526 = SemaRef.VerifyIntegerConstantExpression(NoexceptExpr,
2527 0, diag::err_noexcept_needs_constant_expression,
2528 /*AllowFold*/ false).take();
Richard Smithe6975e92012-04-17 00:58:00 +00002529 }
2530 }
2531
2532 // Rebuild the function type
2533 const FunctionProtoType *NewProto
2534 = New->getType()->getAs<FunctionProtoType>();
2535 assert(NewProto && "Template instantiation without function prototype?");
2536
2537 FunctionProtoType::ExtProtoInfo EPI = NewProto->getExtProtoInfo();
2538 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
2539 EPI.NumExceptions = Exceptions.size();
2540 EPI.Exceptions = Exceptions.data();
2541 EPI.NoexceptExpr = NoexceptExpr;
2542
2543 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2544 NewProto->arg_type_begin(),
2545 NewProto->getNumArgs(),
2546 EPI));
2547}
2548
2549void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
2550 FunctionDecl *Decl) {
Richard Smith13bffc52012-04-19 00:08:28 +00002551 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
2552 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
Richard Smithe6975e92012-04-17 00:58:00 +00002553 return;
2554
2555 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
2556 InstantiatingTemplate::ExceptionSpecification());
Richard Smithb9d0b762012-07-27 04:22:15 +00002557 if (Inst) {
2558 // We hit the instantiation depth limit. Clear the exception specification
2559 // so that our callers don't have to cope with EST_Uninstantiated.
2560 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
2561 EPI.ExceptionSpecType = EST_None;
2562 Decl->setType(Context.getFunctionType(Proto->getResultType(),
2563 Proto->arg_type_begin(),
2564 Proto->getNumArgs(),
2565 EPI));
Richard Smithe6975e92012-04-17 00:58:00 +00002566 return;
Richard Smithb9d0b762012-07-27 04:22:15 +00002567 }
Richard Smithe6975e92012-04-17 00:58:00 +00002568
2569 // Enter the scope of this instantiation. We don't use
2570 // PushDeclContext because we don't have a scope.
2571 Sema::ContextRAII savedContext(*this, Decl);
2572 LocalInstantiationScope Scope(*this);
2573
2574 MultiLevelTemplateArgumentList TemplateArgs =
2575 getTemplateInstantiationArgs(Decl, 0, /*RelativeToPrimary*/true);
2576
Richard Smith13bffc52012-04-19 00:08:28 +00002577 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
2578 addInstantiatedParametersToScope(*this, Decl, Template, Scope, TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002579
Richard Smith13bffc52012-04-19 00:08:28 +00002580 ::InstantiateExceptionSpec(*this, Decl,
2581 Template->getType()->castAs<FunctionProtoType>(),
2582 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +00002583}
2584
Mike Stump1eb44332009-09-09 15:08:12 +00002585/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002586/// declaration (New) from the corresponding fields of its template (Tmpl).
2587///
2588/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002589bool
2590TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002591 FunctionDecl *Tmpl) {
David Blaikie85f485a2012-07-16 18:50:45 +00002592 if (Tmpl->isDeleted())
Sean Hunt10620eb2011-05-06 20:44:56 +00002593 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002594
Douglas Gregorcca9e962009-07-01 22:01:06 +00002595 // If we are performing substituting explicitly-specified template arguments
2596 // or deduced template arguments into a function template and we reach this
2597 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002598 // to keeping the new function template specialization. We therefore
2599 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002600 // into a template instantiation for this specific function template
2601 // specialization, which is not a SFINAE context, so that we diagnose any
2602 // further errors in the declaration itself.
2603 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2604 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2605 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2606 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002607 if (FunctionTemplateDecl *FunTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002608 = dyn_cast<FunctionTemplateDecl>(ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002609 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002610 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002611 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002612 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +00002613 ActiveInst.Entity = New;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002614 }
2615 }
Mike Stump1eb44332009-09-09 15:08:12 +00002616
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002617 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2618 assert(Proto && "Function template without prototype?");
2619
Sebastian Redl60618fa2011-03-12 11:50:43 +00002620 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
John McCalle23cf432010-12-14 08:05:40 +00002621 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
John McCalle23cf432010-12-14 08:05:40 +00002622
Richard Smithe6975e92012-04-17 00:58:00 +00002623 // DR1330: In C++11, defer instantiation of a non-trivial
2624 // exception specification.
2625 if (SemaRef.getLangOpts().CPlusPlus0x &&
2626 EPI.ExceptionSpecType != EST_None &&
2627 EPI.ExceptionSpecType != EST_DynamicNone &&
2628 EPI.ExceptionSpecType != EST_BasicNoexcept) {
Richard Smith13bffc52012-04-19 00:08:28 +00002629 FunctionDecl *ExceptionSpecTemplate = Tmpl;
2630 if (EPI.ExceptionSpecType == EST_Uninstantiated)
2631 ExceptionSpecTemplate = EPI.ExceptionSpecTemplate;
Richard Smithb9d0b762012-07-27 04:22:15 +00002632 assert(EPI.ExceptionSpecType != EST_Unevaluated &&
2633 "instantiating implicitly-declared special member");
Richard Smith13bffc52012-04-19 00:08:28 +00002634
Richard Smithe6975e92012-04-17 00:58:00 +00002635 // Mark the function has having an uninstantiated exception specification.
2636 const FunctionProtoType *NewProto
2637 = New->getType()->getAs<FunctionProtoType>();
2638 assert(NewProto && "Template instantiation without function prototype?");
2639 EPI = NewProto->getExtProtoInfo();
2640 EPI.ExceptionSpecType = EST_Uninstantiated;
2641 EPI.ExceptionSpecDecl = New;
Richard Smith13bffc52012-04-19 00:08:28 +00002642 EPI.ExceptionSpecTemplate = ExceptionSpecTemplate;
Richard Smithe6975e92012-04-17 00:58:00 +00002643 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2644 NewProto->arg_type_begin(),
2645 NewProto->getNumArgs(),
2646 EPI));
2647 } else {
2648 ::InstantiateExceptionSpec(SemaRef, New, Proto, TemplateArgs);
2649 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002650 }
2651
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002652 // Get the definition. Leaves the variable unchanged if undefined.
Richard Smithe6975e92012-04-17 00:58:00 +00002653 const FunctionDecl *Definition = Tmpl;
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002654 Tmpl->isDefined(Definition);
2655
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002656 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
2657 LateAttrs, StartingScope);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002658
Douglas Gregore53060f2009-06-25 22:08:12 +00002659 return false;
2660}
2661
Douglas Gregor5545e162009-03-24 00:38:23 +00002662/// \brief Initializes common fields of an instantiated method
2663/// declaration (New) from the corresponding fields of its template
2664/// (Tmpl).
2665///
2666/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002667bool
2668TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002669 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002670 if (InitFunctionInstantiation(New, Tmpl))
2671 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002672
Douglas Gregor5545e162009-03-24 00:38:23 +00002673 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002674 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002675 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002676
2677 // FIXME: attributes
2678 // FIXME: New needs a pointer to Tmpl
2679 return false;
2680}
Douglas Gregora58861f2009-05-13 20:28:22 +00002681
2682/// \brief Instantiate the definition of the given function from its
2683/// template.
2684///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002685/// \param PointOfInstantiation the point at which the instantiation was
2686/// required. Note that this is not precisely a "point of instantiation"
2687/// for the function, but it's close.
2688///
Douglas Gregora58861f2009-05-13 20:28:22 +00002689/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002690/// function template specialization or member function of a class template
2691/// specialization.
2692///
2693/// \param Recursive if true, recursively instantiates any functions that
2694/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002695///
2696/// \param DefinitionRequired if true, then we are performing an explicit
2697/// instantiation where the body of the function is required. Complain if
2698/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002699void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002700 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002701 bool Recursive,
2702 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002703 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002704 return;
2705
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002706 // Never instantiate an explicit specialization except if it is a class scope
2707 // explicit specialization.
2708 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2709 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002710 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002711
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002712 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002713 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00002714 assert(PatternDecl && "instantiating a non-template");
2715
2716 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2717 assert(PatternDecl && "template definition is not a template");
2718 if (!Pattern) {
2719 // Try to find a defaulted definition
2720 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00002721 }
Sean Huntf996e052011-05-27 20:00:14 +00002722 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002723
Francois Pichet8387e2a2011-04-22 22:18:13 +00002724 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00002725 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00002726 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00002727 PendingInstantiations.push_back(
2728 std::make_pair(Function, PointOfInstantiation));
2729 return;
2730 }
2731
2732 // Call the LateTemplateParser callback if there a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002733 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00002734 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00002735 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002736 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002737 Pattern = PatternDecl->getBody(PatternDecl);
2738 }
2739
Sean Huntf996e052011-05-27 20:00:14 +00002740 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002741 if (DefinitionRequired) {
2742 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002743 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002744 diag::err_explicit_instantiation_undefined_func_template)
2745 << Function->getPrimaryTemplate();
2746 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002747 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002748 diag::err_explicit_instantiation_undefined_member)
2749 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002750
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002751 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002752 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002753 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002754 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002755 } else if (Function->getTemplateSpecializationKind()
2756 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002757 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002758 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002759 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002760
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002761 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002762 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002763
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002764 // C++0x [temp.explicit]p9:
2765 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002766 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002767 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002768 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002769 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002770 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002771 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002772
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002773 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2774 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002775 return;
2776
Abramo Bagnarae9946242011-11-18 08:08:52 +00002777 // Copy the inner loc start from the pattern.
2778 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2779
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002780 // If we're performing recursive template instantiation, create our own
2781 // queue of pending implicit instantiations that we will instantiate later,
2782 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002783 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002784 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002785 if (Recursive) {
2786 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002787 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002788 }
Mike Stump1eb44332009-09-09 15:08:12 +00002789
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002790 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002791 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002792 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002793
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002794 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002795 // recorded, unless we're actually a member function within a local
2796 // class, in which case we need to merge our results with the parent
2797 // scope (of the enclosing function).
2798 bool MergeWithParentScope = false;
2799 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2800 MergeWithParentScope = Rec->isLocalClass();
2801
2802 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002803
Richard Smith7c5d28b2012-03-13 06:56:52 +00002804 // Enter the scope of this instantiation. We don't use
2805 // PushDeclContext because we don't have a scope.
2806 Sema::ContextRAII savedContext(*this, Function);
2807
2808 MultiLevelTemplateArgumentList TemplateArgs =
2809 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
2810
Richard Smithe6975e92012-04-17 00:58:00 +00002811 addInstantiatedParametersToScope(*this, Function, PatternDecl, Scope,
2812 TemplateArgs);
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002813
Sean Huntcd10dec2011-05-23 23:14:04 +00002814 if (PatternDecl->isDefaulted()) {
2815 ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2816
2817 SetDeclDefaulted(Function, PatternDecl->getLocation());
Sean Huntcd10dec2011-05-23 23:14:04 +00002818 } else {
2819 // If this is a constructor, instantiate the member initializers.
2820 if (const CXXConstructorDecl *Ctor =
2821 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2822 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2823 TemplateArgs);
2824 }
2825
2826 // Instantiate the function body.
2827 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2828
2829 if (Body.isInvalid())
2830 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002831
Sean Huntcd10dec2011-05-23 23:14:04 +00002832 ActOnFinishFunctionBody(Function, Body.get(),
2833 /*IsInstantiation=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002834 }
2835
John McCall0c01d182010-03-24 05:22:00 +00002836 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2837
John McCalleee1d542011-02-14 07:13:47 +00002838 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002839
2840 DeclGroupRef DG(Function);
2841 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Douglas Gregor60406be2010-01-16 22:29:39 +00002843 // This class may have local implicit instantiations that need to be
2844 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002845 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002846 Scope.Exit();
2847
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002848 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002849 // Define any pending vtables.
2850 DefineUsedVTables();
2851
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002852 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002853 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002854 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002856 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00002857 assert(VTableUses.empty() &&
2858 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002859 VTableUses.swap(SavedVTableUses);
2860
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002861 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00002862 assert(PendingInstantiations.empty() &&
2863 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00002864 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002865 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002866}
2867
2868/// \brief Instantiate the definition of the given variable from its
2869/// template.
2870///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002871/// \param PointOfInstantiation the point at which the instantiation was
2872/// required. Note that this is not precisely a "point of instantiation"
2873/// for the function, but it's close.
2874///
2875/// \param Var the already-instantiated declaration of a static member
2876/// variable of a class template specialization.
2877///
2878/// \param Recursive if true, recursively instantiates any functions that
2879/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002880///
2881/// \param DefinitionRequired if true, then we are performing an explicit
2882/// instantiation where an out-of-line definition of the member variable
2883/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002884void Sema::InstantiateStaticDataMemberDefinition(
2885 SourceLocation PointOfInstantiation,
2886 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002887 bool Recursive,
2888 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002889 if (Var->isInvalidDecl())
2890 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002891
Douglas Gregor7caa6822009-07-24 20:34:43 +00002892 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002893 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002894 assert(Def && "This data member was not instantiated from a template?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002895 assert(Def->isStaticDataMember() && "Not a static data member?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002896 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002897
Douglas Gregor0d035142009-10-27 18:42:08 +00002898 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002899 // We did not find an out-of-line definition of this static data member,
2900 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002901 // instantiate this definition (or provide a specialization for it) in
2902 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002903 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002904 Def = Var->getInstantiatedFromStaticDataMember();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002905 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002906 diag::err_explicit_instantiation_undefined_member)
2907 << 2 << Var->getDeclName() << Var->getDeclContext();
2908 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002909 } else if (Var->getTemplateSpecializationKind()
2910 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002911 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002912 std::make_pair(Var, PointOfInstantiation));
2913 }
2914
Douglas Gregor7caa6822009-07-24 20:34:43 +00002915 return;
2916 }
2917
Rafael Espindola234fe652012-03-05 10:54:55 +00002918 TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
2919
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002920 // Never instantiate an explicit specialization.
Rafael Espindola234fe652012-03-05 10:54:55 +00002921 if (TSK == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002922 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002923
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002924 // C++0x [temp.explicit]p9:
2925 // Except for inline functions, other explicit instantiation declarations
2926 // have the effect of suppressing the implicit instantiation of the entity
2927 // to which they refer.
Rafael Espindola234fe652012-03-05 10:54:55 +00002928 if (TSK == TSK_ExplicitInstantiationDeclaration)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002929 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002930
Rafael Espindola02503932012-03-08 15:51:03 +00002931 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
2932
Douglas Gregorf15748a2011-06-03 03:35:07 +00002933 // If we already have a definition, we're done.
Nick Lewycky95e38722012-04-04 02:38:36 +00002934 if (VarDecl *Def = Var->getDefinition()) {
2935 // We may be explicitly instantiating something we've already implicitly
2936 // instantiated.
2937 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
2938 PointOfInstantiation);
Douglas Gregorf15748a2011-06-03 03:35:07 +00002939 return;
Nick Lewycky95e38722012-04-04 02:38:36 +00002940 }
Douglas Gregorf15748a2011-06-03 03:35:07 +00002941
Douglas Gregor7caa6822009-07-24 20:34:43 +00002942 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2943 if (Inst)
2944 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002945
Douglas Gregor7caa6822009-07-24 20:34:43 +00002946 // If we're performing recursive template instantiation, create our own
2947 // queue of pending implicit instantiations that we will instantiate later,
2948 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002949 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002950 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00002951 if (Recursive) {
2952 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002953 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00002954 }
Mike Stump1eb44332009-09-09 15:08:12 +00002955
Douglas Gregor7caa6822009-07-24 20:34:43 +00002956 // Enter the scope of this instantiation. We don't use
2957 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002958 ContextRAII previousContext(*this, Var->getDeclContext());
Douglas Gregor7bdc1522012-02-16 21:36:18 +00002959 LocalInstantiationScope Local(*this);
2960
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002961 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002962 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002963 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002964
2965 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002966
2967 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002968 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2969 assert(MSInfo && "Missing member specialization information?");
2970 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2971 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002972 DeclGroupRef DG(Var);
2973 Consumer.HandleTopLevelDecl(DG);
2974 }
Douglas Gregor7bdc1522012-02-16 21:36:18 +00002975 Local.Exit();
2976
Douglas Gregor7caa6822009-07-24 20:34:43 +00002977 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00002978 // Define any newly required vtables.
2979 DefineUsedVTables();
2980
Douglas Gregor7caa6822009-07-24 20:34:43 +00002981 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002982 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002983 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002984
Nick Lewycky81559102011-05-31 07:58:42 +00002985 // Restore the set of pending vtables.
2986 assert(VTableUses.empty() &&
2987 "VTableUses should be empty before it is discarded, "
2988 "while instantiating static data member.");
2989 VTableUses.swap(SavedVTableUses);
2990
Douglas Gregor7caa6822009-07-24 20:34:43 +00002991 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00002992 assert(PendingInstantiations.empty() &&
2993 "PendingInstantiations should be empty before it is discarded, "
2994 "while instantiating static data member.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00002995 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002996 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002997}
Douglas Gregor815215d2009-05-27 05:35:12 +00002998
Anders Carlsson09025312009-08-29 05:16:22 +00002999void
3000Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
3001 const CXXConstructorDecl *Tmpl,
3002 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Richard Trieu90ab75b2011-09-09 03:18:59 +00003004 SmallVector<CXXCtorInitializer*, 4> NewInits;
Richard Smith54b3ba82012-09-25 00:23:05 +00003005 bool AnyErrors = Tmpl->isInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003006
Anders Carlsson09025312009-08-29 05:16:22 +00003007 // Instantiate all the initializers.
3008 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00003009 InitsEnd = Tmpl->init_end();
3010 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00003011 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00003012
Chandler Carruth030ef472010-09-03 21:54:20 +00003013 // Only instantiate written initializers, let Sema re-construct implicit
3014 // ones.
3015 if (!Init->isWritten())
3016 continue;
3017
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003018 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003019
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003020 if (Init->isPackExpansion()) {
3021 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00003022 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003023 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003024 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
3025 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00003026 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00003027 llvm::Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003028 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003029 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00003030 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003031 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00003032 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003033 NumExpansions)) {
3034 AnyErrors = true;
3035 New->setInvalidDecl();
3036 continue;
3037 }
3038 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003039
3040 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00003041 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003042 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3043
3044 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003045 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3046 /*CXXDirectInit=*/true);
3047 if (TempInit.isInvalid()) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003048 AnyErrors = true;
3049 break;
3050 }
3051
3052 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00003053 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003054 TemplateArgs,
3055 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003056 New->getDeclName());
3057 if (!BaseTInfo) {
3058 AnyErrors = true;
3059 break;
3060 }
3061
3062 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00003063 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003064 BaseTInfo, TempInit.take(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003065 New->getParent(),
3066 SourceLocation());
3067 if (NewInit.isInvalid()) {
3068 AnyErrors = true;
3069 break;
3070 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003071
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003072 NewInits.push_back(NewInit.get());
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003073 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003074
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00003075 continue;
3076 }
3077
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003078 // Instantiate the initializer.
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003079 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
3080 /*CXXDirectInit=*/true);
3081 if (TempInit.isInvalid()) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00003082 AnyErrors = true;
3083 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00003084 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003085
Anders Carlsson09025312009-08-29 05:16:22 +00003086 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00003087 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
3088 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
3089 TemplateArgs,
3090 Init->getSourceLocation(),
3091 New->getDeclName());
3092 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003093 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00003094 New->setInvalidDecl();
3095 continue;
3096 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003097
Douglas Gregor76852c22011-11-01 01:16:03 +00003098 if (Init->isBaseInitializer())
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003099 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003100 New->getParent(), EllipsisLoc);
3101 else
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003102 NewInit = BuildDelegatingInitializer(TInfo, TempInit.take(),
Douglas Gregor76852c22011-11-01 01:16:03 +00003103 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00003104 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00003105 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003106 Init->getMemberLocation(),
3107 Init->getMember(),
3108 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00003109 if (!Member) {
3110 AnyErrors = true;
3111 New->setInvalidDecl();
3112 continue;
3113 }
Mike Stump1eb44332009-09-09 15:08:12 +00003114
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003115 NewInit = BuildMemberInitializer(Member, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003116 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00003117 } else if (Init->isIndirectMemberInitializer()) {
3118 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00003119 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00003120 Init->getMemberLocation(),
3121 Init->getIndirectMember(), TemplateArgs));
3122
Douglas Gregorb7107222011-03-04 19:46:35 +00003123 if (!IndirectMember) {
3124 AnyErrors = true;
3125 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00003126 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00003127 }
Sebastian Redl6df65482011-09-24 17:48:25 +00003128
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003129 NewInit = BuildMemberInitializer(IndirectMember, TempInit.take(),
Sebastian Redl6df65482011-09-24 17:48:25 +00003130 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00003131 }
3132
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003133 if (NewInit.isInvalid()) {
3134 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00003135 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003136 } else {
Richard Trieu90ab75b2011-09-09 03:18:59 +00003137 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00003138 }
3139 }
Mike Stump1eb44332009-09-09 15:08:12 +00003140
Anders Carlsson09025312009-08-29 05:16:22 +00003141 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00003142 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00003143 /*FIXME: ColonLoc */
3144 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00003145 NewInits.data(), NewInits.size(),
3146 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00003147}
3148
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003149ExprResult Sema::SubstInitializer(Expr *Init,
3150 const MultiLevelTemplateArgumentList &TemplateArgs,
3151 bool CXXDirectInit) {
3152 // Initializers are instantiated like expressions, except that various outer
3153 // layers are stripped.
3154 if (!Init)
3155 return Owned(Init);
3156
3157 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
3158 Init = ExprTemp->getSubExpr();
3159
3160 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
3161 Init = Binder->getSubExpr();
3162
3163 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
3164 Init = ICE->getSubExprAsWritten();
3165
3166 // If this is a direct-initializer, we take apart CXXConstructExprs.
3167 // Everything else is passed through.
3168 CXXConstructExpr *Construct;
3169 if (!CXXDirectInit || !(Construct = dyn_cast<CXXConstructExpr>(Init)) ||
3170 isa<CXXTemporaryObjectExpr>(Construct))
3171 return SubstExpr(Init, TemplateArgs);
3172
Benjamin Kramer4e28d9e2012-08-23 22:51:59 +00003173 SmallVector<Expr*, 8> NewArgs;
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003174 if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
3175 TemplateArgs, NewArgs))
3176 return ExprError();
3177
3178 // Treat an empty initializer like none.
3179 if (NewArgs.empty())
3180 return Owned((Expr*)0);
3181
3182 // Build a ParenListExpr to represent anything else.
3183 // FIXME: Fake locations!
3184 SourceLocation Loc = PP.getLocForEndOfToken(Init->getLocStart());
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00003185 return ActOnParenListExpr(Loc, Loc, NewArgs);
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003186}
3187
John McCall52a575a2009-08-29 08:11:13 +00003188// TODO: this could be templated if the various decl types used the
3189// same method name.
3190static bool isInstantiationOf(ClassTemplateDecl *Pattern,
3191 ClassTemplateDecl *Instance) {
3192 Pattern = Pattern->getCanonicalDecl();
3193
3194 do {
3195 Instance = Instance->getCanonicalDecl();
3196 if (Pattern == Instance) return true;
3197 Instance = Instance->getInstantiatedFromMemberTemplate();
3198 } while (Instance);
3199
3200 return false;
3201}
3202
Douglas Gregor0d696532009-09-28 06:34:35 +00003203static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
3204 FunctionTemplateDecl *Instance) {
3205 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003206
Douglas Gregor0d696532009-09-28 06:34:35 +00003207 do {
3208 Instance = Instance->getCanonicalDecl();
3209 if (Pattern == Instance) return true;
3210 Instance = Instance->getInstantiatedFromMemberTemplate();
3211 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003212
Douglas Gregor0d696532009-09-28 06:34:35 +00003213 return false;
3214}
3215
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003216static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00003217isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
3218 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003219 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00003220 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
3221 do {
3222 Instance = cast<ClassTemplatePartialSpecializationDecl>(
3223 Instance->getCanonicalDecl());
3224 if (Pattern == Instance)
3225 return true;
3226 Instance = Instance->getInstantiatedFromMember();
3227 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003228
Douglas Gregored9c0f92009-10-29 00:04:11 +00003229 return false;
3230}
3231
John McCall52a575a2009-08-29 08:11:13 +00003232static bool isInstantiationOf(CXXRecordDecl *Pattern,
3233 CXXRecordDecl *Instance) {
3234 Pattern = Pattern->getCanonicalDecl();
3235
3236 do {
3237 Instance = Instance->getCanonicalDecl();
3238 if (Pattern == Instance) return true;
3239 Instance = Instance->getInstantiatedFromMemberClass();
3240 } while (Instance);
3241
3242 return false;
3243}
3244
3245static bool isInstantiationOf(FunctionDecl *Pattern,
3246 FunctionDecl *Instance) {
3247 Pattern = Pattern->getCanonicalDecl();
3248
3249 do {
3250 Instance = Instance->getCanonicalDecl();
3251 if (Pattern == Instance) return true;
3252 Instance = Instance->getInstantiatedFromMemberFunction();
3253 } while (Instance);
3254
3255 return false;
3256}
3257
3258static bool isInstantiationOf(EnumDecl *Pattern,
3259 EnumDecl *Instance) {
3260 Pattern = Pattern->getCanonicalDecl();
3261
3262 do {
3263 Instance = Instance->getCanonicalDecl();
3264 if (Pattern == Instance) return true;
3265 Instance = Instance->getInstantiatedFromMemberEnum();
3266 } while (Instance);
3267
3268 return false;
3269}
3270
John McCalled976492009-12-04 22:46:56 +00003271static bool isInstantiationOf(UsingShadowDecl *Pattern,
3272 UsingShadowDecl *Instance,
3273 ASTContext &C) {
3274 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
3275}
3276
3277static bool isInstantiationOf(UsingDecl *Pattern,
3278 UsingDecl *Instance,
3279 ASTContext &C) {
3280 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
3281}
3282
John McCall7ba107a2009-11-18 02:36:19 +00003283static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
3284 UsingDecl *Instance,
3285 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003286 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003287}
3288
3289static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003290 UsingDecl *Instance,
3291 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003292 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003293}
3294
John McCall52a575a2009-08-29 08:11:13 +00003295static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3296 VarDecl *Instance) {
3297 assert(Instance->isStaticDataMember());
3298
3299 Pattern = Pattern->getCanonicalDecl();
3300
3301 do {
3302 Instance = Instance->getCanonicalDecl();
3303 if (Pattern == Instance) return true;
3304 Instance = Instance->getInstantiatedFromStaticDataMember();
3305 } while (Instance);
3306
3307 return false;
3308}
3309
John McCalled976492009-12-04 22:46:56 +00003310// Other is the prospective instantiation
3311// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003312static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003313 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003314 if (UnresolvedUsingTypenameDecl *UUD
3315 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3316 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3317 return isInstantiationOf(UUD, UD, Ctx);
3318 }
3319 }
3320
3321 if (UnresolvedUsingValueDecl *UUD
3322 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003323 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3324 return isInstantiationOf(UUD, UD, Ctx);
3325 }
3326 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003327
Anders Carlsson0d8df782009-08-29 19:37:28 +00003328 return false;
3329 }
Mike Stump1eb44332009-09-09 15:08:12 +00003330
John McCall52a575a2009-08-29 08:11:13 +00003331 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3332 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003333
John McCall52a575a2009-08-29 08:11:13 +00003334 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3335 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003336
John McCall52a575a2009-08-29 08:11:13 +00003337 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3338 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003339
Douglas Gregor7caa6822009-07-24 20:34:43 +00003340 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003341 if (Var->isStaticDataMember())
3342 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3343
3344 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3345 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003346
Douglas Gregor0d696532009-09-28 06:34:35 +00003347 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3348 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3349
Douglas Gregored9c0f92009-10-29 00:04:11 +00003350 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3351 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3352 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3353 PartialSpec);
3354
Anders Carlssond8b285f2009-09-01 04:26:58 +00003355 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3356 if (!Field->getDeclName()) {
3357 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00003358 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00003359 cast<FieldDecl>(D);
3360 }
3361 }
Mike Stump1eb44332009-09-09 15:08:12 +00003362
John McCalled976492009-12-04 22:46:56 +00003363 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3364 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3365
3366 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3367 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3368
Douglas Gregor815215d2009-05-27 05:35:12 +00003369 return D->getDeclName() && isa<NamedDecl>(Other) &&
3370 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3371}
3372
3373template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00003374static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00003375 NamedDecl *D,
3376 ForwardIterator first,
3377 ForwardIterator last) {
3378 for (; first != last; ++first)
3379 if (isInstantiationOf(Ctx, D, *first))
3380 return cast<NamedDecl>(*first);
3381
3382 return 0;
3383}
3384
John McCall02cace72009-08-28 07:59:38 +00003385/// \brief Finds the instantiation of the given declaration context
3386/// within the current instantiation.
3387///
3388/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003389DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00003390 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00003391 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003392 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00003393 return cast_or_null<DeclContext>(ID);
3394 } else return DC;
3395}
3396
Douglas Gregored961e72009-05-27 17:54:46 +00003397/// \brief Find the instantiation of the given declaration within the
3398/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00003399///
3400/// This routine is intended to be used when \p D is a declaration
3401/// referenced from within a template, that needs to mapped into the
3402/// corresponding declaration within an instantiation. For example,
3403/// given:
3404///
3405/// \code
3406/// template<typename T>
3407/// struct X {
3408/// enum Kind {
3409/// KnownValue = sizeof(T)
3410/// };
3411///
3412/// bool getKind() const { return KnownValue; }
3413/// };
3414///
3415/// template struct X<int>;
3416/// \endcode
3417///
3418/// In the instantiation of X<int>::getKind(), we need to map the
3419/// EnumConstantDecl for KnownValue (which refers to
James Dennettf198d122012-06-17 03:36:08 +00003420/// X<T>::\<Kind>\::KnownValue) to its instantiation
James Dennettef2b5b32012-06-15 22:23:43 +00003421/// (X<int>::\<Kind>\::KnownValue). InstantiateCurrentDeclRef() performs
Douglas Gregored961e72009-05-27 17:54:46 +00003422/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003423NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00003424 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00003425 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00003426 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00003427 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor7bdc1522012-02-16 21:36:18 +00003428 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext()) ||
3429 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003430 // D is a local of some kind. Look into the map of local
3431 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00003432 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3433 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3434 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003435
Chris Lattner57ad3782011-02-17 20:34:02 +00003436 if (Found) {
3437 if (Decl *FD = Found->dyn_cast<Decl *>())
3438 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003439
Richard Smith9a4db032012-09-12 00:56:43 +00003440 int PackIdx = ArgumentPackSubstitutionIndex;
3441 assert(PackIdx != -1 && "found declaration pack but not pack expanding");
Chris Lattner57ad3782011-02-17 20:34:02 +00003442 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3443 }
3444
3445 // If we didn't find the decl, then we must have a label decl that hasn't
3446 // been found yet. Lazily instantiate it and return it now.
3447 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003448
Chris Lattner57ad3782011-02-17 20:34:02 +00003449 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3450 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003451
Chris Lattner57ad3782011-02-17 20:34:02 +00003452 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3453 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003454 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003455
Douglas Gregore95b4092009-09-16 18:34:49 +00003456 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3457 if (!Record->isDependentContext())
3458 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003459
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003460 // Determine whether this record is the "templated" declaration describing
3461 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00003462 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003463 if (ClassTemplate)
3464 ClassTemplate = ClassTemplate->getCanonicalDecl();
3465 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3466 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3467 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3468
3469 // Walk the current context to find either the record or an instantiation of
3470 // it.
3471 DeclContext *DC = CurContext;
3472 while (!DC->isFileContext()) {
3473 // If we're performing substitution while we're inside the template
3474 // definition, we'll find our own context. We're done.
3475 if (DC->Equals(Record))
3476 return Record;
3477
3478 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3479 // Check whether we're in the process of instantiating a class template
3480 // specialization of the template we're mapping.
3481 if (ClassTemplateSpecializationDecl *InstSpec
3482 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3483 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3484 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3485 return InstRecord;
3486 }
3487
3488 // Check whether we're in the process of instantiating a member class.
3489 if (isInstantiationOf(Record, InstRecord))
3490 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00003491 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003492
3493
3494 // Move to the outer template scope.
3495 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3496 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3497 DC = FD->getLexicalDeclContext();
3498 continue;
3499 }
John McCall52a575a2009-08-29 08:11:13 +00003500 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003501
3502 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00003503 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003504
Douglas Gregore95b4092009-09-16 18:34:49 +00003505 // Fall through to deal with other dependent record types (e.g.,
3506 // anonymous unions in class templates).
3507 }
John McCall52a575a2009-08-29 08:11:13 +00003508
Douglas Gregore95b4092009-09-16 18:34:49 +00003509 if (!ParentDC->isDependentContext())
3510 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003511
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003512 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003513 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003514 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003515
Douglas Gregor815215d2009-05-27 05:35:12 +00003516 if (ParentDC != D->getDeclContext()) {
3517 // We performed some kind of instantiation in the parent context,
3518 // so now we need to look into the instantiated parent context to
3519 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003520
John McCall3cb0ebd2010-03-10 03:28:59 +00003521 // If our context used to be dependent, we may need to instantiate
3522 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003523 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003524 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003525 if (!Spec->isDependentContext()) {
3526 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003527 const RecordType *Tag = T->getAs<RecordType>();
3528 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003529 if (Tag->isBeingDefined())
3530 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003531 if (!Tag->isBeingDefined() &&
3532 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3533 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003534
3535 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003536 }
3537 }
3538
Douglas Gregor815215d2009-05-27 05:35:12 +00003539 NamedDecl *Result = 0;
3540 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003541 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003542 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3543 } else {
3544 // Since we don't have a name for the entity we're looking for,
3545 // our only option is to walk through all of the declarations to
3546 // find that name. This will occur in a few cases:
3547 //
3548 // - anonymous struct/union within a template
3549 // - unnamed class/struct/union/enum within a template
3550 //
3551 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003552 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003553 ParentDC->decls_begin(),
3554 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003555 }
Mike Stump1eb44332009-09-09 15:08:12 +00003556
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003557 if (!Result) {
3558 if (isa<UsingShadowDecl>(D)) {
3559 // UsingShadowDecls can instantiate to nothing because of using hiding.
3560 } else if (Diags.hasErrorOccurred()) {
3561 // We've already complained about something, so most likely this
3562 // declaration failed to instantiate. There's no point in complaining
3563 // further, since this is normal in invalid code.
3564 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003565 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003566 // instantiated, and we haven't gotten around to instantiating this
3567 // member yet. This can happen when the code uses forward declarations
3568 // of member classes, and introduces ordering dependencies via
3569 // template instantiation.
3570 Diag(Loc, diag::err_member_not_yet_instantiated)
3571 << D->getDeclName()
3572 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3573 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
Richard Smith0724b7c2012-03-26 20:28:16 +00003574 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
3575 // This enumeration constant was found when the template was defined,
3576 // but can't be found in the instantiation. This can happen if an
3577 // unscoped enumeration member is explicitly specialized.
3578 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
3579 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
3580 TemplateArgs));
3581 assert(Spec->getTemplateSpecializationKind() ==
3582 TSK_ExplicitSpecialization);
3583 Diag(Loc, diag::err_enumerator_does_not_exist)
3584 << D->getDeclName()
3585 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
3586 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
3587 << Context.getTypeDeclType(Spec);
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003588 } else {
3589 // We should have found something, but didn't.
3590 llvm_unreachable("Unable to find instantiation of declaration!");
3591 }
3592 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003593
Douglas Gregor815215d2009-05-27 05:35:12 +00003594 D = Result;
3595 }
3596
Douglas Gregor815215d2009-05-27 05:35:12 +00003597 return D;
3598}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003599
Mike Stump1eb44332009-09-09 15:08:12 +00003600/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003601/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00003602void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003603 // Load pending instantiations from the external source.
3604 if (!LocalOnly && ExternalSource) {
Richard Smithb9d0b762012-07-27 04:22:15 +00003605 SmallVector<PendingImplicitInstantiation, 4> Pending;
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003606 ExternalSource->ReadPendingInstantiations(Pending);
3607 PendingInstantiations.insert(PendingInstantiations.begin(),
3608 Pending.begin(), Pending.end());
3609 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003610
Douglas Gregor60406be2010-01-16 22:29:39 +00003611 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003612 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003613 PendingImplicitInstantiation Inst;
3614
3615 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003616 Inst = PendingInstantiations.front();
3617 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003618 } else {
3619 Inst = PendingLocalImplicitInstantiations.front();
3620 PendingLocalImplicitInstantiations.pop_front();
3621 }
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Douglas Gregor7caa6822009-07-24 20:34:43 +00003623 // Instantiate function definitions
3624 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003625 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3626 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003627 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3628 TSK_ExplicitInstantiationDefinition;
3629 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3630 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003631 continue;
3632 }
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Douglas Gregor7caa6822009-07-24 20:34:43 +00003634 // Instantiate static data member definitions.
3635 VarDecl *Var = cast<VarDecl>(Inst.first);
3636 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003637
Chandler Carruth291b4412010-02-13 10:17:50 +00003638 // Don't try to instantiate declarations if the most recent redeclaration
3639 // is invalid.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003640 if (Var->getMostRecentDecl()->isInvalidDecl())
Chandler Carruth291b4412010-02-13 10:17:50 +00003641 continue;
3642
3643 // Check if the most recent declaration has changed the specialization kind
3644 // and removed the need for implicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003645 switch (Var->getMostRecentDecl()->getTemplateSpecializationKind()) {
Chandler Carruth291b4412010-02-13 10:17:50 +00003646 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00003647 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00003648 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003649 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003650 continue; // No longer need to instantiate this type.
3651 case TSK_ExplicitInstantiationDefinition:
3652 // We only need an instantiation if the pending instantiation *is* the
3653 // explicit instantiation.
Douglas Gregoref96ee02012-01-14 16:38:05 +00003654 if (Var != Var->getMostRecentDecl()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003655 case TSK_ImplicitInstantiation:
3656 break;
3657 }
3658
John McCallf312b1e2010-08-26 23:41:50 +00003659 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3660 "instantiating static data member "
3661 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003662
Chandler Carruth58e390e2010-08-25 08:27:02 +00003663 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3664 TSK_ExplicitInstantiationDefinition;
3665 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3666 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003667 }
3668}
John McCall0c01d182010-03-24 05:22:00 +00003669
3670void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3671 const MultiLevelTemplateArgumentList &TemplateArgs) {
3672 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3673 E = Pattern->ddiag_end(); I != E; ++I) {
3674 DependentDiagnostic *DD = *I;
3675
3676 switch (DD->getKind()) {
3677 case DependentDiagnostic::Access:
3678 HandleDependentAccessCheck(*DD, TemplateArgs);
3679 break;
3680 }
3681 }
3682}