blob: 3fe5fd5c952852362a571815d112d4f04828b5f5 [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
301 if (!D->isStaticDataMember())
302 Var->setUsed(D->isUsed(false));
Douglas Gregor4469e8a2010-05-19 17:02:24 +0000303
Mike Stump390b4cc2009-05-16 07:39:55 +0000304 // FIXME: In theory, we could have a previous declaration for variables that
305 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000306 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000307 // FIXME: having to fake up a LookupResult is dumb.
308 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000309 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000310 if (D->isStaticDataMember())
311 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000312 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Douglas Gregor7caa6822009-07-24 20:34:43 +0000314 if (D->isOutOfLine()) {
Abramo Bagnaraea7b4882010-06-04 09:35:39 +0000315 if (!D->isStaticDataMember())
316 D->getLexicalDeclContext()->addDecl(Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000317 Owner->makeDeclVisibleInContext(Var);
318 } else {
319 Owner->addDecl(Var);
Douglas Gregorf7d72f52010-05-03 20:22:41 +0000320 if (Owner->isFunctionOrMethod())
321 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Var);
Douglas Gregor7caa6822009-07-24 20:34:43 +0000322 }
John McCall1d8d1cc2010-08-01 02:01:53 +0000323 SemaRef.InstantiateAttrs(TemplateArgs, D, Var);
Fariborz Jahanian8dd0c562010-07-13 00:16:40 +0000324
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000325 // Link instantiations of static data members back to the template from
326 // which they were instantiated.
327 if (Var->isStaticDataMember())
328 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000329 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000330
Douglas Gregor60c93c92010-02-09 07:26:29 +0000331 if (Var->getAnyInitializer()) {
332 // We already have an initializer in the class.
333 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000334 if (Var->isStaticDataMember() && !D->isOutOfLine())
335 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
336 else
337 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
338
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000339 // Instantiate the initializer.
340 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +0000341 ASTOwningVector<Expr*> InitArgs(SemaRef);
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000342 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +0000343 InitArgs, RParenLoc)) {
Richard Smith34b41d92011-02-20 03:19:35 +0000344 bool TypeMayContainAuto = true;
Douglas Gregor07a77b42011-01-14 17:12:22 +0000345 // Attach the initializer to the declaration, if we have one.
346 if (InitArgs.size() == 0)
Richard Smith34b41d92011-02-20 03:19:35 +0000347 SemaRef.ActOnUninitializedDecl(Var, TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000348 else if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000349 // Add the direct initializer to the declaration.
John McCalld226f652010-08-21 09:40:31 +0000350 SemaRef.AddCXXDirectInitializerToDecl(Var,
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000351 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000352 move_arg(InitArgs),
Richard Smith34b41d92011-02-20 03:19:35 +0000353 RParenLoc,
354 TypeMayContainAuto);
Douglas Gregor07a77b42011-01-14 17:12:22 +0000355 } else {
356 assert(InitArgs.size() == 1);
John McCall9ae2f072010-08-23 23:25:46 +0000357 Expr *Init = InitArgs.take()[0];
Richard Smith34b41d92011-02-20 03:19:35 +0000358 SemaRef.AddInitializerToDecl(Var, Init, false, TypeMayContainAuto);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000359 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000360 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000361 // FIXME: Not too happy about invalidating the declaration
362 // because of a bogus initializer.
363 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000364 }
365
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000366 SemaRef.PopExpressionEvaluationContext();
Richard Smithad762fc2011-04-14 22:09:26 +0000367 } else if ((!Var->isStaticDataMember() || Var->isOutOfLine()) &&
368 !Var->isCXXForRangeDecl())
John McCalld226f652010-08-21 09:40:31 +0000369 SemaRef.ActOnUninitializedDecl(Var, false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000370
Douglas Gregor5764f612010-05-08 23:05:03 +0000371 // Diagnose unused local variables.
372 if (!Var->isInvalidDecl() && Owner->isFunctionOrMethod() && !Var->isUsed())
373 SemaRef.DiagnoseUnusedDecl(Var);
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +0000374
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000375 return Var;
376}
377
Abramo Bagnara6206d532010-06-05 05:09:32 +0000378Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
379 AccessSpecDecl* AD
380 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
381 D->getAccessSpecifierLoc(), D->getColonLoc());
382 Owner->addHiddenDecl(AD);
383 return AD;
384}
385
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000386Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
387 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000388 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor836adf62010-05-24 17:22:01 +0000389 if (DI->getType()->isDependentType() ||
390 DI->getType()->isVariablyModifiedType()) {
John McCall07fb6be2009-10-22 23:33:21 +0000391 DI = SemaRef.SubstType(DI, TemplateArgs,
392 D->getLocation(), D->getDeclName());
393 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000394 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000395 Invalid = true;
396 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000397 // C++ [temp.arg.type]p3:
398 // If a declaration acquires a function type through a type
399 // dependent on a template-parameter and this causes a
400 // declaration that does not use the syntactic form of a
401 // function declarator to have function type, the program is
402 // ill-formed.
403 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000404 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000405 Invalid = true;
406 }
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000407 } else {
408 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000409 }
410
411 Expr *BitWidth = D->getBitWidth();
412 if (Invalid)
413 BitWidth = 0;
414 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000415 // The bit-width expression is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000416 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000417
John McCall60d7b3a2010-08-24 06:29:42 +0000418 ExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000419 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000420 if (InstantiatedBitWidth.isInvalid()) {
421 Invalid = true;
422 BitWidth = 0;
423 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000424 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000425 }
426
John McCall07fb6be2009-10-22 23:33:21 +0000427 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
428 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000429 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000430 D->getLocation(),
431 D->isMutable(),
432 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000433 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000434 D->getAccess(),
435 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000436 if (!Field) {
437 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000438 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000439 }
Mike Stump1eb44332009-09-09 15:08:12 +0000440
John McCall1d8d1cc2010-08-01 02:01:53 +0000441 SemaRef.InstantiateAttrs(TemplateArgs, D, Field);
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000442
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000443 if (Invalid)
444 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000445
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000446 if (!Field->getDeclName()) {
447 // Keep track of where this decl came from.
448 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor9901c572010-05-21 00:31:19 +0000449 }
450 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
451 if (Parent->isAnonymousStructOrUnion() &&
Sebastian Redl7a126a42010-08-31 00:36:30 +0000452 Parent->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000453 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000456 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000457 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000458 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000459
460 return Field;
461}
462
Francois Pichet87c2e122010-11-21 06:08:52 +0000463Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
464 NamedDecl **NamedChain =
465 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
466
467 int i = 0;
468 for (IndirectFieldDecl::chain_iterator PI =
469 D->chain_begin(), PE = D->chain_end();
Douglas Gregorb7107222011-03-04 19:46:35 +0000470 PI != PE; ++PI) {
471 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), *PI,
472 TemplateArgs);
473 if (!Next)
474 return 0;
475
476 NamedChain[i++] = Next;
477 }
Francois Pichet87c2e122010-11-21 06:08:52 +0000478
Francois Pichet40e17752010-12-09 10:07:54 +0000479 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
Francois Pichet87c2e122010-11-21 06:08:52 +0000480 IndirectFieldDecl* IndirectField
481 = IndirectFieldDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Francois Pichet40e17752010-12-09 10:07:54 +0000482 D->getIdentifier(), T,
Francois Pichet87c2e122010-11-21 06:08:52 +0000483 NamedChain, D->getChainingSize());
484
485
486 IndirectField->setImplicit(D->isImplicit());
487 IndirectField->setAccess(D->getAccess());
488 Owner->addDecl(IndirectField);
489 return IndirectField;
490}
491
John McCall02cace72009-08-28 07:59:38 +0000492Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000493 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000494 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000495 if (TypeSourceInfo *Ty = D->getFriendType()) {
496 TypeSourceInfo *InstTy =
497 SemaRef.SubstType(Ty, TemplateArgs,
498 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000499 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000500 return 0;
John McCall02cace72009-08-28 07:59:38 +0000501
Douglas Gregor06245bf2010-04-07 17:57:12 +0000502 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
503 if (!FD)
504 return 0;
505
506 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000507 FD->setUnsupportedFriend(D->isUnsupportedFriend());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000508 Owner->addDecl(FD);
509 return FD;
510 }
511
512 NamedDecl *ND = D->getFriendDecl();
513 assert(ND && "friend decl must be a decl or a type!");
514
John McCallaf2094e2010-04-08 09:05:18 +0000515 // All of the Visit implementations for the various potential friend
516 // declarations have to be carefully written to work for friend
517 // objects, with the most important detail being that the target
518 // decl should almost certainly not be placed in Owner.
519 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000520 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000521
John McCall02cace72009-08-28 07:59:38 +0000522 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000523 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
524 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000525 FD->setAccess(AS_public);
John McCall9a34edb2010-10-19 01:40:49 +0000526 FD->setUnsupportedFriend(D->isUnsupportedFriend());
John McCall02cace72009-08-28 07:59:38 +0000527 Owner->addDecl(FD);
528 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000529}
530
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000531Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
532 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000533
Douglas Gregorac7610d2009-06-22 20:57:11 +0000534 // The expression in a static assertion is not potentially evaluated.
John McCallf312b1e2010-08-26 23:41:50 +0000535 EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000536
John McCall60d7b3a2010-08-24 06:29:42 +0000537 ExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000538 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000539 if (InstantiatedAssertExpr.isInvalid())
540 return 0;
541
John McCall60d7b3a2010-08-24 06:29:42 +0000542 ExprResult Message(D->getMessage());
John McCall3fa5cae2010-10-26 07:05:15 +0000543 D->getMessage();
John McCalld226f652010-08-21 09:40:31 +0000544 return SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
John McCall9ae2f072010-08-23 23:25:46 +0000545 InstantiatedAssertExpr.get(),
Abramo Bagnaraa2026c92011-03-08 16:41:52 +0000546 Message.get(),
547 D->getRParenLoc());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000548}
549
550Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000551 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner, D->getLocStart(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000552 D->getLocation(), D->getIdentifier(),
Abramo Bagnaraa88cefd2010-12-03 18:54:17 +0000553 /*PrevDecl=*/0, D->isScoped(),
554 D->isScopedUsingClassTag(), D->isFixed());
Douglas Gregor1274ccd2010-10-08 23:50:27 +0000555 if (D->isFixed()) {
556 if (TypeSourceInfo* TI = D->getIntegerTypeSourceInfo()) {
557 // If we have type source information for the underlying type, it means it
558 // has been explicitly set by the user. Perform substitution on it before
559 // moving on.
560 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
561 Enum->setIntegerTypeSourceInfo(SemaRef.SubstType(TI,
562 TemplateArgs,
563 UnderlyingLoc,
564 DeclarationName()));
565
566 if (!Enum->getIntegerTypeSourceInfo())
567 Enum->setIntegerType(SemaRef.Context.IntTy);
568 }
569 else {
570 assert(!D->getIntegerType()->isDependentType()
571 && "Dependent type without type source info");
572 Enum->setIntegerType(D->getIntegerType());
573 }
574 }
575
John McCall5b629aa2010-10-22 23:36:17 +0000576 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
577
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000578 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000579 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000580 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000581 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000582 Enum->startDefinition();
583
Douglas Gregor96084f12010-03-01 19:00:07 +0000584 if (D->getDeclContext()->isFunctionOrMethod())
585 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
586
John McCalld226f652010-08-21 09:40:31 +0000587 llvm::SmallVector<Decl*, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000588
589 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000590 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
591 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000592 EC != ECEnd; ++EC) {
593 // The specified value for the enumerator.
John McCall60d7b3a2010-08-24 06:29:42 +0000594 ExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000595 if (Expr *UninstValue = EC->getInitExpr()) {
596 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000597 EnterExpressionEvaluationContext Unevaluated(SemaRef,
John McCallf312b1e2010-08-26 23:41:50 +0000598 Sema::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000599
John McCallce3ff2b2009-08-25 22:02:44 +0000600 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000601 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000602
603 // Drop the initial value and continue.
604 bool isInvalid = false;
605 if (Value.isInvalid()) {
606 Value = SemaRef.Owned((Expr *)0);
607 isInvalid = true;
608 }
609
Mike Stump1eb44332009-09-09 15:08:12 +0000610 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000611 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
612 EC->getLocation(), EC->getIdentifier(),
John McCall9ae2f072010-08-23 23:25:46 +0000613 Value.get());
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000614
615 if (isInvalid) {
616 if (EnumConst)
617 EnumConst->setInvalidDecl();
618 Enum->setInvalidDecl();
619 }
620
621 if (EnumConst) {
John McCall5b629aa2010-10-22 23:36:17 +0000622 SemaRef.InstantiateAttrs(TemplateArgs, *EC, EnumConst);
623
John McCall3b85ecf2010-01-23 22:37:59 +0000624 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000625 Enum->addDecl(EnumConst);
John McCalld226f652010-08-21 09:40:31 +0000626 Enumerators.push_back(EnumConst);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000627 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000628
629 if (D->getDeclContext()->isFunctionOrMethod()) {
630 // If the enumeration is within a function or method, record the enum
631 // constant as a local.
632 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
633 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000634 }
635 }
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000637 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000638 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000639 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
John McCalld226f652010-08-21 09:40:31 +0000640 Enum,
Eli Friedmande7a0fc2010-08-15 02:27:09 +0000641 Enumerators.data(), Enumerators.size(),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000642 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000643
644 return Enum;
645}
646
Douglas Gregor6477b692009-03-25 15:04:13 +0000647Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
648 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
649 return 0;
650}
651
John McCalle29ba202009-08-20 01:44:21 +0000652Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000653 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
654
Douglas Gregor550d9b22009-10-31 17:21:17 +0000655 // Create a local instantiation scope for this class template, which
656 // will contain the instantiations of the template parameters.
John McCall2a7fb272010-08-25 05:32:35 +0000657 LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000658 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000659 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000660 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000661 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000662
663 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000664
665 // Instantiate the qualifier. We have to do this first in case
666 // we're a friend declaration, because if we are then we need to put
667 // the new declaration in the appropriate context.
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000668 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
669 if (QualifierLoc) {
670 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
671 TemplateArgs);
672 if (!QualifierLoc)
673 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000674 }
675
676 CXXRecordDecl *PrevDecl = 0;
677 ClassTemplateDecl *PrevClassTemplate = 0;
678
Nick Lewycky37574f52010-11-08 23:29:42 +0000679 if (!isFriend && Pattern->getPreviousDeclaration()) {
680 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
681 if (Found.first != Found.second) {
682 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(*Found.first);
683 if (PrevClassTemplate)
684 PrevDecl = PrevClassTemplate->getTemplatedDecl();
685 }
686 }
687
John McCall93ba8572010-03-25 06:39:04 +0000688 // If this isn't a friend, then it's a member template, in which
689 // case we just want to build the instantiation in the
690 // specialization. If it is a friend, we want to build it in
691 // the appropriate context.
692 DeclContext *DC = Owner;
693 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000694 if (QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000695 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000696 SS.Adopt(QualifierLoc);
John McCall93ba8572010-03-25 06:39:04 +0000697 DC = SemaRef.computeDeclContext(SS);
698 if (!DC) return 0;
699 } else {
700 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
701 Pattern->getDeclContext(),
702 TemplateArgs);
703 }
704
705 // Look for a previous declaration of the template in the owning
706 // context.
707 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
708 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
709 SemaRef.LookupQualifiedName(R, DC);
710
711 if (R.isSingleResult()) {
712 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
713 if (PrevClassTemplate)
714 PrevDecl = PrevClassTemplate->getTemplatedDecl();
715 }
716
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000717 if (!PrevClassTemplate && QualifierLoc) {
John McCall93ba8572010-03-25 06:39:04 +0000718 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000719 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000720 << QualifierLoc.getSourceRange();
John McCall93ba8572010-03-25 06:39:04 +0000721 return 0;
722 }
723
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000724 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000725 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000726 bool Complain = true;
727
728 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
729 // template for struct std::tr1::__detail::_Map_base, where the
730 // template parameters of the friend declaration don't match the
731 // template parameters of the original declaration. In this one
732 // case, we don't complain about the ill-formed friend
733 // declaration.
734 if (isFriend && Pattern->getIdentifier() &&
735 Pattern->getIdentifier()->isStr("_Map_base") &&
736 DC->isNamespace() &&
737 cast<NamespaceDecl>(DC)->getIdentifier() &&
738 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
739 DeclContext *DCParent = DC->getParent();
740 if (DCParent->isNamespace() &&
741 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
742 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
743 DeclContext *DCParent2 = DCParent->getParent();
744 if (DCParent2->isNamespace() &&
745 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
746 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
747 DCParent2->getParent()->isTranslationUnit())
748 Complain = false;
749 }
750 }
751
John McCall93ba8572010-03-25 06:39:04 +0000752 TemplateParameterList *PrevParams
753 = PrevClassTemplate->getTemplateParameters();
754
755 // Make sure the parameter lists match.
756 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000757 Complain,
758 Sema::TPL_TemplateMatch)) {
759 if (Complain)
760 return 0;
761
762 AdoptedPreviousTemplateParams = true;
763 InstParams = PrevParams;
764 }
John McCall93ba8572010-03-25 06:39:04 +0000765
766 // Do some additional validation, then merge default arguments
767 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000768 if (!AdoptedPreviousTemplateParams &&
769 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000770 Sema::TPC_ClassTemplate))
771 return 0;
772 }
773 }
774
John McCalle29ba202009-08-20 01:44:21 +0000775 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000776 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000777 Pattern->getLocStart(), Pattern->getLocation(),
778 Pattern->getIdentifier(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000779 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000780
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000781 if (QualifierLoc)
782 RecordInst->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +0000783
John McCalle29ba202009-08-20 01:44:21 +0000784 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000785 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
786 D->getIdentifier(), InstParams, RecordInst,
787 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000788 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000789
John McCall93ba8572010-03-25 06:39:04 +0000790 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000791 if (PrevClassTemplate)
792 Inst->setAccess(PrevClassTemplate->getAccess());
793 else
794 Inst->setAccess(D->getAccess());
795
John McCall93ba8572010-03-25 06:39:04 +0000796 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
797 // TODO: do we want to track the instantiation progeny of this
798 // friend target decl?
799 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000800 Inst->setAccess(D->getAccess());
Nick Lewycky37574f52010-11-08 23:29:42 +0000801 if (!PrevClassTemplate)
802 Inst->setInstantiatedFromMemberTemplate(D);
John McCall93ba8572010-03-25 06:39:04 +0000803 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000804
805 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000806 SemaRef.Context.getInjectedClassNameType(RecordInst,
Douglas Gregor24bae922010-07-08 18:37:38 +0000807 Inst->getInjectedClassNameSpecialization());
John McCallea7390c2010-04-08 20:25:50 +0000808
Douglas Gregor259571e2009-10-30 22:42:42 +0000809 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000810 if (isFriend) {
811 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000812 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000813 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000814
John McCalle29ba202009-08-20 01:44:21 +0000815 Owner->addDecl(Inst);
Douglas Gregord65587f2010-11-10 19:44:59 +0000816
817 if (!PrevClassTemplate) {
818 // Queue up any out-of-line partial specializations of this member
819 // class template; the client will force their instantiation once
820 // the enclosing class has been instantiated.
821 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
822 D->getPartialSpecializations(PartialSpecs);
823 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
824 if (PartialSpecs[I]->isOutOfLine())
825 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
826 }
827
John McCalle29ba202009-08-20 01:44:21 +0000828 return Inst;
829}
830
Douglas Gregord60e1052009-08-27 16:57:43 +0000831Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000832TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
833 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000834 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
835
836 // Lookup the already-instantiated declaration in the instantiation
837 // of the class template and return that.
838 DeclContext::lookup_result Found
839 = Owner->lookup(ClassTemplate->getDeclName());
840 if (Found.first == Found.second)
841 return 0;
842
843 ClassTemplateDecl *InstClassTemplate
844 = dyn_cast<ClassTemplateDecl>(*Found.first);
845 if (!InstClassTemplate)
846 return 0;
847
Douglas Gregord65587f2010-11-10 19:44:59 +0000848 if (ClassTemplatePartialSpecializationDecl *Result
849 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
850 return Result;
851
852 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000853}
854
855Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000856TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000857 // Create a local instantiation scope for this function template, which
858 // will contain the instantiations of the template parameters and then get
859 // merged with the local instantiation scope for the function template
860 // itself.
John McCall2a7fb272010-08-25 05:32:35 +0000861 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor895162d2010-04-30 18:55:50 +0000862
Douglas Gregord60e1052009-08-27 16:57:43 +0000863 TemplateParameterList *TempParams = D->getTemplateParameters();
864 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000865 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000866 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000867
Douglas Gregora735b202009-10-13 14:39:41 +0000868 FunctionDecl *Instantiated = 0;
869 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
870 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
871 InstParams));
872 else
873 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
874 D->getTemplatedDecl(),
875 InstParams));
876
877 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000878 return 0;
879
John McCall46460a62010-01-20 21:53:11 +0000880 Instantiated->setAccess(D->getAccess());
881
Mike Stump1eb44332009-09-09 15:08:12 +0000882 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000883 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000884 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000885 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000886 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000887 assert(InstTemplate &&
888 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000889
John McCallb1a56e72010-03-26 23:10:15 +0000890 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
891
John McCalle976ffe2009-12-14 23:19:40 +0000892 // Link the instantiation back to the pattern *unless* this is a
893 // non-definition friend declaration.
894 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000895 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000896 InstTemplate->setInstantiatedFromMemberTemplate(D);
897
John McCallb1a56e72010-03-26 23:10:15 +0000898 // Make declarations visible in the appropriate context.
899 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000900 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000901
Douglas Gregord60e1052009-08-27 16:57:43 +0000902 return InstTemplate;
903}
904
Douglas Gregord475b8d2009-03-25 21:17:03 +0000905Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
906 CXXRecordDecl *PrevDecl = 0;
907 if (D->isInjectedClassName())
908 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000909 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000910 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
911 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000912 TemplateArgs);
913 if (!Prev) return 0;
914 PrevDecl = cast<CXXRecordDecl>(Prev);
915 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000916
917 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000918 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +0000919 D->getLocStart(), D->getLocation(),
920 D->getIdentifier(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000921
922 // Substitute the nested name specifier, if any.
923 if (SubstQualifier(D, Record))
924 return 0;
925
Douglas Gregord475b8d2009-03-25 21:17:03 +0000926 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000927 // FIXME: Check against AS_none is an ugly hack to work around the issue that
928 // the tag decls introduced by friend class declarations don't have an access
929 // specifier. Remove once this area of the code gets sorted out.
930 if (D->getAccess() != AS_none)
931 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000932 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000933 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000934
John McCall02cace72009-08-28 07:59:38 +0000935 // If the original function was part of a friend declaration,
936 // inherit its namespace state.
937 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
938 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
939
Douglas Gregor9901c572010-05-21 00:31:19 +0000940 // Make sure that anonymous structs and unions are recorded.
941 if (D->isAnonymousStructOrUnion()) {
942 Record->setAnonymousStructOrUnion(true);
Sebastian Redl7a126a42010-08-31 00:36:30 +0000943 if (Record->getDeclContext()->getRedeclContext()->isFunctionOrMethod())
Douglas Gregor9901c572010-05-21 00:31:19 +0000944 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
945 }
Anders Carlssond8b285f2009-09-01 04:26:58 +0000946
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000947 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000948 return Record;
949}
950
John McCall02cace72009-08-28 07:59:38 +0000951/// Normal class members are of more specific types and therefore
952/// don't make it here. This function serves two purposes:
953/// 1) instantiating function templates
954/// 2) substituting friend declarations
955/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000956Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000957 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000958 // Check whether there is already a function template specialization for
959 // this declaration.
960 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
961 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000962 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor24bae922010-07-08 18:37:38 +0000963 std::pair<const TemplateArgument *, unsigned> Innermost
964 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000966 FunctionDecl *SpecFunc
967 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
968 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Douglas Gregor127102b2009-06-29 20:59:39 +0000970 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +0000971 if (SpecFunc)
972 return SpecFunc;
Douglas Gregor127102b2009-06-29 20:59:39 +0000973 }
Mike Stump1eb44332009-09-09 15:08:12 +0000974
John McCallb0cb0222010-03-27 05:57:59 +0000975 bool isFriend;
976 if (FunctionTemplate)
977 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
978 else
979 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
980
Douglas Gregor79c22782010-01-16 20:21:20 +0000981 bool MergeWithParentScope = (TemplateParams != 0) ||
Douglas Gregorb212d9a2010-05-21 21:25:08 +0000982 Owner->isFunctionOrMethod() ||
Douglas Gregor79c22782010-01-16 20:21:20 +0000983 !(isa<Decl>(Owner) &&
984 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +0000985 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Douglas Gregore53060f2009-06-25 22:08:12 +0000987 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000988 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
989 TInfo = SubstFunctionType(D, Params);
990 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000991 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000992 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000993
Douglas Gregorc22b5ff2011-02-25 02:25:35 +0000994 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
995 if (QualifierLoc) {
996 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
997 TemplateArgs);
998 if (!QualifierLoc)
999 return 0;
John McCalld325daa2010-03-26 04:53:08 +00001000 }
1001
John McCall68b6b872010-02-06 01:50:47 +00001002 // If we're instantiating a local function declaration, put the result
1003 // in the owner; otherwise we need to find the instantiated context.
1004 DeclContext *DC;
1005 if (D->getDeclContext()->isFunctionOrMethod())
1006 DC = Owner;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001007 else if (isFriend && QualifierLoc) {
John McCalld325daa2010-03-26 04:53:08 +00001008 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001009 SS.Adopt(QualifierLoc);
John McCalld325daa2010-03-26 04:53:08 +00001010 DC = SemaRef.computeDeclContext(SS);
1011 if (!DC) return 0;
1012 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001013 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
1014 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +00001015 }
John McCall68b6b872010-02-06 01:50:47 +00001016
John McCall02cace72009-08-28 07:59:38 +00001017 FunctionDecl *Function =
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001018 FunctionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1019 D->getLocation(), D->getDeclName(), T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001020 D->getStorageClass(), D->getStorageClassAsWritten(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001021 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +00001022
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001023 if (QualifierLoc)
1024 Function->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001025
John McCallb1a56e72010-03-26 23:10:15 +00001026 DeclContext *LexicalDC = Owner;
1027 if (!isFriend && D->isOutOfLine()) {
1028 assert(D->getDeclContext()->isFileContext());
1029 LexicalDC = D->getDeclContext();
1030 }
1031
1032 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001033
Douglas Gregore53060f2009-06-25 22:08:12 +00001034 // Attach the parameters
1035 for (unsigned P = 0; P < Params.size(); ++P)
John McCall3019c442010-09-17 00:50:28 +00001036 if (Params[P])
1037 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001038 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001039
Douglas Gregorac7c2c82010-05-17 16:38:00 +00001040 SourceLocation InstantiateAtPOI;
Douglas Gregora735b202009-10-13 14:39:41 +00001041 if (TemplateParams) {
1042 // Our resulting instantiation is actually a function template, since we
1043 // are substituting only the outer template parameters. For example, given
1044 //
1045 // template<typename T>
1046 // struct X {
1047 // template<typename U> friend void f(T, U);
1048 // };
1049 //
1050 // X<int> x;
1051 //
1052 // We are instantiating the friend function template "f" within X<int>,
1053 // which means substituting int for T, but leaving "f" as a friend function
1054 // template.
1055 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001056 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001057 Function->getLocation(),
1058 Function->getDeclName(),
1059 TemplateParams, Function);
1060 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001061
1062 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001063
1064 if (isFriend && D->isThisDeclarationADefinition()) {
1065 // TODO: should we remember this connection regardless of whether
1066 // the friend declaration provided a body?
1067 FunctionTemplate->setInstantiatedFromMemberTemplate(
1068 D->getDescribedFunctionTemplate());
1069 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001070 } else if (FunctionTemplate) {
1071 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001072 std::pair<const TemplateArgument *, unsigned> Innermost
1073 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001074 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001075 TemplateArgumentList::CreateCopy(SemaRef.Context,
Douglas Gregor24bae922010-07-08 18:37:38 +00001076 Innermost.first,
1077 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001078 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001079 } else if (isFriend && D->isThisDeclarationADefinition()) {
1080 // TODO: should we remember this connection regardless of whether
1081 // the friend declaration provided a body?
1082 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001083 }
Douglas Gregora735b202009-10-13 14:39:41 +00001084
Douglas Gregore53060f2009-06-25 22:08:12 +00001085 if (InitFunctionInstantiation(Function, D))
1086 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001087
Douglas Gregore53060f2009-06-25 22:08:12 +00001088 bool Redeclaration = false;
John McCallaf2094e2010-04-08 09:05:18 +00001089 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001090
John McCall68263142009-11-18 22:49:29 +00001091 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1092 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1093
John McCallaf2094e2010-04-08 09:05:18 +00001094 if (DependentFunctionTemplateSpecializationInfo *Info
1095 = D->getDependentSpecializationInfo()) {
1096 assert(isFriend && "non-friend has dependent specialization info?");
1097
1098 // This needs to be set now for future sanity.
1099 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1100
1101 // Instantiate the explicit template arguments.
1102 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1103 Info->getRAngleLoc());
Douglas Gregore02e2622010-12-22 21:19:48 +00001104 if (SemaRef.Subst(Info->getTemplateArgs(), Info->getNumTemplateArgs(),
1105 ExplicitArgs, TemplateArgs))
1106 return 0;
John McCallaf2094e2010-04-08 09:05:18 +00001107
1108 // Map the candidate templates to their instantiations.
1109 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1110 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1111 Info->getTemplate(I),
1112 TemplateArgs);
1113 if (!Temp) return 0;
1114
1115 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1116 }
1117
1118 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1119 &ExplicitArgs,
1120 Previous))
1121 Function->setInvalidDecl();
1122
1123 isExplicitSpecialization = true;
1124
1125 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001126 // Look only into the namespace where the friend would be declared to
1127 // find a previous declaration. This is the innermost enclosing namespace,
1128 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001129 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001130
Douglas Gregora735b202009-10-13 14:39:41 +00001131 // In C++, the previous declaration we find might be a tag type
1132 // (class or enum). In this case, the new declaration will hide the
1133 // tag type. Note that this does does not apply if we're declaring a
1134 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001135 if (Previous.isSingleTagDecl())
1136 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001137 }
1138
John McCall9f54ad42009-12-10 09:41:52 +00001139 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
Peter Collingbournec80e8112011-01-21 02:08:54 +00001140 isExplicitSpecialization, Redeclaration);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001141
John McCall76d32642010-04-24 01:30:58 +00001142 NamedDecl *PrincipalDecl = (TemplateParams
1143 ? cast<NamedDecl>(FunctionTemplate)
1144 : Function);
1145
Douglas Gregora735b202009-10-13 14:39:41 +00001146 // If the original function was part of a friend declaration,
1147 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001148 if (isFriend) {
John McCall68263142009-11-18 22:49:29 +00001149 NamedDecl *PrevDecl;
John McCall76d32642010-04-24 01:30:58 +00001150 if (TemplateParams)
Douglas Gregora735b202009-10-13 14:39:41 +00001151 PrevDecl = FunctionTemplate->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001152 else
Douglas Gregora735b202009-10-13 14:39:41 +00001153 PrevDecl = Function->getPreviousDeclaration();
John McCall76d32642010-04-24 01:30:58 +00001154
1155 PrincipalDecl->setObjectOfFriendDecl(PrevDecl != 0);
1156 DC->makeDeclVisibleInContext(PrincipalDecl, /*Recoverable=*/ false);
Gabor Greifab297ac2010-08-30 21:10:05 +00001157
Gabor Greif77535df2010-08-30 22:25:56 +00001158 bool queuedInstantiation = false;
Gabor Greifab297ac2010-08-30 21:10:05 +00001159
Douglas Gregor238058c2010-05-18 05:45:02 +00001160 if (!SemaRef.getLangOptions().CPlusPlus0x &&
1161 D->isThisDeclarationADefinition()) {
1162 // Check for a function body.
1163 const FunctionDecl *Definition = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001164 if (Function->hasBody(Definition) &&
Douglas Gregor238058c2010-05-18 05:45:02 +00001165 Definition->getTemplateSpecializationKind() == TSK_Undeclared) {
1166 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1167 << Function->getDeclName();
1168 SemaRef.Diag(Definition->getLocation(), diag::note_previous_definition);
1169 Function->setInvalidDecl();
1170 }
1171 // Check for redefinitions due to other instantiations of this or
1172 // a similar friend function.
1173 else for (FunctionDecl::redecl_iterator R = Function->redecls_begin(),
1174 REnd = Function->redecls_end();
1175 R != REnd; ++R) {
Gabor Greif13a8aff2010-08-28 15:42:30 +00001176 if (*R == Function)
1177 continue;
Gabor Greifab297ac2010-08-30 21:10:05 +00001178 switch (R->getFriendObjectKind()) {
1179 case Decl::FOK_None:
1180 if (!queuedInstantiation && R->isUsed(false)) {
1181 if (MemberSpecializationInfo *MSInfo
1182 = Function->getMemberSpecializationInfo()) {
1183 if (MSInfo->getPointOfInstantiation().isInvalid()) {
1184 SourceLocation Loc = R->getLocation(); // FIXME
1185 MSInfo->setPointOfInstantiation(Loc);
1186 SemaRef.PendingLocalImplicitInstantiations.push_back(
1187 std::make_pair(Function, Loc));
1188 queuedInstantiation = true;
1189 }
1190 }
1191 }
1192 break;
1193 default:
Douglas Gregor238058c2010-05-18 05:45:02 +00001194 if (const FunctionDecl *RPattern
Gabor Greif6a557d82010-08-28 15:46:56 +00001195 = R->getTemplateInstantiationPattern())
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001196 if (RPattern->hasBody(RPattern)) {
Douglas Gregor238058c2010-05-18 05:45:02 +00001197 SemaRef.Diag(Function->getLocation(), diag::err_redefinition)
1198 << Function->getDeclName();
Gabor Greif6a557d82010-08-28 15:46:56 +00001199 SemaRef.Diag(R->getLocation(), diag::note_previous_definition);
Douglas Gregor238058c2010-05-18 05:45:02 +00001200 Function->setInvalidDecl();
1201 break;
1202 }
1203 }
1204 }
1205 }
Douglas Gregora735b202009-10-13 14:39:41 +00001206 }
1207
John McCall76d32642010-04-24 01:30:58 +00001208 if (Function->isOverloadedOperator() && !DC->isRecord() &&
1209 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1210 PrincipalDecl->setNonMemberOperator();
1211
Douglas Gregore53060f2009-06-25 22:08:12 +00001212 return Function;
1213}
1214
Douglas Gregord60e1052009-08-27 16:57:43 +00001215Decl *
1216TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1217 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001218 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1219 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001220 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001221 // We are creating a function template specialization from a function
1222 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001223 // specialization for this particular set of template arguments.
Douglas Gregor24bae922010-07-08 18:37:38 +00001224 std::pair<const TemplateArgument *, unsigned> Innermost
1225 = TemplateArgs.getInnermost();
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001227 FunctionDecl *SpecFunc
1228 = FunctionTemplate->findSpecialization(Innermost.first, Innermost.second,
1229 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001230
Douglas Gregor6b906862009-08-21 00:16:32 +00001231 // If we already have a function template specialization, return it.
Argyrios Kyrtzidis2c853e42010-07-20 13:59:58 +00001232 if (SpecFunc)
1233 return SpecFunc;
Douglas Gregor6b906862009-08-21 00:16:32 +00001234 }
1235
John McCallb0cb0222010-03-27 05:57:59 +00001236 bool isFriend;
1237 if (FunctionTemplate)
1238 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1239 else
1240 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1241
Douglas Gregor79c22782010-01-16 20:21:20 +00001242 bool MergeWithParentScope = (TemplateParams != 0) ||
1243 !(isa<Decl>(Owner) &&
1244 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
John McCall2a7fb272010-08-25 05:32:35 +00001245 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001246
John McCall4eab39f2010-10-19 02:26:41 +00001247 // Instantiate enclosing template arguments for friends.
1248 llvm::SmallVector<TemplateParameterList *, 4> TempParamLists;
1249 unsigned NumTempParamLists = 0;
1250 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
1251 TempParamLists.set_size(NumTempParamLists);
1252 for (unsigned I = 0; I != NumTempParamLists; ++I) {
1253 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
1254 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1255 if (!InstParams)
1256 return NULL;
1257 TempParamLists[I] = InstParams;
1258 }
1259 }
1260
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001261 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001262 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1263 TInfo = SubstFunctionType(D, Params);
1264 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001265 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001266 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001267
Abramo Bagnara723df242010-12-14 22:11:44 +00001268 // \brief If the type of this function, after ignoring parentheses,
1269 // is not *directly* a function type, then we're instantiating a function
1270 // that was declared via a typedef, e.g.,
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001271 //
1272 // typedef int functype(int, int);
1273 // functype func;
1274 //
1275 // In this case, we'll just go instantiate the ParmVarDecls that we
1276 // synthesized in the method declaration.
Abramo Bagnara723df242010-12-14 22:11:44 +00001277 if (!isa<FunctionProtoType>(T.IgnoreParens())) {
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001278 assert(!Params.size() && "Instantiating type could not yield parameters");
Douglas Gregor12c9c002011-01-07 16:43:16 +00001279 llvm::SmallVector<QualType, 4> ParamTypes;
1280 if (SemaRef.SubstParmTypes(D->getLocation(), D->param_begin(),
1281 D->getNumParams(), TemplateArgs, ParamTypes,
1282 &Params))
1283 return 0;
Douglas Gregor5f970ee2010-05-04 18:18:31 +00001284 }
1285
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001286 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
1287 if (QualifierLoc) {
1288 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
John McCallb0cb0222010-03-27 05:57:59 +00001289 TemplateArgs);
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001290 if (!QualifierLoc)
1291 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001292 }
1293
1294 DeclContext *DC = Owner;
1295 if (isFriend) {
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001296 if (QualifierLoc) {
John McCallb0cb0222010-03-27 05:57:59 +00001297 CXXScopeSpec SS;
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001298 SS.Adopt(QualifierLoc);
John McCallb0cb0222010-03-27 05:57:59 +00001299 DC = SemaRef.computeDeclContext(SS);
John McCallc54d6882010-10-19 05:01:53 +00001300
1301 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
1302 return 0;
John McCallb0cb0222010-03-27 05:57:59 +00001303 } else {
1304 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1305 D->getDeclContext(),
1306 TemplateArgs);
1307 }
1308 if (!DC) return 0;
1309 }
1310
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001311 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001312 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001313 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001315 SourceLocation StartLoc = D->getInnerLocStart();
Abramo Bagnara25777432010-08-11 22:01:17 +00001316 DeclarationNameInfo NameInfo
1317 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001318 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001319 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001320 StartLoc, NameInfo, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001321 Constructor->isExplicit(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001322 Constructor->isInlineSpecified(),
1323 false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001324 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001325 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001326 StartLoc, NameInfo, T, TInfo,
Abramo Bagnara25777432010-08-11 22:01:17 +00001327 Destructor->isInlineSpecified(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00001328 false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001329 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001330 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001331 StartLoc, NameInfo, T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001332 Conversion->isInlineSpecified(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001333 Conversion->isExplicit(),
1334 Conversion->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001335 } else {
Abramo Bagnara25777432010-08-11 22:01:17 +00001336 Method = CXXMethodDecl::Create(SemaRef.Context, Record,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001337 StartLoc, NameInfo, T, TInfo,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001338 D->isStatic(),
1339 D->getStorageClassAsWritten(),
Douglas Gregorf5251602011-03-08 17:10:18 +00001340 D->isInlineSpecified(),
1341 D->getLocEnd());
Douglas Gregordec06662009-08-21 18:42:58 +00001342 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001343
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00001344 if (QualifierLoc)
1345 Method->setQualifierInfo(QualifierLoc);
John McCallb6217662010-03-15 10:12:16 +00001346
Douglas Gregord60e1052009-08-27 16:57:43 +00001347 if (TemplateParams) {
1348 // Our resulting instantiation is actually a function template, since we
1349 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001350 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001351 // template<typename T>
1352 // struct X {
1353 // template<typename U> void f(T, U);
1354 // };
1355 //
1356 // X<int> x;
1357 //
1358 // We are instantiating the member template "f" within X<int>, which means
1359 // substituting int for T, but leaving "f" as a member function template.
1360 // Build the function template itself.
1361 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1362 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001363 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001364 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001365 if (isFriend) {
1366 FunctionTemplate->setLexicalDeclContext(Owner);
1367 FunctionTemplate->setObjectOfFriendDecl(true);
1368 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001369 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001370 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001371 } else if (FunctionTemplate) {
1372 // Record this function template specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +00001373 std::pair<const TemplateArgument *, unsigned> Innermost
1374 = TemplateArgs.getInnermost();
Douglas Gregor838db382010-02-11 01:19:42 +00001375 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001376 TemplateArgumentList::CreateCopy(SemaRef.Context,
1377 Innermost.first,
1378 Innermost.second),
Douglas Gregor66724ea2009-11-14 01:20:54 +00001379 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001380 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001381 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001382 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001383 }
1384
Mike Stump1eb44332009-09-09 15:08:12 +00001385 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001386 // out-of-line, the instantiation will have the same lexical
1387 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001388 if (isFriend) {
John McCall4eab39f2010-10-19 02:26:41 +00001389 if (NumTempParamLists)
1390 Method->setTemplateParameterListsInfo(SemaRef.Context,
1391 NumTempParamLists,
1392 TempParamLists.data());
1393
John McCallb0cb0222010-03-27 05:57:59 +00001394 Method->setLexicalDeclContext(Owner);
1395 Method->setObjectOfFriendDecl(true);
1396 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001397 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Douglas Gregor5545e162009-03-24 00:38:23 +00001399 // Attach the parameters
1400 for (unsigned P = 0; P < Params.size(); ++P)
1401 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001402 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001403
1404 if (InitMethodInstantiation(Method, D))
1405 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001406
Abramo Bagnara25777432010-08-11 22:01:17 +00001407 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
1408 Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001409
John McCallb0cb0222010-03-27 05:57:59 +00001410 if (!FunctionTemplate || TemplateParams || isFriend) {
1411 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001412
Douglas Gregordec06662009-08-21 18:42:58 +00001413 // In C++, the previous declaration we find might be a tag type
1414 // (class or enum). In this case, the new declaration will hide the
1415 // tag type. Note that this does does not apply if we're declaring a
1416 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001417 if (Previous.isSingleTagDecl())
1418 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001419 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001420
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001421 bool Redeclaration = false;
Peter Collingbournec80e8112011-01-21 02:08:54 +00001422 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001423
Douglas Gregor4ba31362009-12-01 17:24:26 +00001424 if (D->isPure())
1425 SemaRef.CheckPureMethod(Method, SourceRange());
1426
John McCall46460a62010-01-20 21:53:11 +00001427 Method->setAccess(D->getAccess());
1428
Anders Carlsson9eefa222011-01-20 06:52:44 +00001429 SemaRef.CheckOverrideControl(Method);
1430
John McCallb0cb0222010-03-27 05:57:59 +00001431 if (FunctionTemplate) {
1432 // If there's a function template, let our caller handle it.
1433 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1434 // Don't hide a (potentially) valid declaration with an invalid one.
1435 } else {
1436 NamedDecl *DeclToAdd = (TemplateParams
1437 ? cast<NamedDecl>(FunctionTemplate)
1438 : Method);
1439 if (isFriend)
1440 Record->makeDeclVisibleInContext(DeclToAdd);
1441 else
1442 Owner->addDecl(DeclToAdd);
1443 }
Argyrios Kyrtzidisbbc64542010-08-15 01:15:20 +00001444
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001445 return Method;
1446}
1447
Douglas Gregor615c5d42009-03-24 16:43:20 +00001448Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001449 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001450}
1451
Douglas Gregor03b2b072009-03-24 00:15:49 +00001452Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001453 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001454}
1455
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001456Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001457 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001458}
1459
Douglas Gregor6477b692009-03-25 15:04:13 +00001460ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001461 return SemaRef.SubstParmVarDecl(D, TemplateArgs, llvm::Optional<unsigned>());
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001462}
1463
John McCalle29ba202009-08-20 01:44:21 +00001464Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1465 TemplateTypeParmDecl *D) {
1466 // TODO: don't always clone when decls are refcounted.
Douglas Gregorefed5c82010-06-16 15:23:05 +00001467 const Type* T = D->getTypeForDecl();
1468 assert(T->isTemplateTypeParmType());
1469 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001470
John McCalle29ba202009-08-20 01:44:21 +00001471 TemplateTypeParmDecl *Inst =
Abramo Bagnara344577e2011-03-06 15:48:19 +00001472 TemplateTypeParmDecl::Create(SemaRef.Context, Owner,
1473 D->getLocStart(), D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001474 TTPT->getDepth() - TemplateArgs.getNumLevels(),
Nick Lewycky61139c52010-10-30 06:48:20 +00001475 TTPT->getIndex(), D->getIdentifier(),
John McCalle29ba202009-08-20 01:44:21 +00001476 D->wasDeclaredWithTypename(),
1477 D->isParameterPack());
Douglas Gregor9a299e02011-03-04 17:52:15 +00001478 Inst->setAccess(AS_public);
1479
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001480 if (D->hasDefaultArgument())
1481 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001482
Douglas Gregor550d9b22009-10-31 17:21:17 +00001483 // Introduce this template parameter's instantiation into the instantiation
1484 // scope.
1485 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1486
John McCalle29ba202009-08-20 01:44:21 +00001487 return Inst;
1488}
1489
Douglas Gregor33642df2009-10-23 23:25:44 +00001490Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1491 NonTypeTemplateParmDecl *D) {
1492 // Substitute into the type of the non-type template parameter.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001493 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
1494 llvm::SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
1495 llvm::SmallVector<QualType, 4> ExpandedParameterPackTypes;
1496 bool IsExpandedParameterPack = false;
1497 TypeSourceInfo *DI;
Douglas Gregor33642df2009-10-23 23:25:44 +00001498 QualType T;
Douglas Gregor33642df2009-10-23 23:25:44 +00001499 bool Invalid = false;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001500
1501 if (D->isExpandedParameterPack()) {
1502 // The non-type template parameter pack is an already-expanded pack
1503 // expansion of types. Substitute into each of the expanded types.
1504 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
1505 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
1506 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1507 TypeSourceInfo *NewDI =SemaRef.SubstType(D->getExpansionTypeSourceInfo(I),
1508 TemplateArgs,
1509 D->getLocation(),
1510 D->getDeclName());
1511 if (!NewDI)
1512 return 0;
1513
1514 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1515 QualType NewT =SemaRef.CheckNonTypeTemplateParameterType(NewDI->getType(),
1516 D->getLocation());
1517 if (NewT.isNull())
1518 return 0;
1519 ExpandedParameterPackTypes.push_back(NewT);
1520 }
1521
1522 IsExpandedParameterPack = true;
1523 DI = D->getTypeSourceInfo();
1524 T = DI->getType();
1525 } else if (isa<PackExpansionTypeLoc>(TL)) {
1526 // The non-type template parameter pack's type is a pack expansion of types.
1527 // Determine whether we need to expand this parameter pack into separate
1528 // types.
1529 PackExpansionTypeLoc Expansion = cast<PackExpansionTypeLoc>(TL);
1530 TypeLoc Pattern = Expansion.getPatternLoc();
1531 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1532 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1533
1534 // Determine whether the set of unexpanded parameter packs can and should
1535 // be expanded.
1536 bool Expand = true;
1537 bool RetainExpansion = false;
1538 llvm::Optional<unsigned> OrigNumExpansions
1539 = Expansion.getTypePtr()->getNumExpansions();
1540 llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
1541 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
1542 Pattern.getSourceRange(),
1543 Unexpanded.data(),
1544 Unexpanded.size(),
1545 TemplateArgs,
1546 Expand, RetainExpansion,
1547 NumExpansions))
1548 return 0;
1549
1550 if (Expand) {
1551 for (unsigned I = 0; I != *NumExpansions; ++I) {
1552 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
1553 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
1554 D->getLocation(),
1555 D->getDeclName());
1556 if (!NewDI)
1557 return 0;
1558
1559 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
1560 QualType NewT = SemaRef.CheckNonTypeTemplateParameterType(
1561 NewDI->getType(),
1562 D->getLocation());
1563 if (NewT.isNull())
1564 return 0;
1565 ExpandedParameterPackTypes.push_back(NewT);
1566 }
1567
1568 // Note that we have an expanded parameter pack. The "type" of this
1569 // expanded parameter pack is the original expansion type, but callers
1570 // will end up using the expanded parameter pack types for type-checking.
1571 IsExpandedParameterPack = true;
1572 DI = D->getTypeSourceInfo();
1573 T = DI->getType();
1574 } else {
1575 // We cannot fully expand the pack expansion now, so substitute into the
1576 // pattern and create a new pack expansion type.
1577 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
1578 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
1579 D->getLocation(),
1580 D->getDeclName());
1581 if (!NewPattern)
1582 return 0;
1583
1584 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
1585 NumExpansions);
1586 if (!DI)
1587 return 0;
1588
1589 T = DI->getType();
1590 }
1591 } else {
1592 // Simple case: substitution into a parameter that is not a parameter pack.
1593 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
1594 D->getLocation(), D->getDeclName());
1595 if (!DI)
1596 return 0;
1597
1598 // Check that this type is acceptable for a non-type template parameter.
1599 bool Invalid = false;
1600 T = SemaRef.CheckNonTypeTemplateParameterType(DI->getType(),
1601 D->getLocation());
1602 if (T.isNull()) {
1603 T = SemaRef.Context.IntTy;
1604 Invalid = true;
1605 }
Douglas Gregor33642df2009-10-23 23:25:44 +00001606 }
1607
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001608 NonTypeTemplateParmDecl *Param;
1609 if (IsExpandedParameterPack)
1610 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001611 D->getInnerLocStart(),
1612 D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001613 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001614 D->getPosition(),
1615 D->getIdentifier(), T,
1616 DI,
1617 ExpandedParameterPackTypes.data(),
1618 ExpandedParameterPackTypes.size(),
1619 ExpandedParameterPackTypesAsWritten.data());
1620 else
1621 Param = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001622 D->getInnerLocStart(),
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001623 D->getLocation(),
1624 D->getDepth() - TemplateArgs.getNumLevels(),
1625 D->getPosition(),
1626 D->getIdentifier(), T,
1627 D->isParameterPack(), DI);
1628
Douglas Gregor9a299e02011-03-04 17:52:15 +00001629 Param->setAccess(AS_public);
Douglas Gregor33642df2009-10-23 23:25:44 +00001630 if (Invalid)
1631 Param->setInvalidDecl();
1632
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001633 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001634
1635 // Introduce this template parameter's instantiation into the instantiation
1636 // scope.
1637 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001638 return Param;
1639}
1640
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001641Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001642TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1643 TemplateTemplateParmDecl *D) {
1644 // Instantiate the template parameter list of the template template parameter.
1645 TemplateParameterList *TempParams = D->getTemplateParameters();
1646 TemplateParameterList *InstParams;
1647 {
1648 // Perform the actual substitution of template parameters within a new,
1649 // local instantiation scope.
John McCall2a7fb272010-08-25 05:32:35 +00001650 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor9106ef72009-11-11 16:58:32 +00001651 InstParams = SubstTemplateParams(TempParams);
1652 if (!InstParams)
1653 return NULL;
1654 }
1655
1656 // Build the template template parameter.
1657 TemplateTemplateParmDecl *Param
1658 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor71b87e42010-08-30 23:23:59 +00001659 D->getDepth() - TemplateArgs.getNumLevels(),
Douglas Gregor61c4d282011-01-05 15:48:55 +00001660 D->getPosition(), D->isParameterPack(),
1661 D->getIdentifier(), InstParams);
Abramo Bagnarad92f7a22010-06-09 09:26:05 +00001662 Param->setDefaultArgument(D->getDefaultArgument(), false);
Douglas Gregor9a299e02011-03-04 17:52:15 +00001663 Param->setAccess(AS_public);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001664
Douglas Gregor9106ef72009-11-11 16:58:32 +00001665 // Introduce this template parameter's instantiation into the instantiation
1666 // scope.
1667 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1668
1669 return Param;
1670}
1671
Douglas Gregor48c32a72009-11-17 06:07:40 +00001672Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregordb992412011-02-25 16:33:46 +00001673 // Using directives are never dependent (and never contain any types or
1674 // expressions), so they require no explicit instantiation work.
Douglas Gregor48c32a72009-11-17 06:07:40 +00001675
1676 UsingDirectiveDecl *Inst
1677 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1678 D->getNamespaceKeyLocation(),
Douglas Gregordb992412011-02-25 16:33:46 +00001679 D->getQualifierLoc(),
Douglas Gregor48c32a72009-11-17 06:07:40 +00001680 D->getIdentLocation(),
1681 D->getNominatedNamespace(),
1682 D->getCommonAncestor());
1683 Owner->addDecl(Inst);
1684 return Inst;
1685}
1686
John McCalled976492009-12-04 22:46:56 +00001687Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
Douglas Gregor1b398202010-09-29 17:58:28 +00001688
1689 // The nested name specifier may be dependent, for example
1690 // template <typename T> struct t {
1691 // struct s1 { T f1(); };
1692 // struct s2 : s1 { using s1::f1; };
1693 // };
1694 // template struct t<int>;
1695 // Here, in using s1::f1, s1 refers to t<T>::s1;
1696 // we need to substitute for t<int>::s1.
Douglas Gregor5149f372011-02-25 15:54:31 +00001697 NestedNameSpecifierLoc QualifierLoc
1698 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1699 TemplateArgs);
1700 if (!QualifierLoc)
Douglas Gregordc355712011-02-25 00:36:19 +00001701 return 0;
Douglas Gregor1b398202010-09-29 17:58:28 +00001702
1703 // The name info is non-dependent, so no transformation
1704 // is required.
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001705 DeclarationNameInfo NameInfo = D->getNameInfo();
John McCalled976492009-12-04 22:46:56 +00001706
John McCall9f54ad42009-12-10 09:41:52 +00001707 // We only need to do redeclaration lookups if we're in a class
1708 // scope (in fact, it's not really even possible in non-class
1709 // scopes).
1710 bool CheckRedeclaration = Owner->isRecord();
1711
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001712 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
1713 Sema::ForRedeclaration);
John McCall9f54ad42009-12-10 09:41:52 +00001714
John McCalled976492009-12-04 22:46:56 +00001715 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
John McCalled976492009-12-04 22:46:56 +00001716 D->getUsingLocation(),
Douglas Gregor5149f372011-02-25 15:54:31 +00001717 QualifierLoc,
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001718 NameInfo,
John McCalled976492009-12-04 22:46:56 +00001719 D->isTypeName());
1720
Douglas Gregor5149f372011-02-25 15:54:31 +00001721 CXXScopeSpec SS;
1722 SS.Adopt(QualifierLoc);
John McCall9f54ad42009-12-10 09:41:52 +00001723 if (CheckRedeclaration) {
1724 Prev.setHideTags(false);
1725 SemaRef.LookupQualifiedName(Prev, Owner);
1726
1727 // Check for invalid redeclarations.
1728 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1729 D->isTypeName(), SS,
1730 D->getLocation(), Prev))
1731 NewUD->setInvalidDecl();
1732
1733 }
1734
1735 if (!NewUD->isInvalidDecl() &&
1736 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001737 D->getLocation()))
1738 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001739
John McCalled976492009-12-04 22:46:56 +00001740 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1741 NewUD->setAccess(D->getAccess());
1742 Owner->addDecl(NewUD);
1743
John McCall9f54ad42009-12-10 09:41:52 +00001744 // Don't process the shadow decls for an invalid decl.
1745 if (NewUD->isInvalidDecl())
1746 return NewUD;
1747
John McCall323c3102009-12-22 22:26:37 +00001748 bool isFunctionScope = Owner->isFunctionOrMethod();
1749
John McCall9f54ad42009-12-10 09:41:52 +00001750 // Process the shadow decls.
1751 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1752 I != E; ++I) {
1753 UsingShadowDecl *Shadow = *I;
1754 NamedDecl *InstTarget =
Douglas Gregorb7107222011-03-04 19:46:35 +00001755 cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
1756 Shadow->getLocation(),
1757 Shadow->getTargetDecl(),
1758 TemplateArgs));
1759 if (!InstTarget)
1760 return 0;
John McCall9f54ad42009-12-10 09:41:52 +00001761
1762 if (CheckRedeclaration &&
1763 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1764 continue;
1765
1766 UsingShadowDecl *InstShadow
1767 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1768 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001769
1770 if (isFunctionScope)
1771 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001772 }
John McCalled976492009-12-04 22:46:56 +00001773
1774 return NewUD;
1775}
1776
1777Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001778 // Ignore these; we handle them in bulk when processing the UsingDecl.
1779 return 0;
John McCalled976492009-12-04 22:46:56 +00001780}
1781
John McCall7ba107a2009-11-18 02:36:19 +00001782Decl * TemplateDeclInstantiator
1783 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001784 NestedNameSpecifierLoc QualifierLoc
1785 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
1786 TemplateArgs);
1787 if (!QualifierLoc)
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001788 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001789
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001790 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001791 SS.Adopt(QualifierLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001793 // Since NameInfo refers to a typename, it cannot be a C++ special name.
1794 // Hence, no tranformation is required for it.
1795 DeclarationNameInfo NameInfo(D->getDeclName(), D->getLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001796 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001797 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001798 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001799 /*instantiation*/ true,
1800 /*typename*/ true, D->getTypenameLoc());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001801 if (UD)
John McCalled976492009-12-04 22:46:56 +00001802 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1803
John McCall7ba107a2009-11-18 02:36:19 +00001804 return UD;
1805}
1806
1807Decl * TemplateDeclInstantiator
1808 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregor5149f372011-02-25 15:54:31 +00001809 NestedNameSpecifierLoc QualifierLoc
1810 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(), TemplateArgs);
1811 if (!QualifierLoc)
John McCall7ba107a2009-11-18 02:36:19 +00001812 return 0;
Douglas Gregor5149f372011-02-25 15:54:31 +00001813
John McCall7ba107a2009-11-18 02:36:19 +00001814 CXXScopeSpec SS;
Douglas Gregor5149f372011-02-25 15:54:31 +00001815 SS.Adopt(QualifierLoc);
John McCall7ba107a2009-11-18 02:36:19 +00001816
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001817 DeclarationNameInfo NameInfo
1818 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
1819
John McCall7ba107a2009-11-18 02:36:19 +00001820 NamedDecl *UD =
1821 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
Abramo Bagnaraef3dce82010-08-12 11:46:03 +00001822 D->getUsingLoc(), SS, NameInfo, 0,
John McCall7ba107a2009-11-18 02:36:19 +00001823 /*instantiation*/ true,
1824 /*typename*/ false, SourceLocation());
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001825 if (UD)
John McCalled976492009-12-04 22:46:56 +00001826 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1827
Anders Carlsson0d8df782009-08-29 19:37:28 +00001828 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001829}
1830
John McCallce3ff2b2009-08-25 22:02:44 +00001831Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001832 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001833 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001834 if (D->isInvalidDecl())
1835 return 0;
1836
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001837 return Instantiator.Visit(D);
1838}
1839
John McCalle29ba202009-08-20 01:44:21 +00001840/// \brief Instantiates a nested template parameter list in the current
1841/// instantiation context.
1842///
1843/// \param L The parameter list to instantiate
1844///
1845/// \returns NULL if there was an error
1846TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001847TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001848 // Get errors for all the parameters before bailing out.
1849 bool Invalid = false;
1850
1851 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001852 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001853 ParamVector Params;
1854 Params.reserve(N);
1855 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1856 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001857 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001858 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001859 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001860 }
1861
1862 // Clean up if we had an error.
Douglas Gregorff331c12010-07-25 18:17:45 +00001863 if (Invalid)
John McCalle29ba202009-08-20 01:44:21 +00001864 return NULL;
John McCalle29ba202009-08-20 01:44:21 +00001865
1866 TemplateParameterList *InstL
1867 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1868 L->getLAngleLoc(), &Params.front(), N,
1869 L->getRAngleLoc());
1870 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001871}
John McCalle29ba202009-08-20 01:44:21 +00001872
Douglas Gregored9c0f92009-10-29 00:04:11 +00001873/// \brief Instantiate the declaration of a class template partial
1874/// specialization.
1875///
1876/// \param ClassTemplate the (instantiated) class template that is partially
1877// specialized by the instantiation of \p PartialSpec.
1878///
1879/// \param PartialSpec the (uninstantiated) class template partial
1880/// specialization that we are instantiating.
1881///
Douglas Gregord65587f2010-11-10 19:44:59 +00001882/// \returns The instantiated partial specialization, if successful; otherwise,
1883/// NULL to indicate an error.
1884ClassTemplatePartialSpecializationDecl *
Douglas Gregored9c0f92009-10-29 00:04:11 +00001885TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1886 ClassTemplateDecl *ClassTemplate,
1887 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001888 // Create a local instantiation scope for this class template partial
1889 // specialization, which will contain the instantiations of the template
1890 // parameters.
John McCall2a7fb272010-08-25 05:32:35 +00001891 LocalInstantiationScope Scope(SemaRef);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001892
Douglas Gregored9c0f92009-10-29 00:04:11 +00001893 // Substitute into the template parameters of the class template partial
1894 // specialization.
1895 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1896 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1897 if (!InstParams)
Douglas Gregord65587f2010-11-10 19:44:59 +00001898 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001899
1900 // Substitute into the template arguments of the class template partial
1901 // specialization.
John McCalld5532b62009-11-23 01:53:49 +00001902 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
Douglas Gregore02e2622010-12-22 21:19:48 +00001903 if (SemaRef.Subst(PartialSpec->getTemplateArgsAsWritten(),
1904 PartialSpec->getNumTemplateArgsAsWritten(),
1905 InstTemplateArgs, TemplateArgs))
1906 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001907
Douglas Gregored9c0f92009-10-29 00:04:11 +00001908 // Check that the template argument list is well-formed for this
1909 // class template.
Douglas Gregor910f8002010-11-07 23:05:16 +00001910 llvm::SmallVector<TemplateArgument, 4> Converted;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001911 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1912 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001913 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001914 false,
1915 Converted))
Douglas Gregord65587f2010-11-10 19:44:59 +00001916 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001917
1918 // Figure out where to insert this class template partial specialization
1919 // in the member template's set of class template partial specializations.
Douglas Gregored9c0f92009-10-29 00:04:11 +00001920 void *InsertPos = 0;
1921 ClassTemplateSpecializationDecl *PrevDecl
Douglas Gregor910f8002010-11-07 23:05:16 +00001922 = ClassTemplate->findPartialSpecialization(Converted.data(),
1923 Converted.size(), InsertPos);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001924
1925 // Build the canonical type that describes the converted template
1926 // arguments of the class template partial specialization.
1927 QualType CanonType
1928 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
Douglas Gregor910f8002010-11-07 23:05:16 +00001929 Converted.data(),
1930 Converted.size());
Douglas Gregored9c0f92009-10-29 00:04:11 +00001931
1932 // Build the fully-sugared type for this class template
1933 // specialization as the user wrote in the specialization
1934 // itself. This means that we'll pretty-print the type retrieved
1935 // from the specialization's declaration the way that the user
1936 // actually wrote the specialization, rather than formatting the
1937 // name based on the "canonical" representation used to store the
1938 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001939 TypeSourceInfo *WrittenTy
1940 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1941 TemplateName(ClassTemplate),
1942 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001943 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001944 CanonType);
1945
1946 if (PrevDecl) {
1947 // We've already seen a partial specialization with the same template
1948 // parameters and template arguments. This can happen, for example, when
1949 // substituting the outer template arguments ends up causing two
1950 // class template partial specializations of a member class template
1951 // to have identical forms, e.g.,
1952 //
1953 // template<typename T, typename U>
1954 // struct Outer {
1955 // template<typename X, typename Y> struct Inner;
1956 // template<typename Y> struct Inner<T, Y>;
1957 // template<typename Y> struct Inner<U, Y>;
1958 // };
1959 //
1960 // Outer<int, int> outer; // error: the partial specializations of Inner
1961 // // have the same signature.
1962 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
Douglas Gregord65587f2010-11-10 19:44:59 +00001963 << WrittenTy->getType();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001964 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1965 << SemaRef.Context.getTypeDeclType(PrevDecl);
Douglas Gregord65587f2010-11-10 19:44:59 +00001966 return 0;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001967 }
1968
1969
1970 // Create the class template partial specialization declaration.
1971 ClassTemplatePartialSpecializationDecl *InstPartialSpec
Douglas Gregor13c85772010-05-06 00:28:52 +00001972 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context,
1973 PartialSpec->getTagKind(),
1974 Owner,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001975 PartialSpec->getLocStart(),
1976 PartialSpec->getLocation(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00001977 InstParams,
1978 ClassTemplate,
Douglas Gregor910f8002010-11-07 23:05:16 +00001979 Converted.data(),
1980 Converted.size(),
John McCalld5532b62009-11-23 01:53:49 +00001981 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001982 CanonType,
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001983 0,
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001984 ClassTemplate->getNextPartialSpecSequenceNumber());
John McCallb6217662010-03-15 10:12:16 +00001985 // Substitute the nested name specifier, if any.
1986 if (SubstQualifier(PartialSpec, InstPartialSpec))
1987 return 0;
1988
Douglas Gregored9c0f92009-10-29 00:04:11 +00001989 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001990 InstPartialSpec->setTypeAsWritten(WrittenTy);
1991
Douglas Gregored9c0f92009-10-29 00:04:11 +00001992 // Add this partial specialization to the set of class template partial
1993 // specializations.
Argyrios Kyrtzidiscc0b1bc2010-07-20 13:59:28 +00001994 ClassTemplate->AddPartialSpecialization(InstPartialSpec, InsertPos);
Douglas Gregord65587f2010-11-10 19:44:59 +00001995 return InstPartialSpec;
Douglas Gregored9c0f92009-10-29 00:04:11 +00001996}
1997
John McCall21ef0fa2010-03-11 09:03:00 +00001998TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001999TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00002000 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00002001 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
2002 assert(OldTInfo && "substituting function without type source info");
2003 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00002004 TypeSourceInfo *NewTInfo
2005 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
2006 D->getTypeSpecStartLoc(),
2007 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00002008 if (!NewTInfo)
2009 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00002010
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002011 if (NewTInfo != OldTInfo) {
2012 // Get parameters from the new type info.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002013 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002014 if (FunctionProtoTypeLoc *OldProtoLoc
2015 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002016 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002017 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
2018 assert(NewProtoLoc && "Missing prototype?");
Douglas Gregor12c9c002011-01-07 16:43:16 +00002019 unsigned NewIdx = 0, NumNewParams = NewProtoLoc->getNumArgs();
2020 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc->getNumArgs();
2021 OldIdx != NumOldParams; ++OldIdx) {
2022 ParmVarDecl *OldParam = OldProtoLoc->getArg(OldIdx);
2023 if (!OldParam->isParameterPack() ||
2024 (NewIdx < NumNewParams &&
2025 NewProtoLoc->getArg(NewIdx)->isParameterPack())) {
2026 // Simple case: normal parameter, or a parameter pack that's
2027 // instantiated to a (still-dependent) parameter pack.
2028 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2029 Params.push_back(NewParam);
2030 SemaRef.CurrentInstantiationScope->InstantiatedLocal(OldParam,
2031 NewParam);
2032 continue;
2033 }
2034
2035 // Parameter pack: make the instantiation an argument pack.
2036 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(
2037 OldParam);
Douglas Gregor21371ea2011-01-11 03:14:20 +00002038 unsigned NumArgumentsInExpansion
2039 = SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
2040 TemplateArgs);
2041 while (NumArgumentsInExpansion--) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002042 ParmVarDecl *NewParam = NewProtoLoc->getArg(NewIdx++);
2043 Params.push_back(NewParam);
2044 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(OldParam,
2045 NewParam);
2046 }
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002047 }
Douglas Gregor895162d2010-04-30 18:55:50 +00002048 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002049 } else {
2050 // The function type itself was not dependent and therefore no
2051 // substitution occurred. However, we still need to instantiate
2052 // the function parameters themselves.
Abramo Bagnara140a2bd2010-12-13 22:27:55 +00002053 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
Douglas Gregor6920cdc2010-05-03 15:32:18 +00002054 if (FunctionProtoTypeLoc *OldProtoLoc
2055 = dyn_cast<FunctionProtoTypeLoc>(&OldTL)) {
2056 for (unsigned i = 0, i_end = OldProtoLoc->getNumArgs(); i != i_end; ++i) {
2057 ParmVarDecl *Parm = VisitParmVarDecl(OldProtoLoc->getArg(i));
2058 if (!Parm)
2059 return 0;
2060 Params.push_back(Parm);
2061 }
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00002062 }
2063 }
John McCall21ef0fa2010-03-11 09:03:00 +00002064 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00002065}
2066
Mike Stump1eb44332009-09-09 15:08:12 +00002067/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00002068/// declaration (New) from the corresponding fields of its template (Tmpl).
2069///
2070/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002071bool
2072TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00002073 FunctionDecl *Tmpl) {
2074 if (Tmpl->isDeleted())
2075 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00002076
Douglas Gregorcca9e962009-07-01 22:01:06 +00002077 // If we are performing substituting explicitly-specified template arguments
2078 // or deduced template arguments into a function template and we reach this
2079 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00002080 // to keeping the new function template specialization. We therefore
2081 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00002082 // into a template instantiation for this specific function template
2083 // specialization, which is not a SFINAE context, so that we diagnose any
2084 // further errors in the declaration itself.
2085 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
2086 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
2087 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
2088 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00002089 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00002090 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002091 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00002092 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00002093 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002094 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
2095 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00002096 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00002097 }
2098 }
Mike Stump1eb44332009-09-09 15:08:12 +00002099
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002100 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
2101 assert(Proto && "Function template without prototype?");
2102
Sebastian Redl60618fa2011-03-12 11:50:43 +00002103 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002104 // The function has an exception specification or a "noreturn"
2105 // attribute. Substitute into each of the exception types.
2106 llvm::SmallVector<QualType, 4> Exceptions;
2107 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
2108 // FIXME: Poor location information!
Douglas Gregorb99268b2010-12-21 00:52:54 +00002109 if (const PackExpansionType *PackExpansion
2110 = Proto->getExceptionType(I)->getAs<PackExpansionType>()) {
2111 // We have a pack expansion. Instantiate it.
2112 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2113 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
2114 Unexpanded);
2115 assert(!Unexpanded.empty() &&
2116 "Pack expansion without parameter packs?");
Sebastian Redl60618fa2011-03-12 11:50:43 +00002117
Douglas Gregorb99268b2010-12-21 00:52:54 +00002118 bool Expand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002119 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002120 llvm::Optional<unsigned> NumExpansions
2121 = PackExpansion->getNumExpansions();
Douglas Gregorb99268b2010-12-21 00:52:54 +00002122 if (SemaRef.CheckParameterPacksForExpansion(New->getLocation(),
2123 SourceRange(),
2124 Unexpanded.data(),
2125 Unexpanded.size(),
2126 TemplateArgs,
Douglas Gregord3731192011-01-10 07:32:04 +00002127 Expand,
2128 RetainExpansion,
2129 NumExpansions))
Douglas Gregorb99268b2010-12-21 00:52:54 +00002130 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002131
Douglas Gregorb99268b2010-12-21 00:52:54 +00002132 if (!Expand) {
2133 // We can't expand this pack expansion into separate arguments yet;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002134 // just substitute into the pattern and create a new pack expansion
2135 // type.
Douglas Gregorb99268b2010-12-21 00:52:54 +00002136 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2137 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2138 TemplateArgs,
2139 New->getLocation(), New->getDeclName());
2140 if (T.isNull())
2141 break;
2142
Douglas Gregorcded4f62011-01-14 17:04:44 +00002143 T = SemaRef.Context.getPackExpansionType(T, NumExpansions);
Douglas Gregorb99268b2010-12-21 00:52:54 +00002144 Exceptions.push_back(T);
2145 continue;
2146 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002147
Douglas Gregorb99268b2010-12-21 00:52:54 +00002148 // Substitute into the pack expansion pattern for each template
2149 bool Invalid = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002150 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
Douglas Gregorb99268b2010-12-21 00:52:54 +00002151 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, ArgIdx);
2152
2153 QualType T = SemaRef.SubstType(PackExpansion->getPattern(),
2154 TemplateArgs,
2155 New->getLocation(), New->getDeclName());
2156 if (T.isNull()) {
2157 Invalid = true;
2158 break;
2159 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002160
Douglas Gregorb99268b2010-12-21 00:52:54 +00002161 Exceptions.push_back(T);
2162 }
Sebastian Redl60618fa2011-03-12 11:50:43 +00002163
Douglas Gregorb99268b2010-12-21 00:52:54 +00002164 if (Invalid)
2165 break;
Sebastian Redl60618fa2011-03-12 11:50:43 +00002166
Douglas Gregorb99268b2010-12-21 00:52:54 +00002167 continue;
2168 }
2169
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002170 QualType T
2171 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
2172 New->getLocation(), New->getDeclName());
2173 if (T.isNull() ||
2174 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
2175 continue;
2176
2177 Exceptions.push_back(T);
2178 }
Sebastian Redl56fb9262011-03-14 18:51:50 +00002179 Expr *NoexceptExpr = 0;
2180 if (Expr *OldNoexceptExpr = Proto->getNoexceptExpr()) {
2181 ExprResult E = SemaRef.SubstExpr(OldNoexceptExpr, TemplateArgs);
2182 if (E.isUsable())
2183 NoexceptExpr = E.take();
2184 }
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002185
2186 // Rebuild the function type
2187
John McCalle23cf432010-12-14 08:05:40 +00002188 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
Sebastian Redl60618fa2011-03-12 11:50:43 +00002189 EPI.ExceptionSpecType = Proto->getExceptionSpecType();
John McCalle23cf432010-12-14 08:05:40 +00002190 EPI.NumExceptions = Exceptions.size();
2191 EPI.Exceptions = Exceptions.data();
Sebastian Redl56fb9262011-03-14 18:51:50 +00002192 EPI.NoexceptExpr = NoexceptExpr;
John McCalle23cf432010-12-14 08:05:40 +00002193 EPI.ExtInfo = Proto->getExtInfo();
2194
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002195 const FunctionProtoType *NewProto
2196 = New->getType()->getAs<FunctionProtoType>();
2197 assert(NewProto && "Template instantiation without function prototype?");
2198 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
2199 NewProto->arg_type_begin(),
2200 NewProto->getNumArgs(),
John McCalle23cf432010-12-14 08:05:40 +00002201 EPI));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00002202 }
2203
John McCall1d8d1cc2010-08-01 02:01:53 +00002204 SemaRef.InstantiateAttrs(TemplateArgs, Tmpl, New);
Douglas Gregor7cf84d62010-06-15 17:05:35 +00002205
Douglas Gregore53060f2009-06-25 22:08:12 +00002206 return false;
2207}
2208
Douglas Gregor5545e162009-03-24 00:38:23 +00002209/// \brief Initializes common fields of an instantiated method
2210/// declaration (New) from the corresponding fields of its template
2211/// (Tmpl).
2212///
2213/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00002214bool
2215TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00002216 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00002217 if (InitFunctionInstantiation(New, Tmpl))
2218 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00002219
Douglas Gregor5545e162009-03-24 00:38:23 +00002220 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00002221 if (Tmpl->isVirtualAsWritten())
Douglas Gregor85606eb2010-09-28 20:50:54 +00002222 New->setVirtualAsWritten(true);
Douglas Gregor5545e162009-03-24 00:38:23 +00002223
2224 // FIXME: attributes
2225 // FIXME: New needs a pointer to Tmpl
2226 return false;
2227}
Douglas Gregora58861f2009-05-13 20:28:22 +00002228
2229/// \brief Instantiate the definition of the given function from its
2230/// template.
2231///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002232/// \param PointOfInstantiation the point at which the instantiation was
2233/// required. Note that this is not precisely a "point of instantiation"
2234/// for the function, but it's close.
2235///
Douglas Gregora58861f2009-05-13 20:28:22 +00002236/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002237/// function template specialization or member function of a class template
2238/// specialization.
2239///
2240/// \param Recursive if true, recursively instantiates any functions that
2241/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002242///
2243/// \param DefinitionRequired if true, then we are performing an explicit
2244/// instantiation where the body of the function is required. Complain if
2245/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002246void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002247 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002248 bool Recursive,
2249 bool DefinitionRequired) {
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002250 if (Function->isInvalidDecl() || Function->hasBody())
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002251 return;
2252
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002253 // Never instantiate an explicit specialization.
2254 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2255 return;
Douglas Gregor6cfacfe2010-05-17 17:34:56 +00002256
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002257 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00002258 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002259 Stmt *Pattern = 0;
2260 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002261 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002262
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002263 if (!Pattern) {
2264 if (DefinitionRequired) {
2265 if (Function->getPrimaryTemplate())
2266 Diag(PointOfInstantiation,
2267 diag::err_explicit_instantiation_undefined_func_template)
2268 << Function->getPrimaryTemplate();
2269 else
2270 Diag(PointOfInstantiation,
2271 diag::err_explicit_instantiation_undefined_member)
2272 << 1 << Function->getDeclName() << Function->getDeclContext();
2273
2274 if (PatternDecl)
2275 Diag(PatternDecl->getLocation(),
2276 diag::note_explicit_instantiation_here);
Douglas Gregorcfe833b2010-05-17 17:57:54 +00002277 Function->setInvalidDecl();
Chandler Carruth58e390e2010-08-25 08:27:02 +00002278 } else if (Function->getTemplateSpecializationKind()
2279 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002280 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002281 std::make_pair(Function, PointOfInstantiation));
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002282 }
Chandler Carruth58e390e2010-08-25 08:27:02 +00002283
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002284 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002285 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00002286
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002287 // C++0x [temp.explicit]p9:
2288 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00002289 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002290 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00002291 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002292 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002293 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002294 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002296 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2297 if (Inst)
Douglas Gregore7089b02010-05-03 23:29:10 +00002298 return;
2299
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002300 // If we're performing recursive template instantiation, create our own
2301 // queue of pending implicit instantiations that we will instantiate later,
2302 // while we're still within our own instantiation context.
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002303 llvm::SmallVector<VTableUse, 16> SavedVTableUses;
Chandler Carruth62c78d52010-08-25 08:44:16 +00002304 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002305 if (Recursive) {
2306 VTableUses.swap(SavedVTableUses);
Chandler Carruth62c78d52010-08-25 08:44:16 +00002307 PendingInstantiations.swap(SavedPendingInstantiations);
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002308 }
Mike Stump1eb44332009-09-09 15:08:12 +00002309
Douglas Gregor9679caf2010-05-12 17:27:19 +00002310 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002311 Sema::PotentiallyEvaluated);
John McCalld226f652010-08-21 09:40:31 +00002312 ActOnStartOfFunctionDef(0, Function);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002313
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002314 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002315 // recorded, unless we're actually a member function within a local
2316 // class, in which case we need to merge our results with the parent
2317 // scope (of the enclosing function).
2318 bool MergeWithParentScope = false;
2319 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2320 MergeWithParentScope = Rec->isLocalClass();
2321
2322 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002324 // Introduce the instantiated function parameters into the local
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002325 // instantiation scope, and set the parameter names to those used
2326 // in the template.
Douglas Gregor12c9c002011-01-07 16:43:16 +00002327 unsigned FParamIdx = 0;
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002328 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
2329 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002330 if (!PatternParam->isParameterPack()) {
2331 // Simple case: not a parameter pack.
2332 assert(FParamIdx < Function->getNumParams());
2333 ParmVarDecl *FunctionParam = Function->getParamDecl(I);
2334 FunctionParam->setDeclName(PatternParam->getDeclName());
2335 Scope.InstantiatedLocal(PatternParam, FunctionParam);
2336 ++FParamIdx;
2337 continue;
2338 }
2339
2340 // Expand the parameter pack.
2341 Scope.MakeInstantiatedLocalArgPack(PatternParam);
2342 for (unsigned NumFParams = Function->getNumParams();
2343 FParamIdx < NumFParams;
2344 ++FParamIdx) {
2345 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
2346 FunctionParam->setDeclName(PatternParam->getDeclName());
2347 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
2348 }
Peter Collingbourne8a6c0f12010-07-18 16:45:46 +00002349 }
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002350
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002351 // Enter the scope of this instantiation. We don't use
2352 // PushDeclContext because we don't have a scope.
John McCalleee1d542011-02-14 07:13:47 +00002353 Sema::ContextRAII savedContext(*this, Function);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002354
Mike Stump1eb44332009-09-09 15:08:12 +00002355 MultiLevelTemplateArgumentList TemplateArgs =
Douglas Gregore7089b02010-05-03 23:29:10 +00002356 getTemplateInstantiationArgs(Function, 0, false, PatternDecl);
Anders Carlsson09025312009-08-29 05:16:22 +00002357
2358 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002359 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002360 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2361 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2362 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002363 }
2364
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002365 // Instantiate the function body.
John McCall60d7b3a2010-08-24 06:29:42 +00002366 StmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002367
Douglas Gregor52604ab2009-09-11 21:19:12 +00002368 if (Body.isInvalid())
2369 Function->setInvalidDecl();
2370
John McCall9ae2f072010-08-23 23:25:46 +00002371 ActOnFinishFunctionBody(Function, Body.get(),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002372 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002373
John McCall0c01d182010-03-24 05:22:00 +00002374 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2375
John McCalleee1d542011-02-14 07:13:47 +00002376 savedContext.pop();
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002377
2378 DeclGroupRef DG(Function);
2379 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002380
Douglas Gregor60406be2010-01-16 22:29:39 +00002381 // This class may have local implicit instantiations that need to be
2382 // instantiation within this scope.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002383 PerformPendingInstantiations(/*LocalOnly=*/true);
Douglas Gregor60406be2010-01-16 22:29:39 +00002384 Scope.Exit();
2385
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002386 if (Recursive) {
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002387 // Define any pending vtables.
2388 DefineUsedVTables();
2389
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002390 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002391 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002392 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002393
Nick Lewycky2a5f99e2010-11-25 00:35:20 +00002394 // Restore the set of pending vtables.
2395 VTableUses.swap(SavedVTableUses);
2396
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002397 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002398 PendingInstantiations.swap(SavedPendingInstantiations);
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002399 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002400}
2401
2402/// \brief Instantiate the definition of the given variable from its
2403/// template.
2404///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002405/// \param PointOfInstantiation the point at which the instantiation was
2406/// required. Note that this is not precisely a "point of instantiation"
2407/// for the function, but it's close.
2408///
2409/// \param Var the already-instantiated declaration of a static member
2410/// variable of a class template specialization.
2411///
2412/// \param Recursive if true, recursively instantiates any functions that
2413/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002414///
2415/// \param DefinitionRequired if true, then we are performing an explicit
2416/// instantiation where an out-of-line definition of the member variable
2417/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002418void Sema::InstantiateStaticDataMemberDefinition(
2419 SourceLocation PointOfInstantiation,
2420 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002421 bool Recursive,
2422 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002423 if (Var->isInvalidDecl())
2424 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002425
Douglas Gregor7caa6822009-07-24 20:34:43 +00002426 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002427 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002428 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002429 assert(Def->isStaticDataMember() && "Not a static data member?");
2430 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002431
Douglas Gregor0d035142009-10-27 18:42:08 +00002432 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002433 // We did not find an out-of-line definition of this static data member,
2434 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002435 // instantiate this definition (or provide a specialization for it) in
2436 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002437 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002438 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002439 Diag(PointOfInstantiation,
2440 diag::err_explicit_instantiation_undefined_member)
2441 << 2 << Var->getDeclName() << Var->getDeclContext();
2442 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
Chandler Carruth58e390e2010-08-25 08:27:02 +00002443 } else if (Var->getTemplateSpecializationKind()
2444 == TSK_ExplicitInstantiationDefinition) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00002445 PendingInstantiations.push_back(
Chandler Carruth58e390e2010-08-25 08:27:02 +00002446 std::make_pair(Var, PointOfInstantiation));
2447 }
2448
Douglas Gregor7caa6822009-07-24 20:34:43 +00002449 return;
2450 }
2451
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002452 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002453 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002454 return;
2455
2456 // C++0x [temp.explicit]p9:
2457 // Except for inline functions, other explicit instantiation declarations
2458 // have the effect of suppressing the implicit instantiation of the entity
2459 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002460 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002461 == TSK_ExplicitInstantiationDeclaration)
2462 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002463
Douglas Gregor7caa6822009-07-24 20:34:43 +00002464 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2465 if (Inst)
2466 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002467
Douglas Gregor7caa6822009-07-24 20:34:43 +00002468 // If we're performing recursive template instantiation, create our own
2469 // queue of pending implicit instantiations that we will instantiate later,
2470 // while we're still within our own instantiation context.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002471 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
Douglas Gregor7caa6822009-07-24 20:34:43 +00002472 if (Recursive)
Chandler Carruth62c78d52010-08-25 08:44:16 +00002473 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Douglas Gregor7caa6822009-07-24 20:34:43 +00002475 // Enter the scope of this instantiation. We don't use
2476 // PushDeclContext because we don't have a scope.
John McCallf5ba7e02011-02-14 20:37:25 +00002477 ContextRAII previousContext(*this, Var->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002479 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002480 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Nico Weber6bb4dcb2010-11-28 22:53:37 +00002481 getTemplateInstantiationArgs(Var)));
John McCallf5ba7e02011-02-14 20:37:25 +00002482
2483 previousContext.pop();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002484
2485 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002486 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2487 assert(MSInfo && "Missing member specialization information?");
2488 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2489 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002490 DeclGroupRef DG(Var);
2491 Consumer.HandleTopLevelDecl(DG);
2492 }
Mike Stump1eb44332009-09-09 15:08:12 +00002493
Douglas Gregor7caa6822009-07-24 20:34:43 +00002494 if (Recursive) {
2495 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002496 // instantiation of this template.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002497 PerformPendingInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002498
Douglas Gregor7caa6822009-07-24 20:34:43 +00002499 // Restore the set of pending implicit instantiations.
Chandler Carruth62c78d52010-08-25 08:44:16 +00002500 PendingInstantiations.swap(SavedPendingInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002501 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002502}
Douglas Gregor815215d2009-05-27 05:35:12 +00002503
Anders Carlsson09025312009-08-29 05:16:22 +00002504void
2505Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2506 const CXXConstructorDecl *Tmpl,
2507 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Anders Carlsson09025312009-08-29 05:16:22 +00002509 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002510 bool AnyErrors = false;
2511
Anders Carlsson09025312009-08-29 05:16:22 +00002512 // Instantiate all the initializers.
2513 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002514 InitsEnd = Tmpl->init_end();
2515 Inits != InitsEnd; ++Inits) {
Sean Huntcbb67482011-01-08 20:30:50 +00002516 CXXCtorInitializer *Init = *Inits;
Anders Carlsson09025312009-08-29 05:16:22 +00002517
Chandler Carruth030ef472010-09-03 21:54:20 +00002518 // Only instantiate written initializers, let Sema re-construct implicit
2519 // ones.
2520 if (!Init->isWritten())
2521 continue;
2522
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002523 SourceLocation LParenLoc, RParenLoc;
John McCallca0408f2010-08-23 06:44:23 +00002524 ASTOwningVector<Expr*> NewArgs(*this);
Mike Stump1eb44332009-09-09 15:08:12 +00002525
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002526 SourceLocation EllipsisLoc;
2527
2528 if (Init->isPackExpansion()) {
2529 // This is a pack expansion. We should expand it now.
2530 TypeLoc BaseTL = Init->getBaseClassInfo()->getTypeLoc();
2531 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2532 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
2533 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00002534 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00002535 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002536 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
2537 BaseTL.getSourceRange(),
2538 Unexpanded.data(),
2539 Unexpanded.size(),
2540 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00002541 RetainExpansion,
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002542 NumExpansions)) {
2543 AnyErrors = true;
2544 New->setInvalidDecl();
2545 continue;
2546 }
2547 assert(ShouldExpand && "Partial instantiation of base initializer?");
2548
2549 // Loop over all of the arguments in the argument pack(s),
Douglas Gregorcded4f62011-01-14 17:04:44 +00002550 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002551 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2552
2553 // Instantiate the initializer.
2554 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2555 LParenLoc, NewArgs, RParenLoc)) {
2556 AnyErrors = true;
2557 break;
2558 }
2559
2560 // Instantiate the base type.
2561 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
2562 TemplateArgs,
2563 Init->getSourceLocation(),
2564 New->getDeclName());
2565 if (!BaseTInfo) {
2566 AnyErrors = true;
2567 break;
2568 }
2569
2570 // Build the initializer.
2571 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
2572 BaseTInfo,
2573 (Expr **)NewArgs.data(),
2574 NewArgs.size(),
2575 Init->getLParenLoc(),
2576 Init->getRParenLoc(),
2577 New->getParent(),
2578 SourceLocation());
2579 if (NewInit.isInvalid()) {
2580 AnyErrors = true;
2581 break;
2582 }
2583
2584 NewInits.push_back(NewInit.get());
2585 NewArgs.clear();
2586 }
2587
2588 continue;
2589 }
2590
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002591 // Instantiate the initializer.
2592 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00002593 LParenLoc, NewArgs, RParenLoc)) {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002594 AnyErrors = true;
2595 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002596 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002597
Anders Carlsson09025312009-08-29 05:16:22 +00002598 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002599 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002600 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002601 TemplateArgs,
2602 Init->getSourceLocation(),
2603 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002604 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002605 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002606 New->setInvalidDecl();
2607 continue;
2608 }
2609
John McCalla93c9342009-12-07 02:54:59 +00002610 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002611 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002612 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002613 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002614 Init->getRParenLoc(),
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00002615 New->getParent(),
2616 EllipsisLoc);
Anders Carlsson09025312009-08-29 05:16:22 +00002617 } else if (Init->isMemberInitializer()) {
Douglas Gregorb7107222011-03-04 19:46:35 +00002618 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002619 Init->getMemberLocation(),
2620 Init->getMember(),
2621 TemplateArgs));
Douglas Gregorb7107222011-03-04 19:46:35 +00002622 if (!Member) {
2623 AnyErrors = true;
2624 New->setInvalidDecl();
2625 continue;
2626 }
Mike Stump1eb44332009-09-09 15:08:12 +00002627
2628 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002629 NewArgs.size(),
2630 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002631 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002632 Init->getRParenLoc());
Francois Pichet00eb3f92010-12-04 09:14:42 +00002633 } else if (Init->isIndirectMemberInitializer()) {
2634 IndirectFieldDecl *IndirectMember =
Douglas Gregorb7107222011-03-04 19:46:35 +00002635 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
Francois Pichet00eb3f92010-12-04 09:14:42 +00002636 Init->getMemberLocation(),
2637 Init->getIndirectMember(), TemplateArgs));
2638
Douglas Gregorb7107222011-03-04 19:46:35 +00002639 if (!IndirectMember) {
2640 AnyErrors = true;
2641 New->setInvalidDecl();
2642 continue;
2643 }
2644
Francois Pichet00eb3f92010-12-04 09:14:42 +00002645 NewInit = BuildMemberInitializer(IndirectMember, (Expr **)NewArgs.data(),
2646 NewArgs.size(),
2647 Init->getSourceLocation(),
2648 Init->getLParenLoc(),
2649 Init->getRParenLoc());
Anders Carlsson09025312009-08-29 05:16:22 +00002650 }
2651
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002652 if (NewInit.isInvalid()) {
2653 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002654 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002655 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002656 // FIXME: It would be nice if ASTOwningVector had a release function.
2657 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Anders Carlsson09025312009-08-29 05:16:22 +00002659 NewInits.push_back((MemInitTy *)NewInit.get());
2660 }
2661 }
Mike Stump1eb44332009-09-09 15:08:12 +00002662
Anders Carlsson09025312009-08-29 05:16:22 +00002663 // Assign all the initializers to the new constructor.
John McCalld226f652010-08-21 09:40:31 +00002664 ActOnMemInitializers(New,
Anders Carlsson09025312009-08-29 05:16:22 +00002665 /*FIXME: ColonLoc */
2666 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002667 NewInits.data(), NewInits.size(),
2668 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002669}
2670
John McCall52a575a2009-08-29 08:11:13 +00002671// TODO: this could be templated if the various decl types used the
2672// same method name.
2673static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2674 ClassTemplateDecl *Instance) {
2675 Pattern = Pattern->getCanonicalDecl();
2676
2677 do {
2678 Instance = Instance->getCanonicalDecl();
2679 if (Pattern == Instance) return true;
2680 Instance = Instance->getInstantiatedFromMemberTemplate();
2681 } while (Instance);
2682
2683 return false;
2684}
2685
Douglas Gregor0d696532009-09-28 06:34:35 +00002686static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2687 FunctionTemplateDecl *Instance) {
2688 Pattern = Pattern->getCanonicalDecl();
2689
2690 do {
2691 Instance = Instance->getCanonicalDecl();
2692 if (Pattern == Instance) return true;
2693 Instance = Instance->getInstantiatedFromMemberTemplate();
2694 } while (Instance);
2695
2696 return false;
2697}
2698
Douglas Gregored9c0f92009-10-29 00:04:11 +00002699static bool
2700isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2701 ClassTemplatePartialSpecializationDecl *Instance) {
2702 Pattern
2703 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2704 do {
2705 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2706 Instance->getCanonicalDecl());
2707 if (Pattern == Instance)
2708 return true;
2709 Instance = Instance->getInstantiatedFromMember();
2710 } while (Instance);
2711
2712 return false;
2713}
2714
John McCall52a575a2009-08-29 08:11:13 +00002715static bool isInstantiationOf(CXXRecordDecl *Pattern,
2716 CXXRecordDecl *Instance) {
2717 Pattern = Pattern->getCanonicalDecl();
2718
2719 do {
2720 Instance = Instance->getCanonicalDecl();
2721 if (Pattern == Instance) return true;
2722 Instance = Instance->getInstantiatedFromMemberClass();
2723 } while (Instance);
2724
2725 return false;
2726}
2727
2728static bool isInstantiationOf(FunctionDecl *Pattern,
2729 FunctionDecl *Instance) {
2730 Pattern = Pattern->getCanonicalDecl();
2731
2732 do {
2733 Instance = Instance->getCanonicalDecl();
2734 if (Pattern == Instance) return true;
2735 Instance = Instance->getInstantiatedFromMemberFunction();
2736 } while (Instance);
2737
2738 return false;
2739}
2740
2741static bool isInstantiationOf(EnumDecl *Pattern,
2742 EnumDecl *Instance) {
2743 Pattern = Pattern->getCanonicalDecl();
2744
2745 do {
2746 Instance = Instance->getCanonicalDecl();
2747 if (Pattern == Instance) return true;
2748 Instance = Instance->getInstantiatedFromMemberEnum();
2749 } while (Instance);
2750
2751 return false;
2752}
2753
John McCalled976492009-12-04 22:46:56 +00002754static bool isInstantiationOf(UsingShadowDecl *Pattern,
2755 UsingShadowDecl *Instance,
2756 ASTContext &C) {
2757 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2758}
2759
2760static bool isInstantiationOf(UsingDecl *Pattern,
2761 UsingDecl *Instance,
2762 ASTContext &C) {
2763 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2764}
2765
John McCall7ba107a2009-11-18 02:36:19 +00002766static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2767 UsingDecl *Instance,
2768 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002769 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002770}
2771
2772static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002773 UsingDecl *Instance,
2774 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002775 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002776}
2777
John McCall52a575a2009-08-29 08:11:13 +00002778static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2779 VarDecl *Instance) {
2780 assert(Instance->isStaticDataMember());
2781
2782 Pattern = Pattern->getCanonicalDecl();
2783
2784 do {
2785 Instance = Instance->getCanonicalDecl();
2786 if (Pattern == Instance) return true;
2787 Instance = Instance->getInstantiatedFromStaticDataMember();
2788 } while (Instance);
2789
2790 return false;
2791}
2792
John McCalled976492009-12-04 22:46:56 +00002793// Other is the prospective instantiation
2794// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002795static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002796 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002797 if (UnresolvedUsingTypenameDecl *UUD
2798 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2799 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2800 return isInstantiationOf(UUD, UD, Ctx);
2801 }
2802 }
2803
2804 if (UnresolvedUsingValueDecl *UUD
2805 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002806 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2807 return isInstantiationOf(UUD, UD, Ctx);
2808 }
2809 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002810
Anders Carlsson0d8df782009-08-29 19:37:28 +00002811 return false;
2812 }
Mike Stump1eb44332009-09-09 15:08:12 +00002813
John McCall52a575a2009-08-29 08:11:13 +00002814 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2815 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002816
John McCall52a575a2009-08-29 08:11:13 +00002817 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2818 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002819
John McCall52a575a2009-08-29 08:11:13 +00002820 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2821 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002822
Douglas Gregor7caa6822009-07-24 20:34:43 +00002823 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002824 if (Var->isStaticDataMember())
2825 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2826
2827 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2828 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002829
Douglas Gregor0d696532009-09-28 06:34:35 +00002830 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2831 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2832
Douglas Gregored9c0f92009-10-29 00:04:11 +00002833 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2834 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2835 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2836 PartialSpec);
2837
Anders Carlssond8b285f2009-09-01 04:26:58 +00002838 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2839 if (!Field->getDeclName()) {
2840 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002841 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002842 cast<FieldDecl>(D);
2843 }
2844 }
Mike Stump1eb44332009-09-09 15:08:12 +00002845
John McCalled976492009-12-04 22:46:56 +00002846 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2847 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2848
2849 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2850 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2851
Douglas Gregor815215d2009-05-27 05:35:12 +00002852 return D->getDeclName() && isa<NamedDecl>(Other) &&
2853 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2854}
2855
2856template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002857static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002858 NamedDecl *D,
2859 ForwardIterator first,
2860 ForwardIterator last) {
2861 for (; first != last; ++first)
2862 if (isInstantiationOf(Ctx, D, *first))
2863 return cast<NamedDecl>(*first);
2864
2865 return 0;
2866}
2867
John McCall02cace72009-08-28 07:59:38 +00002868/// \brief Finds the instantiation of the given declaration context
2869/// within the current instantiation.
2870///
2871/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002872DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002873 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002874 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002875 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002876 return cast_or_null<DeclContext>(ID);
2877 } else return DC;
2878}
2879
Douglas Gregored961e72009-05-27 17:54:46 +00002880/// \brief Find the instantiation of the given declaration within the
2881/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002882///
2883/// This routine is intended to be used when \p D is a declaration
2884/// referenced from within a template, that needs to mapped into the
2885/// corresponding declaration within an instantiation. For example,
2886/// given:
2887///
2888/// \code
2889/// template<typename T>
2890/// struct X {
2891/// enum Kind {
2892/// KnownValue = sizeof(T)
2893/// };
2894///
2895/// bool getKind() const { return KnownValue; }
2896/// };
2897///
2898/// template struct X<int>;
2899/// \endcode
2900///
2901/// In the instantiation of X<int>::getKind(), we need to map the
2902/// EnumConstantDecl for KnownValue (which refers to
2903/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002904/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2905/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002906NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002907 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002908 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002909 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002910 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
John McCall76672452010-08-19 23:06:02 +00002911 (ParentDC->isFunctionOrMethod() && ParentDC->isDependentContext())) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002912 // D is a local of some kind. Look into the map of local
2913 // declarations to their instantiations.
Chris Lattnerd8e54992011-02-17 19:47:42 +00002914 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2915 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2916 = CurrentInstantiationScope->findInstantiationOf(D);
Chris Lattnerd8e54992011-02-17 19:47:42 +00002917
Chris Lattner57ad3782011-02-17 20:34:02 +00002918 if (Found) {
2919 if (Decl *FD = Found->dyn_cast<Decl *>())
2920 return cast<NamedDecl>(FD);
2921
2922 unsigned PackIdx = ArgumentPackSubstitutionIndex;
2923 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
2924 }
2925
2926 // If we didn't find the decl, then we must have a label decl that hasn't
2927 // been found yet. Lazily instantiate it and return it now.
2928 assert(isa<LabelDecl>(D));
Chris Lattnerd8e54992011-02-17 19:47:42 +00002929
Chris Lattner57ad3782011-02-17 20:34:02 +00002930 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
2931 assert(Inst && "Failed to instantiate label??");
2932
2933 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2934 return cast<LabelDecl>(Inst);
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002935 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002936
Douglas Gregore95b4092009-09-16 18:34:49 +00002937 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2938 if (!Record->isDependentContext())
2939 return D;
2940
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002941 // If the RecordDecl is actually the injected-class-name or a
2942 // "templated" declaration for a class template, class template
2943 // partial specialization, or a member class of a class template,
2944 // substitute into the injected-class-name of the class template
2945 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002946 QualType T;
2947 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2948
2949 if (ClassTemplate) {
Douglas Gregor24bae922010-07-08 18:37:38 +00002950 T = ClassTemplate->getInjectedClassNameSpecialization();
Douglas Gregore95b4092009-09-16 18:34:49 +00002951 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2952 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002953 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002954
2955 // If we call SubstType with an InjectedClassNameType here we
2956 // can end up in an infinite loop.
2957 T = Context.getTypeDeclType(Record);
2958 assert(isa<InjectedClassNameType>(T) &&
2959 "type of partial specialization is not an InjectedClassNameType");
John McCall31f17ec2010-04-27 00:57:59 +00002960 T = cast<InjectedClassNameType>(T)->getInjectedSpecializationType();
John McCall3cb0ebd2010-03-10 03:28:59 +00002961 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002962
2963 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002964 // Substitute into the injected-class-name to get the type
2965 // corresponding to the instantiation we want, which may also be
2966 // the current instantiation (if we're in a template
2967 // definition). This substitution should never fail, since we
2968 // know we can instantiate the injected-class-name or we
2969 // wouldn't have gotten to the injected-class-name!
2970
2971 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2972 // extra instantiation in the common case?
Douglas Gregorb46ae392011-03-03 21:48:55 +00002973 T = SubstType(T, TemplateArgs, Loc, DeclarationName());
Douglas Gregore95b4092009-09-16 18:34:49 +00002974 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2975
2976 if (!T->isDependentType()) {
2977 assert(T->isRecordType() && "Instantiation must produce a record type");
2978 return T->getAs<RecordType>()->getDecl();
2979 }
2980
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002981 // We are performing "partial" template instantiation to create
2982 // the member declarations for the members of a class template
2983 // specialization. Therefore, D is actually referring to something
2984 // in the current instantiation. Look through the current
2985 // context, which contains actual instantiations, to find the
2986 // instantiation of the "current instantiation" that D refers
2987 // to.
2988 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002989 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002990 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002991 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002992 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002993 if (isInstantiationOf(ClassTemplate,
2994 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002995 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002996
2997 if (!DC->isDependentContext())
2998 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002999 }
3000
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003001 // We're performing "instantiation" of a member of the current
3002 // instantiation while we are type-checking the
3003 // definition. Compute the declaration context and return that.
3004 assert(!SawNonDependentContext &&
3005 "No dependent context while instantiating record");
3006 DeclContext *DC = computeDeclContext(T);
3007 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00003008 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003009 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00003010 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00003011
Douglas Gregore95b4092009-09-16 18:34:49 +00003012 // Fall through to deal with other dependent record types (e.g.,
3013 // anonymous unions in class templates).
3014 }
John McCall52a575a2009-08-29 08:11:13 +00003015
Douglas Gregore95b4092009-09-16 18:34:49 +00003016 if (!ParentDC->isDependentContext())
3017 return D;
3018
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003019 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00003020 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00003021 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Douglas Gregor815215d2009-05-27 05:35:12 +00003023 if (ParentDC != D->getDeclContext()) {
3024 // We performed some kind of instantiation in the parent context,
3025 // so now we need to look into the instantiated parent context to
3026 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003027
John McCall3cb0ebd2010-03-10 03:28:59 +00003028 // If our context used to be dependent, we may need to instantiate
3029 // it before performing lookup into that context.
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003030 bool IsBeingInstantiated = false;
John McCall3cb0ebd2010-03-10 03:28:59 +00003031 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003032 if (!Spec->isDependentContext()) {
3033 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00003034 const RecordType *Tag = T->getAs<RecordType>();
3035 assert(Tag && "type of non-dependent record is not a RecordType");
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003036 if (Tag->isBeingDefined())
3037 IsBeingInstantiated = true;
John McCall3cb0ebd2010-03-10 03:28:59 +00003038 if (!Tag->isBeingDefined() &&
3039 RequireCompleteType(Loc, T, diag::err_incomplete_type))
3040 return 0;
Douglas Gregora43064c2010-11-05 23:22:45 +00003041
3042 ParentDC = Tag->getDecl();
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00003043 }
3044 }
3045
Douglas Gregor815215d2009-05-27 05:35:12 +00003046 NamedDecl *Result = 0;
3047 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003048 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00003049 Result = findInstantiationOf(Context, D, Found.first, Found.second);
3050 } else {
3051 // Since we don't have a name for the entity we're looking for,
3052 // our only option is to walk through all of the declarations to
3053 // find that name. This will occur in a few cases:
3054 //
3055 // - anonymous struct/union within a template
3056 // - unnamed class/struct/union/enum within a template
3057 //
3058 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00003059 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003060 ParentDC->decls_begin(),
3061 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00003062 }
Mike Stump1eb44332009-09-09 15:08:12 +00003063
Douglas Gregoreff1dbe2011-03-06 20:12:45 +00003064 if (!Result) {
3065 if (isa<UsingShadowDecl>(D)) {
3066 // UsingShadowDecls can instantiate to nothing because of using hiding.
3067 } else if (Diags.hasErrorOccurred()) {
3068 // We've already complained about something, so most likely this
3069 // declaration failed to instantiate. There's no point in complaining
3070 // further, since this is normal in invalid code.
3071 } else if (IsBeingInstantiated) {
3072 // The class in which this member exists is currently being
3073 // instantiated, and we haven't gotten around to instantiating this
3074 // member yet. This can happen when the code uses forward declarations
3075 // of member classes, and introduces ordering dependencies via
3076 // template instantiation.
3077 Diag(Loc, diag::err_member_not_yet_instantiated)
3078 << D->getDeclName()
3079 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
3080 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
3081 } else {
3082 // We should have found something, but didn't.
3083 llvm_unreachable("Unable to find instantiation of declaration!");
3084 }
3085 }
3086
Douglas Gregor815215d2009-05-27 05:35:12 +00003087 D = Result;
3088 }
3089
Douglas Gregor815215d2009-05-27 05:35:12 +00003090 return D;
3091}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003092
Mike Stump1eb44332009-09-09 15:08:12 +00003093/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003094/// instantiations we have seen until this point.
Chandler Carruth62c78d52010-08-25 08:44:16 +00003095void Sema::PerformPendingInstantiations(bool LocalOnly) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003096 while (!PendingLocalImplicitInstantiations.empty() ||
Chandler Carruth62c78d52010-08-25 08:44:16 +00003097 (!LocalOnly && !PendingInstantiations.empty())) {
Douglas Gregor60406be2010-01-16 22:29:39 +00003098 PendingImplicitInstantiation Inst;
3099
3100 if (PendingLocalImplicitInstantiations.empty()) {
Chandler Carruth62c78d52010-08-25 08:44:16 +00003101 Inst = PendingInstantiations.front();
3102 PendingInstantiations.pop_front();
Douglas Gregor60406be2010-01-16 22:29:39 +00003103 } else {
3104 Inst = PendingLocalImplicitInstantiations.front();
3105 PendingLocalImplicitInstantiations.pop_front();
3106 }
Mike Stump1eb44332009-09-09 15:08:12 +00003107
Douglas Gregor7caa6822009-07-24 20:34:43 +00003108 // Instantiate function definitions
3109 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
John McCallf312b1e2010-08-26 23:41:50 +00003110 PrettyDeclStackTraceEntry CrashInfo(*this, Function, SourceLocation(),
3111 "instantiating function definition");
Chandler Carruth58e390e2010-08-25 08:27:02 +00003112 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
3113 TSK_ExplicitInstantiationDefinition;
3114 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true,
3115 DefinitionRequired);
Douglas Gregor7caa6822009-07-24 20:34:43 +00003116 continue;
3117 }
Mike Stump1eb44332009-09-09 15:08:12 +00003118
Douglas Gregor7caa6822009-07-24 20:34:43 +00003119 // Instantiate static data member definitions.
3120 VarDecl *Var = cast<VarDecl>(Inst.first);
3121 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00003122
Chandler Carruth291b4412010-02-13 10:17:50 +00003123 // Don't try to instantiate declarations if the most recent redeclaration
3124 // is invalid.
3125 if (Var->getMostRecentDeclaration()->isInvalidDecl())
3126 continue;
3127
3128 // Check if the most recent declaration has changed the specialization kind
3129 // and removed the need for implicit instantiation.
3130 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
3131 case TSK_Undeclared:
3132 assert(false && "Cannot instantitiate an undeclared specialization.");
3133 case TSK_ExplicitInstantiationDeclaration:
Chandler Carruth291b4412010-02-13 10:17:50 +00003134 case TSK_ExplicitSpecialization:
Chandler Carruth58e390e2010-08-25 08:27:02 +00003135 continue; // No longer need to instantiate this type.
3136 case TSK_ExplicitInstantiationDefinition:
3137 // We only need an instantiation if the pending instantiation *is* the
3138 // explicit instantiation.
3139 if (Var != Var->getMostRecentDeclaration()) continue;
Chandler Carruth291b4412010-02-13 10:17:50 +00003140 case TSK_ImplicitInstantiation:
3141 break;
3142 }
3143
John McCallf312b1e2010-08-26 23:41:50 +00003144 PrettyDeclStackTraceEntry CrashInfo(*this, Var, Var->getLocation(),
3145 "instantiating static data member "
3146 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00003147
Chandler Carruth58e390e2010-08-25 08:27:02 +00003148 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
3149 TSK_ExplicitInstantiationDefinition;
3150 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true,
3151 DefinitionRequired);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00003152 }
3153}
John McCall0c01d182010-03-24 05:22:00 +00003154
3155void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
3156 const MultiLevelTemplateArgumentList &TemplateArgs) {
3157 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
3158 E = Pattern->ddiag_end(); I != E; ++I) {
3159 DependentDiagnostic *DD = *I;
3160
3161 switch (DD->getKind()) {
3162 case DependentDiagnostic::Access:
3163 HandleDependentAccessCheck(*DD, TemplateArgs);
3164 break;
3165 }
3166 }
3167}