blob: 123548e656528ce9229a760e837b30d220790960 [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 Gregore737f502010-08-12 20:07:10 +000013#include "clang/Sema/Lookup.h"
John McCallf312b1e2010-08-26 23:41:50 +000014#include "clang/Sema/PrettyDeclStackTrace.h"
John McCall7cd088e2010-08-24 07:21:54 +000015#include "clang/Sema/Template.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000016#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000020#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000021#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000022#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000023#include "clang/AST/TypeLoc.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000024#include "clang/Lex/Preprocessor.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
Chandler Carruth4ced79f2010-06-25 03:22:07 +000060// FIXME: Is this still too simple?
John McCall1d8d1cc2010-08-01 02:01:53 +000061void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
Rafael Espindola19f74ac2011-07-06 15:46:09 +000062 const Decl *Tmpl, Decl *New) {
Sean Huntcf807c42010-08-18 23:23:40 +000063 for (AttrVec::const_iterator i = Tmpl->attr_begin(), e = Tmpl->attr_end();
64 i != e; ++i) {
65 const Attr *TmplAttr = *i;
Chandler Carruth4ced79f2010-06-25 03:22:07 +000066 // FIXME: This should be generalized to more than just the AlignedAttr.
67 if (const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr)) {
Sean Huntcf807c42010-08-18 23:23:40 +000068 if (Aligned->isAlignmentDependent()) {
Chandler Carruth4ced79f2010-06-25 03:22:07 +000069 // The alignment expression is not potentially evaluated.
John McCall1d8d1cc2010-08-01 02:01:53 +000070 EnterExpressionEvaluationContext Unevaluated(*this,
John McCallf312b1e2010-08-26 23:41:50 +000071 Sema::Unevaluated);
Chandler Carruth4ced79f2010-06-25 03:22:07 +000072
Sean Huntcf807c42010-08-18 23:23:40 +000073 if (Aligned->isAlignmentExpr()) {
John McCall60d7b3a2010-08-24 06:29:42 +000074 ExprResult Result = SubstExpr(Aligned->getAlignmentExpr(),
Nick Lewycky7663f392010-11-20 01:29:55 +000075 TemplateArgs);
Sean Huntcf807c42010-08-18 23:23:40 +000076 if (!Result.isInvalid())
77 AddAlignedAttr(Aligned->getLocation(), New, Result.takeAs<Expr>());
78 }
79 else {
80 TypeSourceInfo *Result = SubstType(Aligned->getAlignmentType(),
Nick Lewycky7663f392010-11-20 01:29:55 +000081 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +000082 Aligned->getLocation(),
Nick Lewycky7663f392010-11-20 01:29:55 +000083 DeclarationName());
Sean Huntcf807c42010-08-18 23:23:40 +000084 if (Result)
85 AddAlignedAttr(Aligned->getLocation(), New, Result);
86 }
Chandler Carruth4ced79f2010-06-25 03:22:07 +000087 continue;
88 }
89 }
90
Anders Carlssond8fe2d52009-11-07 06:07:58 +000091 // FIXME: Is cloning correct for all attributes?
John McCall1d8d1cc2010-08-01 02:01:53 +000092 Attr *NewAttr = TmplAttr->clone(Context);
Anders Carlssond8fe2d52009-11-07 06:07:58 +000093 New->addAttr(NewAttr);
94 }
95}
96
Douglas Gregor4f722be2009-03-25 15:45:12 +000097Decl *
98TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +000099 llvm_unreachable("Translation units cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000100}
101
102Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000103TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
104 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
105 D->getIdentifier());
106 Owner->addDecl(Inst);
107 return Inst;
108}
109
110Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000111TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000112 llvm_unreachable("Namespaces cannot be instantiated");
Douglas Gregor4f722be2009-03-25 15:45:12 +0000113}
114
John McCall3dbd3d52010-02-16 06:53:13 +0000115Decl *
116TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
117 NamespaceAliasDecl *Inst
118 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
119 D->getNamespaceLoc(),
120 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000121 D->getIdentifier(),
122 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000123 D->getTargetNameLoc(),
124 D->getNamespace());
125 Owner->addDecl(Inst);
126 return Inst;
127}
128
Richard Smith3e4c6c42011-05-05 21:57:07 +0000129Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
130 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000131 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000132 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000133 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000134 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000135 DI = SemaRef.SubstType(DI, TemplateArgs,
136 D->getLocation(), D->getDeclName());
137 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000138 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000139 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000140 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000141 } else {
142 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000143 }
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000146 TypedefNameDecl *Typedef;
147 if (IsTypeAlias)
148 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
149 D->getLocation(), D->getIdentifier(), DI);
150 else
151 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
152 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000153 if (Invalid)
154 Typedef->setInvalidDecl();
155
John McCallcde5a402011-02-01 08:20:08 +0000156 // If the old typedef was the name for linkage purposes of an anonymous
157 // tag decl, re-establish that relationship for the new typedef.
158 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
159 TagDecl *oldTag = oldTagType->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000160 if (oldTag->getTypedefNameForAnonDecl() == D) {
John McCallcde5a402011-02-01 08:20:08 +0000161 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000162 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
163 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000164 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000165 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000166
Richard Smith162e1c12011-04-15 14:24:37 +0000167 if (TypedefNameDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000168 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
169 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000170 if (!InstPrev)
171 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000172
Richard Smith162e1c12011-04-15 14:24:37 +0000173 Typedef->setPreviousDeclaration(cast<TypedefNameDecl>(InstPrev));
John McCall5126fd02009-12-30 00:31:22 +0000174 }
175
John McCall1d8d1cc2010-08-01 02:01:53 +0000176 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000177
John McCall46460a62010-01-20 21:53:11 +0000178 Typedef->setAccess(D->getAccess());
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000180 return Typedef;
181}
182
Richard Smith162e1c12011-04-15 14:24:37 +0000183Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000184 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
185 Owner->addDecl(Typedef);
186 return Typedef;
Richard Smith162e1c12011-04-15 14:24:37 +0000187}
188
189Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
Richard Smith3e4c6c42011-05-05 21:57:07 +0000190 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
191 Owner->addDecl(Typedef);
192 return Typedef;
193}
194
195Decl *
196TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
197 // Create a local instantiation scope for this type alias template, which
198 // will contain the instantiations of the template parameters.
199 LocalInstantiationScope Scope(SemaRef);
200
201 TemplateParameterList *TempParams = D->getTemplateParameters();
202 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
203 if (!InstParams)
204 return 0;
205
206 TypeAliasDecl *Pattern = D->getTemplatedDecl();
207
208 TypeAliasTemplateDecl *PrevAliasTemplate = 0;
209 if (Pattern->getPreviousDeclaration()) {
210 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
211 if (Found.first != Found.second) {
212 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(*Found.first);
213 }
214 }
215
216 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
217 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
218 if (!AliasInst)
219 return 0;
220
221 TypeAliasTemplateDecl *Inst
222 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
223 D->getDeclName(), InstParams, AliasInst);
224 if (PrevAliasTemplate)
225 Inst->setPreviousDeclaration(PrevAliasTemplate);
226
227 Inst->setAccess(D->getAccess());
228
229 if (!PrevAliasTemplate)
230 Inst->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000231
Richard Smith3e4c6c42011-05-05 21:57:07 +0000232 Owner->addDecl(Inst);
233
234 return Inst;
Richard Smith162e1c12011-04-15 14:24:37 +0000235}
236
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000237/// \brief Instantiate an initializer, breaking it into separate
238/// initialization arguments.
239///
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000240/// \param Init The initializer to instantiate.
241///
242/// \param TemplateArgs Template arguments to be substituted into the
243/// initializer.
244///
245/// \param NewArgs Will be filled in with the instantiation arguments.
246///
247/// \returns true if an error occurred, false otherwise
Richard Smith0ff6f8f2011-07-20 00:12:52 +0000248bool Sema::InstantiateInitializer(Expr *Init,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000249 const MultiLevelTemplateArgumentList &TemplateArgs,
Richard Smith0ff6f8f2011-07-20 00:12:52 +0000250 SourceLocation &LParenLoc,
251 ASTOwningVector<Expr*> &NewArgs,
252 SourceLocation &RParenLoc) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000253 NewArgs.clear();
254 LParenLoc = SourceLocation();
255 RParenLoc = SourceLocation();
256
257 if (!Init)
258 return false;
259
John McCall4765fa02010-12-06 08:20:24 +0000260 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000261 Init = ExprTemp->getSubExpr();
262
263 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
264 Init = Binder->getSubExpr();
265
266 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
267 Init = ICE->getSubExprAsWritten();
268
269 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
270 LParenLoc = ParenList->getLParenLoc();
271 RParenLoc = ParenList->getRParenLoc();
Richard Smith0ff6f8f2011-07-20 00:12:52 +0000272 return SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
273 true, TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000274 }
275
276 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000277 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
Richard Smith0ff6f8f2011-07-20 00:12:52 +0000278 if (SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
279 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000280 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000281
Douglas Gregor28329e52010-03-24 21:22:47 +0000282 // FIXME: Fake locations!
Richard Smith0ff6f8f2011-07-20 00:12:52 +0000283 LParenLoc = PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000284 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000285 return false;
286 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000287 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000288
Richard Smith0ff6f8f2011-07-20 00:12:52 +0000289 ExprResult Result = SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000290 if (Result.isInvalid())
291 return true;
292
293 NewArgs.push_back(Result.takeAs<Expr>());
294 return false;
295}
296
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000297Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000298 // If this is the variable for an anonymous struct or union,
299 // instantiate the anonymous struct/union type first.
300 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
301 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
302 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
303 return 0;
304
John McCallce3ff2b2009-08-25 22:02:44 +0000305 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000306 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000307 TemplateArgs,
308 D->getTypeSpecStartLoc(),
309 D->getDeclName());
310 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000311 return 0;
312
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000313 if (DI->getType()->isFunctionType()) {
314 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
315 << D->isStaticDataMember() << DI->getType();
316 return 0;
317 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000318
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000319 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000320 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000321 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000323 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000324 D->getStorageClass(),
325 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000326 Var->setThreadSpecified(D->isThreadSpecified());
327 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Richard Smithad762fc2011-04-14 22:09:26 +0000328 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCallb6217662010-03-15 10:12:16 +0000330 // Substitute the nested name specifier, if any.
331 if (SubstQualifier(D, Var))
332 return 0;
333
Mike Stump1eb44332009-09-09 15:08:12 +0000334 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000335 // out-of-line, the instantiation will have the same lexical
336 // context (which will be a namespace scope) as the template.
337 if (D->isOutOfLine())
338 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000339
John McCall46460a62010-01-20 21:53:11 +0000340 Var->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000341
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000342 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000343 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000344 Var->setReferenced(D->isReferenced());
345 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000346
Mike Stump390b4cc2009-05-16 07:39:55 +0000347 // FIXME: In theory, we could have a previous declaration for variables that
348 // are not static data members.
John McCall68263142009-11-18 22:49:29 +0000349 // FIXME: having to fake up a LookupResult is dumb.
350 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000351 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000352 if (D->isStaticDataMember())
353 SemaRef.LookupQualifiedName(Previous, Owner, false);
Douglas Gregor9aab9c42011-12-10 01:22:52 +0000354
355 // In ARC, infer 'retaining' for variables of retainable type.
356 if (SemaRef.getLangOptions().ObjCAutoRefCount &&
357 SemaRef.inferObjCARCLifetime(Var))
358 Var->setInvalidDecl();
359
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +0000360 SemaRef.CheckVariableDeclaration(Var, Previous);
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Douglas Gregor7caa6822009-07-24 20:34:43 +0000362 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000363 if (!D->isStaticDataMember())
364 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000365 Owner->makeDeclVisibleInContext(Var);
366 } else {
367 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000368 if (Owner->isFunctionOrMethod())
369 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000370 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000371 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000372
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000373 // Link instantiations of static data members back to the template from
374 // which they were instantiated.
375 if (Var->isStaticDataMember())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000376 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000377 TSK_ImplicitInstantiation);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000378
Douglas Gregor60c93c92010-02-09 07:26:29 +0000379 if (Var->getAnyInitializer()) {
380 // We already have an initializer in the class.
381 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000382 if (Var->isStaticDataMember() && !D->isOutOfLine())
383 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
384 else
385 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
386
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000387 // Instantiate the initializer.
388 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000389 ASTOwningVector<Expr*> InitArgs(SemaRef);
Richard Smith0ff6f8f2011-07-20 00:12:52 +0000390 if (!SemaRef.InstantiateInitializer(D->getInit(), TemplateArgs, LParenLoc,
391 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000392 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000393 // Attach the initializer to the declaration, if we have one.
394 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000395 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000396 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000397 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000398 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000399 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000400 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000401 RParenLoc,
402 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000403 } else {
404 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000405 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000406 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000407 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000408 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000409 // FIXME: Not too happy about invalidating the declaration
410 // because of a bogus initializer.
411 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000412 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000413
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000414 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000415 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
416 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000417 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000418
Richard Smithe3499ca2011-06-21 23:42:09 +0000419 // Diagnose unused local variables with dependent types, where the diagnostic
420 // will have been deferred.
421 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed() &&
422 D->getType()->isDependentType())
Douglas Gregor5764f612010-05-08 23:05:03 +0000423 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000424
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000425 return Var;
426}
427
Abramo Bagnara6206d532010-06-05 05:09:32 +0000428Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
429 AccessSpecDecl* AD
430 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
431 D->getAccessSpecifierLoc(), D->getColonLoc());
432 Owner->addHiddenDecl(AD);
433 return AD;
434}
435
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000436Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
437 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000438 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor561f8122011-07-01 01:22:09 +0000439 if (DI->getType()->isInstantiationDependentType() ||
Douglas Gregor836adf62010-05-24 17:22:01 +0000440 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000441 DI = SemaRef.SubstType(DI, TemplateArgs,
442 D->getLocation(), D->getDeclName());
443 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000444 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000445 Invalid = true;
446 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000447 // C++ [temp.arg.type]p3:
448 // If a declaration acquires a function type through a type
449 // dependent on a template-parameter and this causes a
450 // declaration that does not use the syntactic form of a
451 // function declarator to have function type, the program is
452 // ill-formed.
453 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000454 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000455 Invalid = true;
456 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000457 } else {
458 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000459 }
460
461 Expr *BitWidth = D->getBitWidth();
462 if (Invalid)
463 BitWidth = 0;
464 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000465 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000466 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000467
John McCall60d7b3a2010-08-24 06:29:42 +0000468 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000469 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000470 if (InstantiatedBitWidth.isInvalid()) {
471 Invalid = true;
472 BitWidth = 0;
473 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000474 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000475 }
476
John McCall07fb6be2009-10-22 23:33:21 +0000477 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
478 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000479 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000480 D->getLocation(),
481 D->isMutable(),
482 BitWidth,
Richard Smith7a614d82011-06-11 17:19:42 +0000483 D->hasInClassInitializer(),
Steve Naroffea218b82009-07-14 14:58:18 +0000484 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000485 D->getAccess(),
486 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000487 if (!Field) {
488 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000489 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000490 }
Mike Stump1eb44332009-09-09 15:08:12 +0000491
John McCall1d8d1cc2010-08-01 02:01:53 +0000492 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000493
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000494 if (Invalid)
495 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000497 if (!Field->getDeclName()) {
498 // Keep track of where this decl came from.
499 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000500 }
Douglas Gregor9901c572010-05-21 00:31:19 +0000501 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
502 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000503 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000504 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000507 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000508 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000509 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000510
511 return Field;
512}
513
Francois Pichet87c2e122010-11-21 06:08:52 +0000514Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
515 NamedDecl **NamedChain =
516 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
517
518 int i = 0;
519 for (IndirectFieldDecl::chain_iterator PI =
520 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000521 PI != PE; ++PI) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000522 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
Douglas Gregorb7107222011-03-04 19:46:35 +0000523 TemplateArgs);
524 if (!Next)
525 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000526
Douglas Gregorb7107222011-03-04 19:46:35 +0000527 NamedChain[i++] = Next;
528 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000529
Francois Pichet40e17752010-12-09 10:07:54 +0000530 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000531 IndirectFieldDecl* IndirectField
532 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000533 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000534 NamedChain, D->getChainingSize());
535
536
537 IndirectField->setImplicit(D->isImplicit());
538 IndirectField->setAccess(D->getAccess());
539 Owner->addDecl(IndirectField);
540 return IndirectField;
541}
542
John McCall02cace72009-08-28 07:59:38 +0000543Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000544 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000545 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000546 if (TypeSourceInfo *Ty = D->getFriendType()) {
Chandler Carruth4fb86f82011-05-01 00:51:33 +0000547 TypeSourceInfo *InstTy;
548 // If this is an unsupported friend, don't bother substituting template
549 // arguments into it. The actual type referred to won't be used by any
550 // parts of Clang, and may not be valid for instantiating. Just use the
551 // same info for the instantiated friend.
552 if (D->isUnsupportedFriend()) {
553 InstTy = Ty;
554 } else {
555 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
556 D->getLocation(), DeclarationName());
557 }
558 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000559 return 0;
John McCall02cace72009-08-28 07:59:38 +0000560
Abramo Bagnara0216df82011-10-29 20:52:52 +0000561 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getLocation(),
562 D->getFriendLoc(), InstTy);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000563 if (!FD)
564 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000565
Douglas Gregor06245bf2010-04-07 17:57:12 +0000566 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000567 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000568 Owner->addDecl(FD);
569 return FD;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000570 }
571
Douglas Gregor06245bf2010-04-07 17:57:12 +0000572 NamedDecl *ND = D->getFriendDecl();
573 assert(ND && "friend decl must be a decl or a type!");
574
John McCallaf2094e2010-04-08 09:05:18 +0000575 // All of the Visit implementations for the various potential friend
576 // declarations have to be carefully written to work for friend
577 // objects, with the most important detail being that the target
578 // decl should almost certainly not be placed in Owner.
579 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000580 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000581
John McCall02cace72009-08-28 07:59:38 +0000582 FriendDecl *FD =
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000583 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor06245bf2010-04-07 17:57:12 +0000584 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000585 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000586 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000587 Owner->addDecl(FD);
588 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000589}
590
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000591Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
592 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Douglas Gregorac7610d2009-06-22 20:57:11 +0000594 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000595 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000596
John McCall60d7b3a2010-08-24 06:29:42 +0000597 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000598 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000599 if (InstantiatedAssertExpr.isInvalid())
600 return 0;
601
John McCall60d7b3a2010-08-24 06:29:42 +0000602 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000603 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000604 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000605 InstantiatedAssertExpr.get(),
Abramo Bagnaraa2026c92011-03-08 16:41:52 +0000606 Message.get(),
607 D->getRParenLoc());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000608}
609
610Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000611 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000612 D->getLocation(), D->getIdentifier(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000613 /*PrevDecl=*/0, D->isScoped(),
614 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000615 if (D->isFixed()) {
616 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
617 // If we have type source information for the underlying type, it means it
618 // has been explicitly set by the user. Perform substitution on it before
619 // moving on.
620 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
621 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
622 TemplateArgs,
623 UnderlyingLoc,
624 DeclarationName()));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000625
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000626 if (!Enum->getIntegerTypeSourceInfo())
627 Enum->setIntegerType(SemaRef.Context.IntTy);
628 }
629 else {
630 assert(!D->getIntegerType()->isDependentType()
631 && "Dependent type without type source info");
632 Enum->setIntegerType(D->getIntegerType());
633 }
634 }
635
John McCall5b629aa2010-10-22 23:36:17 +0000636 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
637
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000638 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000639 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000640 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000641 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000642 Enum->startDefinition();
643
Douglas Gregor96084f12010-03-01 19:00:07 +0000644 if (D->getDeclContext()->isFunctionOrMethod())
645 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000646
Chris Lattner5f9e2722011-07-23 10:55:15 +0000647 SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000648
649 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000650 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
651 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000652 EC != ECEnd; ++EC) {
653 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000654 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000655 if (Expr *UninstValue = EC->getInitExpr()) {
656 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000657 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000658 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000659
John McCallce3ff2b2009-08-25 22:02:44 +0000660 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000661 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000662
663 // Drop the initial value and continue.
664 bool isInvalid = false;
665 if (Value.isInvalid()) {
666 Value = SemaRef.Owned((Expr *)0);
667 isInvalid = true;
668 }
669
Mike Stump1eb44332009-09-09 15:08:12 +0000670 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000671 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
672 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000673 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000674
675 if (isInvalid) {
676 if (EnumConst)
677 EnumConst->setInvalidDecl();
678 Enum->setInvalidDecl();
679 }
680
681 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000682 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
683
John McCall3b85ecf2010-01-23 22:37:59 +0000684 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000685 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000686 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000687 LastEnumConst = EnumConst;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000688
Douglas Gregor96084f12010-03-01 19:00:07 +0000689 if (D->getDeclContext()->isFunctionOrMethod()) {
690 // If the enumeration is within a function or method, record the enum
691 // constant as a local.
692 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
693 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000694 }
695 }
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000697 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000698 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000699 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000700 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000701 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000702 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000703
704 return Enum;
705}
706
Douglas Gregor6477b692009-03-25 15:04:13 +0000707Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
David Blaikieb219cfc2011-09-23 05:06:16 +0000708 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.");
Douglas Gregor6477b692009-03-25 15:04:13 +0000709}
710
John McCalle29ba202009-08-20 01:44:21 +0000711Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000712 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
713
Douglas Gregor550d9b22009-10-31 17:21:17 +0000714 // Create a local instantiation scope for this class template, which
715 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000716 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000717 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000718 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000719 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000720 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000721
722 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000723
724 // Instantiate the qualifier. We have to do this first in case
725 // we're a friend declaration, because if we are then we need to put
726 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000727 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
728 if (QualifierLoc) {
729 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
730 TemplateArgs);
731 if (!QualifierLoc)
732 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000733 }
734
735 CXXRecordDecl *PrevDecl = 0;
736 ClassTemplateDecl *PrevClassTemplate = 0;
737
Nick Lewycky37574f52010-11-08 23:29:42 +0000738 if (!isFriend && Pattern->getPreviousDeclaration()) {
739 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
740 if (Found.first != Found.second) {
741 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
742 if (PrevClassTemplate)
743 PrevDecl = PrevClassTemplate->getTemplatedDecl();
744 }
745 }
746
John McCall93ba8572010-03-25 06:39:04 +0000747 // If this isn't a friend, then it's a member template, in which
748 // case we just want to build the instantiation in the
749 // specialization. If it is a friend, we want to build it in
750 // the appropriate context.
751 DeclContext *DC = Owner;
752 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000753 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000754 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000755 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000756 DC = SemaRef.computeDeclContext(SS);
757 if (!DC) return 0;
758 } else {
759 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
760 Pattern->getDeclContext(),
761 TemplateArgs);
762 }
763
764 // Look for a previous declaration of the template in the owning
765 // context.
766 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
767 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
768 SemaRef.LookupQualifiedName(R, DC);
769
770 if (R.isSingleResult()) {
771 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
772 if (PrevClassTemplate)
773 PrevDecl = PrevClassTemplate->getTemplatedDecl();
774 }
775
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000776 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000777 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000778 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000779 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000780 return 0;
781 }
782
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000783 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000784 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000785 bool Complain = true;
786
787 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
788 // template for struct std::tr1::__detail::_Map_base, where the
789 // template parameters of the friend declaration don't match the
790 // template parameters of the original declaration. In this one
791 // case, we don't complain about the ill-formed friend
792 // declaration.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000793 if (isFriend && Pattern->getIdentifier() &&
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000794 Pattern->getIdentifier()->isStr("_Map_base") &&
795 DC->isNamespace() &&
796 cast<NamespaceDecl>(DC)->getIdentifier() &&
797 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
798 DeclContext *DCParent = DC->getParent();
799 if (DCParent->isNamespace() &&
800 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
801 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
802 DeclContext *DCParent2 = DCParent->getParent();
803 if (DCParent2->isNamespace() &&
804 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
805 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
806 DCParent2->getParent()->isTranslationUnit())
807 Complain = false;
808 }
809 }
810
John McCall93ba8572010-03-25 06:39:04 +0000811 TemplateParameterList *PrevParams
812 = PrevClassTemplate->getTemplateParameters();
813
814 // Make sure the parameter lists match.
815 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000816 Complain,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000817 Sema::TPL_TemplateMatch)) {
818 if (Complain)
819 return 0;
820
821 AdoptedPreviousTemplateParams = true;
822 InstParams = PrevParams;
823 }
John McCall93ba8572010-03-25 06:39:04 +0000824
825 // Do some additional validation, then merge default arguments
826 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000827 if (!AdoptedPreviousTemplateParams &&
828 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000829 Sema::TPC_ClassTemplate))
830 return 0;
831 }
832 }
833
John McCalle29ba202009-08-20 01:44:21 +0000834 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000835 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000836 Pattern->getLocStart(), Pattern->getLocation(),
837 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000838 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000839
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000840 if (QualifierLoc)
841 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000842
John McCalle29ba202009-08-20 01:44:21 +0000843 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000844 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
845 D->getIdentifier(), InstParams, RecordInst,
846 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000847 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000848
John McCall93ba8572010-03-25 06:39:04 +0000849 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000850 if (PrevClassTemplate)
851 Inst->setAccess(PrevClassTemplate->getAccess());
852 else
853 Inst->setAccess(D->getAccess());
854
John McCall93ba8572010-03-25 06:39:04 +0000855 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
856 // TODO: do we want to track the instantiation progeny of this
857 // friend target decl?
858 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000859 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000860 if (!PrevClassTemplate)
861 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000862 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000863
Douglas Gregorf0510d42009-10-12 23:11:44 +0000864 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000865 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000866 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000867
Douglas Gregor259571e2009-10-30 22:42:42 +0000868 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000869 if (isFriend) {
870 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Abramo Bagnara4c515482011-11-26 13:33:46 +0000871 Inst->setLexicalDeclContext(Owner);
872 RecordInst->setLexicalDeclContext(Owner);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000873 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000874 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000875
Abramo Bagnara4c515482011-11-26 13:33:46 +0000876 if (D->isOutOfLine()) {
877 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
878 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
879 }
880
John McCalle29ba202009-08-20 01:44:21 +0000881 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000882
883 if (!PrevClassTemplate) {
884 // Queue up any out-of-line partial specializations of this member
885 // class template; the client will force their instantiation once
886 // the enclosing class has been instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000887 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregord65587f2010-11-10 19:44:59 +0000888 D->getPartialSpecializations(PartialSpecs);
889 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
890 if (PartialSpecs[I]->isOutOfLine())
891 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
892 }
893
John McCalle29ba202009-08-20 01:44:21 +0000894 return Inst;
895}
896
Douglas Gregord60e1052009-08-27 16:57:43 +0000897Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000898TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
899 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000900 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000901
Douglas Gregored9c0f92009-10-29 00:04:11 +0000902 // Lookup the already-instantiated declaration in the instantiation
903 // of the class template and return that.
904 DeclContext::lookup_result Found
905 = Owner->lookup(ClassTemplate->getDeclName());
906 if (Found.first == Found.second)
907 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000908
Douglas Gregored9c0f92009-10-29 00:04:11 +0000909 ClassTemplateDecl *InstClassTemplate
910 = dyn_cast<ClassTemplateDecl>(*Found.first);
911 if (!InstClassTemplate)
912 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000913
Douglas Gregord65587f2010-11-10 19:44:59 +0000914 if (ClassTemplatePartialSpecializationDecl *Result
915 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
916 return Result;
917
918 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000919}
920
921Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000922TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000923 // Create a local instantiation scope for this function template, which
924 // will contain the instantiations of the template parameters and then get
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000925 // merged with the local instantiation scope for the function template
Douglas Gregor550d9b22009-10-31 17:21:17 +0000926 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000927 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000928
Douglas Gregord60e1052009-08-27 16:57:43 +0000929 TemplateParameterList *TempParams = D->getTemplateParameters();
930 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000931 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000932 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000933
Douglas Gregora735b202009-10-13 14:39:41 +0000934 FunctionDecl *Instantiated = 0;
935 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000936 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
Douglas Gregora735b202009-10-13 14:39:41 +0000937 InstParams));
938 else
939 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000940 D->getTemplatedDecl(),
Douglas Gregora735b202009-10-13 14:39:41 +0000941 InstParams));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000942
Douglas Gregora735b202009-10-13 14:39:41 +0000943 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000944 return 0;
945
John McCall46460a62010-01-20 21:53:11 +0000946 Instantiated->setAccess(D->getAccess());
947
Mike Stump1eb44332009-09-09 15:08:12 +0000948 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000949 // template from which it was instantiated.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000950 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000951 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000952 InstTemplate->setAccess(D->getAccess());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000953 assert(InstTemplate &&
Douglas Gregora735b202009-10-13 14:39:41 +0000954 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000955
John McCallb1a56e72010-03-26 23:10:15 +0000956 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
957
John McCalle976ffe2009-12-14 23:19:40 +0000958 // Link the instantiation back to the pattern *unless* this is a
959 // non-definition friend declaration.
960 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000961 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000962 InstTemplate->setInstantiatedFromMemberTemplate(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +0000963
John McCallb1a56e72010-03-26 23:10:15 +0000964 // Make declarations visible in the appropriate context.
965 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000966 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000967
Douglas Gregord60e1052009-08-27 16:57:43 +0000968 return InstTemplate;
969}
970
Douglas Gregord475b8d2009-03-25 21:17:03 +0000971Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
972 CXXRecordDecl *PrevDecl = 0;
973 if (D->isInjectedClassName())
974 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000975 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000976 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
977 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000978 TemplateArgs);
979 if (!Prev) return 0;
980 PrevDecl = cast<CXXRecordDecl>(Prev);
981 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000982
983 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000984 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000985 D->getLocStart(), D->getLocation(),
986 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000987
988 // Substitute the nested name specifier, if any.
989 if (SubstQualifier(D, Record))
990 return 0;
991
Douglas Gregord475b8d2009-03-25 21:17:03 +0000992 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000993 // FIXME: Check against AS_none is an ugly hack to work around the issue that
994 // the tag decls introduced by friend class declarations don't have an access
995 // specifier. Remove once this area of the code gets sorted out.
996 if (D->getAccess() != AS_none)
997 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000998 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000999 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001000
John McCall02cace72009-08-28 07:59:38 +00001001 // If the original function was part of a friend declaration,
1002 // inherit its namespace state.
1003 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
1004 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
1005
Douglas Gregor9901c572010-05-21 00:31:19 +00001006 // Make sure that anonymous structs and unions are recorded.
1007 if (D->isAnonymousStructOrUnion()) {
1008 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +00001009 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +00001010 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1011 }
Anders Carlssond8b285f2009-09-01 04:26:58 +00001012
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001013 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001014 return Record;
1015}
1016
John McCall02cace72009-08-28 07:59:38 +00001017/// Normal class members are of more specific types and therefore
1018/// don't make it here. This function serves two purposes:
1019/// 1) instantiating function templates
1020/// 2) substituting friend declarations
1021/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +00001022Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +00001023 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +00001024 // Check whether there is already a function template specialization for
1025 // this declaration.
1026 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1027 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +00001028 if (FunctionTemplate && !TemplateParams) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001029 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001030 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001032 FunctionDecl *SpecFunc
1033 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1034 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregor127102b2009-06-29 20:59:39 +00001036 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001037 if (SpecFunc)
1038 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +00001039 }
Mike Stump1eb44332009-09-09 15:08:12 +00001040
John McCallb0cb0222010-03-27 05:57:59 +00001041 bool isFriend;
1042 if (FunctionTemplate)
1043 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1044 else
1045 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1046
Douglas Gregor79c22782010-01-16 20:21:20 +00001047 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +00001048 Owner->isFunctionOrMethod() ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001049 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001050 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001051 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001052
Chris Lattner5f9e2722011-07-23 10:55:15 +00001053 SmallVector<ParmVarDecl *, 4> Params;
David Blaikie64b4b432011-11-10 05:42:04 +00001054 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
John McCall21ef0fa2010-03-11 09:03:00 +00001055 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001056 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001057 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +00001058
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001059 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1060 if (QualifierLoc) {
1061 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1062 TemplateArgs);
1063 if (!QualifierLoc)
1064 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001065 }
1066
John McCall68b6b872010-02-06 01:50:47 +00001067 // If we're instantiating a local function declaration, put the result
1068 // in the owner; otherwise we need to find the instantiated context.
1069 DeclContext *DC;
1070 if (D->getDeclContext()->isFunctionOrMethod())
1071 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001072 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001073 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001074 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001075 DC = SemaRef.computeDeclContext(SS);
1076 if (!DC) return 0;
1077 } else {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001078 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001079 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001080 }
John McCall68b6b872010-02-06 01:50:47 +00001081
John McCall02cace72009-08-28 07:59:38 +00001082 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001083 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1084 D->getLocation(), D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001085 D->getStorageClass(), D->getStorageClassAsWritten(),
Richard Smithaf1fc7a2011-08-15 21:04:07 +00001086 D->isInlineSpecified(), D->hasWrittenPrototype(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001087 /*isConstexpr*/ false);
John McCallb6217662010-03-15 10:12:16 +00001088
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001089 if (QualifierLoc)
1090 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001091
John McCallb1a56e72010-03-26 23:10:15 +00001092 DeclContext *LexicalDC = Owner;
1093 if (!isFriend && D->isOutOfLine()) {
1094 assert(D->getDeclContext()->isFileContext());
1095 LexicalDC = D->getDeclContext();
1096 }
1097
1098 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Douglas Gregore53060f2009-06-25 22:08:12 +00001100 // Attach the parameters
Douglas Gregor5cbe1012011-07-05 18:30:26 +00001101 if (isa<FunctionProtoType>(Function->getType().IgnoreParens())) {
Douglas Gregor1d441ee2011-06-22 18:16:25 +00001102 // Adopt the already-instantiated parameters into our own context.
1103 for (unsigned P = 0; P < Params.size(); ++P)
1104 if (Params[P])
1105 Params[P]->setOwningFunction(Function);
1106 } else {
1107 // Since we were instantiated via a typedef of a function type, create
1108 // new parameters.
1109 const FunctionProtoType *Proto
1110 = Function->getType()->getAs<FunctionProtoType>();
1111 assert(Proto && "No function prototype in template instantiation?");
1112 for (FunctionProtoType::arg_type_iterator AI = Proto->arg_type_begin(),
1113 AE = Proto->arg_type_end(); AI != AE; ++AI) {
1114 ParmVarDecl *Param
1115 = SemaRef.BuildParmVarDeclForTypedef(Function, Function->getLocation(),
1116 *AI);
1117 Param->setScopeInfo(0, Params.size());
1118 Params.push_back(Param);
1119 }
1120 }
David Blaikie4278c652011-09-21 18:16:56 +00001121 Function->setParams(Params);
John McCall02cace72009-08-28 07:59:38 +00001122
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001123 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001124 if (TemplateParams) {
1125 // Our resulting instantiation is actually a function template, since we
1126 // are substituting only the outer template parameters. For example, given
1127 //
1128 // template<typename T>
1129 // struct X {
1130 // template<typename U> friend void f(T, U);
1131 // };
1132 //
1133 // X<int> x;
1134 //
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001135 // We are instantiating the friend function template "f" within X<int>,
Douglas Gregora735b202009-10-13 14:39:41 +00001136 // which means substituting int for T, but leaving "f" as a friend function
1137 // template.
1138 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001139 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001140 Function->getLocation(),
1141 Function->getDeclName(),
1142 TemplateParams, Function);
1143 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001144
1145 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001146
1147 if (isFriend && D->isThisDeclarationADefinition()) {
1148 // TODO: should we remember this connection regardless of whether
1149 // the friend declaration provided a body?
1150 FunctionTemplate->setInstantiatedFromMemberTemplate(
1151 D->getDescribedFunctionTemplate());
1152 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001153 } else if (FunctionTemplate) {
1154 // Record this function template specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001155 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001156 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001157 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001158 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001159 Innermost.first,
1160 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001161 InsertPos);
Chandler Carruth80f5b162011-08-18 09:09:59 +00001162 } else if (isFriend) {
1163 // Note, we need this connection even if the friend doesn't have a body.
1164 // Its body may exist but not have been attached yet due to deferred
1165 // parsing.
1166 // FIXME: It might be cleaner to set this when attaching the body to the
1167 // friend function declaration, however that would require finding all the
1168 // instantiations and modifying them.
John McCalld325daa2010-03-26 04:53:08 +00001169 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001170 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001171
Douglas Gregore53060f2009-06-25 22:08:12 +00001172 if (InitFunctionInstantiation(Function, D))
1173 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001174
John McCallaf2094e2010-04-08 09:05:18 +00001175 bool isExplicitSpecialization = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001176
John McCall68263142009-11-18 22:49:29 +00001177 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1178 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1179
John McCallaf2094e2010-04-08 09:05:18 +00001180 if (DependentFunctionTemplateSpecializationInfo *Info
1181 = D->getDependentSpecializationInfo()) {
1182 assert(isFriend && "non-friend has dependent specialization info?");
1183
1184 // This needs to be set now for future sanity.
1185 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1186
1187 // Instantiate the explicit template arguments.
1188 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1189 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001190 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1191 ExplicitArgs, TemplateArgs))
1192 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001193
1194 // Map the candidate templates to their instantiations.
1195 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1196 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1197 Info->getTemplate(I),
1198 TemplateArgs);
1199 if (!Temp) return 0;
1200
1201 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1202 }
1203
1204 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1205 &ExplicitArgs,
1206 Previous))
1207 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001208
John McCallaf2094e2010-04-08 09:05:18 +00001209 isExplicitSpecialization = true;
1210
1211 } else if (TemplateParams || !FunctionTemplate) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001212 // Look only into the namespace where the friend would be declared to
1213 // find a previous declaration. This is the innermost enclosing namespace,
Douglas Gregora735b202009-10-13 14:39:41 +00001214 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001215 SemaRef.LookupQualifiedName(Previous, DC);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001216
Douglas Gregora735b202009-10-13 14:39:41 +00001217 // In C++, the previous declaration we find might be a tag type
1218 // (class or enum). In this case, the new declaration will hide the
1219 // tag type. Note that this does does not apply if we're declaring a
1220 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001221 if (Previous.isSingleTagDecl())
1222 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001223 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001224
John McCall9f54ad42009-12-10 09:41:52 +00001225 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001226 isExplicitSpecialization);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001227
John McCall76d32642010-04-24 01:30:58 +00001228 NamedDecl *PrincipalDecl = (TemplateParams
1229 ? cast<NamedDecl>(FunctionTemplate)
1230 : Function);
1231
Douglas Gregora735b202009-10-13 14:39:41 +00001232 // If the original function was part of a friend declaration,
1233 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001234 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001235 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001236 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001237 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001238 else
Douglas Gregora735b202009-10-13 14:39:41 +00001239 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001240
1241 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1242 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001243
Gabor Greif77535df2010-08-30 22:25:56 +00001244 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001245
Richard Smith53e53512011-10-19 00:54:10 +00001246 // C++98 [temp.friend]p5: When a function is defined in a friend function
1247 // declaration in a class template, the function is defined at each
1248 // instantiation of the class template. The function is defined even if it
1249 // is never used.
1250 // C++11 [temp.friend]p4: When a function is defined in a friend function
1251 // declaration in a class template, the function is instantiated when the
1252 // function is odr-used.
1253 //
1254 // If -Wc++98-compat is enabled, we go through the motions of checking for a
1255 // redefinition, but don't instantiate the function.
1256 if ((!SemaRef.getLangOptions().CPlusPlus0x ||
1257 SemaRef.Diags.getDiagnosticLevel(
1258 diag::warn_cxx98_compat_friend_redefinition,
1259 Function->getLocation())
1260 != DiagnosticsEngine::Ignored) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001261 D->isThisDeclarationADefinition()) {
1262 // Check for a function body.
1263 const FunctionDecl *Definition = 0;
Sean Hunt10620eb2011-05-06 20:44:56 +00001264 if (Function->isDefined(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001265 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
Richard Smith53e53512011-10-19 00:54:10 +00001266 SemaRef.Diag(Function->getLocation(),
1267 SemaRef.getLangOptions().CPlusPlus0x ?
1268 diag::warn_cxx98_compat_friend_redefinition :
1269 diag::err_redefinition) << Function->getDeclName();
Douglas Gregor238058c2010-05-18 05:45:02 +00001270 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
Richard Smith53e53512011-10-19 00:54:10 +00001271 if (!SemaRef.getLangOptions().CPlusPlus0x)
1272 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001273 }
Douglas Gregor238058c2010-05-18 05:45:02 +00001274 // Check for redefinitions due to other instantiations of this or
1275 // a similar friend function.
1276 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1277 REnd = Function->redecls_end();
1278 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001279 if (*R == Function)
1280 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001281 switch (R->getFriendObjectKind()) {
1282 case Decl::FOK_None:
Richard Smith53e53512011-10-19 00:54:10 +00001283 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1284 !queuedInstantiation && R->isUsed(false)) {
Gabor Greifab297ac2010-08-30 21:10:05 +00001285 if (MemberSpecializationInfo *MSInfo
1286 = Function->getMemberSpecializationInfo()) {
1287 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1288 SourceLocation Loc = R->getLocation(); // FIXME
1289 MSInfo->setPointOfInstantiation(Loc);
1290 SemaRef.PendingLocalImplicitInstantiations.push_back(
1291 std::make_pair(Function, Loc));
1292 queuedInstantiation = true;
1293 }
1294 }
1295 }
1296 break;
1297 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001298 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001299 = R->getTemplateInstantiationPattern())
Sean Hunt10620eb2011-05-06 20:44:56 +00001300 if (RPattern->isDefined(RPattern)) {
Richard Smith53e53512011-10-19 00:54:10 +00001301 SemaRef.Diag(Function->getLocation(),
1302 SemaRef.getLangOptions().CPlusPlus0x ?
1303 diag::warn_cxx98_compat_friend_redefinition :
1304 diag::err_redefinition)
Douglas Gregor238058c2010-05-18 05:45:02 +00001305 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001306 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Richard Smith53e53512011-10-19 00:54:10 +00001307 if (!SemaRef.getLangOptions().CPlusPlus0x)
1308 Function->setInvalidDecl();
Douglas Gregor238058c2010-05-18 05:45:02 +00001309 break;
1310 }
1311 }
1312 }
1313 }
Douglas Gregora735b202009-10-13 14:39:41 +00001314 }
1315
John McCall76d32642010-04-24 01:30:58 +00001316 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1317 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1318 PrincipalDecl->setNonMemberOperator();
1319
Sean Hunteb88ae52011-05-23 21:07:59 +00001320 assert(!D->isDefaulted() && "only methods should be defaulted");
Douglas Gregore53060f2009-06-25 22:08:12 +00001321 return Function;
1322}
1323
Douglas Gregord60e1052009-08-27 16:57:43 +00001324Decl *
1325TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001326 TemplateParameterList *TemplateParams,
1327 bool IsClassScopeSpecialization) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001328 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1329 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001330 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001331 // We are creating a function template specialization from a function
1332 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001333 // specialization for this particular set of template arguments.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001334 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001335 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001336
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001337 FunctionDecl *SpecFunc
1338 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1339 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001340
Douglas Gregor6b906862009-08-21 00:16:32 +00001341 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001342 if (SpecFunc)
1343 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001344 }
1345
John McCallb0cb0222010-03-27 05:57:59 +00001346 bool isFriend;
1347 if (FunctionTemplate)
1348 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1349 else
1350 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1351
Douglas Gregor79c22782010-01-16 20:21:20 +00001352 bool MergeWithParentScope = (TemplateParams != 0) ||
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001353 !(isa<Decl>(Owner) &&
Douglas Gregor79c22782010-01-16 20:21:20 +00001354 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001355 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001356
John McCall4eab39f2010-10-19 02:26:41 +00001357 // Instantiate enclosing template arguments for friends.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001358 SmallVector<TemplateParameterList *, 4> TempParamLists;
John McCall4eab39f2010-10-19 02:26:41 +00001359 unsigned NumTempParamLists = 0;
1360 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1361 TempParamLists.set_size(NumTempParamLists);
1362 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1363 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1364 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1365 if (!InstParams)
1366 return NULL;
1367 TempParamLists[I] = InstParams;
1368 }
1369 }
1370
Chris Lattner5f9e2722011-07-23 10:55:15 +00001371 SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001372 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1373 TInfo = SubstFunctionType(D, Params);
1374 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001375 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001376 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001377
Abramo Bagnara723df242010-12-14 22:11:44 +00001378 // \brief If the type of this function, after ignoring parentheses,
1379 // is not *directly* a function type, then we're instantiating a function
1380 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001381 //
1382 // typedef int functype(int, int);
1383 // functype func;
1384 //
1385 // In this case, we'll just go instantiate the ParmVarDecls that we
1386 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001387 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001388 assert(!Params.size() && "Instantiating type could not yield parameters");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001389 SmallVector<QualType, 4> ParamTypes;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001390 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1391 D->getNumParams(), TemplateArgs, ParamTypes,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001392 &Params))
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001393 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001394 }
1395
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001396 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1397 if (QualifierLoc) {
1398 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001399 TemplateArgs);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001400 if (!QualifierLoc)
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001401 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001402 }
1403
1404 DeclContext *DC = Owner;
1405 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001406 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001407 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001408 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001409 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001410
1411 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1412 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001413 } else {
1414 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1415 D->getDeclContext(),
1416 TemplateArgs);
1417 }
1418 if (!DC) return 0;
1419 }
1420
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001421 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001422 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001423 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001424
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001425 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001426 DeclarationNameInfo NameInfo
1427 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001428 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001429 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001430 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001431 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001432 Constructor->isInlineSpecified(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001433 false, /*isConstexpr*/ false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001434 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001435 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001436 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001437 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001438 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001439 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001440 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001441 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001442 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001443 Conversion->isExplicit(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001444 /*isConstexpr*/ false,
1445 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001446 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001447 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001448 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001449 D->isStatic(),
1450 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001451 D->isInlineSpecified(),
Richard Smith9f569cc2011-10-01 02:31:28 +00001452 /*isConstexpr*/ false, D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001453 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001454
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001455 if (QualifierLoc)
1456 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001457
Douglas Gregord60e1052009-08-27 16:57:43 +00001458 if (TemplateParams) {
1459 // Our resulting instantiation is actually a function template, since we
1460 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001461 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001462 // template<typename T>
1463 // struct X {
1464 // template<typename U> void f(T, U);
1465 // };
1466 //
1467 // X<int> x;
1468 //
1469 // We are instantiating the member template "f" within X<int>, which means
1470 // substituting int for T, but leaving "f" as a member function template.
1471 // Build the function template itself.
1472 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1473 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001474 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001475 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001476 if (isFriend) {
1477 FunctionTemplate->setLexicalDeclContext(Owner);
1478 FunctionTemplate->setObjectOfFriendDecl(true);
1479 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001480 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001481 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001482 } else if (FunctionTemplate) {
1483 // Record this function template specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001484 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor24bae922010-07-08 18:37:38 +00001485 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001486 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001487 TemplateArgumentList::CreateCopy(SemaRef.Context,
1488 Innermost.first,
1489 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001490 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001491 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001492 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001493 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001494 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001495
Mike Stump1eb44332009-09-09 15:08:12 +00001496 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001497 // out-of-line, the instantiation will have the same lexical
1498 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001499 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001500 if (NumTempParamLists)
1501 Method->setTemplateParameterListsInfo(SemaRef.Context,
1502 NumTempParamLists,
1503 TempParamLists.data());
1504
John McCallb0cb0222010-03-27 05:57:59 +00001505 Method->setLexicalDeclContext(Owner);
1506 Method->setObjectOfFriendDecl(true);
1507 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001508 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001509
Douglas Gregor5545e162009-03-24 00:38:23 +00001510 // Attach the parameters
1511 for (unsigned P = 0; P < Params.size(); ++P)
1512 Params[P]->setOwningFunction(Method);
David Blaikie4278c652011-09-21 18:16:56 +00001513 Method->setParams(Params);
Douglas Gregor5545e162009-03-24 00:38:23 +00001514
1515 if (InitMethodInstantiation(Method, D))
1516 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001517
Abramo Bagnara25777432010-08-11 22:01:17 +00001518 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1519 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001520
John McCallb0cb0222010-03-27 05:57:59 +00001521 if (!FunctionTemplate || TemplateParams || isFriend) {
1522 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001523
Douglas Gregordec06662009-08-21 18:42:58 +00001524 // In C++, the previous declaration we find might be a tag type
1525 // (class or enum). In this case, the new declaration will hide the
1526 // tag type. Note that this does does not apply if we're declaring a
1527 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001528 if (Previous.isSingleTagDecl())
1529 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001530 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001531
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001532 if (!IsClassScopeSpecialization)
Kaelyn Uhrain2c712f52011-10-11 00:28:45 +00001533 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001534
Douglas Gregor4ba31362009-12-01 17:24:26 +00001535 if (D->isPure())
1536 SemaRef.CheckPureMethod(Method, SourceRange());
1537
John McCall46460a62010-01-20 21:53:11 +00001538 Method->setAccess(D->getAccess());
1539
Anders Carlsson9eefa222011-01-20 06:52:44 +00001540 SemaRef.CheckOverrideControl(Method);
1541
Eli Friedman3bc45152011-11-15 22:39:08 +00001542 // If a function is defined as defaulted or deleted, mark it as such now.
1543 if (D->isDefaulted())
1544 Method->setDefaulted();
1545 if (D->isDeletedAsWritten())
1546 Method->setDeletedAsWritten();
1547
John McCallb0cb0222010-03-27 05:57:59 +00001548 if (FunctionTemplate) {
1549 // If there's a function template, let our caller handle it.
1550 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1551 // Don't hide a (potentially) valid declaration with an invalid one.
1552 } else {
1553 NamedDecl *DeclToAdd = (TemplateParams
1554 ? cast<NamedDecl>(FunctionTemplate)
1555 : Method);
1556 if (isFriend)
1557 Record->makeDeclVisibleInContext(DeclToAdd);
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001558 else if (!IsClassScopeSpecialization)
John McCallb0cb0222010-03-27 05:57:59 +00001559 Owner->addDecl(DeclToAdd);
1560 }
Sean Hunteb88ae52011-05-23 21:07:59 +00001561
1562 if (D->isExplicitlyDefaulted()) {
1563 SemaRef.SetDeclDefaulted(Method, Method->getLocation());
1564 } else {
1565 assert(!D->isDefaulted() &&
1566 "should not implicitly default uninstantiated function");
1567 }
1568
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001569 return Method;
1570}
1571
Douglas Gregor615c5d42009-03-24 16:43:20 +00001572Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001573 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001574}
1575
Douglas Gregor03b2b072009-03-24 00:15:49 +00001576Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001577 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001578}
1579
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001580Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001581 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001582}
1583
Douglas Gregor6477b692009-03-25 15:04:13 +00001584ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCallfb44de92011-05-01 22:35:37 +00001585 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
1586 llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001587}
1588
John McCalle29ba202009-08-20 01:44:21 +00001589Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1590 TemplateTypeParmDecl *D) {
1591 // TODO: don't always clone when decls are refcounted.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001592 assert(D->getTypeForDecl()->isTemplateTypeParmType());
Mike Stump1eb44332009-09-09 15:08:12 +00001593
John McCalle29ba202009-08-20 01:44:21 +00001594 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001595 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1596 D->getLocStart(), D->getLocation(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001597 D->getDepth() - TemplateArgs.getNumLevels(),
1598 D->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001599 D->wasDeclaredWithTypename(),
1600 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001601 Inst->setAccess(AS_public);
John McCalle29ba202009-08-20 01:44:21 +00001602
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001603 if (D->hasDefaultArgument())
1604 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
1605
1606 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001607 // scope.
1608 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001609
John McCalle29ba202009-08-20 01:44:21 +00001610 return Inst;
1611}
1612
Douglas Gregor33642df2009-10-23 23:25:44 +00001613Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1614 NonTypeTemplateParmDecl *D) {
1615 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001616 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001617 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1618 SmallVector<QualType, 4> ExpandedParameterPackTypes;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001619 bool IsExpandedParameterPack = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001620 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001621 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001622 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001623
1624 if (D->isExpandedParameterPack()) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001625 // The non-type template parameter pack is an already-expanded pack
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001626 // expansion of types. Substitute into each of the expanded types.
1627 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1628 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1629 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1630 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1631 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001632 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001633 D->getDeclName());
1634 if (!NewDI)
1635 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001636
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001637 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1638 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1639 D->getLocation());
1640 if (NewT.isNull())
1641 return 0;
1642 ExpandedParameterPackTypes.push_back(NewT);
1643 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001644
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001645 IsExpandedParameterPack = true;
1646 DI = D->getTypeSourceInfo();
1647 T = DI->getType();
1648 } else if (isa<PackExpansionTypeLoc>(TL)) {
1649 // The non-type template parameter pack's type is a pack expansion of types.
1650 // Determine whether we need to expand this parameter pack into separate
1651 // types.
1652 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1653 TypeLoc Pattern = Expansion.getPatternLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001654 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001655 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001656
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001657 // Determine whether the set of unexpanded parameter packs can and should
1658 // be expanded.
1659 bool Expand = true;
1660 bool RetainExpansion = false;
1661 llvm::Optional<unsigned> OrigNumExpansions
1662 = Expansion.getTypePtr()->getNumExpansions();
1663 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1664 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1665 Pattern.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001666 Unexpanded,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001667 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001668 Expand, RetainExpansion,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001669 NumExpansions))
1670 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001671
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001672 if (Expand) {
1673 for (unsigned I = 0; I != *NumExpansions; ++I) {
1674 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1675 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001676 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001677 D->getDeclName());
1678 if (!NewDI)
1679 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001680
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001681 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1682 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1683 NewDI->getType(),
1684 D->getLocation());
1685 if (NewT.isNull())
1686 return 0;
1687 ExpandedParameterPackTypes.push_back(NewT);
1688 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001689
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001690 // Note that we have an expanded parameter pack. The "type" of this
1691 // expanded parameter pack is the original expansion type, but callers
1692 // will end up using the expanded parameter pack types for type-checking.
1693 IsExpandedParameterPack = true;
1694 DI = D->getTypeSourceInfo();
1695 T = DI->getType();
1696 } else {
1697 // We cannot fully expand the pack expansion now, so substitute into the
1698 // pattern and create a new pack expansion type.
1699 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1700 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001701 D->getLocation(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001702 D->getDeclName());
1703 if (!NewPattern)
1704 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001705
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001706 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1707 NumExpansions);
1708 if (!DI)
1709 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001710
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001711 T = DI->getType();
1712 }
1713 } else {
1714 // Simple case: substitution into a parameter that is not a parameter pack.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001715 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001716 D->getLocation(), D->getDeclName());
1717 if (!DI)
1718 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001719
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001720 // Check that this type is acceptable for a non-type template parameter.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001721 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001722 D->getLocation());
1723 if (T.isNull()) {
1724 T = SemaRef.Context.IntTy;
1725 Invalid = true;
1726 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001727 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001728
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001729 NonTypeTemplateParmDecl *Param;
1730 if (IsExpandedParameterPack)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001731 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001732 D->getInnerLocStart(),
1733 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001734 D->getDepth() - TemplateArgs.getNumLevels(),
1735 D->getPosition(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001736 D->getIdentifier(), T,
1737 DI,
1738 ExpandedParameterPackTypes.data(),
1739 ExpandedParameterPackTypes.size(),
1740 ExpandedParameterPackTypesAsWritten.data());
1741 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001742 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001743 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001744 D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001745 D->getDepth() - TemplateArgs.getNumLevels(),
1746 D->getPosition(),
1747 D->getIdentifier(), T,
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001748 D->isParameterPack(), DI);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001749
Douglas Gregor9a299e02011-03-04 17:52:15 +00001750 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001751 if (Invalid)
1752 Param->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001753
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001754 Param->setDefaultArgument(D->getDefaultArgument(), false);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001755
1756 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor550d9b22009-10-31 17:21:17 +00001757 // scope.
1758 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001759 return Param;
1760}
1761
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001762Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001763TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1764 TemplateTemplateParmDecl *D) {
1765 // Instantiate the template parameter list of the template template parameter.
1766 TemplateParameterList *TempParams = D->getTemplateParameters();
1767 TemplateParameterList *InstParams;
1768 {
1769 // Perform the actual substitution of template parameters within a new,
1770 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001771 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001772 InstParams = SubstTemplateParams(TempParams);
1773 if (!InstParams)
1774 return NULL;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001775 }
1776
Douglas Gregor9106ef72009-11-11 16:58:32 +00001777 // Build the template template parameter.
1778 TemplateTemplateParmDecl *Param
1779 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001780 D->getDepth() - TemplateArgs.getNumLevels(),
1781 D->getPosition(), D->isParameterPack(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001782 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001783 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001784 Param->setAccess(AS_public);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001785
1786 // Introduce this template parameter's instantiation into the instantiation
Douglas Gregor9106ef72009-11-11 16:58:32 +00001787 // scope.
1788 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001789
Douglas Gregor9106ef72009-11-11 16:58:32 +00001790 return Param;
1791}
1792
Douglas Gregor48c32a72009-11-17 06:07:40 +00001793Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001794 // Using directives are never dependent (and never contain any types or
1795 // expressions), so they require no explicit instantiation work.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001796
Douglas Gregor48c32a72009-11-17 06:07:40 +00001797 UsingDirectiveDecl *Inst
1798 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001799 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001800 D->getQualifierLoc(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001801 D->getIdentLocation(),
1802 D->getNominatedNamespace(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001803 D->getCommonAncestor());
1804 Owner->addDecl(Inst);
1805 return Inst;
1806}
1807
John McCalled976492009-12-04 22:46:56 +00001808Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001809
1810 // The nested name specifier may be dependent, for example
1811 // template <typename T> struct t {
1812 // struct s1 { T f1(); };
1813 // struct s2 : s1 { using s1::f1; };
1814 // };
1815 // template struct t<int>;
1816 // Here, in using s1::f1, s1 refers to t<T>::s1;
1817 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001818 NestedNameSpecifierLoc QualifierLoc
1819 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1820 TemplateArgs);
1821 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001822 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001823
1824 // The name info is non-dependent, so no transformation
1825 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001826 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001827
John McCall9f54ad42009-12-10 09:41:52 +00001828 // We only need to do redeclaration lookups if we're in a class
1829 // scope (in fact, it's not really even possible in non-class
1830 // scopes).
1831 bool CheckRedeclaration = Owner->isRecord();
1832
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001833 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1834 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001835
John McCalled976492009-12-04 22:46:56 +00001836 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001837 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001838 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001839 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001840 D->isTypeName());
1841
Douglas Gregor5149f372011-02-25 15:54:31 +00001842 CXXScopeSpec SS;
1843 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001844 if (CheckRedeclaration) {
1845 Prev.setHideTags(false);
1846 SemaRef.LookupQualifiedName(Prev, Owner);
1847
1848 // Check for invalid redeclarations.
1849 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1850 D->isTypeName(), SS,
1851 D->getLocation(), Prev))
1852 NewUD->setInvalidDecl();
1853
1854 }
1855
1856 if (!NewUD->isInvalidDecl() &&
1857 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001858 D->getLocation()))
1859 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001860
John McCalled976492009-12-04 22:46:56 +00001861 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1862 NewUD->setAccess(D->getAccess());
1863 Owner->addDecl(NewUD);
1864
John McCall9f54ad42009-12-10 09:41:52 +00001865 // Don't process the shadow decls for an invalid decl.
1866 if (NewUD->isInvalidDecl())
1867 return NewUD;
1868
John McCall323c3102009-12-22 22:26:37 +00001869 bool isFunctionScope = Owner->isFunctionOrMethod();
1870
John McCall9f54ad42009-12-10 09:41:52 +00001871 // Process the shadow decls.
1872 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1873 I != E; ++I) {
1874 UsingShadowDecl *Shadow = *I;
1875 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001876 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1877 Shadow->getLocation(),
1878 Shadow->getTargetDecl(),
1879 TemplateArgs));
1880 if (!InstTarget)
1881 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001882
1883 if (CheckRedeclaration &&
1884 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1885 continue;
1886
1887 UsingShadowDecl *InstShadow
1888 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1889 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001890
1891 if (isFunctionScope)
1892 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001893 }
John McCalled976492009-12-04 22:46:56 +00001894
1895 return NewUD;
1896}
1897
1898Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001899 // Ignore these; we handle them in bulk when processing the UsingDecl.
1900 return 0;
John McCalled976492009-12-04 22:46:56 +00001901}
1902
John McCall7ba107a2009-11-18 02:36:19 +00001903Decl * TemplateDeclInstantiator
1904 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001905 NestedNameSpecifierLoc QualifierLoc
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001906 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001907 TemplateArgs);
1908 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001909 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001910
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001911 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001912 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001913
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001914 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1915 // Hence, no tranformation is required for it.
1916 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001917 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001918 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001919 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001920 /*instantiation*/ true,
1921 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001922 if (UD)
John McCalled976492009-12-04 22:46:56 +00001923 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1924
John McCall7ba107a2009-11-18 02:36:19 +00001925 return UD;
1926}
1927
1928Decl * TemplateDeclInstantiator
1929 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001930 NestedNameSpecifierLoc QualifierLoc
1931 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1932 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001933 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00001934
John McCall7ba107a2009-11-18 02:36:19 +00001935 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001936 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001937
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001938 DeclarationNameInfo NameInfo
1939 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1940
John McCall7ba107a2009-11-18 02:36:19 +00001941 NamedDecl *UD =
1942 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001943 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001944 /*instantiation*/ true,
1945 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001946 if (UD)
John McCalled976492009-12-04 22:46:56 +00001947 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1948
Anders Carlsson0d8df782009-08-29 19:37:28 +00001949 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001950}
1951
Francois Pichetaf0f4d02011-08-14 03:52:19 +00001952
1953Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
1954 ClassScopeFunctionSpecializationDecl *Decl) {
1955 CXXMethodDecl *OldFD = Decl->getSpecialization();
1956 CXXMethodDecl *NewFD = cast<CXXMethodDecl>(VisitCXXMethodDecl(OldFD, 0, true));
1957
1958 LookupResult Previous(SemaRef, NewFD->getNameInfo(), Sema::LookupOrdinaryName,
1959 Sema::ForRedeclaration);
1960
1961 SemaRef.LookupQualifiedName(Previous, SemaRef.CurContext);
1962 if (SemaRef.CheckFunctionTemplateSpecialization(NewFD, 0, Previous)) {
1963 NewFD->setInvalidDecl();
1964 return NewFD;
1965 }
1966
1967 // Associate the specialization with the pattern.
1968 FunctionDecl *Specialization = cast<FunctionDecl>(Previous.getFoundDecl());
1969 assert(Specialization && "Class scope Specialization is null");
1970 SemaRef.Context.setClassScopeSpecializationPattern(Specialization, OldFD);
1971
1972 return NewFD;
1973}
1974
John McCallce3ff2b2009-08-25 22:02:44 +00001975Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001976 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001977 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001978 if (D->isInvalidDecl())
1979 return 0;
1980
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001981 return Instantiator.Visit(D);
1982}
1983
John McCalle29ba202009-08-20 01:44:21 +00001984/// \brief Instantiates a nested template parameter list in the current
1985/// instantiation context.
1986///
1987/// \param L The parameter list to instantiate
1988///
1989/// \returns NULL if there was an error
1990TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001991TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001992 // Get errors for all the parameters before bailing out.
1993 bool Invalid = false;
1994
1995 unsigned N = L->size();
Chris Lattner5f9e2722011-07-23 10:55:15 +00001996 typedef SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001997 ParamVector Params;
1998 Params.reserve(N);
1999 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
2000 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002001 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00002002 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00002003 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00002004 }
2005
2006 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00002007 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00002008 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00002009
2010 TemplateParameterList *InstL
2011 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
2012 L->getLAngleLoc(), &Params.front(), N,
2013 L->getRAngleLoc());
2014 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00002015}
John McCalle29ba202009-08-20 01:44:21 +00002016
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002017/// \brief Instantiate the declaration of a class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002018/// specialization.
2019///
2020/// \param ClassTemplate the (instantiated) class template that is partially
2021// specialized by the instantiation of \p PartialSpec.
2022///
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002023/// \param PartialSpec the (uninstantiated) class template partial
Douglas Gregored9c0f92009-10-29 00:04:11 +00002024/// specialization that we are instantiating.
2025///
Douglas Gregord65587f2010-11-10 19:44:59 +00002026/// \returns The instantiated partial specialization, if successful; otherwise,
2027/// NULL to indicate an error.
2028ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00002029TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
2030 ClassTemplateDecl *ClassTemplate,
2031 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00002032 // Create a local instantiation scope for this class template partial
2033 // specialization, which will contain the instantiations of the template
2034 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00002035 LocalInstantiationScope Scope(SemaRef);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002036
Douglas Gregored9c0f92009-10-29 00:04:11 +00002037 // Substitute into the template parameters of the class template partial
2038 // specialization.
2039 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
2040 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2041 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00002042 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002043
Douglas Gregored9c0f92009-10-29 00:04:11 +00002044 // Substitute into the template arguments of the class template partial
2045 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00002046 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002047 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
2048 PartialSpec->getNumTemplateArgsAsWritten(),
Douglas Gregore02e2622010-12-22 21:19:48 +00002049 InstTemplateArgs, TemplateArgs))
2050 return 0;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002051
Douglas Gregored9c0f92009-10-29 00:04:11 +00002052 // Check that the template argument list is well-formed for this
2053 // class template.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002054 SmallVector<TemplateArgument, 4> Converted;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002055 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002056 PartialSpec->getLocation(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002057 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002058 false,
2059 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00002060 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002061
2062 // Figure out where to insert this class template partial specialization
2063 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00002064 void *InsertPos = 0;
2065 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00002066 = ClassTemplate->findPartialSpecialization(Converted.data(),
2067 Converted.size(), InsertPos);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002068
Douglas Gregored9c0f92009-10-29 00:04:11 +00002069 // Build the canonical type that describes the converted template
2070 // arguments of the class template partial specialization.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002071 QualType CanonType
Douglas Gregored9c0f92009-10-29 00:04:11 +00002072 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00002073 Converted.data(),
2074 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00002075
2076 // Build the fully-sugared type for this class template
2077 // specialization as the user wrote in the specialization
2078 // itself. This means that we'll pretty-print the type retrieved
2079 // from the specialization's declaration the way that the user
2080 // actually wrote the specialization, rather than formatting the
2081 // name based on the "canonical" representation used to store the
2082 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00002083 TypeSourceInfo *WrittenTy
2084 = SemaRef.Context.getTemplateSpecializationTypeInfo(
2085 TemplateName(ClassTemplate),
2086 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00002087 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002088 CanonType);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002089
Douglas Gregored9c0f92009-10-29 00:04:11 +00002090 if (PrevDecl) {
2091 // We've already seen a partial specialization with the same template
2092 // parameters and template arguments. This can happen, for example, when
2093 // substituting the outer template arguments ends up causing two
2094 // class template partial specializations of a member class template
2095 // to have identical forms, e.g.,
2096 //
2097 // template<typename T, typename U>
2098 // struct Outer {
2099 // template<typename X, typename Y> struct Inner;
2100 // template<typename Y> struct Inner<T, Y>;
2101 // template<typename Y> struct Inner<U, Y>;
2102 // };
2103 //
2104 // Outer<int, int> outer; // error: the partial specializations of Inner
2105 // // have the same signature.
2106 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00002107 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002108 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
2109 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00002110 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002111 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002112
2113
Douglas Gregored9c0f92009-10-29 00:04:11 +00002114 // Create the class template partial specialization declaration.
2115 ClassTemplatePartialSpecializationDecl *InstPartialSpec
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002116 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
Douglas Gregor13c85772010-05-06 00:28:52 +00002117 PartialSpec->getTagKind(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002118 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002119 PartialSpec->getLocStart(),
2120 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002121 InstParams,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002122 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00002123 Converted.data(),
2124 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00002125 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00002126 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002127 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002128 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00002129 // Substitute the nested name specifier, if any.
2130 if (SubstQualifier(PartialSpec, InstPartialSpec))
2131 return 0;
2132
Douglas Gregored9c0f92009-10-29 00:04:11 +00002133 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00002134 InstPartialSpec->setTypeAsWritten(WrittenTy);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002135
Douglas Gregored9c0f92009-10-29 00:04:11 +00002136 // Add this partial specialization to the set of class template partial
2137 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00002138 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00002139 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002140}
2141
John McCall21ef0fa2010-03-11 09:03:00 +00002142TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002143TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002144 SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002145 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2146 assert(OldTInfo && "substituting function without type source info");
2147 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00002148 TypeSourceInfo *NewTInfo
2149 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2150 D->getTypeSpecStartLoc(),
2151 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00002152 if (!NewTInfo)
2153 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002154
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002155 if (NewTInfo != OldTInfo) {
2156 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002157 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002158 if (FunctionProtoTypeLoc *OldProtoLoc
2159 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002160 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002161 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2162 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00002163 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2164 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2165 OldIdx != NumOldParams; ++OldIdx) {
2166 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2167 if (!OldParam->isParameterPack() ||
2168 (NewIdx < NumNewParams &&
2169 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002170 // Simple case: normal parameter, or a parameter pack that's
Douglas Gregor12c9c002011-01-07 16:43:16 +00002171 // instantiated to a (still-dependent) parameter pack.
2172 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2173 Params.push_back(NewParam);
2174 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2175 NewParam);
2176 continue;
2177 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002178
Douglas Gregor12c9c002011-01-07 16:43:16 +00002179 // Parameter pack: make the instantiation an argument pack.
2180 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2181 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002182 unsigned NumArgumentsInExpansion
2183 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2184 TemplateArgs);
2185 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002186 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2187 Params.push_back(NewParam);
2188 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2189 NewParam);
2190 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002191 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002192 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002193 } else {
2194 // The function type itself was not dependent and therefore no
2195 // substitution occurred. However, we still need to instantiate
2196 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002197 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002198 if (FunctionProtoTypeLoc *OldProtoLoc
2199 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2200 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2201 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2202 if (!Parm)
2203 return 0;
2204 Params.push_back(Parm);
2205 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002206 }
2207 }
John McCall21ef0fa2010-03-11 09:03:00 +00002208 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002209}
2210
Mike Stump1eb44332009-09-09 15:08:12 +00002211/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002212/// declaration (New) from the corresponding fields of its template (Tmpl).
2213///
2214/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002215bool
2216TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002217 FunctionDecl *Tmpl) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002218 if (Tmpl->isDeletedAsWritten())
2219 New->setDeletedAsWritten();
Mike Stump1eb44332009-09-09 15:08:12 +00002220
Douglas Gregorcca9e962009-07-01 22:01:06 +00002221 // If we are performing substituting explicitly-specified template arguments
2222 // or deduced template arguments into a function template and we reach this
2223 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002224 // to keeping the new function template specialization. We therefore
2225 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002226 // into a template instantiation for this specific function template
2227 // specialization, which is not a SFINAE context, so that we diagnose any
2228 // further errors in the declaration itself.
2229 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2230 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2231 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2232 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002233 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002234 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002235 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002236 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002237 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002238 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2239 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002240 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002241 }
2242 }
Mike Stump1eb44332009-09-09 15:08:12 +00002243
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002244 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2245 assert(Proto && "Function template without prototype?");
2246
Sebastian Redl60618fa2011-03-12 11:50:43 +00002247 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002248 // The function has an exception specification or a "noreturn"
2249 // attribute. Substitute into each of the exception types.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002250 SmallVector<QualType, 4> Exceptions;
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002251 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2252 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002253 if (const PackExpansionType *PackExpansion
2254 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2255 // We have a pack expansion. Instantiate it.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002256 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorb99268b2010-12-21 00:52:54 +00002257 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2258 Unexpanded);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002259 assert(!Unexpanded.empty() &&
Douglas Gregorb99268b2010-12-21 00:52:54 +00002260 "Pack expansion without parameter packs?");
Sebastian Redl60618fa2011-03-12 11:50:43 +00002261
Douglas Gregorb99268b2010-12-21 00:52:54 +00002262 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002263 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002264 llvm::Optional<unsigned> NumExpansions
2265 = PackExpansion->getNumExpansions();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002266 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
Douglas Gregorb99268b2010-12-21 00:52:54 +00002267 SourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00002268 Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +00002269 TemplateArgs,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002270 Expand,
Douglas Gregord3731192011-01-10 07:32:04 +00002271 RetainExpansion,
2272 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002273 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002274
Douglas Gregorb99268b2010-12-21 00:52:54 +00002275 if (!Expand) {
2276 // We can't expand this pack expansion into separate arguments yet;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002277 // just substitute into the pattern and create a new pack expansion
Douglas Gregorcded4f62011-01-14 17:04:44 +00002278 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002279 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002280 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
Douglas Gregorb99268b2010-12-21 00:52:54 +00002281 TemplateArgs,
2282 New->getLocation(), New->getDeclName());
2283 if (T.isNull())
2284 break;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002285
Douglas Gregorcded4f62011-01-14 17:04:44 +00002286 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002287 Exceptions.push_back(T);
2288 continue;
2289 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002290
Douglas Gregorb99268b2010-12-21 00:52:54 +00002291 // Substitute into the pack expansion pattern for each template
2292 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002293 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002294 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002295
2296 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
Douglas Gregorb99268b2010-12-21 00:52:54 +00002297 TemplateArgs,
2298 New->getLocation(), New->getDeclName());
2299 if (T.isNull()) {
2300 Invalid = true;
2301 break;
2302 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002303
Douglas Gregorb99268b2010-12-21 00:52:54 +00002304 Exceptions.push_back(T);
2305 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002306
Douglas Gregorb99268b2010-12-21 00:52:54 +00002307 if (Invalid)
2308 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002309
Douglas Gregorb99268b2010-12-21 00:52:54 +00002310 continue;
2311 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002312
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002313 QualType T
2314 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2315 New->getLocation(), New->getDeclName());
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002316 if (T.isNull() ||
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002317 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2318 continue;
2319
2320 Exceptions.push_back(T);
2321 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002322 Expr *NoexceptExpr = 0;
2323 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
Douglas Gregor3617e192011-06-01 15:55:51 +00002324 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Sebastian Redl56fb9262011-03-14 18:51:50 +00002325 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2326 if (E.isUsable())
Douglas Gregor5c340e82011-10-09 18:31:23 +00002327 E = SemaRef.CheckBooleanCondition(E.get(), E.get()->getLocStart());
2328
2329 if (E.isUsable()) {
2330 SourceLocation ErrLoc;
2331 llvm::APSInt NoexceptVal;
Sebastian Redl56fb9262011-03-14 18:51:50 +00002332 NoexceptExpr = E.take();
Douglas Gregor5c340e82011-10-09 18:31:23 +00002333 if (!NoexceptExpr->isTypeDependent() &&
2334 !NoexceptExpr->isValueDependent() &&
2335 !NoexceptExpr->isIntegerConstantExpr(NoexceptVal, SemaRef.Context,
2336 &ErrLoc, /*evaluated=*/false)){
2337 SemaRef.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
2338 << NoexceptExpr->getSourceRange();
2339 NoexceptExpr = 0;
2340 }
2341 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002342 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002343
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002344 // Rebuild the function type
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002345
John McCalle23cf432010-12-14 08:05:40 +00002346 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002347 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00002348 EPI.NumExceptions = Exceptions.size();
2349 EPI.Exceptions = Exceptions.data();
Sebastian Redl56fb9262011-03-14 18:51:50 +00002350 EPI.NoexceptExpr = NoexceptExpr;
John McCalle23cf432010-12-14 08:05:40 +00002351 EPI.ExtInfo = Proto->getExtInfo();
2352
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002353 const FunctionProtoType *NewProto
2354 = New->getType()->getAs<FunctionProtoType>();
2355 assert(NewProto && "Template instantiation without function prototype?");
2356 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2357 NewProto->arg_type_begin(),
2358 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002359 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002360 }
2361
Richard Smith9f569cc2011-10-01 02:31:28 +00002362 // C++0x [dcl.constexpr]p6: If the instantiated template specialization of
2363 // a constexpr function template satisfies the requirements for a constexpr
2364 // function, then it is a constexpr function.
2365 if (Tmpl->isConstexpr() &&
2366 SemaRef.CheckConstexprFunctionDecl(New, Sema::CCK_Instantiation))
2367 New->setConstexpr(true);
2368
Rafael Espindola19f74ac2011-07-06 15:46:09 +00002369 const FunctionDecl* Definition = Tmpl;
2370
2371 // Get the definition. Leaves the variable unchanged if undefined.
2372 Tmpl->isDefined(Definition);
2373
2374 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002375
Douglas Gregore53060f2009-06-25 22:08:12 +00002376 return false;
2377}
2378
Douglas Gregor5545e162009-03-24 00:38:23 +00002379/// \brief Initializes common fields of an instantiated method
2380/// declaration (New) from the corresponding fields of its template
2381/// (Tmpl).
2382///
2383/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002384bool
2385TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002386 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002387 if (InitFunctionInstantiation(New, Tmpl))
2388 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002389
Douglas Gregor5545e162009-03-24 00:38:23 +00002390 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002391 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002392 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002393
2394 // FIXME: attributes
2395 // FIXME: New needs a pointer to Tmpl
2396 return false;
2397}
Douglas Gregora58861f2009-05-13 20:28:22 +00002398
2399/// \brief Instantiate the definition of the given function from its
2400/// template.
2401///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002402/// \param PointOfInstantiation the point at which the instantiation was
2403/// required. Note that this is not precisely a "point of instantiation"
2404/// for the function, but it's close.
2405///
Douglas Gregora58861f2009-05-13 20:28:22 +00002406/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002407/// function template specialization or member function of a class template
2408/// specialization.
2409///
2410/// \param Recursive if true, recursively instantiates any functions that
2411/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002412///
2413/// \param DefinitionRequired if true, then we are performing an explicit
2414/// instantiation where the body of the function is required. Complain if
2415/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002416void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002417 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002418 bool Recursive,
2419 bool DefinitionRequired) {
Sean Hunt10620eb2011-05-06 20:44:56 +00002420 if (Function->isInvalidDecl() || Function->isDefined())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002421 return;
2422
Francois Pichetaf0f4d02011-08-14 03:52:19 +00002423 // Never instantiate an explicit specialization except if it is a class scope
2424 // explicit specialization.
2425 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
2426 !Function->getClassScopeSpecializationPattern())
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002427 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002428
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002429 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002430 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Sean Huntf996e052011-05-27 20:00:14 +00002431 assert(PatternDecl && "instantiating a non-template");
2432
2433 Stmt *Pattern = PatternDecl->getBody(PatternDecl);
2434 assert(PatternDecl && "template definition is not a template");
2435 if (!Pattern) {
2436 // Try to find a defaulted definition
2437 PatternDecl->isDefined(PatternDecl);
Sean Huntdfab8542011-05-25 22:02:25 +00002438 }
Sean Huntf996e052011-05-27 20:00:14 +00002439 assert(PatternDecl && "template definition is not a template");
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002440
Francois Pichet8387e2a2011-04-22 22:18:13 +00002441 // Postpone late parsed template instantiations.
Sean Huntf996e052011-05-27 20:00:14 +00002442 if (PatternDecl->isLateTemplateParsed() &&
Nick Lewycky8a29bc02011-05-12 03:51:24 +00002443 !LateTemplateParser) {
Francois Pichet8387e2a2011-04-22 22:18:13 +00002444 PendingInstantiations.push_back(
2445 std::make_pair(Function, PointOfInstantiation));
2446 return;
2447 }
2448
2449 // Call the LateTemplateParser callback if there a need to late parse
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002450 // a templated function definition.
Sean Huntf996e052011-05-27 20:00:14 +00002451 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
Francois Pichet8387e2a2011-04-22 22:18:13 +00002452 LateTemplateParser) {
Francois Pichet4a47e8d2011-04-23 11:52:20 +00002453 LateTemplateParser(OpaqueParser, PatternDecl);
Francois Pichet8387e2a2011-04-22 22:18:13 +00002454 Pattern = PatternDecl->getBody(PatternDecl);
2455 }
2456
Sean Huntf996e052011-05-27 20:00:14 +00002457 if (!Pattern && !PatternDecl->isDefaulted()) {
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002458 if (DefinitionRequired) {
2459 if (Function->getPrimaryTemplate())
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002460 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002461 diag::err_explicit_instantiation_undefined_func_template)
2462 << Function->getPrimaryTemplate();
2463 else
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002464 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002465 diag::err_explicit_instantiation_undefined_member)
2466 << 1 << Function->getDeclName() << Function->getDeclContext();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002467
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002468 if (PatternDecl)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002469 Diag(PatternDecl->getLocation(),
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002470 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002471 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002472 } else if (Function->getTemplateSpecializationKind()
2473 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002474 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002475 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002476 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002477
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002478 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002479 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002480
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002481 // C++0x [temp.explicit]p9:
2482 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002483 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002484 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002485 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002486 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002487 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002488 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002489
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002490 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2491 if (Inst)
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002492 return;
2493
Abramo Bagnarae9946242011-11-18 08:08:52 +00002494 // Copy the inner loc start from the pattern.
2495 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
2496
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002497 // If we're performing recursive template instantiation, create our own
2498 // queue of pending implicit instantiations that we will instantiate later,
2499 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002500 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002501 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002502 if (Recursive) {
2503 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002504 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002505 }
Mike Stump1eb44332009-09-09 15:08:12 +00002506
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002507 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002508 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002509 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002510
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002511 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002512 // recorded, unless we're actually a member function within a local
2513 // class, in which case we need to merge our results with the parent
2514 // scope (of the enclosing function).
2515 bool MergeWithParentScope = false;
2516 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2517 MergeWithParentScope = Rec->isLocalClass();
2518
2519 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002520
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002521 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002522 // instantiation scope, and set the parameter names to those used
2523 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002524 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002525 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2526 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002527 if (!PatternParam->isParameterPack()) {
2528 // Simple case: not a parameter pack.
2529 assert(FParamIdx < Function->getNumParams());
2530 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2531 FunctionParam->setDeclName(PatternParam->getDeclName());
2532 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2533 ++FParamIdx;
2534 continue;
2535 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002536
Douglas Gregor12c9c002011-01-07 16:43:16 +00002537 // Expand the parameter pack.
2538 Scope.MakeInstantiatedLocalArgPack(PatternParam);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002539 for (unsigned NumFParams = Function->getNumParams();
2540 FParamIdx < NumFParams;
Douglas Gregor12c9c002011-01-07 16:43:16 +00002541 ++FParamIdx) {
2542 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2543 FunctionParam->setDeclName(PatternParam->getDeclName());
2544 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2545 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002546 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002547
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002548 // Enter the scope of this instantiation. We don't use
2549 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002550 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002551
Mike Stump1eb44332009-09-09 15:08:12 +00002552 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002553 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002554
Sean Huntcd10dec2011-05-23 23:14:04 +00002555 if (PatternDecl->isDefaulted()) {
2556 ActOnFinishFunctionBody(Function, 0, /*IsInstantiation=*/true);
2557
2558 SetDeclDefaulted(Function, PatternDecl->getLocation());
Sean Huntcd10dec2011-05-23 23:14:04 +00002559 } else {
2560 // If this is a constructor, instantiate the member initializers.
2561 if (const CXXConstructorDecl *Ctor =
2562 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2563 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2564 TemplateArgs);
2565 }
2566
2567 // Instantiate the function body.
2568 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
2569
2570 if (Body.isInvalid())
2571 Function->setInvalidDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002572
Sean Huntcd10dec2011-05-23 23:14:04 +00002573 ActOnFinishFunctionBody(Function, Body.get(),
2574 /*IsInstantiation=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00002575 }
2576
John McCall0c01d182010-03-24 05:22:00 +00002577 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2578
John McCalleee1d542011-02-14 07:13:47 +00002579 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002580
2581 DeclGroupRef DG(Function);
2582 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002583
Douglas Gregor60406be2010-01-16 22:29:39 +00002584 // This class may have local implicit instantiations that need to be
2585 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002586 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002587 Scope.Exit();
2588
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002589 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002590 // Define any pending vtables.
2591 DefineUsedVTables();
2592
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002593 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002594 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002595 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002597 // Restore the set of pending vtables.
Nick Lewycky81559102011-05-31 07:58:42 +00002598 assert(VTableUses.empty() &&
2599 "VTableUses should be empty before it is discarded.");
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002600 VTableUses.swap(SavedVTableUses);
2601
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002602 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00002603 assert(PendingInstantiations.empty() &&
2604 "PendingInstantiations should be empty before it is discarded.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00002605 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002606 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002607}
2608
2609/// \brief Instantiate the definition of the given variable from its
2610/// template.
2611///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002612/// \param PointOfInstantiation the point at which the instantiation was
2613/// required. Note that this is not precisely a "point of instantiation"
2614/// for the function, but it's close.
2615///
2616/// \param Var the already-instantiated declaration of a static member
2617/// variable of a class template specialization.
2618///
2619/// \param Recursive if true, recursively instantiates any functions that
2620/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002621///
2622/// \param DefinitionRequired if true, then we are performing an explicit
2623/// instantiation where an out-of-line definition of the member variable
2624/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002625void Sema::InstantiateStaticDataMemberDefinition(
2626 SourceLocation PointOfInstantiation,
2627 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002628 bool Recursive,
2629 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002630 if (Var->isInvalidDecl())
2631 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002632
Douglas Gregor7caa6822009-07-24 20:34:43 +00002633 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002634 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002635 assert(Def && "This data member was not instantiated from a template?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002636 assert(Def->isStaticDataMember() && "Not a static data member?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002637 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Douglas Gregor0d035142009-10-27 18:42:08 +00002639 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002640 // We did not find an out-of-line definition of this static data member,
2641 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002642 // instantiate this definition (or provide a specialization for it) in
2643 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002644 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002645 Def = Var->getInstantiatedFromStaticDataMember();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002646 Diag(PointOfInstantiation,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002647 diag::err_explicit_instantiation_undefined_member)
2648 << 2 << Var->getDeclName() << Var->getDeclContext();
2649 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002650 } else if (Var->getTemplateSpecializationKind()
2651 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002652 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002653 std::make_pair(Var, PointOfInstantiation));
2654 }
2655
Douglas Gregor7caa6822009-07-24 20:34:43 +00002656 return;
2657 }
2658
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002659 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002660 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002661 return;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002662
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002663 // C++0x [temp.explicit]p9:
2664 // Except for inline functions, other explicit instantiation declarations
2665 // have the effect of suppressing the implicit instantiation of the entity
2666 // to which they refer.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002667 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002668 == TSK_ExplicitInstantiationDeclaration)
2669 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002670
Douglas Gregorf15748a2011-06-03 03:35:07 +00002671 // If we already have a definition, we're done.
2672 if (Var->getDefinition())
2673 return;
2674
Douglas Gregor7caa6822009-07-24 20:34:43 +00002675 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2676 if (Inst)
2677 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002678
Douglas Gregor7caa6822009-07-24 20:34:43 +00002679 // If we're performing recursive template instantiation, create our own
2680 // queue of pending implicit instantiations that we will instantiate later,
2681 // while we're still within our own instantiation context.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002682 SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002683 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky81559102011-05-31 07:58:42 +00002684 if (Recursive) {
2685 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002686 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky81559102011-05-31 07:58:42 +00002687 }
Mike Stump1eb44332009-09-09 15:08:12 +00002688
Douglas Gregor7caa6822009-07-24 20:34:43 +00002689 // Enter the scope of this instantiation. We don't use
2690 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002691 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002692
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002693 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002694 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002695 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002696
2697 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002698
2699 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002700 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2701 assert(MSInfo && "Missing member specialization information?");
2702 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2703 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002704 DeclGroupRef DG(Var);
2705 Consumer.HandleTopLevelDecl(DG);
2706 }
Mike Stump1eb44332009-09-09 15:08:12 +00002707
Douglas Gregor7caa6822009-07-24 20:34:43 +00002708 if (Recursive) {
Nick Lewycky81559102011-05-31 07:58:42 +00002709 // Define any newly required vtables.
2710 DefineUsedVTables();
2711
Douglas Gregor7caa6822009-07-24 20:34:43 +00002712 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002713 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002714 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002715
Nick Lewycky81559102011-05-31 07:58:42 +00002716 // Restore the set of pending vtables.
2717 assert(VTableUses.empty() &&
2718 "VTableUses should be empty before it is discarded, "
2719 "while instantiating static data member.");
2720 VTableUses.swap(SavedVTableUses);
2721
Douglas Gregor7caa6822009-07-24 20:34:43 +00002722 // Restore the set of pending implicit instantiations.
Nick Lewycky81559102011-05-31 07:58:42 +00002723 assert(PendingInstantiations.empty() &&
2724 "PendingInstantiations should be empty before it is discarded, "
2725 "while instantiating static data member.");
Chandler Carruth62c78d52010-08-25 08:44:16 +00002726 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002727 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002728}
Douglas Gregor815215d2009-05-27 05:35:12 +00002729
Benjamin Kramer54dec5f2011-10-08 16:15:07 +00002730static MultiInitializer CreateMultiInitializer(SmallVectorImpl<Expr*> &Args,
2731 const CXXCtorInitializer *Init) {
Sebastian Redl6df65482011-09-24 17:48:25 +00002732 // FIXME: This is a hack that will do slightly the wrong thing for an
2733 // initializer of the form foo({...}).
2734 // The right thing to do would be to modify InstantiateInitializer to create
2735 // the MultiInitializer.
2736 if (Args.size() == 1 && isa<InitListExpr>(Args[0]))
2737 return MultiInitializer(Args[0]);
Sebastian Redlc046f302011-10-17 16:53:50 +00002738 return MultiInitializer(Init->getLParenLoc(), Args.data(),
Sebastian Redl6df65482011-09-24 17:48:25 +00002739 Args.size(), Init->getRParenLoc());
2740}
2741
Anders Carlsson09025312009-08-29 05:16:22 +00002742void
2743Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2744 const CXXConstructorDecl *Tmpl,
2745 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Richard Trieu90ab75b2011-09-09 03:18:59 +00002747 SmallVector<CXXCtorInitializer*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002748 bool AnyErrors = false;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002749
Anders Carlsson09025312009-08-29 05:16:22 +00002750 // Instantiate all the initializers.
2751 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002752 InitsEnd = Tmpl->init_end();
2753 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002754 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002755
Chandler Carruth030ef472010-09-03 21:54:20 +00002756 // Only instantiate written initializers, let Sema re-construct implicit
2757 // ones.
2758 if (!Init->isWritten())
2759 continue;
2760
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002761 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002762 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002763
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002764 SourceLocation EllipsisLoc;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002765
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002766 if (Init->isPackExpansion()) {
2767 // This is a pack expansion. We should expand it now.
Douglas Gregor76852c22011-11-01 01:16:03 +00002768 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002769 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002770 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2771 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002772 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002773 llvm::Optional<unsigned> NumExpansions;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002774 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002775 BaseTL.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00002776 Unexpanded,
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002777 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002778 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002779 NumExpansions)) {
2780 AnyErrors = true;
2781 New->setInvalidDecl();
2782 continue;
2783 }
2784 assert(ShouldExpand && "Partial instantiation of base initializer?");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002785
2786 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002787 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002788 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2789
2790 // Instantiate the initializer.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002791 if (InstantiateInitializer(Init->getInit(), TemplateArgs,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002792 LParenLoc, NewArgs, RParenLoc)) {
2793 AnyErrors = true;
2794 break;
2795 }
2796
2797 // Instantiate the base type.
Douglas Gregor76852c22011-11-01 01:16:03 +00002798 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002799 TemplateArgs,
2800 Init->getSourceLocation(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002801 New->getDeclName());
2802 if (!BaseTInfo) {
2803 AnyErrors = true;
2804 break;
2805 }
2806
2807 // Build the initializer.
Sebastian Redl6df65482011-09-24 17:48:25 +00002808 MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
2809 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2810 BaseTInfo, MultiInit,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002811 New->getParent(),
2812 SourceLocation());
2813 if (NewInit.isInvalid()) {
2814 AnyErrors = true;
2815 break;
2816 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002817
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002818 NewInits.push_back(NewInit.get());
2819 NewArgs.clear();
2820 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002821
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002822 continue;
2823 }
2824
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002825 // Instantiate the initializer.
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002826 if (InstantiateInitializer(Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002827 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002828 AnyErrors = true;
2829 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002830 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002831
Anders Carlsson09025312009-08-29 05:16:22 +00002832 MemInitResult NewInit;
Douglas Gregor76852c22011-11-01 01:16:03 +00002833 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
2834 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
2835 TemplateArgs,
2836 Init->getSourceLocation(),
2837 New->getDeclName());
2838 if (!TInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002839 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002840 New->setInvalidDecl();
2841 continue;
2842 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002843
2844 MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
Douglas Gregor76852c22011-11-01 01:16:03 +00002845
2846 if (Init->isBaseInitializer())
2847 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, MultiInit,
2848 New->getParent(), EllipsisLoc);
2849 else
2850 NewInit = BuildDelegatingInitializer(TInfo, MultiInit,
2851 cast<CXXRecordDecl>(CurContext->getParent()));
Anders Carlsson09025312009-08-29 05:16:22 +00002852 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002853 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002854 Init->getMemberLocation(),
2855 Init->getMember(),
2856 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002857 if (!Member) {
2858 AnyErrors = true;
2859 New->setInvalidDecl();
2860 continue;
2861 }
Mike Stump1eb44332009-09-09 15:08:12 +00002862
Sebastian Redl6df65482011-09-24 17:48:25 +00002863 MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
2864 NewInit = BuildMemberInitializer(Member, MultiInit,
2865 Init->getSourceLocation());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002866 } else if (Init->isIndirectMemberInitializer()) {
2867 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002868 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002869 Init->getMemberLocation(),
2870 Init->getIndirectMember(), TemplateArgs));
2871
Douglas Gregorb7107222011-03-04 19:46:35 +00002872 if (!IndirectMember) {
2873 AnyErrors = true;
2874 New->setInvalidDecl();
Sebastian Redl6df65482011-09-24 17:48:25 +00002875 continue;
Douglas Gregorb7107222011-03-04 19:46:35 +00002876 }
Sebastian Redl6df65482011-09-24 17:48:25 +00002877
2878 MultiInitializer MultiInit(CreateMultiInitializer(NewArgs, Init));
2879 NewInit = BuildMemberInitializer(IndirectMember, MultiInit,
2880 Init->getSourceLocation());
Anders Carlsson09025312009-08-29 05:16:22 +00002881 }
2882
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002883 if (NewInit.isInvalid()) {
2884 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002885 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002886 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002887 // FIXME: It would be nice if ASTOwningVector had a release function.
2888 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002889
Richard Trieu90ab75b2011-09-09 03:18:59 +00002890 NewInits.push_back(NewInit.get());
Anders Carlsson09025312009-08-29 05:16:22 +00002891 }
2892 }
Mike Stump1eb44332009-09-09 15:08:12 +00002893
Anders Carlsson09025312009-08-29 05:16:22 +00002894 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002895 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002896 /*FIXME: ColonLoc */
2897 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002898 NewInits.data(), NewInits.size(),
2899 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002900}
2901
John McCall52a575a2009-08-29 08:11:13 +00002902// TODO: this could be templated if the various decl types used the
2903// same method name.
2904static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2905 ClassTemplateDecl *Instance) {
2906 Pattern = Pattern->getCanonicalDecl();
2907
2908 do {
2909 Instance = Instance->getCanonicalDecl();
2910 if (Pattern == Instance) return true;
2911 Instance = Instance->getInstantiatedFromMemberTemplate();
2912 } while (Instance);
2913
2914 return false;
2915}
2916
Douglas Gregor0d696532009-09-28 06:34:35 +00002917static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2918 FunctionTemplateDecl *Instance) {
2919 Pattern = Pattern->getCanonicalDecl();
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002920
Douglas Gregor0d696532009-09-28 06:34:35 +00002921 do {
2922 Instance = Instance->getCanonicalDecl();
2923 if (Pattern == Instance) return true;
2924 Instance = Instance->getInstantiatedFromMemberTemplate();
2925 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002926
Douglas Gregor0d696532009-09-28 06:34:35 +00002927 return false;
2928}
2929
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002930static bool
Douglas Gregored9c0f92009-10-29 00:04:11 +00002931isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2932 ClassTemplatePartialSpecializationDecl *Instance) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002933 Pattern
Douglas Gregored9c0f92009-10-29 00:04:11 +00002934 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2935 do {
2936 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2937 Instance->getCanonicalDecl());
2938 if (Pattern == Instance)
2939 return true;
2940 Instance = Instance->getInstantiatedFromMember();
2941 } while (Instance);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00002942
Douglas Gregored9c0f92009-10-29 00:04:11 +00002943 return false;
2944}
2945
John McCall52a575a2009-08-29 08:11:13 +00002946static bool isInstantiationOf(CXXRecordDecl *Pattern,
2947 CXXRecordDecl *Instance) {
2948 Pattern = Pattern->getCanonicalDecl();
2949
2950 do {
2951 Instance = Instance->getCanonicalDecl();
2952 if (Pattern == Instance) return true;
2953 Instance = Instance->getInstantiatedFromMemberClass();
2954 } while (Instance);
2955
2956 return false;
2957}
2958
2959static bool isInstantiationOf(FunctionDecl *Pattern,
2960 FunctionDecl *Instance) {
2961 Pattern = Pattern->getCanonicalDecl();
2962
2963 do {
2964 Instance = Instance->getCanonicalDecl();
2965 if (Pattern == Instance) return true;
2966 Instance = Instance->getInstantiatedFromMemberFunction();
2967 } while (Instance);
2968
2969 return false;
2970}
2971
2972static bool isInstantiationOf(EnumDecl *Pattern,
2973 EnumDecl *Instance) {
2974 Pattern = Pattern->getCanonicalDecl();
2975
2976 do {
2977 Instance = Instance->getCanonicalDecl();
2978 if (Pattern == Instance) return true;
2979 Instance = Instance->getInstantiatedFromMemberEnum();
2980 } while (Instance);
2981
2982 return false;
2983}
2984
John McCalled976492009-12-04 22:46:56 +00002985static bool isInstantiationOf(UsingShadowDecl *Pattern,
2986 UsingShadowDecl *Instance,
2987 ASTContext &C) {
2988 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2989}
2990
2991static bool isInstantiationOf(UsingDecl *Pattern,
2992 UsingDecl *Instance,
2993 ASTContext &C) {
2994 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2995}
2996
John McCall7ba107a2009-11-18 02:36:19 +00002997static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2998 UsingDecl *Instance,
2999 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003000 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00003001}
3002
3003static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00003004 UsingDecl *Instance,
3005 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00003006 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00003007}
3008
John McCall52a575a2009-08-29 08:11:13 +00003009static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
3010 VarDecl *Instance) {
3011 assert(Instance->isStaticDataMember());
3012
3013 Pattern = Pattern->getCanonicalDecl();
3014
3015 do {
3016 Instance = Instance->getCanonicalDecl();
3017 if (Pattern == Instance) return true;
3018 Instance = Instance->getInstantiatedFromStaticDataMember();
3019 } while (Instance);
3020
3021 return false;
3022}
3023
John McCalled976492009-12-04 22:46:56 +00003024// Other is the prospective instantiation
3025// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00003026static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003027 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00003028 if (UnresolvedUsingTypenameDecl *UUD
3029 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
3030 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3031 return isInstantiationOf(UUD, UD, Ctx);
3032 }
3033 }
3034
3035 if (UnresolvedUsingValueDecl *UUD
3036 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00003037 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
3038 return isInstantiationOf(UUD, UD, Ctx);
3039 }
3040 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003041
Anders Carlsson0d8df782009-08-29 19:37:28 +00003042 return false;
3043 }
Mike Stump1eb44332009-09-09 15:08:12 +00003044
John McCall52a575a2009-08-29 08:11:13 +00003045 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
3046 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00003047
John McCall52a575a2009-08-29 08:11:13 +00003048 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
3049 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00003050
John McCall52a575a2009-08-29 08:11:13 +00003051 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
3052 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00003053
Douglas Gregor7caa6822009-07-24 20:34:43 +00003054 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00003055 if (Var->isStaticDataMember())
3056 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
3057
3058 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
3059 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00003060
Douglas Gregor0d696532009-09-28 06:34:35 +00003061 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
3062 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
3063
Douglas Gregored9c0f92009-10-29 00:04:11 +00003064 if (ClassTemplatePartialSpecializationDecl *PartialSpec
3065 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
3066 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
3067 PartialSpec);
3068
Anders Carlssond8b285f2009-09-01 04:26:58 +00003069 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
3070 if (!Field->getDeclName()) {
3071 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00003072 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00003073 cast<FieldDecl>(D);
3074 }
3075 }
Mike Stump1eb44332009-09-09 15:08:12 +00003076
John McCalled976492009-12-04 22:46:56 +00003077 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
3078 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
3079
3080 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
3081 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
3082
Douglas Gregor815215d2009-05-27 05:35:12 +00003083 return D->getDeclName() && isa<NamedDecl>(Other) &&
3084 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
3085}
3086
3087template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00003088static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00003089 NamedDecl *D,
3090 ForwardIterator first,
3091 ForwardIterator last) {
3092 for (; first != last; ++first)
3093 if (isInstantiationOf(Ctx, D, *first))
3094 return cast<NamedDecl>(*first);
3095
3096 return 0;
3097}
3098
John McCall02cace72009-08-28 07:59:38 +00003099/// \brief Finds the instantiation of the given declaration context
3100/// within the current instantiation.
3101///
3102/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003103DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00003104 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00003105 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003106 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00003107 return cast_or_null<DeclContext>(ID);
3108 } else return DC;
3109}
3110
Douglas Gregored961e72009-05-27 17:54:46 +00003111/// \brief Find the instantiation of the given declaration within the
3112/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00003113///
3114/// This routine is intended to be used when \p D is a declaration
3115/// referenced from within a template, that needs to mapped into the
3116/// corresponding declaration within an instantiation. For example,
3117/// given:
3118///
3119/// \code
3120/// template<typename T>
3121/// struct X {
3122/// enum Kind {
3123/// KnownValue = sizeof(T)
3124/// };
3125///
3126/// bool getKind() const { return KnownValue; }
3127/// };
3128///
3129/// template struct X<int>;
3130/// \endcode
3131///
3132/// In the instantiation of X<int>::getKind(), we need to map the
3133/// EnumConstantDecl for KnownValue (which refers to
3134/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00003135/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
3136/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003137NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00003138 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00003139 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00003140 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00003141 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00003142 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003143 // D is a local of some kind. Look into the map of local
3144 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00003145 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
3146 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
3147 = CurrentInstantiationScope->findInstantiationOf(D);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003148
Chris Lattner57ad3782011-02-17 20:34:02 +00003149 if (Found) {
3150 if (Decl *FD = Found->dyn_cast<Decl *>())
3151 return cast<NamedDecl>(FD);
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003152
Chris Lattner57ad3782011-02-17 20:34:02 +00003153 unsigned PackIdx = ArgumentPackSubstitutionIndex;
3154 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
3155 }
3156
3157 // If we didn't find the decl, then we must have a label decl that hasn't
3158 // been found yet. Lazily instantiate it and return it now.
3159 assert(isa<LabelDecl>(D));
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003160
Chris Lattner57ad3782011-02-17 20:34:02 +00003161 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
3162 assert(Inst && "Failed to instantiate label??");
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003163
Chris Lattner57ad3782011-02-17 20:34:02 +00003164 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
3165 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00003166 }
Douglas Gregor815215d2009-05-27 05:35:12 +00003167
Douglas Gregore95b4092009-09-16 18:34:49 +00003168 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
3169 if (!Record->isDependentContext())
3170 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003171
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003172 // Determine whether this record is the "templated" declaration describing
3173 // a class template or class template partial specialization.
Douglas Gregore95b4092009-09-16 18:34:49 +00003174 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003175 if (ClassTemplate)
3176 ClassTemplate = ClassTemplate->getCanonicalDecl();
3177 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
3178 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
3179 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
3180
3181 // Walk the current context to find either the record or an instantiation of
3182 // it.
3183 DeclContext *DC = CurContext;
3184 while (!DC->isFileContext()) {
3185 // If we're performing substitution while we're inside the template
3186 // definition, we'll find our own context. We're done.
3187 if (DC->Equals(Record))
3188 return Record;
3189
3190 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
3191 // Check whether we're in the process of instantiating a class template
3192 // specialization of the template we're mapping.
3193 if (ClassTemplateSpecializationDecl *InstSpec
3194 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
3195 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
3196 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
3197 return InstRecord;
3198 }
3199
3200 // Check whether we're in the process of instantiating a member class.
3201 if (isInstantiationOf(Record, InstRecord))
3202 return InstRecord;
Douglas Gregore95b4092009-09-16 18:34:49 +00003203 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003204
3205
3206 // Move to the outer template scope.
3207 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
3208 if (FD->getFriendObjectKind() && FD->getDeclContext()->isFileContext()){
3209 DC = FD->getLexicalDeclContext();
3210 continue;
3211 }
John McCall52a575a2009-08-29 08:11:13 +00003212 }
Douglas Gregor2c1227c2011-11-07 17:43:18 +00003213
3214 DC = DC->getParent();
John McCall52a575a2009-08-29 08:11:13 +00003215 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003216
Douglas Gregore95b4092009-09-16 18:34:49 +00003217 // Fall through to deal with other dependent record types (e.g.,
3218 // anonymous unions in class templates).
3219 }
John McCall52a575a2009-08-29 08:11:13 +00003220
Douglas Gregore95b4092009-09-16 18:34:49 +00003221 if (!ParentDC->isDependentContext())
3222 return D;
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003223
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003224 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003225 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003226 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003227
Douglas Gregor815215d2009-05-27 05:35:12 +00003228 if (ParentDC != D->getDeclContext()) {
3229 // We performed some kind of instantiation in the parent context,
3230 // so now we need to look into the instantiated parent context to
3231 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003232
John McCall3cb0ebd2010-03-10 03:28:59 +00003233 // If our context used to be dependent, we may need to instantiate
3234 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003235 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003236 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003237 if (!Spec->isDependentContext()) {
3238 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003239 const RecordType *Tag = T->getAs<RecordType>();
3240 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003241 if (Tag->isBeingDefined())
3242 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003243 if (!Tag->isBeingDefined() &&
3244 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3245 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003246
3247 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003248 }
3249 }
3250
Douglas Gregor815215d2009-05-27 05:35:12 +00003251 NamedDecl *Result = 0;
3252 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003253 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003254 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3255 } else {
3256 // Since we don't have a name for the entity we're looking for,
3257 // our only option is to walk through all of the declarations to
3258 // find that name. This will occur in a few cases:
3259 //
3260 // - anonymous struct/union within a template
3261 // - unnamed class/struct/union/enum within a template
3262 //
3263 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003264 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003265 ParentDC->decls_begin(),
3266 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003267 }
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003269 if (!Result) {
3270 if (isa<UsingShadowDecl>(D)) {
3271 // UsingShadowDecls can instantiate to nothing because of using hiding.
3272 } else if (Diags.hasErrorOccurred()) {
3273 // We've already complained about something, so most likely this
3274 // declaration failed to instantiate. There's no point in complaining
3275 // further, since this is normal in invalid code.
3276 } else if (IsBeingInstantiated) {
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003277 // The class in which this member exists is currently being
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003278 // instantiated, and we haven't gotten around to instantiating this
3279 // member yet. This can happen when the code uses forward declarations
3280 // of member classes, and introduces ordering dependencies via
3281 // template instantiation.
3282 Diag(Loc, diag::err_member_not_yet_instantiated)
3283 << D->getDeclName()
3284 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3285 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3286 } else {
3287 // We should have found something, but didn't.
3288 llvm_unreachable("Unable to find instantiation of declaration!");
3289 }
3290 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003291
Douglas Gregor815215d2009-05-27 05:35:12 +00003292 D = Result;
3293 }
3294
Douglas Gregor815215d2009-05-27 05:35:12 +00003295 return D;
3296}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003297
Mike Stump1eb44332009-09-09 15:08:12 +00003298/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003299/// instantiations we have seen until this point.
Nick Lewycky81559102011-05-31 07:58:42 +00003300void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor6e4a3f52011-07-28 19:49:54 +00003301 // Load pending instantiations from the external source.
3302 if (!LocalOnly && ExternalSource) {
3303 SmallVector<std::pair<ValueDecl *, SourceLocation>, 4> Pending;
3304 ExternalSource->ReadPendingInstantiations(Pending);
3305 PendingInstantiations.insert(PendingInstantiations.begin(),
3306 Pending.begin(), Pending.end());
3307 }
NAKAMURA Takumia789ca92011-10-08 11:31:46 +00003308
Douglas Gregor60406be2010-01-16 22:29:39 +00003309 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003310 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003311 PendingImplicitInstantiation Inst;
3312
3313 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003314 Inst = PendingInstantiations.front();
3315 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003316 } else {
3317 Inst = PendingLocalImplicitInstantiations.front();
3318 PendingLocalImplicitInstantiations.pop_front();
3319 }
Mike Stump1eb44332009-09-09 15:08:12 +00003320
Douglas Gregor7caa6822009-07-24 20:34:43 +00003321 // Instantiate function definitions
3322 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003323 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3324 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003325 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3326 TSK_ExplicitInstantiationDefinition;
3327 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3328 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003329 continue;
3330 }
Mike Stump1eb44332009-09-09 15:08:12 +00003331
Douglas Gregor7caa6822009-07-24 20:34:43 +00003332 // Instantiate static data member definitions.
3333 VarDecl *Var = cast<VarDecl>(Inst.first);
3334 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003335
Chandler Carruth291b4412010-02-13 10:17:50 +00003336 // Don't try to instantiate declarations if the most recent redeclaration
3337 // is invalid.
3338 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3339 continue;
3340
3341 // Check if the most recent declaration has changed the specialization kind
3342 // and removed the need for implicit instantiation.
3343 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3344 case TSK_Undeclared:
David Blaikieb219cfc2011-09-23 05:06:16 +00003345 llvm_unreachable("Cannot instantitiate an undeclared specialization.");
Chandler Carruth291b4412010-02-13 10:17:50 +00003346 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003347 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003348 continue; // No longer need to instantiate this type.
3349 case TSK_ExplicitInstantiationDefinition:
3350 // We only need an instantiation if the pending instantiation *is* the
3351 // explicit instantiation.
3352 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003353 case TSK_ImplicitInstantiation:
3354 break;
3355 }
3356
John McCallf312b1e2010-08-26 23:41:50 +00003357 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3358 "instantiating static data member "
3359 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003360
Chandler Carruth58e390e2010-08-25 08:27:02 +00003361 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3362 TSK_ExplicitInstantiationDefinition;
3363 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3364 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003365 }
3366}
John McCall0c01d182010-03-24 05:22:00 +00003367
3368void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3369 const MultiLevelTemplateArgumentList &TemplateArgs) {
3370 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3371 E = Pattern->ddiag_end(); I != E; ++I) {
3372 DependentDiagnostic *DD = *I;
3373
3374 switch (DD->getKind()) {
3375 case DependentDiagnostic::Access:
3376 HandleDependentAccessCheck(*DD, TemplateArgs);
3377 break;
3378 }
3379 }
3380}