blob: 3375ccc0ebcd170c23cb610162b956b000fac0ca [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//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000022#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000024
25using namespace clang;
26
27namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000028 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000030 Sema &SemaRef;
31 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000032 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Anders Carlssond8fe2d52009-11-07 06:07:58 +000034 void InstantiateAttrs(Decl *Tmpl, Decl *New);
35
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036 public:
37 typedef Sema::OwningExprResult OwningExprResult;
38
39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000040 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000041 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000042
Mike Stump390b4cc2009-05-16 07:39:55 +000043 // FIXME: Once we get closer to completion, replace these manually-written
44 // declarations with automatically-generated ones from
45 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000046 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
47 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000048 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000050 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000051 Decl *VisitFieldDecl(FieldDecl *D);
52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
53 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000055 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000056 Decl *VisitFunctionDecl(FunctionDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000058 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
60 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000061 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000062 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000063 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000064 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000066 Decl *VisitClassTemplatePartialSpecializationDecl(
67 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000068 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000069 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000070 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000071 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000072 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000073 Decl *VisitUsingDecl(UsingDecl *D);
74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000075 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor8dbc2692009-03-17 21:15:40 +000078 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000079 Decl *VisitDecl(Decl *D) {
80 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
81 Diagnostic::Error,
82 "cannot instantiate %0 yet");
83 SemaRef.Diag(D->getLocation(), DiagID)
84 << D->getDeclKindName();
85
Douglas Gregor8dbc2692009-03-17 21:15:40 +000086 return 0;
87 }
Douglas Gregor5545e162009-03-24 00:38:23 +000088
John McCallfd810b12009-08-14 02:03:10 +000089 const LangOptions &getLangOptions() {
90 return SemaRef.getLangOptions();
91 }
92
Douglas Gregor5545e162009-03-24 00:38:23 +000093 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000094 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000095 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000096 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000097 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000098
99 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000100 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +0000101
102 bool SubstQualifier(const DeclaratorDecl *OldDecl,
103 DeclaratorDecl *NewDecl);
104 bool SubstQualifier(const TagDecl *OldDecl,
105 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000106
107 bool InstantiateClassTemplatePartialSpecialization(
108 ClassTemplateDecl *ClassTemplate,
109 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000110 };
111}
112
John McCallb6217662010-03-15 10:12:16 +0000113bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
114 DeclaratorDecl *NewDecl) {
115 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
116 if (!OldQual) return false;
117
118 SourceRange QualRange = OldDecl->getQualifierRange();
119
120 NestedNameSpecifier *NewQual
121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
122 if (!NewQual)
123 return true;
124
125 NewDecl->setQualifierInfo(NewQual, QualRange);
126 return false;
127}
128
129bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
130 TagDecl *NewDecl) {
131 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
132 if (!OldQual) return false;
133
134 SourceRange QualRange = OldDecl->getQualifierRange();
135
136 NestedNameSpecifier *NewQual
137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
138 if (!NewQual)
139 return true;
140
141 NewDecl->setQualifierInfo(NewQual, QualRange);
142 return false;
143}
144
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000145// FIXME: Is this too simple?
146void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
148 TmplAttr = TmplAttr->getNext()) {
149
150 // FIXME: Is cloning correct for all attributes?
151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
152
153 New->addAttr(NewAttr);
154 }
155}
156
Douglas Gregor4f722be2009-03-25 15:45:12 +0000157Decl *
158TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
159 assert(false && "Translation units cannot be instantiated");
160 return D;
161}
162
163Decl *
164TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
165 assert(false && "Namespaces cannot be instantiated");
166 return D;
167}
168
John McCall3dbd3d52010-02-16 06:53:13 +0000169Decl *
170TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
171 NamespaceAliasDecl *Inst
172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
173 D->getNamespaceLoc(),
174 D->getAliasLoc(),
175 D->getNamespace()->getIdentifier(),
176 D->getQualifierRange(),
177 D->getQualifier(),
178 D->getTargetNameLoc(),
179 D->getNamespace());
180 Owner->addDecl(Inst);
181 return Inst;
182}
183
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
185 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000186 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000187 if (DI->getType()->isDependentType()) {
188 DI = SemaRef.SubstType(DI, TemplateArgs,
189 D->getLocation(), D->getDeclName());
190 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000191 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000193 }
194 }
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196 // Create the new typedef
197 TypedefDecl *Typedef
198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000199 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000200 if (Invalid)
201 Typedef->setInvalidDecl();
202
John McCall5126fd02009-12-30 00:31:22 +0000203 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000204 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
205 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000206 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
207 }
208
John McCall46460a62010-01-20 21:53:11 +0000209 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000210 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000212 return Typedef;
213}
214
Douglas Gregor6eef5192009-12-14 19:27:10 +0000215/// \brief Instantiate the arguments provided as part of initialization.
216///
217/// \returns true if an error occurred, false otherwise.
218static bool InstantiateInitializationArguments(Sema &SemaRef,
219 Expr **Args, unsigned NumArgs,
220 const MultiLevelTemplateArgumentList &TemplateArgs,
221 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
222 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
223 for (unsigned I = 0; I != NumArgs; ++I) {
224 // When we hit the first defaulted argument, break out of the loop:
225 // we don't pass those default arguments on.
226 if (Args[I]->isDefaultArgument())
227 break;
228
229 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
230 if (Arg.isInvalid())
231 return true;
232
233 Expr *ArgExpr = (Expr *)Arg.get();
234 InitArgs.push_back(Arg.release());
235
236 // FIXME: We're faking all of the comma locations. Do we need them?
237 FakeCommaLocs.push_back(
238 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
239 }
240
241 return false;
242}
243
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000244/// \brief Instantiate an initializer, breaking it into separate
245/// initialization arguments.
246///
247/// \param S The semantic analysis object.
248///
249/// \param Init The initializer to instantiate.
250///
251/// \param TemplateArgs Template arguments to be substituted into the
252/// initializer.
253///
254/// \param NewArgs Will be filled in with the instantiation arguments.
255///
256/// \returns true if an error occurred, false otherwise
257static bool InstantiateInitializer(Sema &S, Expr *Init,
258 const MultiLevelTemplateArgumentList &TemplateArgs,
259 SourceLocation &LParenLoc,
260 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
261 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
262 SourceLocation &RParenLoc) {
263 NewArgs.clear();
264 LParenLoc = SourceLocation();
265 RParenLoc = SourceLocation();
266
267 if (!Init)
268 return false;
269
270 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
271 Init = ExprTemp->getSubExpr();
272
273 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
274 Init = Binder->getSubExpr();
275
276 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
277 Init = ICE->getSubExprAsWritten();
278
279 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
280 LParenLoc = ParenList->getLParenLoc();
281 RParenLoc = ParenList->getRParenLoc();
282 return InstantiateInitializationArguments(S, ParenList->getExprs(),
283 ParenList->getNumExprs(),
284 TemplateArgs, CommaLocs,
285 NewArgs);
286 }
287
288 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000289 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
290 if (InstantiateInitializationArguments(S,
291 Construct->getArgs(),
292 Construct->getNumArgs(),
293 TemplateArgs,
294 CommaLocs, NewArgs))
295 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000296
Douglas Gregor28329e52010-03-24 21:22:47 +0000297 // FIXME: Fake locations!
298 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
299 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
300 return false;
301 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000302 }
303
304 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
305 if (Result.isInvalid())
306 return true;
307
308 NewArgs.push_back(Result.takeAs<Expr>());
309 return false;
310}
311
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000312Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000313 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000314 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000315 TemplateArgs,
316 D->getTypeSpecStartLoc(),
317 D->getDeclName());
318 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000319 return 0;
320
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000321 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
323 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000324 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000325 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000326 Var->setThreadSpecified(D->isThreadSpecified());
327 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
328 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCallb6217662010-03-15 10:12:16 +0000330 // Substitute the nested name specifier, if any.
331 if (SubstQualifier(D, Var))
332 return 0;
333
Mike Stump1eb44332009-09-09 15:08:12 +0000334 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000335 // out-of-line, the instantiation will have the same lexical
336 // context (which will be a namespace scope) as the template.
337 if (D->isOutOfLine())
338 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000339
John McCall46460a62010-01-20 21:53:11 +0000340 Var->setAccess(D->getAccess());
341
Mike Stump390b4cc2009-05-16 07:39:55 +0000342 // FIXME: In theory, we could have a previous declaration for variables that
343 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000344 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000345 // FIXME: having to fake up a LookupResult is dumb.
346 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000347 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000348 if (D->isStaticDataMember())
349 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000350 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Douglas Gregor7caa6822009-07-24 20:34:43 +0000352 if (D->isOutOfLine()) {
353 D->getLexicalDeclContext()->addDecl(Var);
354 Owner->makeDeclVisibleInContext(Var);
355 } else {
356 Owner->addDecl(Var);
357 }
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000359 // Link instantiations of static data members back to the template from
360 // which they were instantiated.
361 if (Var->isStaticDataMember())
362 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000363 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000364
Douglas Gregor60c93c92010-02-09 07:26:29 +0000365 if (Var->getAnyInitializer()) {
366 // We already have an initializer in the class.
367 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000368 if (Var->isStaticDataMember() && !D->isOutOfLine())
369 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
370 else
371 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
372
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000373 // Instantiate the initializer.
374 SourceLocation LParenLoc, RParenLoc;
375 llvm::SmallVector<SourceLocation, 4> CommaLocs;
376 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
377 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
378 CommaLocs, InitArgs, RParenLoc)) {
379 // Attach the initializer to the declaration.
380 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000381 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000382 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000383 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000384 move_arg(InitArgs),
385 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000386 RParenLoc);
387 } else if (InitArgs.size() == 1) {
388 Expr *Init = (Expr*)(InitArgs.take()[0]);
389 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
390 SemaRef.Owned(Init),
391 false);
392 } else {
393 assert(InitArgs.size() == 0);
394 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000395 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000396 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000397 // FIXME: Not too happy about invalidating the declaration
398 // because of a bogus initializer.
399 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000400 }
401
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000402 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000403 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
404 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000405
406 return Var;
407}
408
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000409Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
410 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000411 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000412 if (DI->getType()->isDependentType()) {
413 DI = SemaRef.SubstType(DI, TemplateArgs,
414 D->getLocation(), D->getDeclName());
415 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000416 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000417 Invalid = true;
418 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000419 // C++ [temp.arg.type]p3:
420 // If a declaration acquires a function type through a type
421 // dependent on a template-parameter and this causes a
422 // declaration that does not use the syntactic form of a
423 // function declarator to have function type, the program is
424 // ill-formed.
425 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000426 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000427 Invalid = true;
428 }
429 }
430
431 Expr *BitWidth = D->getBitWidth();
432 if (Invalid)
433 BitWidth = 0;
434 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000435 // The bit-width expression is not potentially evaluated.
436 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000438 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000439 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000440 if (InstantiatedBitWidth.isInvalid()) {
441 Invalid = true;
442 BitWidth = 0;
443 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000444 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000445 }
446
John McCall07fb6be2009-10-22 23:33:21 +0000447 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
448 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000449 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450 D->getLocation(),
451 D->isMutable(),
452 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000453 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000454 D->getAccess(),
455 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000456 if (!Field) {
457 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000458 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000461 InstantiateAttrs(D, Field);
462
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000463 if (Invalid)
464 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000466 if (!Field->getDeclName()) {
467 // Keep track of where this decl came from.
468 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000471 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000472 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000473 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000474
475 return Field;
476}
477
John McCall02cace72009-08-28 07:59:38 +0000478Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
479 FriendDecl::FriendUnion FU;
480
481 // Handle friend type expressions by simply substituting template
482 // parameters into the pattern type.
John McCall32f2fb52010-03-25 18:04:51 +0000483 if (TypeSourceInfo *Ty = D->getFriendType()) {
484 TypeSourceInfo *InstTy =
485 SemaRef.SubstType(Ty, TemplateArgs,
486 D->getLocation(), DeclarationName());
487 if (!InstTy) return 0;
John McCall02cace72009-08-28 07:59:38 +0000488
John McCall32f2fb52010-03-25 18:04:51 +0000489 // This assertion is valid because the source type was necessarily
490 // an elaborated-type-specifier with a record tag.
491 assert(getLangOptions().CPlusPlus0x || InstTy->getType()->isRecordType());
492
493 FU = InstTy;
John McCall02cace72009-08-28 07:59:38 +0000494
495 // Handle everything else by appropriate substitution.
496 } else {
497 NamedDecl *ND = D->getFriendDecl();
498 assert(ND && "friend decl must be a decl or a type!");
499
Douglas Gregora735b202009-10-13 14:39:41 +0000500 // FIXME: We have a problem here, because the nested call to Visit(ND)
501 // will inject the thing that the friend references into the current
502 // owner, which is wrong.
John McCalle129d442009-12-17 23:21:11 +0000503 Decl *NewND;
504
505 // Hack to make this work almost well pending a rewrite.
John McCallb0cb0222010-03-27 05:57:59 +0000506 if (D->wasSpecialization()) {
Douglas Gregor7557a132009-12-24 20:56:24 +0000507 // Totally egregious hack to work around PR5866
508 return 0;
John McCall93ba8572010-03-25 06:39:04 +0000509 } else {
John McCalle129d442009-12-17 23:21:11 +0000510 NewND = Visit(ND);
John McCall93ba8572010-03-25 06:39:04 +0000511 }
John McCall02cace72009-08-28 07:59:38 +0000512 if (!NewND) return 0;
513
514 FU = cast<NamedDecl>(NewND);
John McCallfd810b12009-08-14 02:03:10 +0000515 }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
John McCall02cace72009-08-28 07:59:38 +0000517 FriendDecl *FD =
518 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
519 D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000520 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000521 Owner->addDecl(FD);
522 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000523}
524
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000525Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
526 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000527
Douglas Gregorac7610d2009-06-22 20:57:11 +0000528 // The expression in a static assertion is not potentially evaluated.
529 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000530
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000531 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000532 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000533 if (InstantiatedAssertExpr.isInvalid())
534 return 0;
535
Douglas Gregor43d9d922009-08-08 01:41:12 +0000536 OwningExprResult Message(SemaRef, D->getMessage());
537 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000538 Decl *StaticAssert
539 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000540 move(InstantiatedAssertExpr),
541 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000542 return StaticAssert;
543}
544
545Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000546 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000547 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000548 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000549 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000550 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000551 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000552 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000553 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000554 Enum->startDefinition();
555
Douglas Gregor96084f12010-03-01 19:00:07 +0000556 if (D->getDeclContext()->isFunctionOrMethod())
557 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
558
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000559 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000560
561 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000562 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
563 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000564 EC != ECEnd; ++EC) {
565 // The specified value for the enumerator.
566 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000567 if (Expr *UninstValue = EC->getInitExpr()) {
568 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000569 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000570 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000571
John McCallce3ff2b2009-08-25 22:02:44 +0000572 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000573 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000574
575 // Drop the initial value and continue.
576 bool isInvalid = false;
577 if (Value.isInvalid()) {
578 Value = SemaRef.Owned((Expr *)0);
579 isInvalid = true;
580 }
581
Mike Stump1eb44332009-09-09 15:08:12 +0000582 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000583 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
584 EC->getLocation(), EC->getIdentifier(),
585 move(Value));
586
587 if (isInvalid) {
588 if (EnumConst)
589 EnumConst->setInvalidDecl();
590 Enum->setInvalidDecl();
591 }
592
593 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000594 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000595 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000596 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000597 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000598
599 if (D->getDeclContext()->isFunctionOrMethod()) {
600 // If the enumeration is within a function or method, record the enum
601 // constant as a local.
602 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
603 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000604 }
605 }
Mike Stump1eb44332009-09-09 15:08:12 +0000606
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000607 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000608 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000609 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
610 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000611 &Enumerators[0], Enumerators.size(),
612 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000613
614 return Enum;
615}
616
Douglas Gregor6477b692009-03-25 15:04:13 +0000617Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
618 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
619 return 0;
620}
621
Douglas Gregored9c0f92009-10-29 00:04:11 +0000622namespace {
623 class SortDeclByLocation {
624 SourceManager &SourceMgr;
625
626 public:
627 explicit SortDeclByLocation(SourceManager &SourceMgr)
628 : SourceMgr(SourceMgr) { }
629
630 bool operator()(const Decl *X, const Decl *Y) const {
631 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
632 Y->getLocation());
633 }
634 };
635}
636
John McCalle29ba202009-08-20 01:44:21 +0000637Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000638 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
639
Douglas Gregor550d9b22009-10-31 17:21:17 +0000640 // Create a local instantiation scope for this class template, which
641 // will contain the instantiations of the template parameters.
642 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000643 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000644 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000645 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000646 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000647
648 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000649
650 // Instantiate the qualifier. We have to do this first in case
651 // we're a friend declaration, because if we are then we need to put
652 // the new declaration in the appropriate context.
653 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
654 if (Qualifier) {
655 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
656 Pattern->getQualifierRange(),
657 TemplateArgs);
658 if (!Qualifier) return 0;
659 }
660
661 CXXRecordDecl *PrevDecl = 0;
662 ClassTemplateDecl *PrevClassTemplate = 0;
663
664 // If this isn't a friend, then it's a member template, in which
665 // case we just want to build the instantiation in the
666 // specialization. If it is a friend, we want to build it in
667 // the appropriate context.
668 DeclContext *DC = Owner;
669 if (isFriend) {
670 if (Qualifier) {
671 CXXScopeSpec SS;
672 SS.setScopeRep(Qualifier);
673 SS.setRange(Pattern->getQualifierRange());
674 DC = SemaRef.computeDeclContext(SS);
675 if (!DC) return 0;
676 } else {
677 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
678 Pattern->getDeclContext(),
679 TemplateArgs);
680 }
681
682 // Look for a previous declaration of the template in the owning
683 // context.
684 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
685 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
686 SemaRef.LookupQualifiedName(R, DC);
687
688 if (R.isSingleResult()) {
689 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
690 if (PrevClassTemplate)
691 PrevDecl = PrevClassTemplate->getTemplatedDecl();
692 }
693
694 if (!PrevClassTemplate && Qualifier) {
695 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000696 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
697 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000698 return 0;
699 }
700
701 if (PrevClassTemplate) {
702 TemplateParameterList *PrevParams
703 = PrevClassTemplate->getTemplateParameters();
704
705 // Make sure the parameter lists match.
706 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
707 /*Complain=*/true,
708 Sema::TPL_TemplateMatch))
709 return 0;
710
711 // Do some additional validation, then merge default arguments
712 // from the existing declarations.
713 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
714 Sema::TPC_ClassTemplate))
715 return 0;
716 }
717 }
718
John McCalle29ba202009-08-20 01:44:21 +0000719 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000720 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000721 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000722 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000723 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000724
John McCall93ba8572010-03-25 06:39:04 +0000725 if (Qualifier)
726 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000727
John McCalle29ba202009-08-20 01:44:21 +0000728 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000729 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
730 D->getIdentifier(), InstParams, RecordInst,
731 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000732 RecordInst->setDescribedClassTemplate(Inst);
John McCall93ba8572010-03-25 06:39:04 +0000733 if (isFriend) {
734 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
735 // TODO: do we want to track the instantiation progeny of this
736 // friend target decl?
737 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000738 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000739 Inst->setInstantiatedFromMemberTemplate(D);
740 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000741
742 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000743 SemaRef.Context.getInjectedClassNameType(RecordInst,
744 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
Douglas Gregorf0510d42009-10-12 23:11:44 +0000745
Douglas Gregor259571e2009-10-30 22:42:42 +0000746 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000747 if (isFriend) {
748 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000749 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000750 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000751
John McCall46460a62010-01-20 21:53:11 +0000752 Inst->setAccess(D->getAccess());
John McCalle29ba202009-08-20 01:44:21 +0000753 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000754
755 // First, we sort the partial specializations by location, so
756 // that we instantiate them in the order they were declared.
757 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
758 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
759 P = D->getPartialSpecializations().begin(),
760 PEnd = D->getPartialSpecializations().end();
761 P != PEnd; ++P)
762 PartialSpecs.push_back(&*P);
763 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
764 SortDeclByLocation(SemaRef.SourceMgr));
765
766 // Instantiate all of the partial specializations of this member class
767 // template.
768 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
769 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
770
John McCalle29ba202009-08-20 01:44:21 +0000771 return Inst;
772}
773
Douglas Gregord60e1052009-08-27 16:57:43 +0000774Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000775TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
776 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000777 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
778
779 // Lookup the already-instantiated declaration in the instantiation
780 // of the class template and return that.
781 DeclContext::lookup_result Found
782 = Owner->lookup(ClassTemplate->getDeclName());
783 if (Found.first == Found.second)
784 return 0;
785
786 ClassTemplateDecl *InstClassTemplate
787 = dyn_cast<ClassTemplateDecl>(*Found.first);
788 if (!InstClassTemplate)
789 return 0;
790
791 Decl *DCanon = D->getCanonicalDecl();
792 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
793 P = InstClassTemplate->getPartialSpecializations().begin(),
794 PEnd = InstClassTemplate->getPartialSpecializations().end();
795 P != PEnd; ++P) {
796 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
797 return &*P;
798 }
799
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000800 return 0;
801}
802
803Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000804TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000805 // Create a local instantiation scope for this function template, which
806 // will contain the instantiations of the template parameters and then get
807 // merged with the local instantiation scope for the function template
808 // itself.
809 Sema::LocalInstantiationScope Scope(SemaRef);
810
Douglas Gregord60e1052009-08-27 16:57:43 +0000811 TemplateParameterList *TempParams = D->getTemplateParameters();
812 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000813 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000814 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000815
Douglas Gregora735b202009-10-13 14:39:41 +0000816 FunctionDecl *Instantiated = 0;
817 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
818 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
819 InstParams));
820 else
821 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
822 D->getTemplatedDecl(),
823 InstParams));
824
825 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000826 return 0;
827
John McCall46460a62010-01-20 21:53:11 +0000828 Instantiated->setAccess(D->getAccess());
829
Mike Stump1eb44332009-09-09 15:08:12 +0000830 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000831 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000832 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000833 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000834 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000835 assert(InstTemplate &&
836 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000837
John McCallb1a56e72010-03-26 23:10:15 +0000838 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
839
John McCalle976ffe2009-12-14 23:19:40 +0000840 // Link the instantiation back to the pattern *unless* this is a
841 // non-definition friend declaration.
842 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000843 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000844 InstTemplate->setInstantiatedFromMemberTemplate(D);
845
John McCallb1a56e72010-03-26 23:10:15 +0000846 // Make declarations visible in the appropriate context.
847 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000848 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000849
Douglas Gregord60e1052009-08-27 16:57:43 +0000850 return InstTemplate;
851}
852
Douglas Gregord475b8d2009-03-25 21:17:03 +0000853Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
854 CXXRecordDecl *PrevDecl = 0;
855 if (D->isInjectedClassName())
856 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000857 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000858 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
859 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000860 TemplateArgs);
861 if (!Prev) return 0;
862 PrevDecl = cast<CXXRecordDecl>(Prev);
863 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000864
865 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000866 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000867 D->getLocation(), D->getIdentifier(),
868 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000869
870 // Substitute the nested name specifier, if any.
871 if (SubstQualifier(D, Record))
872 return 0;
873
Douglas Gregord475b8d2009-03-25 21:17:03 +0000874 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000875 // FIXME: Check against AS_none is an ugly hack to work around the issue that
876 // the tag decls introduced by friend class declarations don't have an access
877 // specifier. Remove once this area of the code gets sorted out.
878 if (D->getAccess() != AS_none)
879 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000880 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000881 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000882
John McCall02cace72009-08-28 07:59:38 +0000883 // If the original function was part of a friend declaration,
884 // inherit its namespace state.
885 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
886 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
887
Anders Carlssond8b285f2009-09-01 04:26:58 +0000888 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
889
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000890 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000891 return Record;
892}
893
John McCall02cace72009-08-28 07:59:38 +0000894/// Normal class members are of more specific types and therefore
895/// don't make it here. This function serves two purposes:
896/// 1) instantiating function templates
897/// 2) substituting friend declarations
898/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000899Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000900 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000901 // Check whether there is already a function template specialization for
902 // this declaration.
903 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
904 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000905 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000906 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000907 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000908 TemplateArgs.getInnermost().getFlatArgumentList(),
909 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000910 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000911
912 FunctionTemplateSpecializationInfo *Info
913 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000914 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregor127102b2009-06-29 20:59:39 +0000916 // If we already have a function template specialization, return it.
917 if (Info)
918 return Info->Function;
919 }
Mike Stump1eb44332009-09-09 15:08:12 +0000920
John McCallb0cb0222010-03-27 05:57:59 +0000921 bool isFriend;
922 if (FunctionTemplate)
923 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
924 else
925 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
926
Douglas Gregor79c22782010-01-16 20:21:20 +0000927 bool MergeWithParentScope = (TemplateParams != 0) ||
928 !(isa<Decl>(Owner) &&
929 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
930 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000931
Douglas Gregore53060f2009-06-25 22:08:12 +0000932 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000933 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
934 TInfo = SubstFunctionType(D, Params);
935 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000936 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000937 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000938
John McCalld325daa2010-03-26 04:53:08 +0000939 NestedNameSpecifier *Qualifier = D->getQualifier();
940 if (Qualifier) {
941 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
942 D->getQualifierRange(),
943 TemplateArgs);
944 if (!Qualifier) return 0;
945 }
946
John McCall68b6b872010-02-06 01:50:47 +0000947 // If we're instantiating a local function declaration, put the result
948 // in the owner; otherwise we need to find the instantiated context.
949 DeclContext *DC;
950 if (D->getDeclContext()->isFunctionOrMethod())
951 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000952 else if (isFriend && Qualifier) {
953 CXXScopeSpec SS;
954 SS.setScopeRep(Qualifier);
955 SS.setRange(D->getQualifierRange());
956 DC = SemaRef.computeDeclContext(SS);
957 if (!DC) return 0;
958 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000959 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
960 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000961 }
John McCall68b6b872010-02-06 01:50:47 +0000962
John McCall02cace72009-08-28 07:59:38 +0000963 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000964 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000965 D->getDeclName(), T, TInfo,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000966 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000967 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +0000968
John McCalld325daa2010-03-26 04:53:08 +0000969 if (Qualifier)
970 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000971
John McCallb1a56e72010-03-26 23:10:15 +0000972 DeclContext *LexicalDC = Owner;
973 if (!isFriend && D->isOutOfLine()) {
974 assert(D->getDeclContext()->isFileContext());
975 LexicalDC = D->getDeclContext();
976 }
977
978 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Douglas Gregore53060f2009-06-25 22:08:12 +0000980 // Attach the parameters
981 for (unsigned P = 0; P < Params.size(); ++P)
982 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +0000983 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +0000984
Douglas Gregora735b202009-10-13 14:39:41 +0000985 if (TemplateParams) {
986 // Our resulting instantiation is actually a function template, since we
987 // are substituting only the outer template parameters. For example, given
988 //
989 // template<typename T>
990 // struct X {
991 // template<typename U> friend void f(T, U);
992 // };
993 //
994 // X<int> x;
995 //
996 // We are instantiating the friend function template "f" within X<int>,
997 // which means substituting int for T, but leaving "f" as a friend function
998 // template.
999 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001000 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001001 Function->getLocation(),
1002 Function->getDeclName(),
1003 TemplateParams, Function);
1004 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001005
1006 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001007
1008 if (isFriend && D->isThisDeclarationADefinition()) {
1009 // TODO: should we remember this connection regardless of whether
1010 // the friend declaration provided a body?
1011 FunctionTemplate->setInstantiatedFromMemberTemplate(
1012 D->getDescribedFunctionTemplate());
1013 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001014 } else if (FunctionTemplate) {
1015 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001016 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001017 &TemplateArgs.getInnermost(),
1018 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001019 } else if (isFriend && D->isThisDeclarationADefinition()) {
1020 // TODO: should we remember this connection regardless of whether
1021 // the friend declaration provided a body?
1022 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001023 }
Douglas Gregora735b202009-10-13 14:39:41 +00001024
Douglas Gregore53060f2009-06-25 22:08:12 +00001025 if (InitFunctionInstantiation(Function, D))
1026 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Douglas Gregore53060f2009-06-25 22:08:12 +00001028 bool Redeclaration = false;
1029 bool OverloadableAttrRequired = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001030
John McCall68263142009-11-18 22:49:29 +00001031 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1032 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1033
Douglas Gregora735b202009-10-13 14:39:41 +00001034 if (TemplateParams || !FunctionTemplate) {
1035 // Look only into the namespace where the friend would be declared to
1036 // find a previous declaration. This is the innermost enclosing namespace,
1037 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001038 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001039
Douglas Gregora735b202009-10-13 14:39:41 +00001040 // In C++, the previous declaration we find might be a tag type
1041 // (class or enum). In this case, the new declaration will hide the
1042 // tag type. Note that this does does not apply if we're declaring a
1043 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001044 if (Previous.isSingleTagDecl())
1045 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001046 }
1047
John McCall9f54ad42009-12-10 09:41:52 +00001048 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1049 false, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001050 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001051
Douglas Gregora735b202009-10-13 14:39:41 +00001052 // If the original function was part of a friend declaration,
1053 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001054 if (isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001055 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +00001056 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +00001057 if (TemplateParams) {
1058 ToFriendD = cast<NamedDecl>(FunctionTemplate);
1059 PrevDecl = FunctionTemplate->getPreviousDeclaration();
1060 } else {
1061 ToFriendD = Function;
1062 PrevDecl = Function->getPreviousDeclaration();
1063 }
1064 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
John McCalld325daa2010-03-26 04:53:08 +00001065 DC->makeDeclVisibleInContext(ToFriendD, /*Recoverable=*/ false);
Douglas Gregora735b202009-10-13 14:39:41 +00001066 }
1067
Douglas Gregore53060f2009-06-25 22:08:12 +00001068 return Function;
1069}
1070
Douglas Gregord60e1052009-08-27 16:57:43 +00001071Decl *
1072TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1073 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001074 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1075 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001076 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001077 // We are creating a function template specialization from a function
1078 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001079 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001080 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001081 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001082 TemplateArgs.getInnermost().getFlatArgumentList(),
1083 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001084 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001085
1086 FunctionTemplateSpecializationInfo *Info
1087 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001088 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Douglas Gregor6b906862009-08-21 00:16:32 +00001090 // If we already have a function template specialization, return it.
1091 if (Info)
1092 return Info->Function;
1093 }
1094
John McCallb0cb0222010-03-27 05:57:59 +00001095 bool isFriend;
1096 if (FunctionTemplate)
1097 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1098 else
1099 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1100
Douglas Gregor79c22782010-01-16 20:21:20 +00001101 bool MergeWithParentScope = (TemplateParams != 0) ||
1102 !(isa<Decl>(Owner) &&
1103 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1104 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001105
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001106 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001107 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1108 TInfo = SubstFunctionType(D, Params);
1109 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001110 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001111 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001112
John McCallb0cb0222010-03-27 05:57:59 +00001113 NestedNameSpecifier *Qualifier = D->getQualifier();
1114 if (Qualifier) {
1115 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1116 D->getQualifierRange(),
1117 TemplateArgs);
1118 if (!Qualifier) return 0;
1119 }
1120
1121 DeclContext *DC = Owner;
1122 if (isFriend) {
1123 if (Qualifier) {
1124 CXXScopeSpec SS;
1125 SS.setScopeRep(Qualifier);
1126 SS.setRange(D->getQualifierRange());
1127 DC = SemaRef.computeDeclContext(SS);
1128 } else {
1129 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1130 D->getDeclContext(),
1131 TemplateArgs);
1132 }
1133 if (!DC) return 0;
1134 }
1135
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001136 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001137 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001138 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Douglas Gregordec06662009-08-21 18:42:58 +00001140 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001141 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001142 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1143 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1144 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001145 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1146 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001147 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001148 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001149 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001150 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1151 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1152 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1153 SemaRef.Context.getCanonicalType(ClassTy));
1154 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1155 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001156 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001157 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001158 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001159 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001160 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001161 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1162 ConvTy);
1163 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1164 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001165 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001166 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001167 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001168 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001169 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001170 D->getDeclName(), T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001171 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001172 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001173
John McCallb0cb0222010-03-27 05:57:59 +00001174 if (Qualifier)
1175 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001176
Douglas Gregord60e1052009-08-27 16:57:43 +00001177 if (TemplateParams) {
1178 // Our resulting instantiation is actually a function template, since we
1179 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001180 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001181 // template<typename T>
1182 // struct X {
1183 // template<typename U> void f(T, U);
1184 // };
1185 //
1186 // X<int> x;
1187 //
1188 // We are instantiating the member template "f" within X<int>, which means
1189 // substituting int for T, but leaving "f" as a member function template.
1190 // Build the function template itself.
1191 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1192 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001193 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001194 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001195 if (isFriend) {
1196 FunctionTemplate->setLexicalDeclContext(Owner);
1197 FunctionTemplate->setObjectOfFriendDecl(true);
1198 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001199 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001200 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001201 } else if (FunctionTemplate) {
1202 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001203 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001204 &TemplateArgs.getInnermost(),
1205 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001206 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001207 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001208 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001209 }
1210
Mike Stump1eb44332009-09-09 15:08:12 +00001211 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001212 // out-of-line, the instantiation will have the same lexical
1213 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001214 if (isFriend) {
1215 Method->setLexicalDeclContext(Owner);
1216 Method->setObjectOfFriendDecl(true);
1217 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001218 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Douglas Gregor5545e162009-03-24 00:38:23 +00001220 // Attach the parameters
1221 for (unsigned P = 0; P < Params.size(); ++P)
1222 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001223 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001224
1225 if (InitMethodInstantiation(Method, D))
1226 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001227
John McCall68263142009-11-18 22:49:29 +00001228 LookupResult Previous(SemaRef, Name, SourceLocation(),
1229 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001230
John McCallb0cb0222010-03-27 05:57:59 +00001231 if (!FunctionTemplate || TemplateParams || isFriend) {
1232 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001233
Douglas Gregordec06662009-08-21 18:42:58 +00001234 // In C++, the previous declaration we find might be a tag type
1235 // (class or enum). In this case, the new declaration will hide the
1236 // tag type. Note that this does does not apply if we're declaring a
1237 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001238 if (Previous.isSingleTagDecl())
1239 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001240 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001241
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001242 bool Redeclaration = false;
1243 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001244 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001245 /*FIXME:*/OverloadableAttrRequired);
1246
Douglas Gregor4ba31362009-12-01 17:24:26 +00001247 if (D->isPure())
1248 SemaRef.CheckPureMethod(Method, SourceRange());
1249
John McCall46460a62010-01-20 21:53:11 +00001250 Method->setAccess(D->getAccess());
1251
John McCallb0cb0222010-03-27 05:57:59 +00001252 if (FunctionTemplate) {
1253 // If there's a function template, let our caller handle it.
1254 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1255 // Don't hide a (potentially) valid declaration with an invalid one.
1256 } else {
1257 NamedDecl *DeclToAdd = (TemplateParams
1258 ? cast<NamedDecl>(FunctionTemplate)
1259 : Method);
1260 if (isFriend)
1261 Record->makeDeclVisibleInContext(DeclToAdd);
1262 else
1263 Owner->addDecl(DeclToAdd);
1264 }
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001266 return Method;
1267}
1268
Douglas Gregor615c5d42009-03-24 16:43:20 +00001269Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001270 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001271}
1272
Douglas Gregor03b2b072009-03-24 00:15:49 +00001273Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001274 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001275}
1276
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001277Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001278 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001279}
1280
Douglas Gregor6477b692009-03-25 15:04:13 +00001281ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +00001282 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001283 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +00001284 if (DI) {
1285 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1286 D->getDeclName());
1287 if (DI) T = DI->getType();
1288 } else {
1289 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1290 D->getDeclName());
1291 DI = 0;
1292 }
1293
1294 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001295 return 0;
1296
John McCall58e46772009-10-23 21:48:59 +00001297 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001298
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001299 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001300 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001301 = ParmVarDecl::Create(SemaRef.Context,
1302 SemaRef.Context.getTranslationUnitDecl(),
1303 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001304 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001305
Anders Carlsson9351c172009-08-25 03:18:48 +00001306 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001307 if (D->hasUninstantiatedDefaultArg())
1308 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001309 else if (Expr *Arg = D->getDefaultArg())
1310 Param->setUninstantiatedDefaultArg(Arg);
1311
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001312 // Note: we don't try to instantiate function parameters until after
1313 // we've instantiated the function's type. Therefore, we don't have
1314 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001315 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001316 return Param;
1317}
1318
John McCalle29ba202009-08-20 01:44:21 +00001319Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1320 TemplateTypeParmDecl *D) {
1321 // TODO: don't always clone when decls are refcounted.
1322 const Type* T = D->getTypeForDecl();
1323 assert(T->isTemplateTypeParmType());
1324 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001325
John McCalle29ba202009-08-20 01:44:21 +00001326 TemplateTypeParmDecl *Inst =
1327 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001328 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001329 TTPT->getName(),
1330 D->wasDeclaredWithTypename(),
1331 D->isParameterPack());
1332
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001333 if (D->hasDefaultArgument())
1334 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001335
Douglas Gregor550d9b22009-10-31 17:21:17 +00001336 // Introduce this template parameter's instantiation into the instantiation
1337 // scope.
1338 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1339
John McCalle29ba202009-08-20 01:44:21 +00001340 return Inst;
1341}
1342
Douglas Gregor33642df2009-10-23 23:25:44 +00001343Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1344 NonTypeTemplateParmDecl *D) {
1345 // Substitute into the type of the non-type template parameter.
1346 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001347 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001348 if (DI) {
1349 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1350 D->getDeclName());
1351 if (DI) T = DI->getType();
1352 } else {
1353 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1354 D->getDeclName());
1355 DI = 0;
1356 }
1357 if (T.isNull())
1358 return 0;
1359
1360 // Check that this type is acceptable for a non-type template parameter.
1361 bool Invalid = false;
1362 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1363 if (T.isNull()) {
1364 T = SemaRef.Context.IntTy;
1365 Invalid = true;
1366 }
1367
1368 NonTypeTemplateParmDecl *Param
1369 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1370 D->getDepth() - 1, D->getPosition(),
1371 D->getIdentifier(), T, DI);
1372 if (Invalid)
1373 Param->setInvalidDecl();
1374
1375 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001376
1377 // Introduce this template parameter's instantiation into the instantiation
1378 // scope.
1379 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001380 return Param;
1381}
1382
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001383Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001384TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1385 TemplateTemplateParmDecl *D) {
1386 // Instantiate the template parameter list of the template template parameter.
1387 TemplateParameterList *TempParams = D->getTemplateParameters();
1388 TemplateParameterList *InstParams;
1389 {
1390 // Perform the actual substitution of template parameters within a new,
1391 // local instantiation scope.
1392 Sema::LocalInstantiationScope Scope(SemaRef);
1393 InstParams = SubstTemplateParams(TempParams);
1394 if (!InstParams)
1395 return NULL;
1396 }
1397
1398 // Build the template template parameter.
1399 TemplateTemplateParmDecl *Param
1400 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1401 D->getDepth() - 1, D->getPosition(),
1402 D->getIdentifier(), InstParams);
1403 Param->setDefaultArgument(D->getDefaultArgument());
1404
1405 // Introduce this template parameter's instantiation into the instantiation
1406 // scope.
1407 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1408
1409 return Param;
1410}
1411
Douglas Gregor48c32a72009-11-17 06:07:40 +00001412Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1413 // Using directives are never dependent, so they require no explicit
1414
1415 UsingDirectiveDecl *Inst
1416 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1417 D->getNamespaceKeyLocation(),
1418 D->getQualifierRange(), D->getQualifier(),
1419 D->getIdentLocation(),
1420 D->getNominatedNamespace(),
1421 D->getCommonAncestor());
1422 Owner->addDecl(Inst);
1423 return Inst;
1424}
1425
John McCalled976492009-12-04 22:46:56 +00001426Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1427 // The nested name specifier is non-dependent, so no transformation
1428 // is required.
1429
John McCall9f54ad42009-12-10 09:41:52 +00001430 // We only need to do redeclaration lookups if we're in a class
1431 // scope (in fact, it's not really even possible in non-class
1432 // scopes).
1433 bool CheckRedeclaration = Owner->isRecord();
1434
1435 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1436 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1437
John McCalled976492009-12-04 22:46:56 +00001438 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1439 D->getLocation(),
1440 D->getNestedNameRange(),
1441 D->getUsingLocation(),
1442 D->getTargetNestedNameDecl(),
1443 D->getDeclName(),
1444 D->isTypeName());
1445
1446 CXXScopeSpec SS;
1447 SS.setScopeRep(D->getTargetNestedNameDecl());
1448 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001449
1450 if (CheckRedeclaration) {
1451 Prev.setHideTags(false);
1452 SemaRef.LookupQualifiedName(Prev, Owner);
1453
1454 // Check for invalid redeclarations.
1455 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1456 D->isTypeName(), SS,
1457 D->getLocation(), Prev))
1458 NewUD->setInvalidDecl();
1459
1460 }
1461
1462 if (!NewUD->isInvalidDecl() &&
1463 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001464 D->getLocation()))
1465 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001466
John McCalled976492009-12-04 22:46:56 +00001467 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1468 NewUD->setAccess(D->getAccess());
1469 Owner->addDecl(NewUD);
1470
John McCall9f54ad42009-12-10 09:41:52 +00001471 // Don't process the shadow decls for an invalid decl.
1472 if (NewUD->isInvalidDecl())
1473 return NewUD;
1474
John McCall323c3102009-12-22 22:26:37 +00001475 bool isFunctionScope = Owner->isFunctionOrMethod();
1476
John McCall9f54ad42009-12-10 09:41:52 +00001477 // Process the shadow decls.
1478 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1479 I != E; ++I) {
1480 UsingShadowDecl *Shadow = *I;
1481 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001482 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1483 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001484 TemplateArgs));
1485
1486 if (CheckRedeclaration &&
1487 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1488 continue;
1489
1490 UsingShadowDecl *InstShadow
1491 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1492 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001493
1494 if (isFunctionScope)
1495 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001496 }
John McCalled976492009-12-04 22:46:56 +00001497
1498 return NewUD;
1499}
1500
1501Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001502 // Ignore these; we handle them in bulk when processing the UsingDecl.
1503 return 0;
John McCalled976492009-12-04 22:46:56 +00001504}
1505
John McCall7ba107a2009-11-18 02:36:19 +00001506Decl * TemplateDeclInstantiator
1507 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001508 NestedNameSpecifier *NNS =
1509 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1510 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001511 TemplateArgs);
1512 if (!NNS)
1513 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001515 CXXScopeSpec SS;
1516 SS.setRange(D->getTargetNestedNameRange());
1517 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001518
1519 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001520 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001521 D->getUsingLoc(), SS, D->getLocation(),
1522 D->getDeclName(), 0,
1523 /*instantiation*/ true,
1524 /*typename*/ true, D->getTypenameLoc());
1525 if (UD)
John McCalled976492009-12-04 22:46:56 +00001526 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1527
John McCall7ba107a2009-11-18 02:36:19 +00001528 return UD;
1529}
1530
1531Decl * TemplateDeclInstantiator
1532 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1533 NestedNameSpecifier *NNS =
1534 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1535 D->getTargetNestedNameRange(),
1536 TemplateArgs);
1537 if (!NNS)
1538 return 0;
1539
1540 CXXScopeSpec SS;
1541 SS.setRange(D->getTargetNestedNameRange());
1542 SS.setScopeRep(NNS);
1543
1544 NamedDecl *UD =
1545 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1546 D->getUsingLoc(), SS, D->getLocation(),
1547 D->getDeclName(), 0,
1548 /*instantiation*/ true,
1549 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001550 if (UD)
John McCalled976492009-12-04 22:46:56 +00001551 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1552
Anders Carlsson0d8df782009-08-29 19:37:28 +00001553 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001554}
1555
John McCallce3ff2b2009-08-25 22:02:44 +00001556Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001557 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001558 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001559 if (D->isInvalidDecl())
1560 return 0;
1561
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001562 return Instantiator.Visit(D);
1563}
1564
John McCalle29ba202009-08-20 01:44:21 +00001565/// \brief Instantiates a nested template parameter list in the current
1566/// instantiation context.
1567///
1568/// \param L The parameter list to instantiate
1569///
1570/// \returns NULL if there was an error
1571TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001572TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001573 // Get errors for all the parameters before bailing out.
1574 bool Invalid = false;
1575
1576 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001577 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001578 ParamVector Params;
1579 Params.reserve(N);
1580 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1581 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001582 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001583 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001584 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001585 }
1586
1587 // Clean up if we had an error.
1588 if (Invalid) {
1589 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1590 PI != PE; ++PI)
1591 if (*PI)
1592 (*PI)->Destroy(SemaRef.Context);
1593 return NULL;
1594 }
1595
1596 TemplateParameterList *InstL
1597 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1598 L->getLAngleLoc(), &Params.front(), N,
1599 L->getRAngleLoc());
1600 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001601}
John McCalle29ba202009-08-20 01:44:21 +00001602
Douglas Gregored9c0f92009-10-29 00:04:11 +00001603/// \brief Instantiate the declaration of a class template partial
1604/// specialization.
1605///
1606/// \param ClassTemplate the (instantiated) class template that is partially
1607// specialized by the instantiation of \p PartialSpec.
1608///
1609/// \param PartialSpec the (uninstantiated) class template partial
1610/// specialization that we are instantiating.
1611///
1612/// \returns true if there was an error, false otherwise.
1613bool
1614TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1615 ClassTemplateDecl *ClassTemplate,
1616 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001617 // Create a local instantiation scope for this class template partial
1618 // specialization, which will contain the instantiations of the template
1619 // parameters.
1620 Sema::LocalInstantiationScope Scope(SemaRef);
1621
Douglas Gregored9c0f92009-10-29 00:04:11 +00001622 // Substitute into the template parameters of the class template partial
1623 // specialization.
1624 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1625 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1626 if (!InstParams)
1627 return true;
1628
1629 // Substitute into the template arguments of the class template partial
1630 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001631 const TemplateArgumentLoc *PartialSpecTemplateArgs
1632 = PartialSpec->getTemplateArgsAsWritten();
1633 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1634
John McCalld5532b62009-11-23 01:53:49 +00001635 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001636 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001637 TemplateArgumentLoc Loc;
1638 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001639 return true;
John McCalld5532b62009-11-23 01:53:49 +00001640 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001641 }
1642
1643
1644 // Check that the template argument list is well-formed for this
1645 // class template.
1646 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1647 InstTemplateArgs.size());
1648 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1649 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001650 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001651 false,
1652 Converted))
1653 return true;
1654
1655 // Figure out where to insert this class template partial specialization
1656 // in the member template's set of class template partial specializations.
1657 llvm::FoldingSetNodeID ID;
1658 ClassTemplatePartialSpecializationDecl::Profile(ID,
1659 Converted.getFlatArguments(),
1660 Converted.flatSize(),
1661 SemaRef.Context);
1662 void *InsertPos = 0;
1663 ClassTemplateSpecializationDecl *PrevDecl
1664 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1665 InsertPos);
1666
1667 // Build the canonical type that describes the converted template
1668 // arguments of the class template partial specialization.
1669 QualType CanonType
1670 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1671 Converted.getFlatArguments(),
1672 Converted.flatSize());
1673
1674 // Build the fully-sugared type for this class template
1675 // specialization as the user wrote in the specialization
1676 // itself. This means that we'll pretty-print the type retrieved
1677 // from the specialization's declaration the way that the user
1678 // actually wrote the specialization, rather than formatting the
1679 // name based on the "canonical" representation used to store the
1680 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001681 TypeSourceInfo *WrittenTy
1682 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1683 TemplateName(ClassTemplate),
1684 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001685 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001686 CanonType);
1687
1688 if (PrevDecl) {
1689 // We've already seen a partial specialization with the same template
1690 // parameters and template arguments. This can happen, for example, when
1691 // substituting the outer template arguments ends up causing two
1692 // class template partial specializations of a member class template
1693 // to have identical forms, e.g.,
1694 //
1695 // template<typename T, typename U>
1696 // struct Outer {
1697 // template<typename X, typename Y> struct Inner;
1698 // template<typename Y> struct Inner<T, Y>;
1699 // template<typename Y> struct Inner<U, Y>;
1700 // };
1701 //
1702 // Outer<int, int> outer; // error: the partial specializations of Inner
1703 // // have the same signature.
1704 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1705 << WrittenTy;
1706 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1707 << SemaRef.Context.getTypeDeclType(PrevDecl);
1708 return true;
1709 }
1710
1711
1712 // Create the class template partial specialization declaration.
1713 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1714 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1715 PartialSpec->getLocation(),
1716 InstParams,
1717 ClassTemplate,
1718 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001719 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001720 CanonType,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001721 0);
John McCallb6217662010-03-15 10:12:16 +00001722 // Substitute the nested name specifier, if any.
1723 if (SubstQualifier(PartialSpec, InstPartialSpec))
1724 return 0;
1725
Douglas Gregored9c0f92009-10-29 00:04:11 +00001726 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1727 InstPartialSpec->setTypeAsWritten(WrittenTy);
1728
1729 // Add this partial specialization to the set of class template partial
1730 // specializations.
1731 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1732 InsertPos);
1733 return false;
1734}
1735
John McCall21ef0fa2010-03-11 09:03:00 +00001736bool
1737Sema::CheckInstantiatedParams(llvm::SmallVectorImpl<ParmVarDecl*> &Params) {
1738 bool Invalid = false;
1739 for (unsigned i = 0, i_end = Params.size(); i != i_end; ++i)
1740 if (ParmVarDecl *PInst = Params[i]) {
1741 if (PInst->isInvalidDecl())
1742 Invalid = true;
1743 else if (PInst->getType()->isVoidType()) {
1744 Diag(PInst->getLocation(), diag::err_param_with_void_type);
1745 PInst->setInvalidDecl();
1746 Invalid = true;
1747 }
1748 else if (RequireNonAbstractType(PInst->getLocation(),
1749 PInst->getType(),
1750 diag::err_abstract_type_in_decl,
1751 Sema::AbstractParamType)) {
1752 PInst->setInvalidDecl();
1753 Invalid = true;
1754 }
1755 }
1756 return Invalid;
1757}
Douglas Gregor5545e162009-03-24 00:38:23 +00001758
John McCall21ef0fa2010-03-11 09:03:00 +00001759TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001760TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001761 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001762 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1763 assert(OldTInfo && "substituting function without type source info");
1764 assert(Params.empty() && "parameter vector is non-empty at start");
1765 TypeSourceInfo *NewTInfo = SemaRef.SubstType(OldTInfo, TemplateArgs,
1766 D->getTypeSpecStartLoc(),
1767 D->getDeclName());
1768 if (!NewTInfo)
1769 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001770
John McCall21ef0fa2010-03-11 09:03:00 +00001771 // Get parameters from the new type info.
1772 TypeLoc NewTL = NewTInfo->getTypeLoc();
1773 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1774 assert(NewProtoLoc && "Missing prototype?");
1775 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1776 Params.push_back(NewProtoLoc->getArg(i));
Douglas Gregor5545e162009-03-24 00:38:23 +00001777
John McCall21ef0fa2010-03-11 09:03:00 +00001778 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001779}
1780
Mike Stump1eb44332009-09-09 15:08:12 +00001781/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001782/// declaration (New) from the corresponding fields of its template (Tmpl).
1783///
1784/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001785bool
1786TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001787 FunctionDecl *Tmpl) {
1788 if (Tmpl->isDeleted())
1789 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Douglas Gregorcca9e962009-07-01 22:01:06 +00001791 // If we are performing substituting explicitly-specified template arguments
1792 // or deduced template arguments into a function template and we reach this
1793 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001794 // to keeping the new function template specialization. We therefore
1795 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001796 // into a template instantiation for this specific function template
1797 // specialization, which is not a SFINAE context, so that we diagnose any
1798 // further errors in the declaration itself.
1799 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1800 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1801 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1802 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001803 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001804 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001805 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001806 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001807 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001808 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1809 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001810 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001811 }
1812 }
Mike Stump1eb44332009-09-09 15:08:12 +00001813
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001814 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1815 assert(Proto && "Function template without prototype?");
1816
1817 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1818 Proto->getNoReturnAttr()) {
1819 // The function has an exception specification or a "noreturn"
1820 // attribute. Substitute into each of the exception types.
1821 llvm::SmallVector<QualType, 4> Exceptions;
1822 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1823 // FIXME: Poor location information!
1824 QualType T
1825 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1826 New->getLocation(), New->getDeclName());
1827 if (T.isNull() ||
1828 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1829 continue;
1830
1831 Exceptions.push_back(T);
1832 }
1833
1834 // Rebuild the function type
1835
1836 const FunctionProtoType *NewProto
1837 = New->getType()->getAs<FunctionProtoType>();
1838 assert(NewProto && "Template instantiation without function prototype?");
1839 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1840 NewProto->arg_type_begin(),
1841 NewProto->getNumArgs(),
1842 NewProto->isVariadic(),
1843 NewProto->getTypeQuals(),
1844 Proto->hasExceptionSpec(),
1845 Proto->hasAnyExceptionSpec(),
1846 Exceptions.size(),
1847 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001848 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001849 }
1850
Douglas Gregore53060f2009-06-25 22:08:12 +00001851 return false;
1852}
1853
Douglas Gregor5545e162009-03-24 00:38:23 +00001854/// \brief Initializes common fields of an instantiated method
1855/// declaration (New) from the corresponding fields of its template
1856/// (Tmpl).
1857///
1858/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001859bool
1860TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001861 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001862 if (InitFunctionInstantiation(New, Tmpl))
1863 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001864
Douglas Gregor5545e162009-03-24 00:38:23 +00001865 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1866 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001867 if (Tmpl->isVirtualAsWritten())
1868 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001869
1870 // FIXME: attributes
1871 // FIXME: New needs a pointer to Tmpl
1872 return false;
1873}
Douglas Gregora58861f2009-05-13 20:28:22 +00001874
1875/// \brief Instantiate the definition of the given function from its
1876/// template.
1877///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001878/// \param PointOfInstantiation the point at which the instantiation was
1879/// required. Note that this is not precisely a "point of instantiation"
1880/// for the function, but it's close.
1881///
Douglas Gregora58861f2009-05-13 20:28:22 +00001882/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001883/// function template specialization or member function of a class template
1884/// specialization.
1885///
1886/// \param Recursive if true, recursively instantiates any functions that
1887/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001888///
1889/// \param DefinitionRequired if true, then we are performing an explicit
1890/// instantiation where the body of the function is required. Complain if
1891/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001892void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001893 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001894 bool Recursive,
1895 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001896 if (Function->isInvalidDecl())
1897 return;
1898
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001899 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001900
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001901 // Never instantiate an explicit specialization.
1902 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1903 return;
1904
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001905 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001906 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001907 Stmt *Pattern = 0;
1908 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001909 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001910
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001911 if (!Pattern) {
1912 if (DefinitionRequired) {
1913 if (Function->getPrimaryTemplate())
1914 Diag(PointOfInstantiation,
1915 diag::err_explicit_instantiation_undefined_func_template)
1916 << Function->getPrimaryTemplate();
1917 else
1918 Diag(PointOfInstantiation,
1919 diag::err_explicit_instantiation_undefined_member)
1920 << 1 << Function->getDeclName() << Function->getDeclContext();
1921
1922 if (PatternDecl)
1923 Diag(PatternDecl->getLocation(),
1924 diag::note_explicit_instantiation_here);
1925 }
1926
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001927 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001928 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001929
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001930 // C++0x [temp.explicit]p9:
1931 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001932 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001933 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001934 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001935 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00001936 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001937 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001939 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1940 if (Inst)
1941 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001942
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001943 // If we're performing recursive template instantiation, create our own
1944 // queue of pending implicit instantiations that we will instantiate later,
1945 // while we're still within our own instantiation context.
1946 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1947 if (Recursive)
1948 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00001949
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001950 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1951
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001952 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00001953 // recorded, unless we're actually a member function within a local
1954 // class, in which case we need to merge our results with the parent
1955 // scope (of the enclosing function).
1956 bool MergeWithParentScope = false;
1957 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1958 MergeWithParentScope = Rec->isLocalClass();
1959
1960 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00001961
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001962 // Introduce the instantiated function parameters into the local
1963 // instantiation scope.
1964 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1965 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1966 Function->getParamDecl(I));
1967
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001968 // Enter the scope of this instantiation. We don't use
1969 // PushDeclContext because we don't have a scope.
1970 DeclContext *PreviousContext = CurContext;
1971 CurContext = Function;
1972
Mike Stump1eb44332009-09-09 15:08:12 +00001973 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00001974 getTemplateInstantiationArgs(Function);
1975
1976 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00001977 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00001978 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1979 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1980 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00001981 }
1982
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001983 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00001984 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001985
Douglas Gregor52604ab2009-09-11 21:19:12 +00001986 if (Body.isInvalid())
1987 Function->setInvalidDecl();
1988
Mike Stump1eb44332009-09-09 15:08:12 +00001989 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00001990 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001991
John McCall0c01d182010-03-24 05:22:00 +00001992 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
1993
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00001994 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001995
1996 DeclGroupRef DG(Function);
1997 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00001998
Douglas Gregor60406be2010-01-16 22:29:39 +00001999 // This class may have local implicit instantiations that need to be
2000 // instantiation within this scope.
2001 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2002 Scope.Exit();
2003
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002004 if (Recursive) {
2005 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002006 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002007 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002008
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002009 // Restore the set of pending implicit instantiations.
2010 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2011 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002012}
2013
2014/// \brief Instantiate the definition of the given variable from its
2015/// template.
2016///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002017/// \param PointOfInstantiation the point at which the instantiation was
2018/// required. Note that this is not precisely a "point of instantiation"
2019/// for the function, but it's close.
2020///
2021/// \param Var the already-instantiated declaration of a static member
2022/// variable of a class template specialization.
2023///
2024/// \param Recursive if true, recursively instantiates any functions that
2025/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002026///
2027/// \param DefinitionRequired if true, then we are performing an explicit
2028/// instantiation where an out-of-line definition of the member variable
2029/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002030void Sema::InstantiateStaticDataMemberDefinition(
2031 SourceLocation PointOfInstantiation,
2032 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002033 bool Recursive,
2034 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002035 if (Var->isInvalidDecl())
2036 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Douglas Gregor7caa6822009-07-24 20:34:43 +00002038 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002039 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002040 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002041 assert(Def->isStaticDataMember() && "Not a static data member?");
2042 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002043
Douglas Gregor0d035142009-10-27 18:42:08 +00002044 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002045 // We did not find an out-of-line definition of this static data member,
2046 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002047 // instantiate this definition (or provide a specialization for it) in
2048 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002049 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002050 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002051 Diag(PointOfInstantiation,
2052 diag::err_explicit_instantiation_undefined_member)
2053 << 2 << Var->getDeclName() << Var->getDeclContext();
2054 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2055 }
2056
Douglas Gregor7caa6822009-07-24 20:34:43 +00002057 return;
2058 }
2059
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002060 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002061 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002062 return;
2063
2064 // C++0x [temp.explicit]p9:
2065 // Except for inline functions, other explicit instantiation declarations
2066 // have the effect of suppressing the implicit instantiation of the entity
2067 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002068 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002069 == TSK_ExplicitInstantiationDeclaration)
2070 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002071
Douglas Gregor7caa6822009-07-24 20:34:43 +00002072 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2073 if (Inst)
2074 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002075
Douglas Gregor7caa6822009-07-24 20:34:43 +00002076 // If we're performing recursive template instantiation, create our own
2077 // queue of pending implicit instantiations that we will instantiate later,
2078 // while we're still within our own instantiation context.
2079 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2080 if (Recursive)
2081 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002082
Douglas Gregor7caa6822009-07-24 20:34:43 +00002083 // Enter the scope of this instantiation. We don't use
2084 // PushDeclContext because we don't have a scope.
2085 DeclContext *PreviousContext = CurContext;
2086 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002088 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002089 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002090 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002091 CurContext = PreviousContext;
2092
2093 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002094 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2095 assert(MSInfo && "Missing member specialization information?");
2096 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2097 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002098 DeclGroupRef DG(Var);
2099 Consumer.HandleTopLevelDecl(DG);
2100 }
Mike Stump1eb44332009-09-09 15:08:12 +00002101
Douglas Gregor7caa6822009-07-24 20:34:43 +00002102 if (Recursive) {
2103 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002104 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002105 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002106
Douglas Gregor7caa6822009-07-24 20:34:43 +00002107 // Restore the set of pending implicit instantiations.
2108 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002109 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002110}
Douglas Gregor815215d2009-05-27 05:35:12 +00002111
Anders Carlsson09025312009-08-29 05:16:22 +00002112void
2113Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2114 const CXXConstructorDecl *Tmpl,
2115 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Anders Carlsson09025312009-08-29 05:16:22 +00002117 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002118 bool AnyErrors = false;
2119
Anders Carlsson09025312009-08-29 05:16:22 +00002120 // Instantiate all the initializers.
2121 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002122 InitsEnd = Tmpl->init_end();
2123 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002124 CXXBaseOrMemberInitializer *Init = *Inits;
2125
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002126 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002127 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002128 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002129
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002130 // Instantiate the initializer.
2131 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2132 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2133 AnyErrors = true;
2134 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002135 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002136
Anders Carlsson09025312009-08-29 05:16:22 +00002137 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002138 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002139 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002140 TemplateArgs,
2141 Init->getSourceLocation(),
2142 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002143 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002144 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002145 New->setInvalidDecl();
2146 continue;
2147 }
2148
John McCalla93c9342009-12-07 02:54:59 +00002149 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002150 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002151 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002152 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002153 Init->getRParenLoc(),
2154 New->getParent());
2155 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002156 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002157
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002158 // Is this an anonymous union?
2159 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002160 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2161 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002162 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002163 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2164 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002165 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002166
2167 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002168 NewArgs.size(),
2169 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002170 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002171 Init->getRParenLoc());
2172 }
2173
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002174 if (NewInit.isInvalid()) {
2175 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002176 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002177 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002178 // FIXME: It would be nice if ASTOwningVector had a release function.
2179 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002180
Anders Carlsson09025312009-08-29 05:16:22 +00002181 NewInits.push_back((MemInitTy *)NewInit.get());
2182 }
2183 }
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Anders Carlsson09025312009-08-29 05:16:22 +00002185 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002186 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002187 /*FIXME: ColonLoc */
2188 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002189 NewInits.data(), NewInits.size(),
2190 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002191}
2192
John McCall52a575a2009-08-29 08:11:13 +00002193// TODO: this could be templated if the various decl types used the
2194// same method name.
2195static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2196 ClassTemplateDecl *Instance) {
2197 Pattern = Pattern->getCanonicalDecl();
2198
2199 do {
2200 Instance = Instance->getCanonicalDecl();
2201 if (Pattern == Instance) return true;
2202 Instance = Instance->getInstantiatedFromMemberTemplate();
2203 } while (Instance);
2204
2205 return false;
2206}
2207
Douglas Gregor0d696532009-09-28 06:34:35 +00002208static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2209 FunctionTemplateDecl *Instance) {
2210 Pattern = Pattern->getCanonicalDecl();
2211
2212 do {
2213 Instance = Instance->getCanonicalDecl();
2214 if (Pattern == Instance) return true;
2215 Instance = Instance->getInstantiatedFromMemberTemplate();
2216 } while (Instance);
2217
2218 return false;
2219}
2220
Douglas Gregored9c0f92009-10-29 00:04:11 +00002221static bool
2222isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2223 ClassTemplatePartialSpecializationDecl *Instance) {
2224 Pattern
2225 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2226 do {
2227 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2228 Instance->getCanonicalDecl());
2229 if (Pattern == Instance)
2230 return true;
2231 Instance = Instance->getInstantiatedFromMember();
2232 } while (Instance);
2233
2234 return false;
2235}
2236
John McCall52a575a2009-08-29 08:11:13 +00002237static bool isInstantiationOf(CXXRecordDecl *Pattern,
2238 CXXRecordDecl *Instance) {
2239 Pattern = Pattern->getCanonicalDecl();
2240
2241 do {
2242 Instance = Instance->getCanonicalDecl();
2243 if (Pattern == Instance) return true;
2244 Instance = Instance->getInstantiatedFromMemberClass();
2245 } while (Instance);
2246
2247 return false;
2248}
2249
2250static bool isInstantiationOf(FunctionDecl *Pattern,
2251 FunctionDecl *Instance) {
2252 Pattern = Pattern->getCanonicalDecl();
2253
2254 do {
2255 Instance = Instance->getCanonicalDecl();
2256 if (Pattern == Instance) return true;
2257 Instance = Instance->getInstantiatedFromMemberFunction();
2258 } while (Instance);
2259
2260 return false;
2261}
2262
2263static bool isInstantiationOf(EnumDecl *Pattern,
2264 EnumDecl *Instance) {
2265 Pattern = Pattern->getCanonicalDecl();
2266
2267 do {
2268 Instance = Instance->getCanonicalDecl();
2269 if (Pattern == Instance) return true;
2270 Instance = Instance->getInstantiatedFromMemberEnum();
2271 } while (Instance);
2272
2273 return false;
2274}
2275
John McCalled976492009-12-04 22:46:56 +00002276static bool isInstantiationOf(UsingShadowDecl *Pattern,
2277 UsingShadowDecl *Instance,
2278 ASTContext &C) {
2279 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2280}
2281
2282static bool isInstantiationOf(UsingDecl *Pattern,
2283 UsingDecl *Instance,
2284 ASTContext &C) {
2285 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2286}
2287
John McCall7ba107a2009-11-18 02:36:19 +00002288static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2289 UsingDecl *Instance,
2290 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002291 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002292}
2293
2294static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002295 UsingDecl *Instance,
2296 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002297 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002298}
2299
John McCall52a575a2009-08-29 08:11:13 +00002300static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2301 VarDecl *Instance) {
2302 assert(Instance->isStaticDataMember());
2303
2304 Pattern = Pattern->getCanonicalDecl();
2305
2306 do {
2307 Instance = Instance->getCanonicalDecl();
2308 if (Pattern == Instance) return true;
2309 Instance = Instance->getInstantiatedFromStaticDataMember();
2310 } while (Instance);
2311
2312 return false;
2313}
2314
John McCalled976492009-12-04 22:46:56 +00002315// Other is the prospective instantiation
2316// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002317static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002318 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002319 if (UnresolvedUsingTypenameDecl *UUD
2320 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2321 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2322 return isInstantiationOf(UUD, UD, Ctx);
2323 }
2324 }
2325
2326 if (UnresolvedUsingValueDecl *UUD
2327 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002328 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2329 return isInstantiationOf(UUD, UD, Ctx);
2330 }
2331 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002332
Anders Carlsson0d8df782009-08-29 19:37:28 +00002333 return false;
2334 }
Mike Stump1eb44332009-09-09 15:08:12 +00002335
John McCall52a575a2009-08-29 08:11:13 +00002336 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2337 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002338
John McCall52a575a2009-08-29 08:11:13 +00002339 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2340 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002341
John McCall52a575a2009-08-29 08:11:13 +00002342 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2343 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002344
Douglas Gregor7caa6822009-07-24 20:34:43 +00002345 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002346 if (Var->isStaticDataMember())
2347 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2348
2349 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2350 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002351
Douglas Gregor0d696532009-09-28 06:34:35 +00002352 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2353 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2354
Douglas Gregored9c0f92009-10-29 00:04:11 +00002355 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2356 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2357 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2358 PartialSpec);
2359
Anders Carlssond8b285f2009-09-01 04:26:58 +00002360 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2361 if (!Field->getDeclName()) {
2362 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002363 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002364 cast<FieldDecl>(D);
2365 }
2366 }
Mike Stump1eb44332009-09-09 15:08:12 +00002367
John McCalled976492009-12-04 22:46:56 +00002368 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2369 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2370
2371 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2372 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2373
Douglas Gregor815215d2009-05-27 05:35:12 +00002374 return D->getDeclName() && isa<NamedDecl>(Other) &&
2375 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2376}
2377
2378template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002379static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002380 NamedDecl *D,
2381 ForwardIterator first,
2382 ForwardIterator last) {
2383 for (; first != last; ++first)
2384 if (isInstantiationOf(Ctx, D, *first))
2385 return cast<NamedDecl>(*first);
2386
2387 return 0;
2388}
2389
John McCall02cace72009-08-28 07:59:38 +00002390/// \brief Finds the instantiation of the given declaration context
2391/// within the current instantiation.
2392///
2393/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002394DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002395 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002396 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002397 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002398 return cast_or_null<DeclContext>(ID);
2399 } else return DC;
2400}
2401
Douglas Gregored961e72009-05-27 17:54:46 +00002402/// \brief Find the instantiation of the given declaration within the
2403/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002404///
2405/// This routine is intended to be used when \p D is a declaration
2406/// referenced from within a template, that needs to mapped into the
2407/// corresponding declaration within an instantiation. For example,
2408/// given:
2409///
2410/// \code
2411/// template<typename T>
2412/// struct X {
2413/// enum Kind {
2414/// KnownValue = sizeof(T)
2415/// };
2416///
2417/// bool getKind() const { return KnownValue; }
2418/// };
2419///
2420/// template struct X<int>;
2421/// \endcode
2422///
2423/// In the instantiation of X<int>::getKind(), we need to map the
2424/// EnumConstantDecl for KnownValue (which refers to
2425/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002426/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2427/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002428NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002429 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002430 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002431 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002432 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002433 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002434 // D is a local of some kind. Look into the map of local
2435 // declarations to their instantiations.
2436 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2437 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002438
Douglas Gregore95b4092009-09-16 18:34:49 +00002439 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2440 if (!Record->isDependentContext())
2441 return D;
2442
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002443 // If the RecordDecl is actually the injected-class-name or a
2444 // "templated" declaration for a class template, class template
2445 // partial specialization, or a member class of a class template,
2446 // substitute into the injected-class-name of the class template
2447 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002448 QualType T;
2449 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2450
2451 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002452 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002453 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2454 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002455 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002456
2457 // If we call SubstType with an InjectedClassNameType here we
2458 // can end up in an infinite loop.
2459 T = Context.getTypeDeclType(Record);
2460 assert(isa<InjectedClassNameType>(T) &&
2461 "type of partial specialization is not an InjectedClassNameType");
2462 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2463 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002464
2465 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002466 // Substitute into the injected-class-name to get the type
2467 // corresponding to the instantiation we want, which may also be
2468 // the current instantiation (if we're in a template
2469 // definition). This substitution should never fail, since we
2470 // know we can instantiate the injected-class-name or we
2471 // wouldn't have gotten to the injected-class-name!
2472
2473 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2474 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002475 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2476 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2477
2478 if (!T->isDependentType()) {
2479 assert(T->isRecordType() && "Instantiation must produce a record type");
2480 return T->getAs<RecordType>()->getDecl();
2481 }
2482
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002483 // We are performing "partial" template instantiation to create
2484 // the member declarations for the members of a class template
2485 // specialization. Therefore, D is actually referring to something
2486 // in the current instantiation. Look through the current
2487 // context, which contains actual instantiations, to find the
2488 // instantiation of the "current instantiation" that D refers
2489 // to.
2490 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002491 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002492 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002493 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002494 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002495 if (isInstantiationOf(ClassTemplate,
2496 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002497 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002498
2499 if (!DC->isDependentContext())
2500 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002501 }
2502
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002503 // We're performing "instantiation" of a member of the current
2504 // instantiation while we are type-checking the
2505 // definition. Compute the declaration context and return that.
2506 assert(!SawNonDependentContext &&
2507 "No dependent context while instantiating record");
2508 DeclContext *DC = computeDeclContext(T);
2509 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002510 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002511 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002512 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002513
Douglas Gregore95b4092009-09-16 18:34:49 +00002514 // Fall through to deal with other dependent record types (e.g.,
2515 // anonymous unions in class templates).
2516 }
John McCall52a575a2009-08-29 08:11:13 +00002517
Douglas Gregore95b4092009-09-16 18:34:49 +00002518 if (!ParentDC->isDependentContext())
2519 return D;
2520
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002521 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002522 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002523 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002524
Douglas Gregor815215d2009-05-27 05:35:12 +00002525 if (ParentDC != D->getDeclContext()) {
2526 // We performed some kind of instantiation in the parent context,
2527 // so now we need to look into the instantiated parent context to
2528 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002529
John McCall3cb0ebd2010-03-10 03:28:59 +00002530 // If our context used to be dependent, we may need to instantiate
2531 // it before performing lookup into that context.
2532 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002533 if (!Spec->isDependentContext()) {
2534 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002535 const RecordType *Tag = T->getAs<RecordType>();
2536 assert(Tag && "type of non-dependent record is not a RecordType");
2537 if (!Tag->isBeingDefined() &&
2538 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2539 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002540 }
2541 }
2542
Douglas Gregor815215d2009-05-27 05:35:12 +00002543 NamedDecl *Result = 0;
2544 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002545 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002546 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2547 } else {
2548 // Since we don't have a name for the entity we're looking for,
2549 // our only option is to walk through all of the declarations to
2550 // find that name. This will occur in a few cases:
2551 //
2552 // - anonymous struct/union within a template
2553 // - unnamed class/struct/union/enum within a template
2554 //
2555 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002556 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002557 ParentDC->decls_begin(),
2558 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002559 }
Mike Stump1eb44332009-09-09 15:08:12 +00002560
John McCall9f54ad42009-12-10 09:41:52 +00002561 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002562 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2563 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002564 && "Unable to find instantiation of declaration!");
2565
Douglas Gregor815215d2009-05-27 05:35:12 +00002566 D = Result;
2567 }
2568
Douglas Gregor815215d2009-05-27 05:35:12 +00002569 return D;
2570}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002571
Mike Stump1eb44332009-09-09 15:08:12 +00002572/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002573/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002574void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2575 while (!PendingLocalImplicitInstantiations.empty() ||
2576 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2577 PendingImplicitInstantiation Inst;
2578
2579 if (PendingLocalImplicitInstantiations.empty()) {
2580 Inst = PendingImplicitInstantiations.front();
2581 PendingImplicitInstantiations.pop_front();
2582 } else {
2583 Inst = PendingLocalImplicitInstantiations.front();
2584 PendingLocalImplicitInstantiations.pop_front();
2585 }
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Douglas Gregor7caa6822009-07-24 20:34:43 +00002587 // Instantiate function definitions
2588 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002589 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002590 Function->getLocation(), *this,
2591 Context.getSourceManager(),
2592 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002594 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002595 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002596 continue;
2597 }
Mike Stump1eb44332009-09-09 15:08:12 +00002598
Douglas Gregor7caa6822009-07-24 20:34:43 +00002599 // Instantiate static data member definitions.
2600 VarDecl *Var = cast<VarDecl>(Inst.first);
2601 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002602
Chandler Carruth291b4412010-02-13 10:17:50 +00002603 // Don't try to instantiate declarations if the most recent redeclaration
2604 // is invalid.
2605 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2606 continue;
2607
2608 // Check if the most recent declaration has changed the specialization kind
2609 // and removed the need for implicit instantiation.
2610 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2611 case TSK_Undeclared:
2612 assert(false && "Cannot instantitiate an undeclared specialization.");
2613 case TSK_ExplicitInstantiationDeclaration:
2614 case TSK_ExplicitInstantiationDefinition:
2615 case TSK_ExplicitSpecialization:
2616 continue; // No longer need implicit instantiation.
2617 case TSK_ImplicitInstantiation:
2618 break;
2619 }
2620
Mike Stump1eb44332009-09-09 15:08:12 +00002621 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002622 Var->getLocation(), *this,
2623 Context.getSourceManager(),
2624 "instantiating static data member "
2625 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002626
Douglas Gregor7caa6822009-07-24 20:34:43 +00002627 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002628 }
2629}
John McCall0c01d182010-03-24 05:22:00 +00002630
2631void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2632 const MultiLevelTemplateArgumentList &TemplateArgs) {
2633 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2634 E = Pattern->ddiag_end(); I != E; ++I) {
2635 DependentDiagnostic *DD = *I;
2636
2637 switch (DD->getKind()) {
2638 case DependentDiagnostic::Access:
2639 HandleDependentAccessCheck(*DD, TemplateArgs);
2640 break;
2641 }
2642 }
2643}