blob: 0ff7ff4d4064bd81bca0a7318c89f118e245ffbb [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;
32
33 NestedNameSpecifierLoc NewQualifierLoc
34 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
35 TemplateArgs);
36
37 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000038 return true;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000039
40 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;
48
49 NestedNameSpecifierLoc NewQualifierLoc
50 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
51 TemplateArgs);
52
53 if (!NewQualifierLoc)
John McCallb6217662010-03-15 10:12:16 +000054 return true;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +000055
56 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,
62 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,
82 Aligned->getLocation(),
83 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) {
99 assert(false && "Translation units cannot be instantiated");
100 return D;
101}
102
103Decl *
Chris Lattner57ad3782011-02-17 20:34:02 +0000104TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
105 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
106 D->getIdentifier());
107 Owner->addDecl(Inst);
108 return Inst;
109}
110
111Decl *
Douglas Gregor4f722be2009-03-25 15:45:12 +0000112TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
113 assert(false && "Namespaces cannot be instantiated");
114 return D;
115}
116
John McCall3dbd3d52010-02-16 06:53:13 +0000117Decl *
118TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
119 NamespaceAliasDecl *Inst
120 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
121 D->getNamespaceLoc(),
122 D->getAliasLoc(),
Douglas Gregor0cfaf6a2011-02-25 17:08:07 +0000123 D->getIdentifier(),
124 D->getQualifierLoc(),
John McCall3dbd3d52010-02-16 06:53:13 +0000125 D->getTargetNameLoc(),
126 D->getNamespace());
127 Owner->addDecl(Inst);
128 return Inst;
129}
130
Richard Smith162e1c12011-04-15 14:24:37 +0000131Decl *TemplateDeclInstantiator::VisitTypedefNameDecl(TypedefNameDecl *D,
132 bool IsTypeAlias) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000133 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000134 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000135 if (DI->getType()->isDependentType() ||
136 DI->getType()->isVariablyModifiedType()) {
John McCallba6a9bd2009-10-24 08:00:42 +0000137 DI = SemaRef.SubstType(DI, TemplateArgs,
138 D->getLocation(), D->getDeclName());
139 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000140 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000141 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000142 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000143 } else {
144 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000145 }
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000147 // Create the new typedef
Richard Smith162e1c12011-04-15 14:24:37 +0000148 TypedefNameDecl *Typedef;
149 if (IsTypeAlias)
150 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
151 D->getLocation(), D->getIdentifier(), DI);
152 else
153 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
154 D->getLocation(), D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000155 if (Invalid)
156 Typedef->setInvalidDecl();
157
John McCallcde5a402011-02-01 08:20:08 +0000158 // If the old typedef was the name for linkage purposes of an anonymous
159 // tag decl, re-establish that relationship for the new typedef.
160 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
161 TagDecl *oldTag = oldTagType->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000162 if (oldTag->getTypedefNameForAnonDecl() == D) {
John McCallcde5a402011-02-01 08:20:08 +0000163 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
Richard Smith162e1c12011-04-15 14:24:37 +0000164 assert(!newTag->getIdentifier() && !newTag->getTypedefNameForAnonDecl());
165 newTag->setTypedefNameForAnonDecl(Typedef);
John McCallcde5a402011-02-01 08:20:08 +0000166 }
Douglas Gregord57a38e2010-04-23 16:25:07 +0000167 }
168
Richard Smith162e1c12011-04-15 14:24:37 +0000169 if (TypedefNameDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000170 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
171 TemplateArgs);
Douglas Gregorb7107222011-03-04 19:46:35 +0000172 if (!InstPrev)
173 return 0;
174
Richard Smith162e1c12011-04-15 14:24:37 +0000175 Typedef->setPreviousDeclaration(cast<TypedefNameDecl>(InstPrev));
John McCall5126fd02009-12-30 00:31:22 +0000176 }
177
John McCall1d8d1cc2010-08-01 02:01:53 +0000178 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
Douglas Gregord57a38e2010-04-23 16:25:07 +0000179
John McCall46460a62010-01-20 21:53:11 +0000180 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000181 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000183 return Typedef;
184}
185
Richard Smith162e1c12011-04-15 14:24:37 +0000186Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
187 return VisitTypedefNameDecl(D, /*IsTypeAlias=*/false);
188}
189
190Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
191 return VisitTypedefNameDecl(D, /*IsTypeAlias=*/true);
192}
193
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000194/// \brief Instantiate an initializer, breaking it into separate
195/// initialization arguments.
196///
197/// \param S The semantic analysis object.
198///
199/// \param Init The initializer to instantiate.
200///
201/// \param TemplateArgs Template arguments to be substituted into the
202/// initializer.
203///
204/// \param NewArgs Will be filled in with the instantiation arguments.
205///
206/// \returns true if an error occurred, false otherwise
207static bool InstantiateInitializer(Sema &S, Expr *Init,
208 const MultiLevelTemplateArgumentList &TemplateArgs,
209 SourceLocation &LParenLoc,
Nick Lewycky7663f392010-11-20 01:29:55 +0000210 ASTOwningVector<Expr*> &NewArgs,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000211 SourceLocation &RParenLoc) {
212 NewArgs.clear();
213 LParenLoc = SourceLocation();
214 RParenLoc = SourceLocation();
215
216 if (!Init)
217 return false;
218
John McCall4765fa02010-12-06 08:20:24 +0000219 if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000220 Init = ExprTemp->getSubExpr();
221
222 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
223 Init = Binder->getSubExpr();
224
225 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
226 Init = ICE->getSubExprAsWritten();
227
228 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
229 LParenLoc = ParenList->getLParenLoc();
230 RParenLoc = ParenList->getRParenLoc();
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000231 return S.SubstExprs(ParenList->getExprs(), ParenList->getNumExprs(),
232 true, TemplateArgs, NewArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000233 }
234
235 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000236 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +0000237 if (S.SubstExprs(Construct->getArgs(), Construct->getNumArgs(), true,
238 TemplateArgs, NewArgs))
Douglas Gregor28329e52010-03-24 21:22:47 +0000239 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000240
Douglas Gregor28329e52010-03-24 21:22:47 +0000241 // FIXME: Fake locations!
242 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
Douglas Gregora1a04782010-09-09 16:33:13 +0000243 RParenLoc = LParenLoc;
Douglas Gregor28329e52010-03-24 21:22:47 +0000244 return false;
245 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000246 }
247
John McCall60d7b3a2010-08-24 06:29:42 +0000248 ExprResult Result = S.SubstExpr(Init, TemplateArgs);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000249 if (Result.isInvalid())
250 return true;
251
252 NewArgs.push_back(Result.takeAs<Expr>());
253 return false;
254}
255
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000256Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
Douglas Gregor9901c572010-05-21 00:31:19 +0000257 // If this is the variable for an anonymous struct or union,
258 // instantiate the anonymous struct/union type first.
259 if (const RecordType *RecordTy = D->getType()->getAs<RecordType>())
260 if (RecordTy->getDecl()->isAnonymousStructOrUnion())
261 if (!VisitCXXRecordDecl(cast<CXXRecordDecl>(RecordTy->getDecl())))
262 return 0;
263
John McCallce3ff2b2009-08-25 22:02:44 +0000264 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000265 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000266 TemplateArgs,
267 D->getTypeSpecStartLoc(),
268 D->getDeclName());
269 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000270 return 0;
271
Douglas Gregorc6dbc3f2010-09-12 07:37:24 +0000272 if (DI->getType()->isFunctionType()) {
273 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
274 << D->isStaticDataMember() << DI->getType();
275 return 0;
276 }
277
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000278 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000279 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000280 D->getInnerLocStart(),
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000281 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000282 DI->getType(), DI,
Douglas Gregor16573fa2010-04-19 22:54:31 +0000283 D->getStorageClass(),
284 D->getStorageClassAsWritten());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000285 Var->setThreadSpecified(D->isThreadSpecified());
286 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
Richard Smithad762fc2011-04-14 22:09:26 +0000287 Var->setCXXForRangeDecl(D->isCXXForRangeDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000288
John McCallb6217662010-03-15 10:12:16 +0000289 // Substitute the nested name specifier, if any.
290 if (SubstQualifier(D, Var))
291 return 0;
292
Mike Stump1eb44332009-09-09 15:08:12 +0000293 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000294 // out-of-line, the instantiation will have the same lexical
295 // context (which will be a namespace scope) as the template.
296 if (D->isOutOfLine())
297 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000298
John McCall46460a62010-01-20 21:53:11 +0000299 Var->setAccess(D->getAccess());
Douglas Gregorc070cc62010-06-17 23:14:26 +0000300
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000301 if (!D->isStaticDataMember()) {
Douglas Gregorc070cc62010-06-17 23:14:26 +0000302 Var->setUsed(D->isUsed(false));
Argyrios Kyrtzidis6b6b42a2011-04-19 19:51:10 +0000303 Var->setReferenced(D->isReferenced());
304 }
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000305
Mike Stump390b4cc2009-05-16 07:39:55 +0000306 // FIXME: In theory, we could have a previous declaration for variables that
307 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000308 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000309 // FIXME: having to fake up a LookupResult is dumb.
310 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000311 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000312 if (D->isStaticDataMember())
313 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000314 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000315
Douglas Gregor7caa6822009-07-24 20:34:43 +0000316 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000317 if (!D->isStaticDataMember())
318 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000319 Owner->makeDeclVisibleInContext(Var);
320 } else {
321 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000322 if (Owner->isFunctionOrMethod())
323 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000324 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000325 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000326
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000327 // Link instantiations of static data members back to the template from
328 // which they were instantiated.
329 if (Var->isStaticDataMember())
330 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000331 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000332
Douglas Gregor60c93c92010-02-09 07:26:29 +0000333 if (Var->getAnyInitializer()) {
334 // We already have an initializer in the class.
335 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000336 if (Var->isStaticDataMember() && !D->isOutOfLine())
337 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
338 else
339 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
340
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000341 // Instantiate the initializer.
342 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000343 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000344 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000345 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000346 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000347 // Attach the initializer to the declaration, if we have one.
348 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000349 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000350 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000351 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000352 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000353 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000354 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000355 RParenLoc,
356 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000357 } else {
358 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000359 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000360 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000361 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000362 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000363 // FIXME: Not too happy about invalidating the declaration
364 // because of a bogus initializer.
365 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000366 }
367
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000368 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000369 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
370 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000371 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000372
Douglas Gregor5764f612010-05-08 23:05:03 +0000373 // Diagnose unused local variables.
374 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
375 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000376
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000377 return Var;
378}
379
Abramo Bagnara6206d532010-06-05 05:09:32 +0000380Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
381 AccessSpecDecl* AD
382 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
383 D->getAccessSpecifierLoc(), D->getColonLoc());
384 Owner->addHiddenDecl(AD);
385 return AD;
386}
387
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000388Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
389 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000390 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000391 if (DI->getType()->isDependentType() ||
392 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000393 DI = SemaRef.SubstType(DI, TemplateArgs,
394 D->getLocation(), D->getDeclName());
395 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000396 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000397 Invalid = true;
398 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000399 // C++ [temp.arg.type]p3:
400 // If a declaration acquires a function type through a type
401 // dependent on a template-parameter and this causes a
402 // declaration that does not use the syntactic form of a
403 // function declarator to have function type, the program is
404 // ill-formed.
405 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000406 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000407 Invalid = true;
408 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000409 } else {
410 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000411 }
412
413 Expr *BitWidth = D->getBitWidth();
414 if (Invalid)
415 BitWidth = 0;
416 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000417 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000418 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000419
John McCall60d7b3a2010-08-24 06:29:42 +0000420 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000421 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000422 if (InstantiatedBitWidth.isInvalid()) {
423 Invalid = true;
424 BitWidth = 0;
425 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000426 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000427 }
428
John McCall07fb6be2009-10-22 23:33:21 +0000429 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
430 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000431 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000432 D->getLocation(),
433 D->isMutable(),
434 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000435 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000436 D->getAccess(),
437 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000438 if (!Field) {
439 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000440 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000441 }
Mike Stump1eb44332009-09-09 15:08:12 +0000442
John McCall1d8d1cc2010-08-01 02:01:53 +0000443 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000444
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000445 if (Invalid)
446 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000448 if (!Field->getDeclName()) {
449 // Keep track of where this decl came from.
450 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000451 }
452 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
453 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000454 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000455 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000456 }
Mike Stump1eb44332009-09-09 15:08:12 +0000457
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000458 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000459 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000460 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000461
462 return Field;
463}
464
Francois Pichet87c2e122010-11-21 06:08:52 +0000465Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
466 NamedDecl **NamedChain =
467 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
468
469 int i = 0;
470 for (IndirectFieldDecl::chain_iterator PI =
471 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000472 PI != PE; ++PI) {
473 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
474 TemplateArgs);
475 if (!Next)
476 return 0;
477
478 NamedChain[i++] = Next;
479 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000480
Francois Pichet40e17752010-12-09 10:07:54 +0000481 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000482 IndirectFieldDecl* IndirectField
483 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000484 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000485 NamedChain, D->getChainingSize());
486
487
488 IndirectField->setImplicit(D->isImplicit());
489 IndirectField->setAccess(D->getAccess());
490 Owner->addDecl(IndirectField);
491 return IndirectField;
492}
493
John McCall02cace72009-08-28 07:59:38 +0000494Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000495 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000496 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000497 if (TypeSourceInfo *Ty = D->getFriendType()) {
498 TypeSourceInfo *InstTy =
499 SemaRef.SubstType(Ty, TemplateArgs,
500 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000501 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000502 return 0;
John McCall02cace72009-08-28 07:59:38 +0000503
Douglas Gregor06245bf2010-04-07 17:57:12 +0000504 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
505 if (!FD)
506 return 0;
507
508 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000509 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000510 Owner->addDecl(FD);
511 return FD;
512 }
513
514 NamedDecl *ND = D->getFriendDecl();
515 assert(ND && "friend decl must be a decl or a type!");
516
John McCallaf2094e2010-04-08 09:05:18 +0000517 // All of the Visit implementations for the various potential friend
518 // declarations have to be carefully written to work for friend
519 // objects, with the most important detail being that the target
520 // decl should almost certainly not be placed in Owner.
521 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000522 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000523
John McCall02cace72009-08-28 07:59:38 +0000524 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000525 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
526 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000527 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000528 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000529 Owner->addDecl(FD);
530 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000531}
532
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000533Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
534 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Douglas Gregorac7610d2009-06-22 20:57:11 +0000536 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000537 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000538
John McCall60d7b3a2010-08-24 06:29:42 +0000539 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000540 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000541 if (InstantiatedAssertExpr.isInvalid())
542 return 0;
543
John McCall60d7b3a2010-08-24 06:29:42 +0000544 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000545 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000546 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000547 InstantiatedAssertExpr.get(),
Abramo Bagnaraa2026c92011-03-08 16:41:52 +0000548 Message.get(),
549 D->getRParenLoc());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000550}
551
552Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000553 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000554 D->getLocation(), D->getIdentifier(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000555 /*PrevDecl=*/0, D->isScoped(),
556 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000557 if (D->isFixed()) {
558 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
559 // If we have type source information for the underlying type, it means it
560 // has been explicitly set by the user. Perform substitution on it before
561 // moving on.
562 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
563 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
564 TemplateArgs,
565 UnderlyingLoc,
566 DeclarationName()));
567
568 if (!Enum->getIntegerTypeSourceInfo())
569 Enum->setIntegerType(SemaRef.Context.IntTy);
570 }
571 else {
572 assert(!D->getIntegerType()->isDependentType()
573 && "Dependent type without type source info");
574 Enum->setIntegerType(D->getIntegerType());
575 }
576 }
577
John McCall5b629aa2010-10-22 23:36:17 +0000578 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
579
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000580 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000581 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000582 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000583 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000584 Enum->startDefinition();
585
Douglas Gregor96084f12010-03-01 19:00:07 +0000586 if (D->getDeclContext()->isFunctionOrMethod())
587 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
588
John McCalld226f652010-08-21 09:40:31 +0000589 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000590
591 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000592 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
593 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000594 EC != ECEnd; ++EC) {
595 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000596 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000597 if (Expr *UninstValue = EC->getInitExpr()) {
598 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000599 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000600 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000601
John McCallce3ff2b2009-08-25 22:02:44 +0000602 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000603 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000604
605 // Drop the initial value and continue.
606 bool isInvalid = false;
607 if (Value.isInvalid()) {
608 Value = SemaRef.Owned((Expr *)0);
609 isInvalid = true;
610 }
611
Mike Stump1eb44332009-09-09 15:08:12 +0000612 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000613 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
614 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000615 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000616
617 if (isInvalid) {
618 if (EnumConst)
619 EnumConst->setInvalidDecl();
620 Enum->setInvalidDecl();
621 }
622
623 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000624 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
625
John McCall3b85ecf2010-01-23 22:37:59 +0000626 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000627 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000628 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000629 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000630
631 if (D->getDeclContext()->isFunctionOrMethod()) {
632 // If the enumeration is within a function or method, record the enum
633 // constant as a local.
634 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
635 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000636 }
637 }
Mike Stump1eb44332009-09-09 15:08:12 +0000638
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000639 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000640 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000641 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000642 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000643 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000644 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000645
646 return Enum;
647}
648
Douglas Gregor6477b692009-03-25 15:04:13 +0000649Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
650 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
651 return 0;
652}
653
John McCalle29ba202009-08-20 01:44:21 +0000654Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000655 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
656
Douglas Gregor550d9b22009-10-31 17:21:17 +0000657 // Create a local instantiation scope for this class template, which
658 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000659 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000660 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000661 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000662 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000663 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000664
665 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000666
667 // Instantiate the qualifier. We have to do this first in case
668 // we're a friend declaration, because if we are then we need to put
669 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000670 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
671 if (QualifierLoc) {
672 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
673 TemplateArgs);
674 if (!QualifierLoc)
675 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000676 }
677
678 CXXRecordDecl *PrevDecl = 0;
679 ClassTemplateDecl *PrevClassTemplate = 0;
680
Nick Lewycky37574f52010-11-08 23:29:42 +0000681 if (!isFriend && Pattern->getPreviousDeclaration()) {
682 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
683 if (Found.first != Found.second) {
684 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
685 if (PrevClassTemplate)
686 PrevDecl = PrevClassTemplate->getTemplatedDecl();
687 }
688 }
689
John McCall93ba8572010-03-25 06:39:04 +0000690 // If this isn't a friend, then it's a member template, in which
691 // case we just want to build the instantiation in the
692 // specialization. If it is a friend, we want to build it in
693 // the appropriate context.
694 DeclContext *DC = Owner;
695 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000696 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000697 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000698 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000699 DC = SemaRef.computeDeclContext(SS);
700 if (!DC) return 0;
701 } else {
702 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
703 Pattern->getDeclContext(),
704 TemplateArgs);
705 }
706
707 // Look for a previous declaration of the template in the owning
708 // context.
709 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
710 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
711 SemaRef.LookupQualifiedName(R, DC);
712
713 if (R.isSingleResult()) {
714 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
715 if (PrevClassTemplate)
716 PrevDecl = PrevClassTemplate->getTemplatedDecl();
717 }
718
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000719 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000720 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000721 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000722 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000723 return 0;
724 }
725
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000726 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000727 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000728 bool Complain = true;
729
730 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
731 // template for struct std::tr1::__detail::_Map_base, where the
732 // template parameters of the friend declaration don't match the
733 // template parameters of the original declaration. In this one
734 // case, we don't complain about the ill-formed friend
735 // declaration.
736 if (isFriend && Pattern->getIdentifier() &&
737 Pattern->getIdentifier()->isStr("_Map_base") &&
738 DC->isNamespace() &&
739 cast<NamespaceDecl>(DC)->getIdentifier() &&
740 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
741 DeclContext *DCParent = DC->getParent();
742 if (DCParent->isNamespace() &&
743 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
744 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
745 DeclContext *DCParent2 = DCParent->getParent();
746 if (DCParent2->isNamespace() &&
747 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
748 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
749 DCParent2->getParent()->isTranslationUnit())
750 Complain = false;
751 }
752 }
753
John McCall93ba8572010-03-25 06:39:04 +0000754 TemplateParameterList *PrevParams
755 = PrevClassTemplate->getTemplateParameters();
756
757 // Make sure the parameter lists match.
758 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000759 Complain,
760 Sema::TPL_TemplateMatch)) {
761 if (Complain)
762 return 0;
763
764 AdoptedPreviousTemplateParams = true;
765 InstParams = PrevParams;
766 }
John McCall93ba8572010-03-25 06:39:04 +0000767
768 // Do some additional validation, then merge default arguments
769 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000770 if (!AdoptedPreviousTemplateParams &&
771 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000772 Sema::TPC_ClassTemplate))
773 return 0;
774 }
775 }
776
John McCalle29ba202009-08-20 01:44:21 +0000777 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000778 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000779 Pattern->getLocStart(), Pattern->getLocation(),
780 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000781 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000782
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000783 if (QualifierLoc)
784 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000785
John McCalle29ba202009-08-20 01:44:21 +0000786 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000787 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
788 D->getIdentifier(), InstParams, RecordInst,
789 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000790 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000791
John McCall93ba8572010-03-25 06:39:04 +0000792 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000793 if (PrevClassTemplate)
794 Inst->setAccess(PrevClassTemplate->getAccess());
795 else
796 Inst->setAccess(D->getAccess());
797
John McCall93ba8572010-03-25 06:39:04 +0000798 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
799 // TODO: do we want to track the instantiation progeny of this
800 // friend target decl?
801 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000802 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000803 if (!PrevClassTemplate)
804 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000805 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000806
807 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000808 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000809 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000810
Douglas Gregor259571e2009-10-30 22:42:42 +0000811 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000812 if (isFriend) {
813 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000814 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000815 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000816
John McCalle29ba202009-08-20 01:44:21 +0000817 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000818
819 if (!PrevClassTemplate) {
820 // Queue up any out-of-line partial specializations of this member
821 // class template; the client will force their instantiation once
822 // the enclosing class has been instantiated.
823 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
824 D->getPartialSpecializations(PartialSpecs);
825 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
826 if (PartialSpecs[I]->isOutOfLine())
827 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
828 }
829
John McCalle29ba202009-08-20 01:44:21 +0000830 return Inst;
831}
832
Douglas Gregord60e1052009-08-27 16:57:43 +0000833Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000834TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
835 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000836 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
837
838 // Lookup the already-instantiated declaration in the instantiation
839 // of the class template and return that.
840 DeclContext::lookup_result Found
841 = Owner->lookup(ClassTemplate->getDeclName());
842 if (Found.first == Found.second)
843 return 0;
844
845 ClassTemplateDecl *InstClassTemplate
846 = dyn_cast<ClassTemplateDecl>(*Found.first);
847 if (!InstClassTemplate)
848 return 0;
849
Douglas Gregord65587f2010-11-10 19:44:59 +0000850 if (ClassTemplatePartialSpecializationDecl *Result
851 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
852 return Result;
853
854 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000855}
856
857Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000858TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000859 // Create a local instantiation scope for this function template, which
860 // will contain the instantiations of the template parameters and then get
861 // merged with the local instantiation scope for the function template
862 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000863 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000864
Douglas Gregord60e1052009-08-27 16:57:43 +0000865 TemplateParameterList *TempParams = D->getTemplateParameters();
866 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000867 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000868 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000869
Douglas Gregora735b202009-10-13 14:39:41 +0000870 FunctionDecl *Instantiated = 0;
871 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
872 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
873 InstParams));
874 else
875 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
876 D->getTemplatedDecl(),
877 InstParams));
878
879 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000880 return 0;
881
John McCall46460a62010-01-20 21:53:11 +0000882 Instantiated->setAccess(D->getAccess());
883
Mike Stump1eb44332009-09-09 15:08:12 +0000884 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000885 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000886 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000887 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000888 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000889 assert(InstTemplate &&
890 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000891
John McCallb1a56e72010-03-26 23:10:15 +0000892 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
893
John McCalle976ffe2009-12-14 23:19:40 +0000894 // Link the instantiation back to the pattern *unless* this is a
895 // non-definition friend declaration.
896 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000897 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000898 InstTemplate->setInstantiatedFromMemberTemplate(D);
899
John McCallb1a56e72010-03-26 23:10:15 +0000900 // Make declarations visible in the appropriate context.
901 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000902 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000903
Douglas Gregord60e1052009-08-27 16:57:43 +0000904 return InstTemplate;
905}
906
Douglas Gregord475b8d2009-03-25 21:17:03 +0000907Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
908 CXXRecordDecl *PrevDecl = 0;
909 if (D->isInjectedClassName())
910 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000911 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000912 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
913 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000914 TemplateArgs);
915 if (!Prev) return 0;
916 PrevDecl = cast<CXXRecordDecl>(Prev);
917 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000918
919 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000920 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000921 D->getLocStart(), D->getLocation(),
922 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000923
924 // Substitute the nested name specifier, if any.
925 if (SubstQualifier(D, Record))
926 return 0;
927
Douglas Gregord475b8d2009-03-25 21:17:03 +0000928 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000929 // FIXME: Check against AS_none is an ugly hack to work around the issue that
930 // the tag decls introduced by friend class declarations don't have an access
931 // specifier. Remove once this area of the code gets sorted out.
932 if (D->getAccess() != AS_none)
933 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000934 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000935 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000936
John McCall02cace72009-08-28 07:59:38 +0000937 // If the original function was part of a friend declaration,
938 // inherit its namespace state.
939 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
940 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
941
Douglas Gregor9901c572010-05-21 00:31:19 +0000942 // Make sure that anonymous structs and unions are recorded.
943 if (D->isAnonymousStructOrUnion()) {
944 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000945 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000946 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
947 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000948
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000949 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000950 return Record;
951}
952
John McCall02cace72009-08-28 07:59:38 +0000953/// Normal class members are of more specific types and therefore
954/// don't make it here. This function serves two purposes:
955/// 1) instantiating function templates
956/// 2) substituting friend declarations
957/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000958Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000959 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000960 // Check whether there is already a function template specialization for
961 // this declaration.
962 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
963 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000964 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000965 std::pair<const TemplateArgument *, unsigned> Innermost
966 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000967
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000968 FunctionDecl *SpecFunc
969 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
970 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000971
Douglas Gregor127102b2009-06-29 20:59:39 +0000972 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000973 if (SpecFunc)
974 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000975 }
Mike Stump1eb44332009-09-09 15:08:12 +0000976
John McCallb0cb0222010-03-27 05:57:59 +0000977 bool isFriend;
978 if (FunctionTemplate)
979 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
980 else
981 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
982
Douglas Gregor79c22782010-01-16 20:21:20 +0000983 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000984 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000985 !(isa<Decl>(Owner) &&
986 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000987 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Douglas Gregore53060f2009-06-25 22:08:12 +0000989 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000990 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
991 TInfo = SubstFunctionType(D, Params);
992 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000993 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000994 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000995
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000996 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
997 if (QualifierLoc) {
998 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
999 TemplateArgs);
1000 if (!QualifierLoc)
1001 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001002 }
1003
John McCall68b6b872010-02-06 01:50:47 +00001004 // If we're instantiating a local function declaration, put the result
1005 // in the owner; otherwise we need to find the instantiated context.
1006 DeclContext *DC;
1007 if (D->getDeclContext()->isFunctionOrMethod())
1008 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001009 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001010 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001011 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001012 DC = SemaRef.computeDeclContext(SS);
1013 if (!DC) return 0;
1014 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001015 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1016 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001017 }
John McCall68b6b872010-02-06 01:50:47 +00001018
John McCall02cace72009-08-28 07:59:38 +00001019 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001020 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1021 D->getLocation(), D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001022 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001023 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001024
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001025 if (QualifierLoc)
1026 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001027
John McCallb1a56e72010-03-26 23:10:15 +00001028 DeclContext *LexicalDC = Owner;
1029 if (!isFriend && D->isOutOfLine()) {
1030 assert(D->getDeclContext()->isFileContext());
1031 LexicalDC = D->getDeclContext();
1032 }
1033
1034 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001035
Douglas Gregore53060f2009-06-25 22:08:12 +00001036 // Attach the parameters
1037 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001038 if (Params[P])
1039 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001040 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001041
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001042 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001043 if (TemplateParams) {
1044 // Our resulting instantiation is actually a function template, since we
1045 // are substituting only the outer template parameters. For example, given
1046 //
1047 // template<typename T>
1048 // struct X {
1049 // template<typename U> friend void f(T, U);
1050 // };
1051 //
1052 // X<int> x;
1053 //
1054 // We are instantiating the friend function template "f" within X<int>,
1055 // which means substituting int for T, but leaving "f" as a friend function
1056 // template.
1057 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001058 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001059 Function->getLocation(),
1060 Function->getDeclName(),
1061 TemplateParams, Function);
1062 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001063
1064 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001065
1066 if (isFriend && D->isThisDeclarationADefinition()) {
1067 // TODO: should we remember this connection regardless of whether
1068 // the friend declaration provided a body?
1069 FunctionTemplate->setInstantiatedFromMemberTemplate(
1070 D->getDescribedFunctionTemplate());
1071 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001072 } else if (FunctionTemplate) {
1073 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001074 std::pair<const TemplateArgument *, unsigned> Innermost
1075 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001076 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001077 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001078 Innermost.first,
1079 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001080 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001081 } else if (isFriend && D->isThisDeclarationADefinition()) {
1082 // TODO: should we remember this connection regardless of whether
1083 // the friend declaration provided a body?
1084 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001085 }
Douglas Gregora735b202009-10-13 14:39:41 +00001086
Douglas Gregore53060f2009-06-25 22:08:12 +00001087 if (InitFunctionInstantiation(Function, D))
1088 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Douglas Gregore53060f2009-06-25 22:08:12 +00001090 bool Redeclaration = false;
John McCallaf2094e2010-04-08 09:05:18 +00001091 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001092
John McCall68263142009-11-18 22:49:29 +00001093 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1094 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1095
John McCallaf2094e2010-04-08 09:05:18 +00001096 if (DependentFunctionTemplateSpecializationInfo *Info
1097 = D->getDependentSpecializationInfo()) {
1098 assert(isFriend && "non-friend has dependent specialization info?");
1099
1100 // This needs to be set now for future sanity.
1101 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1102
1103 // Instantiate the explicit template arguments.
1104 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1105 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001106 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1107 ExplicitArgs, TemplateArgs))
1108 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001109
1110 // Map the candidate templates to their instantiations.
1111 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1112 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1113 Info->getTemplate(I),
1114 TemplateArgs);
1115 if (!Temp) return 0;
1116
1117 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1118 }
1119
1120 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1121 &ExplicitArgs,
1122 Previous))
1123 Function->setInvalidDecl();
1124
1125 isExplicitSpecialization = true;
1126
1127 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001128 // Look only into the namespace where the friend would be declared to
1129 // find a previous declaration. This is the innermost enclosing namespace,
1130 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001131 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001132
Douglas Gregora735b202009-10-13 14:39:41 +00001133 // In C++, the previous declaration we find might be a tag type
1134 // (class or enum). In this case, the new declaration will hide the
1135 // tag type. Note that this does does not apply if we're declaring a
1136 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001137 if (Previous.isSingleTagDecl())
1138 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001139 }
1140
John McCall9f54ad42009-12-10 09:41:52 +00001141 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Peter Collingbournec80e8112011-01-21 02:08:54 +00001142 isExplicitSpecialization, Redeclaration);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001143
John McCall76d32642010-04-24 01:30:58 +00001144 NamedDecl *PrincipalDecl = (TemplateParams
1145 ? cast<NamedDecl>(FunctionTemplate)
1146 : Function);
1147
Douglas Gregora735b202009-10-13 14:39:41 +00001148 // If the original function was part of a friend declaration,
1149 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001150 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001151 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001152 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001153 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001154 else
Douglas Gregora735b202009-10-13 14:39:41 +00001155 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001156
1157 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1158 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001159
Gabor Greif77535df2010-08-30 22:25:56 +00001160 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001161
Douglas Gregor238058c2010-05-18 05:45:02 +00001162 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1163 D->isThisDeclarationADefinition()) {
1164 // Check for a function body.
1165 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001166 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001167 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1168 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1169 << Function->getDeclName();
1170 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1171 Function->setInvalidDecl();
1172 }
1173 // Check for redefinitions due to other instantiations of this or
1174 // a similar friend function.
1175 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1176 REnd = Function->redecls_end();
1177 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001178 if (*R == Function)
1179 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001180 switch (R->getFriendObjectKind()) {
1181 case Decl::FOK_None:
1182 if (!queuedInstantiation && R->isUsed(false)) {
1183 if (MemberSpecializationInfo *MSInfo
1184 = Function->getMemberSpecializationInfo()) {
1185 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1186 SourceLocation Loc = R->getLocation(); // FIXME
1187 MSInfo->setPointOfInstantiation(Loc);
1188 SemaRef.PendingLocalImplicitInstantiations.push_back(
1189 std::make_pair(Function, Loc));
1190 queuedInstantiation = true;
1191 }
1192 }
1193 }
1194 break;
1195 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001196 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001197 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001198 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001199 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1200 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001201 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001202 Function->setInvalidDecl();
1203 break;
1204 }
1205 }
1206 }
1207 }
Douglas Gregora735b202009-10-13 14:39:41 +00001208 }
1209
John McCall76d32642010-04-24 01:30:58 +00001210 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1211 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1212 PrincipalDecl->setNonMemberOperator();
1213
Douglas Gregore53060f2009-06-25 22:08:12 +00001214 return Function;
1215}
1216
Douglas Gregord60e1052009-08-27 16:57:43 +00001217Decl *
1218TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1219 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001220 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1221 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001222 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001223 // We are creating a function template specialization from a function
1224 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001225 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001226 std::pair<const TemplateArgument *, unsigned> Innermost
1227 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001229 FunctionDecl *SpecFunc
1230 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1231 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001232
Douglas Gregor6b906862009-08-21 00:16:32 +00001233 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001234 if (SpecFunc)
1235 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001236 }
1237
John McCallb0cb0222010-03-27 05:57:59 +00001238 bool isFriend;
1239 if (FunctionTemplate)
1240 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1241 else
1242 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1243
Douglas Gregor79c22782010-01-16 20:21:20 +00001244 bool MergeWithParentScope = (TemplateParams != 0) ||
1245 !(isa<Decl>(Owner) &&
1246 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001247 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001248
John McCall4eab39f2010-10-19 02:26:41 +00001249 // Instantiate enclosing template arguments for friends.
1250 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1251 unsigned NumTempParamLists = 0;
1252 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1253 TempParamLists.set_size(NumTempParamLists);
1254 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1255 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1256 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1257 if (!InstParams)
1258 return NULL;
1259 TempParamLists[I] = InstParams;
1260 }
1261 }
1262
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001263 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001264 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1265 TInfo = SubstFunctionType(D, Params);
1266 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001267 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001268 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001269
Abramo Bagnara723df242010-12-14 22:11:44 +00001270 // \brief If the type of this function, after ignoring parentheses,
1271 // is not *directly* a function type, then we're instantiating a function
1272 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001273 //
1274 // typedef int functype(int, int);
1275 // functype func;
1276 //
1277 // In this case, we'll just go instantiate the ParmVarDecls that we
1278 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001279 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001280 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001281 llvm::SmallVector<QualType, 4> ParamTypes;
1282 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1283 D->getNumParams(), TemplateArgs, ParamTypes,
1284 &Params))
1285 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001286 }
1287
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001288 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1289 if (QualifierLoc) {
1290 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001291 TemplateArgs);
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001292 if (!QualifierLoc)
1293 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001294 }
1295
1296 DeclContext *DC = Owner;
1297 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001298 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001299 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001300 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001301 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001302
1303 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1304 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001305 } else {
1306 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1307 D->getDeclContext(),
1308 TemplateArgs);
1309 }
1310 if (!DC) return 0;
1311 }
1312
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001313 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001314 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001315 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001317 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001318 DeclarationNameInfo NameInfo
1319 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001320 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001321 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001322 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001323 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001324 Constructor->isInlineSpecified(),
1325 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001326 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001327 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001328 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001329 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001330 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001331 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001332 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001333 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001334 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001335 Conversion->isExplicit(),
1336 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001337 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001338 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001339 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001340 D->isStatic(),
1341 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001342 D->isInlineSpecified(),
1343 D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001344 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001345
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001346 if (QualifierLoc)
1347 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001348
Douglas Gregord60e1052009-08-27 16:57:43 +00001349 if (TemplateParams) {
1350 // Our resulting instantiation is actually a function template, since we
1351 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001352 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001353 // template<typename T>
1354 // struct X {
1355 // template<typename U> void f(T, U);
1356 // };
1357 //
1358 // X<int> x;
1359 //
1360 // We are instantiating the member template "f" within X<int>, which means
1361 // substituting int for T, but leaving "f" as a member function template.
1362 // Build the function template itself.
1363 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1364 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001365 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001366 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001367 if (isFriend) {
1368 FunctionTemplate->setLexicalDeclContext(Owner);
1369 FunctionTemplate->setObjectOfFriendDecl(true);
1370 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001371 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001372 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001373 } else if (FunctionTemplate) {
1374 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001375 std::pair<const TemplateArgument *, unsigned> Innermost
1376 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001377 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001378 TemplateArgumentList::CreateCopy(SemaRef.Context,
1379 Innermost.first,
1380 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001381 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001382 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001383 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001384 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001385 }
1386
Mike Stump1eb44332009-09-09 15:08:12 +00001387 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001388 // out-of-line, the instantiation will have the same lexical
1389 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001390 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001391 if (NumTempParamLists)
1392 Method->setTemplateParameterListsInfo(SemaRef.Context,
1393 NumTempParamLists,
1394 TempParamLists.data());
1395
John McCallb0cb0222010-03-27 05:57:59 +00001396 Method->setLexicalDeclContext(Owner);
1397 Method->setObjectOfFriendDecl(true);
1398 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001399 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregor5545e162009-03-24 00:38:23 +00001401 // Attach the parameters
1402 for (unsigned P = 0; P < Params.size(); ++P)
1403 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001404 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001405
1406 if (InitMethodInstantiation(Method, D))
1407 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001408
Abramo Bagnara25777432010-08-11 22:01:17 +00001409 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1410 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
John McCallb0cb0222010-03-27 05:57:59 +00001412 if (!FunctionTemplate || TemplateParams || isFriend) {
1413 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Douglas Gregordec06662009-08-21 18:42:58 +00001415 // In C++, the previous declaration we find might be a tag type
1416 // (class or enum). In this case, the new declaration will hide the
1417 // tag type. Note that this does does not apply if we're declaring a
1418 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001419 if (Previous.isSingleTagDecl())
1420 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001421 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001422
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001423 bool Redeclaration = false;
Peter Collingbournec80e8112011-01-21 02:08:54 +00001424 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001425
Douglas Gregor4ba31362009-12-01 17:24:26 +00001426 if (D->isPure())
1427 SemaRef.CheckPureMethod(Method, SourceRange());
1428
John McCall46460a62010-01-20 21:53:11 +00001429 Method->setAccess(D->getAccess());
1430
Anders Carlsson9eefa222011-01-20 06:52:44 +00001431 SemaRef.CheckOverrideControl(Method);
1432
John McCallb0cb0222010-03-27 05:57:59 +00001433 if (FunctionTemplate) {
1434 // If there's a function template, let our caller handle it.
1435 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1436 // Don't hide a (potentially) valid declaration with an invalid one.
1437 } else {
1438 NamedDecl *DeclToAdd = (TemplateParams
1439 ? cast<NamedDecl>(FunctionTemplate)
1440 : Method);
1441 if (isFriend)
1442 Record->makeDeclVisibleInContext(DeclToAdd);
1443 else
1444 Owner->addDecl(DeclToAdd);
1445 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001446
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001447 return Method;
1448}
1449
Douglas Gregor615c5d42009-03-24 16:43:20 +00001450Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001451 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001452}
1453
Douglas Gregor03b2b072009-03-24 00:15:49 +00001454Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001455 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001456}
1457
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001458Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001459 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001460}
1461
Douglas Gregor6477b692009-03-25 15:04:13 +00001462ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001463 return SemaRef.SubstParmVarDecl(D, TemplateArgs, llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001464}
1465
John McCalle29ba202009-08-20 01:44:21 +00001466Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1467 TemplateTypeParmDecl *D) {
1468 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001469 const Type* T = D->getTypeForDecl();
1470 assert(T->isTemplateTypeParmType());
1471 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001472
John McCalle29ba202009-08-20 01:44:21 +00001473 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001474 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1475 D->getLocStart(), D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001476 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001477 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001478 D->wasDeclaredWithTypename(),
1479 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001480 Inst->setAccess(AS_public);
1481
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001482 if (D->hasDefaultArgument())
1483 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001484
Douglas Gregor550d9b22009-10-31 17:21:17 +00001485 // Introduce this template parameter's instantiation into the instantiation
1486 // scope.
1487 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1488
John McCalle29ba202009-08-20 01:44:21 +00001489 return Inst;
1490}
1491
Douglas Gregor33642df2009-10-23 23:25:44 +00001492Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1493 NonTypeTemplateParmDecl *D) {
1494 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001495 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1496 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1497 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1498 bool IsExpandedParameterPack = false;
1499 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001500 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001501 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001502
1503 if (D->isExpandedParameterPack()) {
1504 // The non-type template parameter pack is an already-expanded pack
1505 // expansion of types. Substitute into each of the expanded types.
1506 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1507 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1508 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1509 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1510 TemplateArgs,
1511 D->getLocation(),
1512 D->getDeclName());
1513 if (!NewDI)
1514 return 0;
1515
1516 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1517 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1518 D->getLocation());
1519 if (NewT.isNull())
1520 return 0;
1521 ExpandedParameterPackTypes.push_back(NewT);
1522 }
1523
1524 IsExpandedParameterPack = true;
1525 DI = D->getTypeSourceInfo();
1526 T = DI->getType();
1527 } else if (isa<PackExpansionTypeLoc>(TL)) {
1528 // The non-type template parameter pack's type is a pack expansion of types.
1529 // Determine whether we need to expand this parameter pack into separate
1530 // types.
1531 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1532 TypeLoc Pattern = Expansion.getPatternLoc();
1533 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1534 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1535
1536 // Determine whether the set of unexpanded parameter packs can and should
1537 // be expanded.
1538 bool Expand = true;
1539 bool RetainExpansion = false;
1540 llvm::Optional<unsigned> OrigNumExpansions
1541 = Expansion.getTypePtr()->getNumExpansions();
1542 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1543 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1544 Pattern.getSourceRange(),
1545 Unexpanded.data(),
1546 Unexpanded.size(),
1547 TemplateArgs,
1548 Expand, RetainExpansion,
1549 NumExpansions))
1550 return 0;
1551
1552 if (Expand) {
1553 for (unsigned I = 0; I != *NumExpansions; ++I) {
1554 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1555 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1556 D->getLocation(),
1557 D->getDeclName());
1558 if (!NewDI)
1559 return 0;
1560
1561 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1562 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1563 NewDI->getType(),
1564 D->getLocation());
1565 if (NewT.isNull())
1566 return 0;
1567 ExpandedParameterPackTypes.push_back(NewT);
1568 }
1569
1570 // Note that we have an expanded parameter pack. The "type" of this
1571 // expanded parameter pack is the original expansion type, but callers
1572 // will end up using the expanded parameter pack types for type-checking.
1573 IsExpandedParameterPack = true;
1574 DI = D->getTypeSourceInfo();
1575 T = DI->getType();
1576 } else {
1577 // We cannot fully expand the pack expansion now, so substitute into the
1578 // pattern and create a new pack expansion type.
1579 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1580 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1581 D->getLocation(),
1582 D->getDeclName());
1583 if (!NewPattern)
1584 return 0;
1585
1586 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1587 NumExpansions);
1588 if (!DI)
1589 return 0;
1590
1591 T = DI->getType();
1592 }
1593 } else {
1594 // Simple case: substitution into a parameter that is not a parameter pack.
1595 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1596 D->getLocation(), D->getDeclName());
1597 if (!DI)
1598 return 0;
1599
1600 // Check that this type is acceptable for a non-type template parameter.
1601 bool Invalid = false;
1602 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1603 D->getLocation());
1604 if (T.isNull()) {
1605 T = SemaRef.Context.IntTy;
1606 Invalid = true;
1607 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001608 }
1609
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001610 NonTypeTemplateParmDecl *Param;
1611 if (IsExpandedParameterPack)
1612 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001613 D->getInnerLocStart(),
1614 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001615 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001616 D->getPosition(),
1617 D->getIdentifier(), T,
1618 DI,
1619 ExpandedParameterPackTypes.data(),
1620 ExpandedParameterPackTypes.size(),
1621 ExpandedParameterPackTypesAsWritten.data());
1622 else
1623 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001624 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001625 D->getLocation(),
1626 D->getDepth() - TemplateArgs.getNumLevels(),
1627 D->getPosition(),
1628 D->getIdentifier(), T,
1629 D->isParameterPack(), DI);
1630
Douglas Gregor9a299e02011-03-04 17:52:15 +00001631 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001632 if (Invalid)
1633 Param->setInvalidDecl();
1634
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001635 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001636
1637 // Introduce this template parameter's instantiation into the instantiation
1638 // scope.
1639 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001640 return Param;
1641}
1642
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001643Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001644TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1645 TemplateTemplateParmDecl *D) {
1646 // Instantiate the template parameter list of the template template parameter.
1647 TemplateParameterList *TempParams = D->getTemplateParameters();
1648 TemplateParameterList *InstParams;
1649 {
1650 // Perform the actual substitution of template parameters within a new,
1651 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001652 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001653 InstParams = SubstTemplateParams(TempParams);
1654 if (!InstParams)
1655 return NULL;
1656 }
1657
1658 // Build the template template parameter.
1659 TemplateTemplateParmDecl *Param
1660 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001661 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001662 D->getPosition(), D->isParameterPack(),
1663 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001664 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001665 Param->setAccess(AS_public);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001666
Douglas Gregor9106ef72009-11-11 16:58:32 +00001667 // Introduce this template parameter's instantiation into the instantiation
1668 // scope.
1669 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1670
1671 return Param;
1672}
1673
Douglas Gregor48c32a72009-11-17 06:07:40 +00001674Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001675 // Using directives are never dependent (and never contain any types or
1676 // expressions), so they require no explicit instantiation work.
Douglas Gregor48c32a72009-11-17 06:07:40 +00001677
1678 UsingDirectiveDecl *Inst
1679 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1680 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001681 D->getQualifierLoc(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001682 D->getIdentLocation(),
1683 D->getNominatedNamespace(),
1684 D->getCommonAncestor());
1685 Owner->addDecl(Inst);
1686 return Inst;
1687}
1688
John McCalled976492009-12-04 22:46:56 +00001689Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001690
1691 // The nested name specifier may be dependent, for example
1692 // template <typename T> struct t {
1693 // struct s1 { T f1(); };
1694 // struct s2 : s1 { using s1::f1; };
1695 // };
1696 // template struct t<int>;
1697 // Here, in using s1::f1, s1 refers to t<T>::s1;
1698 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001699 NestedNameSpecifierLoc QualifierLoc
1700 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1701 TemplateArgs);
1702 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001703 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001704
1705 // The name info is non-dependent, so no transformation
1706 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001707 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001708
John McCall9f54ad42009-12-10 09:41:52 +00001709 // We only need to do redeclaration lookups if we're in a class
1710 // scope (in fact, it's not really even possible in non-class
1711 // scopes).
1712 bool CheckRedeclaration = Owner->isRecord();
1713
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001714 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1715 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001716
John McCalled976492009-12-04 22:46:56 +00001717 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001718 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001719 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001720 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001721 D->isTypeName());
1722
Douglas Gregor5149f372011-02-25 15:54:31 +00001723 CXXScopeSpec SS;
1724 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001725 if (CheckRedeclaration) {
1726 Prev.setHideTags(false);
1727 SemaRef.LookupQualifiedName(Prev, Owner);
1728
1729 // Check for invalid redeclarations.
1730 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1731 D->isTypeName(), SS,
1732 D->getLocation(), Prev))
1733 NewUD->setInvalidDecl();
1734
1735 }
1736
1737 if (!NewUD->isInvalidDecl() &&
1738 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001739 D->getLocation()))
1740 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001741
John McCalled976492009-12-04 22:46:56 +00001742 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1743 NewUD->setAccess(D->getAccess());
1744 Owner->addDecl(NewUD);
1745
John McCall9f54ad42009-12-10 09:41:52 +00001746 // Don't process the shadow decls for an invalid decl.
1747 if (NewUD->isInvalidDecl())
1748 return NewUD;
1749
John McCall323c3102009-12-22 22:26:37 +00001750 bool isFunctionScope = Owner->isFunctionOrMethod();
1751
John McCall9f54ad42009-12-10 09:41:52 +00001752 // Process the shadow decls.
1753 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1754 I != E; ++I) {
1755 UsingShadowDecl *Shadow = *I;
1756 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001757 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1758 Shadow->getLocation(),
1759 Shadow->getTargetDecl(),
1760 TemplateArgs));
1761 if (!InstTarget)
1762 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001763
1764 if (CheckRedeclaration &&
1765 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1766 continue;
1767
1768 UsingShadowDecl *InstShadow
1769 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1770 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001771
1772 if (isFunctionScope)
1773 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001774 }
John McCalled976492009-12-04 22:46:56 +00001775
1776 return NewUD;
1777}
1778
1779Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001780 // Ignore these; we handle them in bulk when processing the UsingDecl.
1781 return 0;
John McCalled976492009-12-04 22:46:56 +00001782}
1783
John McCall7ba107a2009-11-18 02:36:19 +00001784Decl * TemplateDeclInstantiator
1785 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001786 NestedNameSpecifierLoc QualifierLoc
1787 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1788 TemplateArgs);
1789 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001790 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001791
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001792 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001793 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001795 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1796 // Hence, no tranformation is required for it.
1797 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001798 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001799 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001800 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001801 /*instantiation*/ true,
1802 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001803 if (UD)
John McCalled976492009-12-04 22:46:56 +00001804 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1805
John McCall7ba107a2009-11-18 02:36:19 +00001806 return UD;
1807}
1808
1809Decl * TemplateDeclInstantiator
1810 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001811 NestedNameSpecifierLoc QualifierLoc
1812 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1813 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001814 return 0;
Douglas Gregor5149f372011-02-25 15:54:31 +00001815
John McCall7ba107a2009-11-18 02:36:19 +00001816 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001817 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001818
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001819 DeclarationNameInfo NameInfo
1820 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1821
John McCall7ba107a2009-11-18 02:36:19 +00001822 NamedDecl *UD =
1823 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001824 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001825 /*instantiation*/ true,
1826 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001827 if (UD)
John McCalled976492009-12-04 22:46:56 +00001828 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1829
Anders Carlsson0d8df782009-08-29 19:37:28 +00001830 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001831}
1832
John McCallce3ff2b2009-08-25 22:02:44 +00001833Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001834 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001835 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001836 if (D->isInvalidDecl())
1837 return 0;
1838
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001839 return Instantiator.Visit(D);
1840}
1841
John McCalle29ba202009-08-20 01:44:21 +00001842/// \brief Instantiates a nested template parameter list in the current
1843/// instantiation context.
1844///
1845/// \param L The parameter list to instantiate
1846///
1847/// \returns NULL if there was an error
1848TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001849TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001850 // Get errors for all the parameters before bailing out.
1851 bool Invalid = false;
1852
1853 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001854 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001855 ParamVector Params;
1856 Params.reserve(N);
1857 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1858 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001859 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001860 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001861 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001862 }
1863
1864 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001865 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001866 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001867
1868 TemplateParameterList *InstL
1869 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1870 L->getLAngleLoc(), &Params.front(), N,
1871 L->getRAngleLoc());
1872 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001873}
John McCalle29ba202009-08-20 01:44:21 +00001874
Douglas Gregored9c0f92009-10-29 00:04:11 +00001875/// \brief Instantiate the declaration of a class template partial
1876/// specialization.
1877///
1878/// \param ClassTemplate the (instantiated) class template that is partially
1879// specialized by the instantiation of \p PartialSpec.
1880///
1881/// \param PartialSpec the (uninstantiated) class template partial
1882/// specialization that we are instantiating.
1883///
Douglas Gregord65587f2010-11-10 19:44:59 +00001884/// \returns The instantiated partial specialization, if successful; otherwise,
1885/// NULL to indicate an error.
1886ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001887TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1888 ClassTemplateDecl *ClassTemplate,
1889 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001890 // Create a local instantiation scope for this class template partial
1891 // specialization, which will contain the instantiations of the template
1892 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001893 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001894
Douglas Gregored9c0f92009-10-29 00:04:11 +00001895 // Substitute into the template parameters of the class template partial
1896 // specialization.
1897 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1898 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1899 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001900 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001901
1902 // Substitute into the template arguments of the class template partial
1903 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001904 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001905 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1906 PartialSpec->getNumTemplateArgsAsWritten(),
1907 InstTemplateArgs, TemplateArgs))
1908 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001909
Douglas Gregored9c0f92009-10-29 00:04:11 +00001910 // Check that the template argument list is well-formed for this
1911 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001912 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001913 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1914 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001915 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001916 false,
1917 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001918 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001919
1920 // Figure out where to insert this class template partial specialization
1921 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001922 void *InsertPos = 0;
1923 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001924 = ClassTemplate->findPartialSpecialization(Converted.data(),
1925 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001926
1927 // Build the canonical type that describes the converted template
1928 // arguments of the class template partial specialization.
1929 QualType CanonType
1930 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001931 Converted.data(),
1932 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001933
1934 // Build the fully-sugared type for this class template
1935 // specialization as the user wrote in the specialization
1936 // itself. This means that we'll pretty-print the type retrieved
1937 // from the specialization's declaration the way that the user
1938 // actually wrote the specialization, rather than formatting the
1939 // name based on the "canonical" representation used to store the
1940 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001941 TypeSourceInfo *WrittenTy
1942 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1943 TemplateName(ClassTemplate),
1944 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001945 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001946 CanonType);
1947
1948 if (PrevDecl) {
1949 // We've already seen a partial specialization with the same template
1950 // parameters and template arguments. This can happen, for example, when
1951 // substituting the outer template arguments ends up causing two
1952 // class template partial specializations of a member class template
1953 // to have identical forms, e.g.,
1954 //
1955 // template<typename T, typename U>
1956 // struct Outer {
1957 // template<typename X, typename Y> struct Inner;
1958 // template<typename Y> struct Inner<T, Y>;
1959 // template<typename Y> struct Inner<U, Y>;
1960 // };
1961 //
1962 // Outer<int, int> outer; // error: the partial specializations of Inner
1963 // // have the same signature.
1964 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001965 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001966 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1967 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001968 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001969 }
1970
1971
1972 // Create the class template partial specialization declaration.
1973 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001974 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1975 PartialSpec->getTagKind(),
1976 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001977 PartialSpec->getLocStart(),
1978 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00001979 InstParams,
1980 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001981 Converted.data(),
1982 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001983 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001984 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001985 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001986 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001987 // Substitute the nested name specifier, if any.
1988 if (SubstQualifier(PartialSpec, InstPartialSpec))
1989 return 0;
1990
Douglas Gregored9c0f92009-10-29 00:04:11 +00001991 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001992 InstPartialSpec->setTypeAsWritten(WrittenTy);
1993
Douglas Gregored9c0f92009-10-29 00:04:11 +00001994 // Add this partial specialization to the set of class template partial
1995 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001996 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001997 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001998}
1999
John McCall21ef0fa2010-03-11 09:03:00 +00002000TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00002001TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00002002 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002003 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2004 assert(OldTInfo && "substituting function without type source info");
2005 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00002006 TypeSourceInfo *NewTInfo
2007 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2008 D->getTypeSpecStartLoc(),
2009 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00002010 if (!NewTInfo)
2011 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002012
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002013 if (NewTInfo != OldTInfo) {
2014 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002015 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002016 if (FunctionProtoTypeLoc *OldProtoLoc
2017 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002018 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002019 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2020 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00002021 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2022 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2023 OldIdx != NumOldParams; ++OldIdx) {
2024 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2025 if (!OldParam->isParameterPack() ||
2026 (NewIdx < NumNewParams &&
2027 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2028 // Simple case: normal parameter, or a parameter pack that's
2029 // instantiated to a (still-dependent) parameter pack.
2030 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2031 Params.push_back(NewParam);
2032 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2033 NewParam);
2034 continue;
2035 }
2036
2037 // Parameter pack: make the instantiation an argument pack.
2038 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2039 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002040 unsigned NumArgumentsInExpansion
2041 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2042 TemplateArgs);
2043 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002044 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2045 Params.push_back(NewParam);
2046 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2047 NewParam);
2048 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002049 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002050 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002051 } else {
2052 // The function type itself was not dependent and therefore no
2053 // substitution occurred. However, we still need to instantiate
2054 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002055 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002056 if (FunctionProtoTypeLoc *OldProtoLoc
2057 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2058 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2059 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2060 if (!Parm)
2061 return 0;
2062 Params.push_back(Parm);
2063 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002064 }
2065 }
John McCall21ef0fa2010-03-11 09:03:00 +00002066 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002067}
2068
Mike Stump1eb44332009-09-09 15:08:12 +00002069/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002070/// declaration (New) from the corresponding fields of its template (Tmpl).
2071///
2072/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002073bool
2074TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002075 FunctionDecl *Tmpl) {
2076 if (Tmpl->isDeleted())
2077 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00002078
Douglas Gregorcca9e962009-07-01 22:01:06 +00002079 // If we are performing substituting explicitly-specified template arguments
2080 // or deduced template arguments into a function template and we reach this
2081 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002082 // to keeping the new function template specialization. We therefore
2083 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002084 // into a template instantiation for this specific function template
2085 // specialization, which is not a SFINAE context, so that we diagnose any
2086 // further errors in the declaration itself.
2087 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2088 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2089 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2090 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002091 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002092 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002093 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002094 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002095 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002096 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2097 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002098 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002099 }
2100 }
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002102 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2103 assert(Proto && "Function template without prototype?");
2104
Sebastian Redl60618fa2011-03-12 11:50:43 +00002105 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002106 // The function has an exception specification or a "noreturn"
2107 // attribute. Substitute into each of the exception types.
2108 llvm::SmallVector<QualType, 4> Exceptions;
2109 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2110 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002111 if (const PackExpansionType *PackExpansion
2112 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2113 // We have a pack expansion. Instantiate it.
2114 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2115 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2116 Unexpanded);
2117 assert(!Unexpanded.empty() &&
2118 "Pack expansion without parameter packs?");
Sebastian Redl60618fa2011-03-12 11:50:43 +00002119
Douglas Gregorb99268b2010-12-21 00:52:54 +00002120 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002121 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002122 llvm::Optional<unsigned> NumExpansions
2123 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002124 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2125 SourceRange(),
2126 Unexpanded.data(),
2127 Unexpanded.size(),
2128 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002129 Expand,
2130 RetainExpansion,
2131 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002132 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002133
Douglas Gregorb99268b2010-12-21 00:52:54 +00002134 if (!Expand) {
2135 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002136 // just substitute into the pattern and create a new pack expansion
2137 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002138 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2139 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2140 TemplateArgs,
2141 New->getLocation(), New->getDeclName());
2142 if (T.isNull())
2143 break;
2144
Douglas Gregorcded4f62011-01-14 17:04:44 +00002145 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002146 Exceptions.push_back(T);
2147 continue;
2148 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002149
Douglas Gregorb99268b2010-12-21 00:52:54 +00002150 // Substitute into the pack expansion pattern for each template
2151 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002152 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002153 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2154
2155 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2156 TemplateArgs,
2157 New->getLocation(), New->getDeclName());
2158 if (T.isNull()) {
2159 Invalid = true;
2160 break;
2161 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002162
Douglas Gregorb99268b2010-12-21 00:52:54 +00002163 Exceptions.push_back(T);
2164 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002165
Douglas Gregorb99268b2010-12-21 00:52:54 +00002166 if (Invalid)
2167 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002168
Douglas Gregorb99268b2010-12-21 00:52:54 +00002169 continue;
2170 }
2171
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002172 QualType T
2173 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2174 New->getLocation(), New->getDeclName());
2175 if (T.isNull() ||
2176 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2177 continue;
2178
2179 Exceptions.push_back(T);
2180 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002181 Expr *NoexceptExpr = 0;
2182 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2183 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2184 if (E.isUsable())
2185 NoexceptExpr = E.take();
2186 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002187
2188 // Rebuild the function type
2189
John McCalle23cf432010-12-14 08:05:40 +00002190 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002191 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00002192 EPI.NumExceptions = Exceptions.size();
2193 EPI.Exceptions = Exceptions.data();
Sebastian Redl56fb9262011-03-14 18:51:50 +00002194 EPI.NoexceptExpr = NoexceptExpr;
John McCalle23cf432010-12-14 08:05:40 +00002195 EPI.ExtInfo = Proto->getExtInfo();
2196
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002197 const FunctionProtoType *NewProto
2198 = New->getType()->getAs<FunctionProtoType>();
2199 assert(NewProto && "Template instantiation without function prototype?");
2200 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2201 NewProto->arg_type_begin(),
2202 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002203 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002204 }
2205
John McCall1d8d1cc2010-08-01 02:01:53 +00002206 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002207
Douglas Gregore53060f2009-06-25 22:08:12 +00002208 return false;
2209}
2210
Douglas Gregor5545e162009-03-24 00:38:23 +00002211/// \brief Initializes common fields of an instantiated method
2212/// declaration (New) from the corresponding fields of its template
2213/// (Tmpl).
2214///
2215/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002216bool
2217TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002218 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002219 if (InitFunctionInstantiation(New, Tmpl))
2220 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Douglas Gregor5545e162009-03-24 00:38:23 +00002222 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002223 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002224 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002225
2226 // FIXME: attributes
2227 // FIXME: New needs a pointer to Tmpl
2228 return false;
2229}
Douglas Gregora58861f2009-05-13 20:28:22 +00002230
2231/// \brief Instantiate the definition of the given function from its
2232/// template.
2233///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002234/// \param PointOfInstantiation the point at which the instantiation was
2235/// required. Note that this is not precisely a "point of instantiation"
2236/// for the function, but it's close.
2237///
Douglas Gregora58861f2009-05-13 20:28:22 +00002238/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002239/// function template specialization or member function of a class template
2240/// specialization.
2241///
2242/// \param Recursive if true, recursively instantiates any functions that
2243/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002244///
2245/// \param DefinitionRequired if true, then we are performing an explicit
2246/// instantiation where the body of the function is required. Complain if
2247/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002248void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002249 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002250 bool Recursive,
2251 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002252 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002253 return;
2254
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002255 // Never instantiate an explicit specialization.
2256 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2257 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002258
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002259 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002260 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002261 Stmt *Pattern = 0;
2262 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002263 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002264
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002265 if (!Pattern) {
2266 if (DefinitionRequired) {
2267 if (Function->getPrimaryTemplate())
2268 Diag(PointOfInstantiation,
2269 diag::err_explicit_instantiation_undefined_func_template)
2270 << Function->getPrimaryTemplate();
2271 else
2272 Diag(PointOfInstantiation,
2273 diag::err_explicit_instantiation_undefined_member)
2274 << 1 << Function->getDeclName() << Function->getDeclContext();
2275
2276 if (PatternDecl)
2277 Diag(PatternDecl->getLocation(),
2278 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002279 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002280 } else if (Function->getTemplateSpecializationKind()
2281 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002282 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002283 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002284 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002285
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002286 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002287 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002288
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002289 // C++0x [temp.explicit]p9:
2290 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002291 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002292 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002293 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002294 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002295 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002296 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002297
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002298 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2299 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002300 return;
2301
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002302 // If we're performing recursive template instantiation, create our own
2303 // queue of pending implicit instantiations that we will instantiate later,
2304 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002305 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002306 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002307 if (Recursive) {
2308 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002309 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Douglas Gregor9679caf2010-05-12 17:27:19 +00002312 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002313 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002314 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002315
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002316 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002317 // recorded, unless we're actually a member function within a local
2318 // class, in which case we need to merge our results with the parent
2319 // scope (of the enclosing function).
2320 bool MergeWithParentScope = false;
2321 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2322 MergeWithParentScope = Rec->isLocalClass();
2323
2324 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002326 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002327 // instantiation scope, and set the parameter names to those used
2328 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002329 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002330 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2331 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002332 if (!PatternParam->isParameterPack()) {
2333 // Simple case: not a parameter pack.
2334 assert(FParamIdx < Function->getNumParams());
2335 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2336 FunctionParam->setDeclName(PatternParam->getDeclName());
2337 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2338 ++FParamIdx;
2339 continue;
2340 }
2341
2342 // Expand the parameter pack.
2343 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2344 for (unsigned NumFParams = Function->getNumParams();
2345 FParamIdx < NumFParams;
2346 ++FParamIdx) {
2347 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2348 FunctionParam->setDeclName(PatternParam->getDeclName());
2349 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2350 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002351 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002352
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002353 // Enter the scope of this instantiation. We don't use
2354 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002355 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002356
Mike Stump1eb44332009-09-09 15:08:12 +00002357 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002358 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002359
2360 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002361 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002362 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2363 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2364 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002365 }
2366
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002367 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002368 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002369
Douglas Gregor52604ab2009-09-11 21:19:12 +00002370 if (Body.isInvalid())
2371 Function->setInvalidDecl();
2372
John McCall9ae2f072010-08-23 23:25:46 +00002373 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002374 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002375
John McCall0c01d182010-03-24 05:22:00 +00002376 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2377
John McCalleee1d542011-02-14 07:13:47 +00002378 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002379
2380 DeclGroupRef DG(Function);
2381 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002382
Douglas Gregor60406be2010-01-16 22:29:39 +00002383 // This class may have local implicit instantiations that need to be
2384 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002385 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002386 Scope.Exit();
2387
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002388 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002389 // Define any pending vtables.
2390 DefineUsedVTables();
2391
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002392 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002393 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002394 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002395
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002396 // Restore the set of pending vtables.
2397 VTableUses.swap(SavedVTableUses);
2398
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002399 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002400 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002401 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002402}
2403
2404/// \brief Instantiate the definition of the given variable from its
2405/// template.
2406///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002407/// \param PointOfInstantiation the point at which the instantiation was
2408/// required. Note that this is not precisely a "point of instantiation"
2409/// for the function, but it's close.
2410///
2411/// \param Var the already-instantiated declaration of a static member
2412/// variable of a class template specialization.
2413///
2414/// \param Recursive if true, recursively instantiates any functions that
2415/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002416///
2417/// \param DefinitionRequired if true, then we are performing an explicit
2418/// instantiation where an out-of-line definition of the member variable
2419/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002420void Sema::InstantiateStaticDataMemberDefinition(
2421 SourceLocation PointOfInstantiation,
2422 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002423 bool Recursive,
2424 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002425 if (Var->isInvalidDecl())
2426 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Douglas Gregor7caa6822009-07-24 20:34:43 +00002428 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002429 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002430 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002431 assert(Def->isStaticDataMember() && "Not a static data member?");
2432 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002433
Douglas Gregor0d035142009-10-27 18:42:08 +00002434 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002435 // We did not find an out-of-line definition of this static data member,
2436 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002437 // instantiate this definition (or provide a specialization for it) in
2438 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002439 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002440 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002441 Diag(PointOfInstantiation,
2442 diag::err_explicit_instantiation_undefined_member)
2443 << 2 << Var->getDeclName() << Var->getDeclContext();
2444 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002445 } else if (Var->getTemplateSpecializationKind()
2446 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002447 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002448 std::make_pair(Var, PointOfInstantiation));
2449 }
2450
Douglas Gregor7caa6822009-07-24 20:34:43 +00002451 return;
2452 }
2453
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002454 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002455 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002456 return;
2457
2458 // C++0x [temp.explicit]p9:
2459 // Except for inline functions, other explicit instantiation declarations
2460 // have the effect of suppressing the implicit instantiation of the entity
2461 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002462 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002463 == TSK_ExplicitInstantiationDeclaration)
2464 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002465
Douglas Gregor7caa6822009-07-24 20:34:43 +00002466 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2467 if (Inst)
2468 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Douglas Gregor7caa6822009-07-24 20:34:43 +00002470 // If we're performing recursive template instantiation, create our own
2471 // queue of pending implicit instantiations that we will instantiate later,
2472 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002473 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002474 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002475 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002476
Douglas Gregor7caa6822009-07-24 20:34:43 +00002477 // Enter the scope of this instantiation. We don't use
2478 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002479 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002481 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002482 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002483 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002484
2485 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002486
2487 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002488 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2489 assert(MSInfo && "Missing member specialization information?");
2490 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2491 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002492 DeclGroupRef DG(Var);
2493 Consumer.HandleTopLevelDecl(DG);
2494 }
Mike Stump1eb44332009-09-09 15:08:12 +00002495
Douglas Gregor7caa6822009-07-24 20:34:43 +00002496 if (Recursive) {
2497 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002498 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002499 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Douglas Gregor7caa6822009-07-24 20:34:43 +00002501 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002502 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002503 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002504}
Douglas Gregor815215d2009-05-27 05:35:12 +00002505
Anders Carlsson09025312009-08-29 05:16:22 +00002506void
2507Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2508 const CXXConstructorDecl *Tmpl,
2509 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002510
Anders Carlsson09025312009-08-29 05:16:22 +00002511 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002512 bool AnyErrors = false;
2513
Anders Carlsson09025312009-08-29 05:16:22 +00002514 // Instantiate all the initializers.
2515 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002516 InitsEnd = Tmpl->init_end();
2517 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002518 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002519
Chandler Carruth030ef472010-09-03 21:54:20 +00002520 // Only instantiate written initializers, let Sema re-construct implicit
2521 // ones.
2522 if (!Init->isWritten())
2523 continue;
2524
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002525 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002526 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002527
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002528 SourceLocation EllipsisLoc;
2529
2530 if (Init->isPackExpansion()) {
2531 // This is a pack expansion. We should expand it now.
2532 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2533 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2534 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2535 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002536 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002537 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002538 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2539 BaseTL.getSourceRange(),
2540 Unexpanded.data(),
2541 Unexpanded.size(),
2542 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002543 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002544 NumExpansions)) {
2545 AnyErrors = true;
2546 New->setInvalidDecl();
2547 continue;
2548 }
2549 assert(ShouldExpand && "Partial instantiation of base initializer?");
2550
2551 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002552 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002553 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2554
2555 // Instantiate the initializer.
2556 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2557 LParenLoc, NewArgs, RParenLoc)) {
2558 AnyErrors = true;
2559 break;
2560 }
2561
2562 // Instantiate the base type.
2563 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2564 TemplateArgs,
2565 Init->getSourceLocation(),
2566 New->getDeclName());
2567 if (!BaseTInfo) {
2568 AnyErrors = true;
2569 break;
2570 }
2571
2572 // Build the initializer.
2573 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2574 BaseTInfo,
2575 (Expr **)NewArgs.data(),
2576 NewArgs.size(),
2577 Init->getLParenLoc(),
2578 Init->getRParenLoc(),
2579 New->getParent(),
2580 SourceLocation());
2581 if (NewInit.isInvalid()) {
2582 AnyErrors = true;
2583 break;
2584 }
2585
2586 NewInits.push_back(NewInit.get());
2587 NewArgs.clear();
2588 }
2589
2590 continue;
2591 }
2592
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002593 // Instantiate the initializer.
2594 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002595 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002596 AnyErrors = true;
2597 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002598 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002599
Anders Carlsson09025312009-08-29 05:16:22 +00002600 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002601 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002602 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002603 TemplateArgs,
2604 Init->getSourceLocation(),
2605 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002606 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002607 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002608 New->setInvalidDecl();
2609 continue;
2610 }
2611
John McCalla93c9342009-12-07 02:54:59 +00002612 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002613 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002614 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002615 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002616 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002617 New->getParent(),
2618 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002619 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002620 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002621 Init->getMemberLocation(),
2622 Init->getMember(),
2623 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002624 if (!Member) {
2625 AnyErrors = true;
2626 New->setInvalidDecl();
2627 continue;
2628 }
Mike Stump1eb44332009-09-09 15:08:12 +00002629
2630 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002631 NewArgs.size(),
2632 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002633 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002634 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002635 } else if (Init->isIndirectMemberInitializer()) {
2636 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002637 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002638 Init->getMemberLocation(),
2639 Init->getIndirectMember(), TemplateArgs));
2640
Douglas Gregorb7107222011-03-04 19:46:35 +00002641 if (!IndirectMember) {
2642 AnyErrors = true;
2643 New->setInvalidDecl();
2644 continue;
2645 }
2646
Francois Pichet00eb3f92010-12-04 09:14:42 +00002647 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2648 NewArgs.size(),
2649 Init->getSourceLocation(),
2650 Init->getLParenLoc(),
2651 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002652 }
2653
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002654 if (NewInit.isInvalid()) {
2655 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002656 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002657 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002658 // FIXME: It would be nice if ASTOwningVector had a release function.
2659 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002660
Anders Carlsson09025312009-08-29 05:16:22 +00002661 NewInits.push_back((MemInitTy *)NewInit.get());
2662 }
2663 }
Mike Stump1eb44332009-09-09 15:08:12 +00002664
Anders Carlsson09025312009-08-29 05:16:22 +00002665 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002666 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002667 /*FIXME: ColonLoc */
2668 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002669 NewInits.data(), NewInits.size(),
2670 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002671}
2672
John McCall52a575a2009-08-29 08:11:13 +00002673// TODO: this could be templated if the various decl types used the
2674// same method name.
2675static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2676 ClassTemplateDecl *Instance) {
2677 Pattern = Pattern->getCanonicalDecl();
2678
2679 do {
2680 Instance = Instance->getCanonicalDecl();
2681 if (Pattern == Instance) return true;
2682 Instance = Instance->getInstantiatedFromMemberTemplate();
2683 } while (Instance);
2684
2685 return false;
2686}
2687
Douglas Gregor0d696532009-09-28 06:34:35 +00002688static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2689 FunctionTemplateDecl *Instance) {
2690 Pattern = Pattern->getCanonicalDecl();
2691
2692 do {
2693 Instance = Instance->getCanonicalDecl();
2694 if (Pattern == Instance) return true;
2695 Instance = Instance->getInstantiatedFromMemberTemplate();
2696 } while (Instance);
2697
2698 return false;
2699}
2700
Douglas Gregored9c0f92009-10-29 00:04:11 +00002701static bool
2702isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2703 ClassTemplatePartialSpecializationDecl *Instance) {
2704 Pattern
2705 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2706 do {
2707 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2708 Instance->getCanonicalDecl());
2709 if (Pattern == Instance)
2710 return true;
2711 Instance = Instance->getInstantiatedFromMember();
2712 } while (Instance);
2713
2714 return false;
2715}
2716
John McCall52a575a2009-08-29 08:11:13 +00002717static bool isInstantiationOf(CXXRecordDecl *Pattern,
2718 CXXRecordDecl *Instance) {
2719 Pattern = Pattern->getCanonicalDecl();
2720
2721 do {
2722 Instance = Instance->getCanonicalDecl();
2723 if (Pattern == Instance) return true;
2724 Instance = Instance->getInstantiatedFromMemberClass();
2725 } while (Instance);
2726
2727 return false;
2728}
2729
2730static bool isInstantiationOf(FunctionDecl *Pattern,
2731 FunctionDecl *Instance) {
2732 Pattern = Pattern->getCanonicalDecl();
2733
2734 do {
2735 Instance = Instance->getCanonicalDecl();
2736 if (Pattern == Instance) return true;
2737 Instance = Instance->getInstantiatedFromMemberFunction();
2738 } while (Instance);
2739
2740 return false;
2741}
2742
2743static bool isInstantiationOf(EnumDecl *Pattern,
2744 EnumDecl *Instance) {
2745 Pattern = Pattern->getCanonicalDecl();
2746
2747 do {
2748 Instance = Instance->getCanonicalDecl();
2749 if (Pattern == Instance) return true;
2750 Instance = Instance->getInstantiatedFromMemberEnum();
2751 } while (Instance);
2752
2753 return false;
2754}
2755
John McCalled976492009-12-04 22:46:56 +00002756static bool isInstantiationOf(UsingShadowDecl *Pattern,
2757 UsingShadowDecl *Instance,
2758 ASTContext &C) {
2759 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2760}
2761
2762static bool isInstantiationOf(UsingDecl *Pattern,
2763 UsingDecl *Instance,
2764 ASTContext &C) {
2765 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2766}
2767
John McCall7ba107a2009-11-18 02:36:19 +00002768static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2769 UsingDecl *Instance,
2770 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002771 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002772}
2773
2774static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002775 UsingDecl *Instance,
2776 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002777 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002778}
2779
John McCall52a575a2009-08-29 08:11:13 +00002780static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2781 VarDecl *Instance) {
2782 assert(Instance->isStaticDataMember());
2783
2784 Pattern = Pattern->getCanonicalDecl();
2785
2786 do {
2787 Instance = Instance->getCanonicalDecl();
2788 if (Pattern == Instance) return true;
2789 Instance = Instance->getInstantiatedFromStaticDataMember();
2790 } while (Instance);
2791
2792 return false;
2793}
2794
John McCalled976492009-12-04 22:46:56 +00002795// Other is the prospective instantiation
2796// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002797static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002798 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002799 if (UnresolvedUsingTypenameDecl *UUD
2800 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2801 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2802 return isInstantiationOf(UUD, UD, Ctx);
2803 }
2804 }
2805
2806 if (UnresolvedUsingValueDecl *UUD
2807 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002808 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2809 return isInstantiationOf(UUD, UD, Ctx);
2810 }
2811 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002812
Anders Carlsson0d8df782009-08-29 19:37:28 +00002813 return false;
2814 }
Mike Stump1eb44332009-09-09 15:08:12 +00002815
John McCall52a575a2009-08-29 08:11:13 +00002816 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2817 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002818
John McCall52a575a2009-08-29 08:11:13 +00002819 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2820 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002821
John McCall52a575a2009-08-29 08:11:13 +00002822 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2823 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002824
Douglas Gregor7caa6822009-07-24 20:34:43 +00002825 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002826 if (Var->isStaticDataMember())
2827 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2828
2829 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2830 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002831
Douglas Gregor0d696532009-09-28 06:34:35 +00002832 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2833 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2834
Douglas Gregored9c0f92009-10-29 00:04:11 +00002835 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2836 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2837 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2838 PartialSpec);
2839
Anders Carlssond8b285f2009-09-01 04:26:58 +00002840 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2841 if (!Field->getDeclName()) {
2842 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002843 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002844 cast<FieldDecl>(D);
2845 }
2846 }
Mike Stump1eb44332009-09-09 15:08:12 +00002847
John McCalled976492009-12-04 22:46:56 +00002848 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2849 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2850
2851 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2852 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2853
Douglas Gregor815215d2009-05-27 05:35:12 +00002854 return D->getDeclName() && isa<NamedDecl>(Other) &&
2855 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2856}
2857
2858template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002859static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002860 NamedDecl *D,
2861 ForwardIterator first,
2862 ForwardIterator last) {
2863 for (; first != last; ++first)
2864 if (isInstantiationOf(Ctx, D, *first))
2865 return cast<NamedDecl>(*first);
2866
2867 return 0;
2868}
2869
John McCall02cace72009-08-28 07:59:38 +00002870/// \brief Finds the instantiation of the given declaration context
2871/// within the current instantiation.
2872///
2873/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002874DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002875 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002876 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002877 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002878 return cast_or_null<DeclContext>(ID);
2879 } else return DC;
2880}
2881
Douglas Gregored961e72009-05-27 17:54:46 +00002882/// \brief Find the instantiation of the given declaration within the
2883/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002884///
2885/// This routine is intended to be used when \p D is a declaration
2886/// referenced from within a template, that needs to mapped into the
2887/// corresponding declaration within an instantiation. For example,
2888/// given:
2889///
2890/// \code
2891/// template<typename T>
2892/// struct X {
2893/// enum Kind {
2894/// KnownValue = sizeof(T)
2895/// };
2896///
2897/// bool getKind() const { return KnownValue; }
2898/// };
2899///
2900/// template struct X<int>;
2901/// \endcode
2902///
2903/// In the instantiation of X<int>::getKind(), we need to map the
2904/// EnumConstantDecl for KnownValue (which refers to
2905/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002906/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2907/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002908NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002909 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002910 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002911 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002912 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002913 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002914 // D is a local of some kind. Look into the map of local
2915 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00002916 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2917 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2918 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00002919
Chris Lattner57ad3782011-02-17 20:34:02 +00002920 if (Found) {
2921 if (Decl *FD = Found->dyn_cast<Decl *>())
2922 return cast<NamedDecl>(FD);
2923
2924 unsigned PackIdx = ArgumentPackSubstitutionIndex;
2925 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
2926 }
2927
2928 // If we didn't find the decl, then we must have a label decl that hasn't
2929 // been found yet. Lazily instantiate it and return it now.
2930 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00002931
Chris Lattner57ad3782011-02-17 20:34:02 +00002932 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
2933 assert(Inst && "Failed to instantiate label??");
2934
2935 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2936 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002937 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002938
Douglas Gregore95b4092009-09-16 18:34:49 +00002939 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2940 if (!Record->isDependentContext())
2941 return D;
2942
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002943 // If the RecordDecl is actually the injected-class-name or a
2944 // "templated" declaration for a class template, class template
2945 // partial specialization, or a member class of a class template,
2946 // substitute into the injected-class-name of the class template
2947 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002948 QualType T;
2949 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2950
2951 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002952 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002953 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2954 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002955 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002956
2957 // If we call SubstType with an InjectedClassNameType here we
2958 // can end up in an infinite loop.
2959 T = Context.getTypeDeclType(Record);
2960 assert(isa<InjectedClassNameType>(T) &&
2961 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002962 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002963 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002964
2965 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002966 // Substitute into the injected-class-name to get the type
2967 // corresponding to the instantiation we want, which may also be
2968 // the current instantiation (if we're in a template
2969 // definition). This substitution should never fail, since we
2970 // know we can instantiate the injected-class-name or we
2971 // wouldn't have gotten to the injected-class-name!
2972
2973 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2974 // extra instantiation in the common case?
Douglas Gregorb46ae392011-03-03 21:48:55 +00002975 T = SubstType(T, TemplateArgs, Loc, DeclarationName());
Douglas Gregore95b4092009-09-16 18:34:49 +00002976 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2977
2978 if (!T->isDependentType()) {
2979 assert(T->isRecordType() && "Instantiation must produce a record type");
2980 return T->getAs<RecordType>()->getDecl();
2981 }
2982
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002983 // We are performing "partial" template instantiation to create
2984 // the member declarations for the members of a class template
2985 // specialization. Therefore, D is actually referring to something
2986 // in the current instantiation. Look through the current
2987 // context, which contains actual instantiations, to find the
2988 // instantiation of the "current instantiation" that D refers
2989 // to.
2990 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002991 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002992 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002993 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002994 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002995 if (isInstantiationOf(ClassTemplate,
2996 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002997 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002998
2999 if (!DC->isDependentContext())
3000 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00003001 }
3002
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003003 // We're performing "instantiation" of a member of the current
3004 // instantiation while we are type-checking the
3005 // definition. Compute the declaration context and return that.
3006 assert(!SawNonDependentContext &&
3007 "No dependent context while instantiating record");
3008 DeclContext *DC = computeDeclContext(T);
3009 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00003010 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003011 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00003012 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003013
Douglas Gregore95b4092009-09-16 18:34:49 +00003014 // Fall through to deal with other dependent record types (e.g.,
3015 // anonymous unions in class templates).
3016 }
John McCall52a575a2009-08-29 08:11:13 +00003017
Douglas Gregore95b4092009-09-16 18:34:49 +00003018 if (!ParentDC->isDependentContext())
3019 return D;
3020
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003021 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003022 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003023 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003024
Douglas Gregor815215d2009-05-27 05:35:12 +00003025 if (ParentDC != D->getDeclContext()) {
3026 // We performed some kind of instantiation in the parent context,
3027 // so now we need to look into the instantiated parent context to
3028 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003029
John McCall3cb0ebd2010-03-10 03:28:59 +00003030 // If our context used to be dependent, we may need to instantiate
3031 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003032 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003033 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003034 if (!Spec->isDependentContext()) {
3035 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003036 const RecordType *Tag = T->getAs<RecordType>();
3037 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003038 if (Tag->isBeingDefined())
3039 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003040 if (!Tag->isBeingDefined() &&
3041 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3042 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003043
3044 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003045 }
3046 }
3047
Douglas Gregor815215d2009-05-27 05:35:12 +00003048 NamedDecl *Result = 0;
3049 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003050 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003051 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3052 } else {
3053 // Since we don't have a name for the entity we're looking for,
3054 // our only option is to walk through all of the declarations to
3055 // find that name. This will occur in a few cases:
3056 //
3057 // - anonymous struct/union within a template
3058 // - unnamed class/struct/union/enum within a template
3059 //
3060 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003061 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003062 ParentDC->decls_begin(),
3063 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003064 }
Mike Stump1eb44332009-09-09 15:08:12 +00003065
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003066 if (!Result) {
3067 if (isa<UsingShadowDecl>(D)) {
3068 // UsingShadowDecls can instantiate to nothing because of using hiding.
3069 } else if (Diags.hasErrorOccurred()) {
3070 // We've already complained about something, so most likely this
3071 // declaration failed to instantiate. There's no point in complaining
3072 // further, since this is normal in invalid code.
3073 } else if (IsBeingInstantiated) {
3074 // The class in which this member exists is currently being
3075 // instantiated, and we haven't gotten around to instantiating this
3076 // member yet. This can happen when the code uses forward declarations
3077 // of member classes, and introduces ordering dependencies via
3078 // template instantiation.
3079 Diag(Loc, diag::err_member_not_yet_instantiated)
3080 << D->getDeclName()
3081 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3082 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3083 } else {
3084 // We should have found something, but didn't.
3085 llvm_unreachable("Unable to find instantiation of declaration!");
3086 }
3087 }
3088
Douglas Gregor815215d2009-05-27 05:35:12 +00003089 D = Result;
3090 }
3091
Douglas Gregor815215d2009-05-27 05:35:12 +00003092 return D;
3093}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003094
Mike Stump1eb44332009-09-09 15:08:12 +00003095/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003096/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003097void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003098 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003099 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003100 PendingImplicitInstantiation Inst;
3101
3102 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003103 Inst = PendingInstantiations.front();
3104 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003105 } else {
3106 Inst = PendingLocalImplicitInstantiations.front();
3107 PendingLocalImplicitInstantiations.pop_front();
3108 }
Mike Stump1eb44332009-09-09 15:08:12 +00003109
Douglas Gregor7caa6822009-07-24 20:34:43 +00003110 // Instantiate function definitions
3111 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003112 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3113 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003114 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3115 TSK_ExplicitInstantiationDefinition;
3116 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3117 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003118 continue;
3119 }
Mike Stump1eb44332009-09-09 15:08:12 +00003120
Douglas Gregor7caa6822009-07-24 20:34:43 +00003121 // Instantiate static data member definitions.
3122 VarDecl *Var = cast<VarDecl>(Inst.first);
3123 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003124
Chandler Carruth291b4412010-02-13 10:17:50 +00003125 // Don't try to instantiate declarations if the most recent redeclaration
3126 // is invalid.
3127 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3128 continue;
3129
3130 // Check if the most recent declaration has changed the specialization kind
3131 // and removed the need for implicit instantiation.
3132 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3133 case TSK_Undeclared:
3134 assert(false && "Cannot instantitiate an undeclared specialization.");
3135 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003136 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003137 continue; // No longer need to instantiate this type.
3138 case TSK_ExplicitInstantiationDefinition:
3139 // We only need an instantiation if the pending instantiation *is* the
3140 // explicit instantiation.
3141 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003142 case TSK_ImplicitInstantiation:
3143 break;
3144 }
3145
John McCallf312b1e2010-08-26 23:41:50 +00003146 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3147 "instantiating static data member "
3148 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Chandler Carruth58e390e2010-08-25 08:27:02 +00003150 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3151 TSK_ExplicitInstantiationDefinition;
3152 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3153 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003154 }
3155}
John McCall0c01d182010-03-24 05:22:00 +00003156
3157void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3158 const MultiLevelTemplateArgumentList &TemplateArgs) {
3159 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3160 E = Pattern->ddiag_end(); I != E; ++I) {
3161 DependentDiagnostic *DD = *I;
3162
3163 switch (DD->getKind()) {
3164 case DependentDiagnostic::Access:
3165 HandleDependentAccessCheck(*DD, TemplateArgs);
3166 break;
3167 }
3168 }
3169}