blob: 9777569b31872a8e211bf509a39e7a3951a48d9d [file] [log] [blame]
Douglas Gregord7e7a512009-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 McCall5cebab12009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCallc62bb642010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregor6131b442009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall58f10c32010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Anders Carlsson62215c42009-09-01 05:12:24 +000022#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor402250f2009-08-26 21:14:46 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregord7e7a512009-03-17 21:15:40 +000024
25using namespace clang;
26
27namespace {
Benjamin Kramer337e3a52009-11-28 19:45:26 +000028 class TemplateDeclInstantiator
Chris Lattner83f095c2009-03-28 19:18:32 +000029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregord7e7a512009-03-17 21:15:40 +000030 Sema &SemaRef;
31 DeclContext *Owner;
Douglas Gregor01afeef2009-08-28 20:31:08 +000032 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump11289f42009-09-09 15:08:12 +000033
Anders Carlsson3d709752009-11-07 06:07:58 +000034 void InstantiateAttrs(Decl *Tmpl, Decl *New);
35
Douglas Gregord7e7a512009-03-17 21:15:40 +000036 public:
37 typedef Sema::OwningExprResult OwningExprResult;
38
39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +000040 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregord002c7b2009-05-11 23:53:27 +000041 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump11289f42009-09-09 15:08:12 +000042
Mike Stump87c57ac2009-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 Gregor8a655532009-03-25 15:45:12 +000046 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
47 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCalld8d0d432010-02-16 06:53:13 +000048 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregord7e7a512009-03-17 21:15:40 +000049 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregoref1a09a2009-03-25 23:32:15 +000050 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregord7e7a512009-03-17 21:15:40 +000051 Decl *VisitFieldDecl(FieldDecl *D);
52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
53 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor9106b822009-03-25 15:04:13 +000054 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCallaa74a0c2009-08-28 07:59:38 +000055 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregor3a88c1d2009-10-13 14:39:41 +000056 Decl *VisitFunctionDecl(FunctionDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +000058 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregore704c9d2009-08-27 16:57:43 +000059 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
60 TemplateParameterList *TemplateParams = 0);
Douglas Gregor4044d992009-03-24 16:43:20 +000061 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor654b07e2009-03-24 00:15:49 +000062 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregor1880ba52009-03-25 00:34:44 +000063 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor9106b822009-03-25 15:04:13 +000064 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCall87a44eb2009-08-20 01:44:21 +000065 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregore4b05162009-10-07 17:21:34 +000066 Decl *VisitClassTemplatePartialSpecializationDecl(
67 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregore704c9d2009-08-27 16:57:43 +000068 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCall87a44eb2009-08-20 01:44:21 +000069 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor6b815c82009-10-23 23:25:44 +000070 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor38fee962009-11-11 16:58:32 +000071 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregore0b28662009-11-17 06:07:40 +000072 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCallb96ec562009-12-04 22:46:56 +000073 Decl *VisitUsingDecl(UsingDecl *D);
74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCalle61f2ba2009-11-18 02:36:19 +000075 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump11289f42009-09-09 15:08:12 +000077
Douglas Gregord7e7a512009-03-17 21:15:40 +000078 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregore0b28662009-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 Gregord7e7a512009-03-17 21:15:40 +000086 return 0;
87 }
Douglas Gregor21342092009-03-24 00:38:23 +000088
John McCall58de3582009-08-14 02:03:10 +000089 const LangOptions &getLangOptions() {
90 return SemaRef.getLangOptions();
91 }
92
Douglas Gregor21342092009-03-24 00:38:23 +000093 // Helper functions for instantiating methods.
John McCall58f10c32010-03-11 09:03:00 +000094 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor21342092009-03-24 00:38:23 +000095 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +000096 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor21342092009-03-24 00:38:23 +000097 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCall87a44eb2009-08-20 01:44:21 +000098
99 TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +0000100 SubstTemplateParams(TemplateParameterList *List);
John McCall3e11ebe2010-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 Gregor21610382009-10-29 00:04:11 +0000106
107 bool InstantiateClassTemplatePartialSpecialization(
108 ClassTemplateDecl *ClassTemplate,
109 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000110 };
111}
112
John McCall3e11ebe2010-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 Carlsson3d709752009-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 Gregor8a655532009-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 McCalld8d0d432010-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 Gregord7e7a512009-03-17 21:15:40 +0000184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
185 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000186 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall703a3f82009-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 Gregord7e7a512009-03-17 21:15:40 +0000191 Invalid = true;
John McCallbcd03502009-12-07 02:54:59 +0000192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000193 }
194 }
Mike Stump11289f42009-09-09 15:08:12 +0000195
Douglas Gregord7e7a512009-03-17 21:15:40 +0000196 // Create the new typedef
197 TypedefDecl *Typedef
198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCall703a3f82009-10-24 08:00:42 +0000199 D->getIdentifier(), DI);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000200 if (Invalid)
201 Typedef->setInvalidDecl();
202
John McCall91f1a022009-12-30 00:31:22 +0000203 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000204 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
205 TemplateArgs);
John McCall91f1a022009-12-30 00:31:22 +0000206 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
207 }
208
John McCall401982f2010-01-20 21:53:11 +0000209 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000210 Owner->addDecl(Typedef);
Mike Stump11289f42009-09-09 15:08:12 +0000211
Douglas Gregord7e7a512009-03-17 21:15:40 +0000212 return Typedef;
213}
214
Douglas Gregord196a582009-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 Gregorb30f22b2010-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 Gregordc764032010-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 Gregorb30f22b2010-03-02 07:38:39 +0000296
Douglas Gregordc764032010-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 Gregorb30f22b2010-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 Gregoref1a09a2009-03-25 23:32:15 +0000312Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000313 // Do substitution on the type of the declaration
John McCallbcd03502009-12-07 02:54:59 +0000314 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCallf1abcdc2009-10-21 02:39:02 +0000315 TemplateArgs,
316 D->getTypeSpecStartLoc(),
317 D->getDeclName());
318 if (!DI)
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000319 return 0;
320
Douglas Gregor923feac2009-05-15 00:01:03 +0000321 // Build the instantiated declaration
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000322 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
323 D->getLocation(), D->getIdentifier(),
John McCallf1abcdc2009-10-21 02:39:02 +0000324 DI->getType(), DI,
Argyrios Kyrtzidis6032ef12009-08-21 00:31:54 +0000325 D->getStorageClass());
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000326 Var->setThreadSpecified(D->isThreadSpecified());
327 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
328 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump11289f42009-09-09 15:08:12 +0000329
John McCall3e11ebe2010-03-15 10:12:16 +0000330 // Substitute the nested name specifier, if any.
331 if (SubstQualifier(D, Var))
332 return 0;
333
Mike Stump11289f42009-09-09 15:08:12 +0000334 // If we are instantiating a static data member defined
Douglas Gregora6ef8f02009-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 Stump11289f42009-09-09 15:08:12 +0000339
John McCall401982f2010-01-20 21:53:11 +0000340 Var->setAccess(D->getAccess());
341
Mike Stump87c57ac2009-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 Gregoref1a09a2009-03-25 23:32:15 +0000344 bool Redeclaration = false;
John McCall1f82f242009-11-18 22:49:29 +0000345 // FIXME: having to fake up a LookupResult is dumb.
346 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor79e31db2010-03-01 19:11:54 +0000347 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregore6565622010-02-09 07:26:29 +0000348 if (D->isStaticDataMember())
349 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall1f82f242009-11-18 22:49:29 +0000350 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump11289f42009-09-09 15:08:12 +0000351
Douglas Gregora6ef8f02009-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 Stump11289f42009-09-09 15:08:12 +0000358
Douglas Gregor86d142a2009-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 Gregor0840cc02009-11-01 20:32:48 +0000363 TSK_ImplicitInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +0000364
Douglas Gregore6565622010-02-09 07:26:29 +0000365 if (Var->getAnyInitializer()) {
366 // We already have an initializer in the class.
367 } else if (D->getInit()) {
Douglas Gregor580cd4a2009-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 Gregorb30f22b2010-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 Gregord196a582009-12-14 19:27:10 +0000381 // Add the direct initializer to the declaration.
Douglas Gregor6131b442009-12-12 18:16:41 +0000382 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregorb30f22b2010-03-02 07:38:39 +0000383 LParenLoc,
Douglas Gregord196a582009-12-14 19:27:10 +0000384 move_arg(InitArgs),
385 CommaLocs.data(),
Douglas Gregorb30f22b2010-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 Gregord196a582009-12-14 19:27:10 +0000395 }
Douglas Gregord196a582009-12-14 19:27:10 +0000396 } else {
Douglas Gregorb30f22b2010-03-02 07:38:39 +0000397 // FIXME: Not too happy about invalidating the declaration
398 // because of a bogus initializer.
399 Var->setInvalidDecl();
Douglas Gregord196a582009-12-14 19:27:10 +0000400 }
401
Douglas Gregor580cd4a2009-12-03 17:10:37 +0000402 SemaRef.PopExpressionEvaluationContext();
Douglas Gregord6129972009-07-27 17:43:39 +0000403 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
404 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregoref1a09a2009-03-25 23:32:15 +0000405
406 return Var;
407}
408
Douglas Gregord7e7a512009-03-17 21:15:40 +0000409Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
410 bool Invalid = false;
John McCallbcd03502009-12-07 02:54:59 +0000411 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall90459c52009-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 McCallbcd03502009-12-07 02:54:59 +0000416 DI = D->getTypeSourceInfo();
John McCall90459c52009-10-22 23:33:21 +0000417 Invalid = true;
418 } else if (DI->getType()->isFunctionType()) {
Douglas Gregord7e7a512009-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 McCall90459c52009-10-22 23:33:21 +0000426 << DI->getType();
Douglas Gregord7e7a512009-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 Gregor0b6a6242009-06-22 20:57:11 +0000435 // The bit-width expression is not potentially evaluated.
436 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000437
Douglas Gregord7e7a512009-03-17 21:15:40 +0000438 OwningExprResult InstantiatedBitWidth
John McCall76d824f2009-08-25 22:02:44 +0000439 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000440 if (InstantiatedBitWidth.isInvalid()) {
441 Invalid = true;
442 BitWidth = 0;
443 } else
Anders Carlssonb781bcd2009-05-01 19:49:17 +0000444 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000445 }
446
John McCall90459c52009-10-22 23:33:21 +0000447 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
448 DI->getType(), DI,
Mike Stump11289f42009-09-09 15:08:12 +0000449 cast<RecordDecl>(Owner),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000450 D->getLocation(),
451 D->isMutable(),
452 BitWidth,
Steve Naroff5ec6ff72009-07-14 14:58:18 +0000453 D->getTypeSpecStartLoc(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000454 D->getAccess(),
455 0);
Douglas Gregor3c74d412009-10-14 20:14:33 +0000456 if (!Field) {
457 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000458 return 0;
Douglas Gregor3c74d412009-10-14 20:14:33 +0000459 }
Mike Stump11289f42009-09-09 15:08:12 +0000460
Anders Carlsson3d709752009-11-07 06:07:58 +0000461 InstantiateAttrs(D, Field);
462
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000463 if (Invalid)
464 Field->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000465
Anders Carlsson2e56cc62009-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 Gregord7e7a512009-03-17 21:15:40 +0000469 }
Mike Stump11289f42009-09-09 15:08:12 +0000470
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000471 Field->setImplicit(D->isImplicit());
John McCall401982f2010-01-20 21:53:11 +0000472 Field->setAccess(D->getAccess());
Anders Carlsson2e56cc62009-09-02 19:17:55 +0000473 Owner->addDecl(Field);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000474
475 return Field;
476}
477
John McCallaa74a0c2009-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 McCall15ad0962010-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 McCallaa74a0c2009-08-28 07:59:38 +0000488
John McCall15ad0962010-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 McCallaa74a0c2009-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 Gregor3a88c1d2009-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 McCall90d3bb92009-12-17 23:21:11 +0000503 Decl *NewND;
504
505 // Hack to make this work almost well pending a rewrite.
John McCall2f88d7d2010-03-27 05:57:59 +0000506 if (D->wasSpecialization()) {
Douglas Gregor33636e62009-12-24 20:56:24 +0000507 // Totally egregious hack to work around PR5866
508 return 0;
John McCall598b4402010-03-25 06:39:04 +0000509 } else {
John McCall90d3bb92009-12-17 23:21:11 +0000510 NewND = Visit(ND);
John McCall598b4402010-03-25 06:39:04 +0000511 }
John McCallaa74a0c2009-08-28 07:59:38 +0000512 if (!NewND) return 0;
513
514 FU = cast<NamedDecl>(NewND);
John McCall58de3582009-08-14 02:03:10 +0000515 }
Mike Stump11289f42009-09-09 15:08:12 +0000516
John McCallaa74a0c2009-08-28 07:59:38 +0000517 FriendDecl *FD =
518 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(), FU,
519 D->getFriendLoc());
John McCall75c03bb2009-08-29 03:50:18 +0000520 FD->setAccess(AS_public);
John McCallaa74a0c2009-08-28 07:59:38 +0000521 Owner->addDecl(FD);
522 return FD;
John McCall58de3582009-08-14 02:03:10 +0000523}
524
Douglas Gregord7e7a512009-03-17 21:15:40 +0000525Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
526 Expr *AssertExpr = D->getAssertExpr();
Mike Stump11289f42009-09-09 15:08:12 +0000527
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000528 // The expression in a static assertion is not potentially evaluated.
529 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000530
Douglas Gregord7e7a512009-03-17 21:15:40 +0000531 OwningExprResult InstantiatedAssertExpr
John McCall76d824f2009-08-25 22:02:44 +0000532 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000533 if (InstantiatedAssertExpr.isInvalid())
534 return 0;
535
Douglas Gregor2c742022009-08-08 01:41:12 +0000536 OwningExprResult Message(SemaRef, D->getMessage());
537 D->getMessage()->Retain();
Mike Stump11289f42009-09-09 15:08:12 +0000538 Decl *StaticAssert
539 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattner83f095c2009-03-28 19:18:32 +0000540 move(InstantiatedAssertExpr),
541 move(Message)).getAs<Decl>();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000542 return StaticAssert;
543}
544
545Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +0000546 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregord7e7a512009-03-17 21:15:40 +0000547 D->getLocation(), D->getIdentifier(),
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000548 D->getTagKeywordLoc(),
Douglas Gregord7e7a512009-03-17 21:15:40 +0000549 /*PrevDecl=*/0);
Douglas Gregor7a749382009-05-27 17:20:35 +0000550 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor6c2adff2009-03-25 22:00:53 +0000551 Enum->setAccess(D->getAccess());
John McCall3e11ebe2010-03-15 10:12:16 +0000552 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000553 Owner->addDecl(Enum);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000554 Enum->startDefinition();
555
Douglas Gregoraff9c1a2010-03-01 19:00:07 +0000556 if (D->getDeclContext()->isFunctionOrMethod())
557 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
558
Douglas Gregor6181ded2009-05-29 18:27:38 +0000559 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregord7e7a512009-03-17 21:15:40 +0000560
561 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000562 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
563 ECEnd = D->enumerator_end();
Douglas Gregord7e7a512009-03-17 21:15:40 +0000564 EC != ECEnd; ++EC) {
565 // The specified value for the enumerator.
566 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000567 if (Expr *UninstValue = EC->getInitExpr()) {
568 // The enumerator's value expression is not potentially evaluated.
Mike Stump11289f42009-09-09 15:08:12 +0000569 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000570 Action::Unevaluated);
Mike Stump11289f42009-09-09 15:08:12 +0000571
John McCall76d824f2009-08-25 22:02:44 +0000572 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000573 }
Douglas Gregord7e7a512009-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 Stump11289f42009-09-09 15:08:12 +0000582 EnumConstantDecl *EnumConst
Douglas Gregord7e7a512009-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 McCallf9b528c2010-01-23 22:37:59 +0000594 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000595 Enum->addDecl(EnumConst);
Chris Lattner83f095c2009-03-28 19:18:32 +0000596 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregord7e7a512009-03-17 21:15:40 +0000597 LastEnumConst = EnumConst;
Douglas Gregoraff9c1a2010-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 Gregord7e7a512009-03-17 21:15:40 +0000604 }
605 }
Mike Stump11289f42009-09-09 15:08:12 +0000606
Mike Stump6814d1c2009-05-16 07:06:02 +0000607 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanc69169d2009-08-08 14:36:57 +0000608 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stump6814d1c2009-05-16 07:06:02 +0000609 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
610 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanc69169d2009-08-08 14:36:57 +0000611 &Enumerators[0], Enumerators.size(),
612 0, 0);
Douglas Gregord7e7a512009-03-17 21:15:40 +0000613
614 return Enum;
615}
616
Douglas Gregor9106b822009-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 Gregor21610382009-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 McCall87a44eb2009-08-20 01:44:21 +0000637Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall598b4402010-03-25 06:39:04 +0000638 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
639
Douglas Gregor954de172009-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 McCall87a44eb2009-08-20 01:44:21 +0000643 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCall76d824f2009-08-25 22:02:44 +0000644 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000645 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000646 return NULL;
John McCall87a44eb2009-08-20 01:44:21 +0000647
648 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall598b4402010-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)
696 << Pattern->getDeclName() << Pattern->getQualifierRange();
697 return 0;
698 }
699
700 if (PrevClassTemplate) {
701 TemplateParameterList *PrevParams
702 = PrevClassTemplate->getTemplateParameters();
703
704 // Make sure the parameter lists match.
705 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
706 /*Complain=*/true,
707 Sema::TPL_TemplateMatch))
708 return 0;
709
710 // Do some additional validation, then merge default arguments
711 // from the existing declarations.
712 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
713 Sema::TPC_ClassTemplate))
714 return 0;
715 }
716 }
717
John McCall87a44eb2009-08-20 01:44:21 +0000718 CXXRecordDecl *RecordInst
John McCall598b4402010-03-25 06:39:04 +0000719 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCall87a44eb2009-08-20 01:44:21 +0000720 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall598b4402010-03-25 06:39:04 +0000721 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000722 /*DelayTypeCreation=*/true);
John McCall87a44eb2009-08-20 01:44:21 +0000723
John McCall598b4402010-03-25 06:39:04 +0000724 if (Qualifier)
725 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCall3e11ebe2010-03-15 10:12:16 +0000726
John McCall87a44eb2009-08-20 01:44:21 +0000727 ClassTemplateDecl *Inst
John McCall598b4402010-03-25 06:39:04 +0000728 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
729 D->getIdentifier(), InstParams, RecordInst,
730 PrevClassTemplate);
John McCall87a44eb2009-08-20 01:44:21 +0000731 RecordInst->setDescribedClassTemplate(Inst);
John McCall598b4402010-03-25 06:39:04 +0000732 if (isFriend) {
733 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
734 // TODO: do we want to track the instantiation progeny of this
735 // friend target decl?
736 } else {
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000737 Inst->setAccess(D->getAccess());
John McCall598b4402010-03-25 06:39:04 +0000738 Inst->setInstantiatedFromMemberTemplate(D);
739 }
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000740
741 // Trigger creation of the type for the instantiation.
John McCalle78aac42010-03-10 03:28:59 +0000742 SemaRef.Context.getInjectedClassNameType(RecordInst,
743 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
Douglas Gregoref06ccf2009-10-12 23:11:44 +0000744
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000745 // Finish handling of friends.
John McCall598b4402010-03-25 06:39:04 +0000746 if (isFriend) {
747 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000748 return Inst;
Douglas Gregorbb3b46e2009-10-30 22:42:42 +0000749 }
Douglas Gregor412e8bc2009-10-30 21:07:27 +0000750
John McCall401982f2010-01-20 21:53:11 +0000751 Inst->setAccess(D->getAccess());
John McCall87a44eb2009-08-20 01:44:21 +0000752 Owner->addDecl(Inst);
Douglas Gregor21610382009-10-29 00:04:11 +0000753
754 // First, we sort the partial specializations by location, so
755 // that we instantiate them in the order they were declared.
756 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
757 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
758 P = D->getPartialSpecializations().begin(),
759 PEnd = D->getPartialSpecializations().end();
760 P != PEnd; ++P)
761 PartialSpecs.push_back(&*P);
762 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
763 SortDeclByLocation(SemaRef.SourceMgr));
764
765 // Instantiate all of the partial specializations of this member class
766 // template.
767 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
768 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
769
John McCall87a44eb2009-08-20 01:44:21 +0000770 return Inst;
771}
772
Douglas Gregore704c9d2009-08-27 16:57:43 +0000773Decl *
Douglas Gregore4b05162009-10-07 17:21:34 +0000774TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
775 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregor21610382009-10-29 00:04:11 +0000776 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
777
778 // Lookup the already-instantiated declaration in the instantiation
779 // of the class template and return that.
780 DeclContext::lookup_result Found
781 = Owner->lookup(ClassTemplate->getDeclName());
782 if (Found.first == Found.second)
783 return 0;
784
785 ClassTemplateDecl *InstClassTemplate
786 = dyn_cast<ClassTemplateDecl>(*Found.first);
787 if (!InstClassTemplate)
788 return 0;
789
790 Decl *DCanon = D->getCanonicalDecl();
791 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
792 P = InstClassTemplate->getPartialSpecializations().begin(),
793 PEnd = InstClassTemplate->getPartialSpecializations().end();
794 P != PEnd; ++P) {
795 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
796 return &*P;
797 }
798
Douglas Gregore4b05162009-10-07 17:21:34 +0000799 return 0;
800}
801
802Decl *
Douglas Gregore704c9d2009-08-27 16:57:43 +0000803TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor954de172009-10-31 17:21:17 +0000804 // Create a local instantiation scope for this function template, which
805 // will contain the instantiations of the template parameters and then get
806 // merged with the local instantiation scope for the function template
807 // itself.
808 Sema::LocalInstantiationScope Scope(SemaRef);
809
Douglas Gregore704c9d2009-08-27 16:57:43 +0000810 TemplateParameterList *TempParams = D->getTemplateParameters();
811 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump11289f42009-09-09 15:08:12 +0000812 if (!InstParams)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000813 return NULL;
Douglas Gregor21610382009-10-29 00:04:11 +0000814
Douglas Gregor3a88c1d2009-10-13 14:39:41 +0000815 FunctionDecl *Instantiated = 0;
816 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
817 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
818 InstParams));
819 else
820 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
821 D->getTemplatedDecl(),
822 InstParams));
823
824 if (!Instantiated)
Douglas Gregore704c9d2009-08-27 16:57:43 +0000825 return 0;
826
John McCall401982f2010-01-20 21:53:11 +0000827 Instantiated->setAccess(D->getAccess());
828
Mike Stump11289f42009-09-09 15:08:12 +0000829 // Link the instantiated function template declaration to the function
Douglas Gregore704c9d2009-08-27 16:57:43 +0000830 // template from which it was instantiated.
Douglas Gregorca027af2009-10-12 22:27:17 +0000831 FunctionTemplateDecl *InstTemplate
Douglas Gregor3a88c1d2009-10-13 14:39:41 +0000832 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregorca027af2009-10-12 22:27:17 +0000833 InstTemplate->setAccess(D->getAccess());
Douglas Gregor3a88c1d2009-10-13 14:39:41 +0000834 assert(InstTemplate &&
835 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCall2079d0b2009-12-14 23:19:40 +0000836
John McCall30837102010-03-26 23:10:15 +0000837 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
838
John McCall2079d0b2009-12-14 23:19:40 +0000839 // Link the instantiation back to the pattern *unless* this is a
840 // non-definition friend declaration.
841 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCall30837102010-03-26 23:10:15 +0000842 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregor3a88c1d2009-10-13 14:39:41 +0000843 InstTemplate->setInstantiatedFromMemberTemplate(D);
844
John McCall30837102010-03-26 23:10:15 +0000845 // Make declarations visible in the appropriate context.
846 if (!isFriend)
Douglas Gregor3a88c1d2009-10-13 14:39:41 +0000847 Owner->addDecl(InstTemplate);
John McCall30837102010-03-26 23:10:15 +0000848
Douglas Gregore704c9d2009-08-27 16:57:43 +0000849 return InstTemplate;
850}
851
Douglas Gregor8ea8fd42009-03-25 21:17:03 +0000852Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
853 CXXRecordDecl *PrevDecl = 0;
854 if (D->isInjectedClassName())
855 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCalle9f92a02009-12-15 22:29:06 +0000856 else if (D->getPreviousDeclaration()) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000857 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
858 D->getPreviousDeclaration(),
John McCalle9f92a02009-12-15 22:29:06 +0000859 TemplateArgs);
860 if (!Prev) return 0;
861 PrevDecl = cast<CXXRecordDecl>(Prev);
862 }
Douglas Gregor8ea8fd42009-03-25 21:17:03 +0000863
864 CXXRecordDecl *Record
Mike Stump11289f42009-09-09 15:08:12 +0000865 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor82fe3e32009-07-21 14:46:17 +0000866 D->getLocation(), D->getIdentifier(),
867 D->getTagKeywordLoc(), PrevDecl);
John McCall3e11ebe2010-03-15 10:12:16 +0000868
869 // Substitute the nested name specifier, if any.
870 if (SubstQualifier(D, Record))
871 return 0;
872
Douglas Gregor8ea8fd42009-03-25 21:17:03 +0000873 Record->setImplicit(D->isImplicit());
Eli Friedmanbda4ef12009-08-27 19:11:42 +0000874 // FIXME: Check against AS_none is an ugly hack to work around the issue that
875 // the tag decls introduced by friend class declarations don't have an access
876 // specifier. Remove once this area of the code gets sorted out.
877 if (D->getAccess() != AS_none)
878 Record->setAccess(D->getAccess());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +0000879 if (!D->isInjectedClassName())
Douglas Gregorbbe8f462009-10-08 15:14:33 +0000880 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +0000881
John McCallaa74a0c2009-08-28 07:59:38 +0000882 // If the original function was part of a friend declaration,
883 // inherit its namespace state.
884 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
885 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
886
Anders Carlsson5da84842009-09-01 04:26:58 +0000887 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
888
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000889 Owner->addDecl(Record);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +0000890 return Record;
891}
892
John McCallaa74a0c2009-08-28 07:59:38 +0000893/// Normal class members are of more specific types and therefore
894/// don't make it here. This function serves two purposes:
895/// 1) instantiating function templates
896/// 2) substituting friend declarations
897/// FIXME: preserve function definitions in case #2
Douglas Gregor33636e62009-12-24 20:56:24 +0000898Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +0000899 TemplateParameterList *TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +0000900 // Check whether there is already a function template specialization for
901 // this declaration.
902 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
903 void *InsertPos = 0;
John McCall2f88d7d2010-03-27 05:57:59 +0000904 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor8f5d4422009-06-29 20:59:39 +0000905 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +0000906 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000907 TemplateArgs.getInnermost().getFlatArgumentList(),
908 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor00044172009-07-29 16:09:57 +0000909 SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +0000910
911 FunctionTemplateSpecializationInfo *Info
912 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor8f5d4422009-06-29 20:59:39 +0000913 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +0000914
Douglas Gregor8f5d4422009-06-29 20:59:39 +0000915 // If we already have a function template specialization, return it.
916 if (Info)
917 return Info->Function;
918 }
Mike Stump11289f42009-09-09 15:08:12 +0000919
John McCall2f88d7d2010-03-27 05:57:59 +0000920 bool isFriend;
921 if (FunctionTemplate)
922 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
923 else
924 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
925
Douglas Gregorf5974fa2010-01-16 20:21:20 +0000926 bool MergeWithParentScope = (TemplateParams != 0) ||
927 !(isa<Decl>(Owner) &&
928 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
929 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +0000930
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000931 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall58f10c32010-03-11 09:03:00 +0000932 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
933 TInfo = SubstFunctionType(D, Params);
934 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +0000935 return 0;
John McCall58f10c32010-03-11 09:03:00 +0000936 QualType T = TInfo->getType();
John McCall58de3582009-08-14 02:03:10 +0000937
John McCalle0b2ddb2010-03-26 04:53:08 +0000938 NestedNameSpecifier *Qualifier = D->getQualifier();
939 if (Qualifier) {
940 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
941 D->getQualifierRange(),
942 TemplateArgs);
943 if (!Qualifier) return 0;
944 }
945
John McCallce410662010-02-06 01:50:47 +0000946 // If we're instantiating a local function declaration, put the result
947 // in the owner; otherwise we need to find the instantiated context.
948 DeclContext *DC;
949 if (D->getDeclContext()->isFunctionOrMethod())
950 DC = Owner;
John McCalle0b2ddb2010-03-26 04:53:08 +0000951 else if (isFriend && Qualifier) {
952 CXXScopeSpec SS;
953 SS.setScopeRep(Qualifier);
954 SS.setRange(D->getQualifierRange());
955 DC = SemaRef.computeDeclContext(SS);
956 if (!DC) return 0;
957 } else {
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000958 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
959 TemplateArgs);
John McCalle0b2ddb2010-03-26 04:53:08 +0000960 }
John McCallce410662010-02-06 01:50:47 +0000961
John McCallaa74a0c2009-08-28 07:59:38 +0000962 FunctionDecl *Function =
Mike Stump11289f42009-09-09 15:08:12 +0000963 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall58f10c32010-03-11 09:03:00 +0000964 D->getDeclName(), T, TInfo,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +0000965 D->getStorageClass(),
Douglas Gregor35b57532009-10-27 21:01:01 +0000966 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCall3e11ebe2010-03-15 10:12:16 +0000967
John McCalle0b2ddb2010-03-26 04:53:08 +0000968 if (Qualifier)
969 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCall3e11ebe2010-03-15 10:12:16 +0000970
John McCall30837102010-03-26 23:10:15 +0000971 DeclContext *LexicalDC = Owner;
972 if (!isFriend && D->isOutOfLine()) {
973 assert(D->getDeclContext()->isFileContext());
974 LexicalDC = D->getDeclContext();
975 }
976
977 Function->setLexicalDeclContext(LexicalDC);
Mike Stump11289f42009-09-09 15:08:12 +0000978
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000979 // Attach the parameters
980 for (unsigned P = 0; P < Params.size(); ++P)
981 Params[P]->setOwningFunction(Function);
Douglas Gregord5058122010-02-11 01:19:42 +0000982 Function->setParams(Params.data(), Params.size());
John McCallaa74a0c2009-08-28 07:59:38 +0000983
Douglas Gregor3a88c1d2009-10-13 14:39:41 +0000984 if (TemplateParams) {
985 // Our resulting instantiation is actually a function template, since we
986 // are substituting only the outer template parameters. For example, given
987 //
988 // template<typename T>
989 // struct X {
990 // template<typename U> friend void f(T, U);
991 // };
992 //
993 // X<int> x;
994 //
995 // We are instantiating the friend function template "f" within X<int>,
996 // which means substituting int for T, but leaving "f" as a friend function
997 // template.
998 // Build the function template itself.
John McCalle0b2ddb2010-03-26 04:53:08 +0000999 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001000 Function->getLocation(),
1001 Function->getDeclName(),
1002 TemplateParams, Function);
1003 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCall30837102010-03-26 23:10:15 +00001004
1005 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalle0b2ddb2010-03-26 04:53:08 +00001006
1007 if (isFriend && D->isThisDeclarationADefinition()) {
1008 // TODO: should we remember this connection regardless of whether
1009 // the friend declaration provided a body?
1010 FunctionTemplate->setInstantiatedFromMemberTemplate(
1011 D->getDescribedFunctionTemplate());
1012 }
Douglas Gregorffe14e32009-11-14 01:20:54 +00001013 } else if (FunctionTemplate) {
1014 // Record this function template specialization.
Douglas Gregord5058122010-02-11 01:19:42 +00001015 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregorffe14e32009-11-14 01:20:54 +00001016 &TemplateArgs.getInnermost(),
1017 InsertPos);
John McCalle0b2ddb2010-03-26 04:53:08 +00001018 } else if (isFriend && D->isThisDeclarationADefinition()) {
1019 // TODO: should we remember this connection regardless of whether
1020 // the friend declaration provided a body?
1021 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCallaa74a0c2009-08-28 07:59:38 +00001022 }
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001023
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001024 if (InitFunctionInstantiation(Function, D))
1025 Function->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001026
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001027 bool Redeclaration = false;
1028 bool OverloadableAttrRequired = false;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001029
John McCall1f82f242009-11-18 22:49:29 +00001030 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1031 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1032
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001033 if (TemplateParams || !FunctionTemplate) {
1034 // Look only into the namespace where the friend would be declared to
1035 // find a previous declaration. This is the innermost enclosing namespace,
1036 // as described in ActOnFriendFunctionDecl.
John McCall1f82f242009-11-18 22:49:29 +00001037 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001038
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001039 // In C++, the previous declaration we find might be a tag type
1040 // (class or enum). In this case, the new declaration will hide the
1041 // tag type. Note that this does does not apply if we're declaring a
1042 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001043 if (Previous.isSingleTagDecl())
1044 Previous.clear();
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001045 }
1046
John McCall84d87672009-12-10 09:41:52 +00001047 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
1048 false, Redeclaration,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001049 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001050
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001051 // If the original function was part of a friend declaration,
1052 // inherit its namespace state and add it to the owner.
John McCalle0b2ddb2010-03-26 04:53:08 +00001053 if (isFriend) {
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001054 NamedDecl *ToFriendD = 0;
John McCall1f82f242009-11-18 22:49:29 +00001055 NamedDecl *PrevDecl;
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001056 if (TemplateParams) {
1057 ToFriendD = cast<NamedDecl>(FunctionTemplate);
1058 PrevDecl = FunctionTemplate->getPreviousDeclaration();
1059 } else {
1060 ToFriendD = Function;
1061 PrevDecl = Function->getPreviousDeclaration();
1062 }
1063 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
John McCalle0b2ddb2010-03-26 04:53:08 +00001064 DC->makeDeclVisibleInContext(ToFriendD, /*Recoverable=*/ false);
Douglas Gregor3a88c1d2009-10-13 14:39:41 +00001065 }
1066
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001067 return Function;
1068}
1069
Douglas Gregore704c9d2009-08-27 16:57:43 +00001070Decl *
1071TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1072 TemplateParameterList *TemplateParams) {
Douglas Gregor97628d62009-08-21 00:16:32 +00001073 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1074 void *InsertPos = 0;
Douglas Gregore704c9d2009-08-27 16:57:43 +00001075 if (FunctionTemplate && !TemplateParams) {
Mike Stump11289f42009-09-09 15:08:12 +00001076 // We are creating a function template specialization from a function
1077 // template. Check whether there is already a function template
Douglas Gregore704c9d2009-08-27 16:57:43 +00001078 // specialization for this particular set of template arguments.
Douglas Gregor97628d62009-08-21 00:16:32 +00001079 llvm::FoldingSetNodeID ID;
Mike Stump11289f42009-09-09 15:08:12 +00001080 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001081 TemplateArgs.getInnermost().getFlatArgumentList(),
1082 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor97628d62009-08-21 00:16:32 +00001083 SemaRef.Context);
Mike Stump11289f42009-09-09 15:08:12 +00001084
1085 FunctionTemplateSpecializationInfo *Info
1086 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor97628d62009-08-21 00:16:32 +00001087 InsertPos);
Mike Stump11289f42009-09-09 15:08:12 +00001088
Douglas Gregor97628d62009-08-21 00:16:32 +00001089 // If we already have a function template specialization, return it.
1090 if (Info)
1091 return Info->Function;
1092 }
1093
John McCall2f88d7d2010-03-27 05:57:59 +00001094 bool isFriend;
1095 if (FunctionTemplate)
1096 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1097 else
1098 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1099
Douglas Gregorf5974fa2010-01-16 20:21:20 +00001100 bool MergeWithParentScope = (TemplateParams != 0) ||
1101 !(isa<Decl>(Owner) &&
1102 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1103 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor37256522009-05-14 21:44:34 +00001104
Douglas Gregor6181ded2009-05-29 18:27:38 +00001105 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall58f10c32010-03-11 09:03:00 +00001106 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1107 TInfo = SubstFunctionType(D, Params);
1108 if (!TInfo)
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001109 return 0;
John McCall58f10c32010-03-11 09:03:00 +00001110 QualType T = TInfo->getType();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001111
John McCall2f88d7d2010-03-27 05:57:59 +00001112 NestedNameSpecifier *Qualifier = D->getQualifier();
1113 if (Qualifier) {
1114 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1115 D->getQualifierRange(),
1116 TemplateArgs);
1117 if (!Qualifier) return 0;
1118 }
1119
1120 DeclContext *DC = Owner;
1121 if (isFriend) {
1122 if (Qualifier) {
1123 CXXScopeSpec SS;
1124 SS.setScopeRep(Qualifier);
1125 SS.setRange(D->getQualifierRange());
1126 DC = SemaRef.computeDeclContext(SS);
1127 } else {
1128 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1129 D->getDeclContext(),
1130 TemplateArgs);
1131 }
1132 if (!DC) return 0;
1133 }
1134
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001135 // Build the instantiated method declaration.
John McCall2f88d7d2010-03-27 05:57:59 +00001136 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001137 CXXMethodDecl *Method = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001138
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001139 DeclarationName Name = D->getDeclName();
Douglas Gregore8394862009-08-21 22:43:28 +00001140 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001141 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1142 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1143 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump11289f42009-09-09 15:08:12 +00001144 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1145 Constructor->getLocation(),
John McCall58f10c32010-03-11 09:03:00 +00001146 Name, T, TInfo,
Mike Stump11289f42009-09-09 15:08:12 +00001147 Constructor->isExplicit(),
Douglas Gregor35b57532009-10-27 21:01:01 +00001148 Constructor->isInlineSpecified(), false);
Douglas Gregore8394862009-08-21 22:43:28 +00001149 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1150 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1151 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1152 SemaRef.Context.getCanonicalType(ClassTy));
1153 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1154 Destructor->getLocation(), Name,
Douglas Gregor35b57532009-10-27 21:01:01 +00001155 T, Destructor->isInlineSpecified(), false);
Douglas Gregor05155d82009-08-21 23:19:43 +00001156 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump11289f42009-09-09 15:08:12 +00001157 CanQualType ConvTy
Douglas Gregor05155d82009-08-21 23:19:43 +00001158 = SemaRef.Context.getCanonicalType(
John McCall9dd450b2009-09-21 23:43:11 +00001159 T->getAs<FunctionType>()->getResultType());
Douglas Gregor05155d82009-08-21 23:19:43 +00001160 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1161 ConvTy);
1162 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1163 Conversion->getLocation(), Name,
John McCall58f10c32010-03-11 09:03:00 +00001164 T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001165 Conversion->isInlineSpecified(),
Douglas Gregor05155d82009-08-21 23:19:43 +00001166 Conversion->isExplicit());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001167 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001168 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall58f10c32010-03-11 09:03:00 +00001169 D->getDeclName(), T, TInfo,
Douglas Gregor35b57532009-10-27 21:01:01 +00001170 D->isStatic(), D->isInlineSpecified());
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001171 }
Douglas Gregor97628d62009-08-21 00:16:32 +00001172
John McCall2f88d7d2010-03-27 05:57:59 +00001173 if (Qualifier)
1174 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCall3e11ebe2010-03-15 10:12:16 +00001175
Douglas Gregore704c9d2009-08-27 16:57:43 +00001176 if (TemplateParams) {
1177 // Our resulting instantiation is actually a function template, since we
1178 // are substituting only the outer template parameters. For example, given
Mike Stump11289f42009-09-09 15:08:12 +00001179 //
Douglas Gregore704c9d2009-08-27 16:57:43 +00001180 // template<typename T>
1181 // struct X {
1182 // template<typename U> void f(T, U);
1183 // };
1184 //
1185 // X<int> x;
1186 //
1187 // We are instantiating the member template "f" within X<int>, which means
1188 // substituting int for T, but leaving "f" as a member function template.
1189 // Build the function template itself.
1190 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1191 Method->getLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00001192 Method->getDeclName(),
Douglas Gregore704c9d2009-08-27 16:57:43 +00001193 TemplateParams, Method);
John McCall2f88d7d2010-03-27 05:57:59 +00001194 if (isFriend) {
1195 FunctionTemplate->setLexicalDeclContext(Owner);
1196 FunctionTemplate->setObjectOfFriendDecl(true);
1197 } else if (D->isOutOfLine())
Mike Stump11289f42009-09-09 15:08:12 +00001198 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregore704c9d2009-08-27 16:57:43 +00001199 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001200 } else if (FunctionTemplate) {
1201 // Record this function template specialization.
Douglas Gregord5058122010-02-11 01:19:42 +00001202 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregorffe14e32009-11-14 01:20:54 +00001203 &TemplateArgs.getInnermost(),
1204 InsertPos);
John McCall2f88d7d2010-03-27 05:57:59 +00001205 } else if (!isFriend) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00001206 // Record that this is an instantiation of a member function.
Douglas Gregord801b062009-10-07 23:56:10 +00001207 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001208 }
1209
Mike Stump11289f42009-09-09 15:08:12 +00001210 // If we are instantiating a member function defined
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001211 // out-of-line, the instantiation will have the same lexical
1212 // context (which will be a namespace scope) as the template.
John McCall2f88d7d2010-03-27 05:57:59 +00001213 if (isFriend) {
1214 Method->setLexicalDeclContext(Owner);
1215 Method->setObjectOfFriendDecl(true);
1216 } else if (D->isOutOfLine())
Douglas Gregora6ef8f02009-07-24 20:34:43 +00001217 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +00001218
Douglas Gregor21342092009-03-24 00:38:23 +00001219 // Attach the parameters
1220 for (unsigned P = 0; P < Params.size(); ++P)
1221 Params[P]->setOwningFunction(Method);
Douglas Gregord5058122010-02-11 01:19:42 +00001222 Method->setParams(Params.data(), Params.size());
Douglas Gregor21342092009-03-24 00:38:23 +00001223
1224 if (InitMethodInstantiation(Method, D))
1225 Method->setInvalidDecl();
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001226
John McCall1f82f242009-11-18 22:49:29 +00001227 LookupResult Previous(SemaRef, Name, SourceLocation(),
1228 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump11289f42009-09-09 15:08:12 +00001229
John McCall2f88d7d2010-03-27 05:57:59 +00001230 if (!FunctionTemplate || TemplateParams || isFriend) {
1231 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump11289f42009-09-09 15:08:12 +00001232
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001233 // In C++, the previous declaration we find might be a tag type
1234 // (class or enum). In this case, the new declaration will hide the
1235 // tag type. Note that this does does not apply if we're declaring a
1236 // typedef (C++ [dcl.typedef]p4).
John McCall1f82f242009-11-18 22:49:29 +00001237 if (Previous.isSingleTagDecl())
1238 Previous.clear();
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001239 }
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001240
Douglas Gregor05155d82009-08-21 23:19:43 +00001241 bool Redeclaration = false;
1242 bool OverloadableAttrRequired = false;
John McCall84d87672009-12-10 09:41:52 +00001243 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor05155d82009-08-21 23:19:43 +00001244 /*FIXME:*/OverloadableAttrRequired);
1245
Douglas Gregor21920e372009-12-01 17:24:26 +00001246 if (D->isPure())
1247 SemaRef.CheckPureMethod(Method, SourceRange());
1248
John McCall401982f2010-01-20 21:53:11 +00001249 Method->setAccess(D->getAccess());
1250
John McCall2f88d7d2010-03-27 05:57:59 +00001251 if (FunctionTemplate) {
1252 // If there's a function template, let our caller handle it.
1253 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1254 // Don't hide a (potentially) valid declaration with an invalid one.
1255 } else {
1256 NamedDecl *DeclToAdd = (TemplateParams
1257 ? cast<NamedDecl>(FunctionTemplate)
1258 : Method);
1259 if (isFriend)
1260 Record->makeDeclVisibleInContext(DeclToAdd);
1261 else
1262 Owner->addDecl(DeclToAdd);
1263 }
Mike Stump11289f42009-09-09 15:08:12 +00001264
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001265 return Method;
1266}
1267
Douglas Gregor4044d992009-03-24 16:43:20 +00001268Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001269 return VisitCXXMethodDecl(D);
Douglas Gregor4044d992009-03-24 16:43:20 +00001270}
1271
Douglas Gregor654b07e2009-03-24 00:15:49 +00001272Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregore8394862009-08-21 22:43:28 +00001273 return VisitCXXMethodDecl(D);
Douglas Gregor654b07e2009-03-24 00:15:49 +00001274}
1275
Douglas Gregor1880ba52009-03-25 00:34:44 +00001276Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor05155d82009-08-21 23:19:43 +00001277 return VisitCXXMethodDecl(D);
Douglas Gregor1880ba52009-03-25 00:34:44 +00001278}
1279
Douglas Gregor9106b822009-03-25 15:04:13 +00001280ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall856bbea2009-10-23 21:48:59 +00001281 QualType T;
John McCallbcd03502009-12-07 02:54:59 +00001282 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall856bbea2009-10-23 21:48:59 +00001283 if (DI) {
1284 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1285 D->getDeclName());
1286 if (DI) T = DI->getType();
1287 } else {
1288 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1289 D->getDeclName());
1290 DI = 0;
1291 }
1292
1293 if (T.isNull())
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001294 return 0;
1295
John McCall856bbea2009-10-23 21:48:59 +00001296 T = SemaRef.adjustParameterType(T);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001297
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001298 // Allocate the parameter
John McCall856bbea2009-10-23 21:48:59 +00001299 ParmVarDecl *Param
John McCallf7b2fb52010-01-22 00:28:27 +00001300 = ParmVarDecl::Create(SemaRef.Context,
1301 SemaRef.Context.getTranslationUnitDecl(),
1302 D->getLocation(),
John McCall856bbea2009-10-23 21:48:59 +00001303 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001304
Anders Carlsson4562f1f2009-08-25 03:18:48 +00001305 // Mark the default argument as being uninstantiated.
Douglas Gregorc103ccd2009-09-25 06:56:31 +00001306 if (D->hasUninstantiatedDefaultArg())
1307 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor25a39672009-09-25 07:03:22 +00001308 else if (Expr *Arg = D->getDefaultArg())
1309 Param->setUninstantiatedDefaultArg(Arg);
1310
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001311 // Note: we don't try to instantiate function parameters until after
1312 // we've instantiated the function's type. Therefore, we don't have
1313 // to check for 'void' parameter types here.
Douglas Gregor37256522009-05-14 21:44:34 +00001314 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregorf4f296d2009-03-23 23:06:20 +00001315 return Param;
1316}
1317
John McCall87a44eb2009-08-20 01:44:21 +00001318Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1319 TemplateTypeParmDecl *D) {
1320 // TODO: don't always clone when decls are refcounted.
1321 const Type* T = D->getTypeForDecl();
1322 assert(T->isTemplateTypeParmType());
1323 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump11289f42009-09-09 15:08:12 +00001324
John McCall87a44eb2009-08-20 01:44:21 +00001325 TemplateTypeParmDecl *Inst =
1326 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor954de172009-10-31 17:21:17 +00001327 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCall87a44eb2009-08-20 01:44:21 +00001328 TTPT->getName(),
1329 D->wasDeclaredWithTypename(),
1330 D->isParameterPack());
1331
Douglas Gregor36d7c5f2009-11-09 19:17:50 +00001332 if (D->hasDefaultArgument())
1333 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCall87a44eb2009-08-20 01:44:21 +00001334
Douglas Gregor954de172009-10-31 17:21:17 +00001335 // Introduce this template parameter's instantiation into the instantiation
1336 // scope.
1337 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1338
John McCall87a44eb2009-08-20 01:44:21 +00001339 return Inst;
1340}
1341
Douglas Gregor6b815c82009-10-23 23:25:44 +00001342Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1343 NonTypeTemplateParmDecl *D) {
1344 // Substitute into the type of the non-type template parameter.
1345 QualType T;
John McCallbcd03502009-12-07 02:54:59 +00001346 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor6b815c82009-10-23 23:25:44 +00001347 if (DI) {
1348 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1349 D->getDeclName());
1350 if (DI) T = DI->getType();
1351 } else {
1352 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1353 D->getDeclName());
1354 DI = 0;
1355 }
1356 if (T.isNull())
1357 return 0;
1358
1359 // Check that this type is acceptable for a non-type template parameter.
1360 bool Invalid = false;
1361 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1362 if (T.isNull()) {
1363 T = SemaRef.Context.IntTy;
1364 Invalid = true;
1365 }
1366
1367 NonTypeTemplateParmDecl *Param
1368 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1369 D->getDepth() - 1, D->getPosition(),
1370 D->getIdentifier(), T, DI);
1371 if (Invalid)
1372 Param->setInvalidDecl();
1373
1374 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor954de172009-10-31 17:21:17 +00001375
1376 // Introduce this template parameter's instantiation into the instantiation
1377 // scope.
1378 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor6b815c82009-10-23 23:25:44 +00001379 return Param;
1380}
1381
Anders Carlsson4bd78752009-08-28 15:18:15 +00001382Decl *
Douglas Gregor38fee962009-11-11 16:58:32 +00001383TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1384 TemplateTemplateParmDecl *D) {
1385 // Instantiate the template parameter list of the template template parameter.
1386 TemplateParameterList *TempParams = D->getTemplateParameters();
1387 TemplateParameterList *InstParams;
1388 {
1389 // Perform the actual substitution of template parameters within a new,
1390 // local instantiation scope.
1391 Sema::LocalInstantiationScope Scope(SemaRef);
1392 InstParams = SubstTemplateParams(TempParams);
1393 if (!InstParams)
1394 return NULL;
1395 }
1396
1397 // Build the template template parameter.
1398 TemplateTemplateParmDecl *Param
1399 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1400 D->getDepth() - 1, D->getPosition(),
1401 D->getIdentifier(), InstParams);
1402 Param->setDefaultArgument(D->getDefaultArgument());
1403
1404 // Introduce this template parameter's instantiation into the instantiation
1405 // scope.
1406 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1407
1408 return Param;
1409}
1410
Douglas Gregore0b28662009-11-17 06:07:40 +00001411Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1412 // Using directives are never dependent, so they require no explicit
1413
1414 UsingDirectiveDecl *Inst
1415 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1416 D->getNamespaceKeyLocation(),
1417 D->getQualifierRange(), D->getQualifier(),
1418 D->getIdentLocation(),
1419 D->getNominatedNamespace(),
1420 D->getCommonAncestor());
1421 Owner->addDecl(Inst);
1422 return Inst;
1423}
1424
John McCallb96ec562009-12-04 22:46:56 +00001425Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1426 // The nested name specifier is non-dependent, so no transformation
1427 // is required.
1428
John McCall84d87672009-12-10 09:41:52 +00001429 // We only need to do redeclaration lookups if we're in a class
1430 // scope (in fact, it's not really even possible in non-class
1431 // scopes).
1432 bool CheckRedeclaration = Owner->isRecord();
1433
1434 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1435 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1436
John McCallb96ec562009-12-04 22:46:56 +00001437 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1438 D->getLocation(),
1439 D->getNestedNameRange(),
1440 D->getUsingLocation(),
1441 D->getTargetNestedNameDecl(),
1442 D->getDeclName(),
1443 D->isTypeName());
1444
1445 CXXScopeSpec SS;
1446 SS.setScopeRep(D->getTargetNestedNameDecl());
1447 SS.setRange(D->getNestedNameRange());
John McCall84d87672009-12-10 09:41:52 +00001448
1449 if (CheckRedeclaration) {
1450 Prev.setHideTags(false);
1451 SemaRef.LookupQualifiedName(Prev, Owner);
1452
1453 // Check for invalid redeclarations.
1454 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1455 D->isTypeName(), SS,
1456 D->getLocation(), Prev))
1457 NewUD->setInvalidDecl();
1458
1459 }
1460
1461 if (!NewUD->isInvalidDecl() &&
1462 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCallb96ec562009-12-04 22:46:56 +00001463 D->getLocation()))
1464 NewUD->setInvalidDecl();
John McCall84d87672009-12-10 09:41:52 +00001465
John McCallb96ec562009-12-04 22:46:56 +00001466 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1467 NewUD->setAccess(D->getAccess());
1468 Owner->addDecl(NewUD);
1469
John McCall84d87672009-12-10 09:41:52 +00001470 // Don't process the shadow decls for an invalid decl.
1471 if (NewUD->isInvalidDecl())
1472 return NewUD;
1473
John McCalla1d85502009-12-22 22:26:37 +00001474 bool isFunctionScope = Owner->isFunctionOrMethod();
1475
John McCall84d87672009-12-10 09:41:52 +00001476 // Process the shadow decls.
1477 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1478 I != E; ++I) {
1479 UsingShadowDecl *Shadow = *I;
1480 NamedDecl *InstTarget =
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001481 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1482 Shadow->getTargetDecl(),
John McCall84d87672009-12-10 09:41:52 +00001483 TemplateArgs));
1484
1485 if (CheckRedeclaration &&
1486 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1487 continue;
1488
1489 UsingShadowDecl *InstShadow
1490 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1491 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCalla1d85502009-12-22 22:26:37 +00001492
1493 if (isFunctionScope)
1494 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall84d87672009-12-10 09:41:52 +00001495 }
John McCallb96ec562009-12-04 22:46:56 +00001496
1497 return NewUD;
1498}
1499
1500Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall84d87672009-12-10 09:41:52 +00001501 // Ignore these; we handle them in bulk when processing the UsingDecl.
1502 return 0;
John McCallb96ec562009-12-04 22:46:56 +00001503}
1504
John McCalle61f2ba2009-11-18 02:36:19 +00001505Decl * TemplateDeclInstantiator
1506 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump11289f42009-09-09 15:08:12 +00001507 NestedNameSpecifier *NNS =
1508 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1509 D->getTargetNestedNameRange(),
Anders Carlsson4bd78752009-08-28 15:18:15 +00001510 TemplateArgs);
1511 if (!NNS)
1512 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001513
Anders Carlsson4bd78752009-08-28 15:18:15 +00001514 CXXScopeSpec SS;
1515 SS.setRange(D->getTargetNestedNameRange());
1516 SS.setScopeRep(NNS);
Mike Stump11289f42009-09-09 15:08:12 +00001517
1518 NamedDecl *UD =
John McCall3f746822009-11-17 05:59:44 +00001519 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCalle61f2ba2009-11-18 02:36:19 +00001520 D->getUsingLoc(), SS, D->getLocation(),
1521 D->getDeclName(), 0,
1522 /*instantiation*/ true,
1523 /*typename*/ true, D->getTypenameLoc());
1524 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00001525 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1526
John McCalle61f2ba2009-11-18 02:36:19 +00001527 return UD;
1528}
1529
1530Decl * TemplateDeclInstantiator
1531 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1532 NestedNameSpecifier *NNS =
1533 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1534 D->getTargetNestedNameRange(),
1535 TemplateArgs);
1536 if (!NNS)
1537 return 0;
1538
1539 CXXScopeSpec SS;
1540 SS.setRange(D->getTargetNestedNameRange());
1541 SS.setScopeRep(NNS);
1542
1543 NamedDecl *UD =
1544 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1545 D->getUsingLoc(), SS, D->getLocation(),
1546 D->getDeclName(), 0,
1547 /*instantiation*/ true,
1548 /*typename*/ false, SourceLocation());
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001549 if (UD)
John McCallb96ec562009-12-04 22:46:56 +00001550 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1551
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00001552 return UD;
Anders Carlsson4bd78752009-08-28 15:18:15 +00001553}
1554
John McCall76d824f2009-08-25 22:02:44 +00001555Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001556 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord002c7b2009-05-11 23:53:27 +00001557 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor71ad4772010-02-16 19:28:15 +00001558 if (D->isInvalidDecl())
1559 return 0;
1560
Douglas Gregord7e7a512009-03-17 21:15:40 +00001561 return Instantiator.Visit(D);
1562}
1563
John McCall87a44eb2009-08-20 01:44:21 +00001564/// \brief Instantiates a nested template parameter list in the current
1565/// instantiation context.
1566///
1567/// \param L The parameter list to instantiate
1568///
1569/// \returns NULL if there was an error
1570TemplateParameterList *
John McCall76d824f2009-08-25 22:02:44 +00001571TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCall87a44eb2009-08-20 01:44:21 +00001572 // Get errors for all the parameters before bailing out.
1573 bool Invalid = false;
1574
1575 unsigned N = L->size();
Douglas Gregorbe999392009-09-15 16:23:51 +00001576 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCall87a44eb2009-08-20 01:44:21 +00001577 ParamVector Params;
1578 Params.reserve(N);
1579 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1580 PI != PE; ++PI) {
Douglas Gregorbe999392009-09-15 16:23:51 +00001581 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCall87a44eb2009-08-20 01:44:21 +00001582 Params.push_back(D);
Douglas Gregore62e6a02009-11-11 19:13:48 +00001583 Invalid = Invalid || !D || D->isInvalidDecl();
John McCall87a44eb2009-08-20 01:44:21 +00001584 }
1585
1586 // Clean up if we had an error.
1587 if (Invalid) {
1588 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1589 PI != PE; ++PI)
1590 if (*PI)
1591 (*PI)->Destroy(SemaRef.Context);
1592 return NULL;
1593 }
1594
1595 TemplateParameterList *InstL
1596 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1597 L->getLAngleLoc(), &Params.front(), N,
1598 L->getRAngleLoc());
1599 return InstL;
Mike Stump11289f42009-09-09 15:08:12 +00001600}
John McCall87a44eb2009-08-20 01:44:21 +00001601
Douglas Gregor21610382009-10-29 00:04:11 +00001602/// \brief Instantiate the declaration of a class template partial
1603/// specialization.
1604///
1605/// \param ClassTemplate the (instantiated) class template that is partially
1606// specialized by the instantiation of \p PartialSpec.
1607///
1608/// \param PartialSpec the (uninstantiated) class template partial
1609/// specialization that we are instantiating.
1610///
1611/// \returns true if there was an error, false otherwise.
1612bool
1613TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1614 ClassTemplateDecl *ClassTemplate,
1615 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor954de172009-10-31 17:21:17 +00001616 // Create a local instantiation scope for this class template partial
1617 // specialization, which will contain the instantiations of the template
1618 // parameters.
1619 Sema::LocalInstantiationScope Scope(SemaRef);
1620
Douglas Gregor21610382009-10-29 00:04:11 +00001621 // Substitute into the template parameters of the class template partial
1622 // specialization.
1623 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1624 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1625 if (!InstParams)
1626 return true;
1627
1628 // Substitute into the template arguments of the class template partial
1629 // specialization.
John McCall0ad16662009-10-29 08:12:44 +00001630 const TemplateArgumentLoc *PartialSpecTemplateArgs
1631 = PartialSpec->getTemplateArgsAsWritten();
1632 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1633
John McCall6b51f282009-11-23 01:53:49 +00001634 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall0ad16662009-10-29 08:12:44 +00001635 for (unsigned I = 0; I != N; ++I) {
John McCall6b51f282009-11-23 01:53:49 +00001636 TemplateArgumentLoc Loc;
1637 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregor21610382009-10-29 00:04:11 +00001638 return true;
John McCall6b51f282009-11-23 01:53:49 +00001639 InstTemplateArgs.addArgument(Loc);
Douglas Gregor21610382009-10-29 00:04:11 +00001640 }
1641
1642
1643 // Check that the template argument list is well-formed for this
1644 // class template.
1645 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1646 InstTemplateArgs.size());
1647 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1648 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00001649 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00001650 false,
1651 Converted))
1652 return true;
1653
1654 // Figure out where to insert this class template partial specialization
1655 // in the member template's set of class template partial specializations.
1656 llvm::FoldingSetNodeID ID;
1657 ClassTemplatePartialSpecializationDecl::Profile(ID,
1658 Converted.getFlatArguments(),
1659 Converted.flatSize(),
1660 SemaRef.Context);
1661 void *InsertPos = 0;
1662 ClassTemplateSpecializationDecl *PrevDecl
1663 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1664 InsertPos);
1665
1666 // Build the canonical type that describes the converted template
1667 // arguments of the class template partial specialization.
1668 QualType CanonType
1669 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1670 Converted.getFlatArguments(),
1671 Converted.flatSize());
1672
1673 // Build the fully-sugared type for this class template
1674 // specialization as the user wrote in the specialization
1675 // itself. This means that we'll pretty-print the type retrieved
1676 // from the specialization's declaration the way that the user
1677 // actually wrote the specialization, rather than formatting the
1678 // name based on the "canonical" representation used to store the
1679 // template arguments in the specialization.
John McCalle78aac42010-03-10 03:28:59 +00001680 TypeSourceInfo *WrittenTy
1681 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1682 TemplateName(ClassTemplate),
1683 PartialSpec->getLocation(),
John McCall6b51f282009-11-23 01:53:49 +00001684 InstTemplateArgs,
Douglas Gregor21610382009-10-29 00:04:11 +00001685 CanonType);
1686
1687 if (PrevDecl) {
1688 // We've already seen a partial specialization with the same template
1689 // parameters and template arguments. This can happen, for example, when
1690 // substituting the outer template arguments ends up causing two
1691 // class template partial specializations of a member class template
1692 // to have identical forms, e.g.,
1693 //
1694 // template<typename T, typename U>
1695 // struct Outer {
1696 // template<typename X, typename Y> struct Inner;
1697 // template<typename Y> struct Inner<T, Y>;
1698 // template<typename Y> struct Inner<U, Y>;
1699 // };
1700 //
1701 // Outer<int, int> outer; // error: the partial specializations of Inner
1702 // // have the same signature.
1703 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1704 << WrittenTy;
1705 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1706 << SemaRef.Context.getTypeDeclType(PrevDecl);
1707 return true;
1708 }
1709
1710
1711 // Create the class template partial specialization declaration.
1712 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1713 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1714 PartialSpec->getLocation(),
1715 InstParams,
1716 ClassTemplate,
1717 Converted,
John McCall6b51f282009-11-23 01:53:49 +00001718 InstTemplateArgs,
John McCalle78aac42010-03-10 03:28:59 +00001719 CanonType,
Douglas Gregor21610382009-10-29 00:04:11 +00001720 0);
John McCall3e11ebe2010-03-15 10:12:16 +00001721 // Substitute the nested name specifier, if any.
1722 if (SubstQualifier(PartialSpec, InstPartialSpec))
1723 return 0;
1724
Douglas Gregor21610382009-10-29 00:04:11 +00001725 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1726 InstPartialSpec->setTypeAsWritten(WrittenTy);
1727
1728 // Add this partial specialization to the set of class template partial
1729 // specializations.
1730 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1731 InsertPos);
1732 return false;
1733}
1734
John McCall58f10c32010-03-11 09:03:00 +00001735bool
1736Sema::CheckInstantiatedParams(llvm::SmallVectorImpl<ParmVarDecl*> &Params) {
1737 bool Invalid = false;
1738 for (unsigned i = 0, i_end = Params.size(); i != i_end; ++i)
1739 if (ParmVarDecl *PInst = Params[i]) {
1740 if (PInst->isInvalidDecl())
1741 Invalid = true;
1742 else if (PInst->getType()->isVoidType()) {
1743 Diag(PInst->getLocation(), diag::err_param_with_void_type);
1744 PInst->setInvalidDecl();
1745 Invalid = true;
1746 }
1747 else if (RequireNonAbstractType(PInst->getLocation(),
1748 PInst->getType(),
1749 diag::err_abstract_type_in_decl,
1750 Sema::AbstractParamType)) {
1751 PInst->setInvalidDecl();
1752 Invalid = true;
1753 }
1754 }
1755 return Invalid;
1756}
Douglas Gregor21342092009-03-24 00:38:23 +00001757
John McCall58f10c32010-03-11 09:03:00 +00001758TypeSourceInfo*
John McCall76d824f2009-08-25 22:02:44 +00001759TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor21342092009-03-24 00:38:23 +00001760 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall58f10c32010-03-11 09:03:00 +00001761 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1762 assert(OldTInfo && "substituting function without type source info");
1763 assert(Params.empty() && "parameter vector is non-empty at start");
1764 TypeSourceInfo *NewTInfo = SemaRef.SubstType(OldTInfo, TemplateArgs,
1765 D->getTypeSpecStartLoc(),
1766 D->getDeclName());
1767 if (!NewTInfo)
1768 return 0;
Douglas Gregor21342092009-03-24 00:38:23 +00001769
John McCall58f10c32010-03-11 09:03:00 +00001770 // Get parameters from the new type info.
1771 TypeLoc NewTL = NewTInfo->getTypeLoc();
1772 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1773 assert(NewProtoLoc && "Missing prototype?");
1774 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1775 Params.push_back(NewProtoLoc->getArg(i));
Douglas Gregor21342092009-03-24 00:38:23 +00001776
John McCall58f10c32010-03-11 09:03:00 +00001777 return NewTInfo;
Douglas Gregor21342092009-03-24 00:38:23 +00001778}
1779
Mike Stump11289f42009-09-09 15:08:12 +00001780/// \brief Initializes the common fields of an instantiation function
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001781/// declaration (New) from the corresponding fields of its template (Tmpl).
1782///
1783/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00001784bool
1785TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001786 FunctionDecl *Tmpl) {
1787 if (Tmpl->isDeleted())
1788 New->setDeleted();
Mike Stump11289f42009-09-09 15:08:12 +00001789
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00001790 // If we are performing substituting explicitly-specified template arguments
1791 // or deduced template arguments into a function template and we reach this
1792 // point, we are now past the point where SFINAE applies and have committed
Mike Stump11289f42009-09-09 15:08:12 +00001793 // to keeping the new function template specialization. We therefore
1794 // convert the active template instantiation for the function template
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00001795 // into a template instantiation for this specific function template
1796 // specialization, which is not a SFINAE context, so that we diagnose any
1797 // further errors in the declaration itself.
1798 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1799 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1800 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1801 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump11289f42009-09-09 15:08:12 +00001802 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00001803 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump11289f42009-09-09 15:08:12 +00001804 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00001805 "Deduction from the wrong function template?");
Daniel Dunbar54c59642009-07-16 22:10:11 +00001806 (void) FunTmpl;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00001807 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1808 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregor84d49a22009-11-11 21:54:23 +00001809 --SemaRef.NonInstantiationEntries;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +00001810 }
1811 }
Mike Stump11289f42009-09-09 15:08:12 +00001812
Douglas Gregor049bdca2009-12-08 17:45:32 +00001813 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1814 assert(Proto && "Function template without prototype?");
1815
1816 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1817 Proto->getNoReturnAttr()) {
1818 // The function has an exception specification or a "noreturn"
1819 // attribute. Substitute into each of the exception types.
1820 llvm::SmallVector<QualType, 4> Exceptions;
1821 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1822 // FIXME: Poor location information!
1823 QualType T
1824 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1825 New->getLocation(), New->getDeclName());
1826 if (T.isNull() ||
1827 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1828 continue;
1829
1830 Exceptions.push_back(T);
1831 }
1832
1833 // Rebuild the function type
1834
1835 const FunctionProtoType *NewProto
1836 = New->getType()->getAs<FunctionProtoType>();
1837 assert(NewProto && "Template instantiation without function prototype?");
1838 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1839 NewProto->arg_type_begin(),
1840 NewProto->getNumArgs(),
1841 NewProto->isVariadic(),
1842 NewProto->getTypeQuals(),
1843 Proto->hasExceptionSpec(),
1844 Proto->hasAnyExceptionSpec(),
1845 Exceptions.size(),
1846 Exceptions.data(),
Rafael Espindolac50c27c2010-03-30 20:24:48 +00001847 Proto->getExtInfo()));
Douglas Gregor049bdca2009-12-08 17:45:32 +00001848 }
1849
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001850 return false;
1851}
1852
Douglas Gregor21342092009-03-24 00:38:23 +00001853/// \brief Initializes common fields of an instantiated method
1854/// declaration (New) from the corresponding fields of its template
1855/// (Tmpl).
1856///
1857/// \returns true if there was an error
Mike Stump11289f42009-09-09 15:08:12 +00001858bool
1859TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor21342092009-03-24 00:38:23 +00001860 CXXMethodDecl *Tmpl) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00001861 if (InitFunctionInstantiation(New, Tmpl))
1862 return true;
Mike Stump11289f42009-09-09 15:08:12 +00001863
Douglas Gregor21342092009-03-24 00:38:23 +00001864 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1865 New->setAccess(Tmpl->getAccess());
Fariborz Jahanian6dfc1972009-12-03 18:44:40 +00001866 if (Tmpl->isVirtualAsWritten())
1867 Record->setMethodAsVirtual(New);
Douglas Gregor21342092009-03-24 00:38:23 +00001868
1869 // FIXME: attributes
1870 // FIXME: New needs a pointer to Tmpl
1871 return false;
1872}
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00001873
1874/// \brief Instantiate the definition of the given function from its
1875/// template.
1876///
Douglas Gregordda7ced2009-06-30 17:20:14 +00001877/// \param PointOfInstantiation the point at which the instantiation was
1878/// required. Note that this is not precisely a "point of instantiation"
1879/// for the function, but it's close.
1880///
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00001881/// \param Function the already-instantiated declaration of a
Douglas Gregordda7ced2009-06-30 17:20:14 +00001882/// function template specialization or member function of a class template
1883/// specialization.
1884///
1885/// \param Recursive if true, recursively instantiates any functions that
1886/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00001887///
1888/// \param DefinitionRequired if true, then we are performing an explicit
1889/// instantiation where the body of the function is required. Complain if
1890/// there is no such body.
Douglas Gregor85673582009-05-18 17:01:57 +00001891void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregordda7ced2009-06-30 17:20:14 +00001892 FunctionDecl *Function,
Douglas Gregora8b89d22009-10-15 14:05:49 +00001893 bool Recursive,
1894 bool DefinitionRequired) {
Douglas Gregorb4850462009-05-14 23:26:13 +00001895 if (Function->isInvalidDecl())
1896 return;
1897
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001898 assert(!Function->getBody() && "Already instantiated!");
Mike Stump11289f42009-09-09 15:08:12 +00001899
Douglas Gregor86d142a2009-10-08 07:24:58 +00001900 // Never instantiate an explicit specialization.
1901 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1902 return;
1903
Douglas Gregor24c332b2009-05-14 21:06:31 +00001904 // Find the function body that we'll be substituting.
Douglas Gregorafca3b42009-10-27 20:53:28 +00001905 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor24c332b2009-05-14 21:06:31 +00001906 Stmt *Pattern = 0;
1907 if (PatternDecl)
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001908 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor24c332b2009-05-14 21:06:31 +00001909
Douglas Gregora8b89d22009-10-15 14:05:49 +00001910 if (!Pattern) {
1911 if (DefinitionRequired) {
1912 if (Function->getPrimaryTemplate())
1913 Diag(PointOfInstantiation,
1914 diag::err_explicit_instantiation_undefined_func_template)
1915 << Function->getPrimaryTemplate();
1916 else
1917 Diag(PointOfInstantiation,
1918 diag::err_explicit_instantiation_undefined_member)
1919 << 1 << Function->getDeclName() << Function->getDeclContext();
1920
1921 if (PatternDecl)
1922 Diag(PatternDecl->getLocation(),
1923 diag::note_explicit_instantiation_here);
1924 }
1925
Douglas Gregor24c332b2009-05-14 21:06:31 +00001926 return;
Douglas Gregora8b89d22009-10-15 14:05:49 +00001927 }
Douglas Gregor24c332b2009-05-14 21:06:31 +00001928
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001929 // C++0x [temp.explicit]p9:
1930 // Except for inline functions, other explicit instantiation declarations
Mike Stump11289f42009-09-09 15:08:12 +00001931 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001932 // to which they refer.
Mike Stump11289f42009-09-09 15:08:12 +00001933 if (Function->getTemplateSpecializationKind()
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001934 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor583dcaf2009-10-27 21:11:48 +00001935 !PatternDecl->isInlined())
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001936 return;
Mike Stump11289f42009-09-09 15:08:12 +00001937
Douglas Gregor85673582009-05-18 17:01:57 +00001938 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
1939 if (Inst)
1940 return;
Douglas Gregor923feac2009-05-15 00:01:03 +00001941
Douglas Gregordda7ced2009-06-30 17:20:14 +00001942 // If we're performing recursive template instantiation, create our own
1943 // queue of pending implicit instantiations that we will instantiate later,
1944 // while we're still within our own instantiation context.
1945 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
1946 if (Recursive)
1947 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00001948
Douglas Gregor67da0d92009-05-15 17:59:04 +00001949 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
1950
Douglas Gregorb4850462009-05-14 23:26:13 +00001951 // Introduce a new scope where local variable instantiations will be
Douglas Gregor7f792cf2010-01-16 22:29:39 +00001952 // recorded, unless we're actually a member function within a local
1953 // class, in which case we need to merge our results with the parent
1954 // scope (of the enclosing function).
1955 bool MergeWithParentScope = false;
1956 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
1957 MergeWithParentScope = Rec->isLocalClass();
1958
1959 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump11289f42009-09-09 15:08:12 +00001960
Douglas Gregorb4850462009-05-14 23:26:13 +00001961 // Introduce the instantiated function parameters into the local
1962 // instantiation scope.
1963 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
1964 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
1965 Function->getParamDecl(I));
1966
Douglas Gregor923feac2009-05-15 00:01:03 +00001967 // Enter the scope of this instantiation. We don't use
1968 // PushDeclContext because we don't have a scope.
1969 DeclContext *PreviousContext = CurContext;
1970 CurContext = Function;
1971
Mike Stump11289f42009-09-09 15:08:12 +00001972 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson70553942009-08-29 05:16:22 +00001973 getTemplateInstantiationArgs(Function);
1974
1975 // If this is a constructor, instantiate the member initializers.
Mike Stump11289f42009-09-09 15:08:12 +00001976 if (const CXXConstructorDecl *Ctor =
Anders Carlsson70553942009-08-29 05:16:22 +00001977 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
1978 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
1979 TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001980 }
1981
Douglas Gregorb4850462009-05-14 23:26:13 +00001982 // Instantiate the function body.
Anders Carlsson70553942009-08-29 05:16:22 +00001983 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregor67da0d92009-05-15 17:59:04 +00001984
Douglas Gregor4aa04b12009-09-11 21:19:12 +00001985 if (Body.isInvalid())
1986 Function->setInvalidDecl();
1987
Mike Stump11289f42009-09-09 15:08:12 +00001988 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregor67da0d92009-05-15 17:59:04 +00001989 /*IsInstantiation=*/true);
Douglas Gregor923feac2009-05-15 00:01:03 +00001990
John McCallc62bb642010-03-24 05:22:00 +00001991 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
1992
Douglas Gregor923feac2009-05-15 00:01:03 +00001993 CurContext = PreviousContext;
Douglas Gregor28ad4b52009-05-26 20:50:29 +00001994
1995 DeclGroupRef DG(Function);
1996 Consumer.HandleTopLevelDecl(DG);
Mike Stump11289f42009-09-09 15:08:12 +00001997
Douglas Gregor7f792cf2010-01-16 22:29:39 +00001998 // This class may have local implicit instantiations that need to be
1999 // instantiation within this scope.
2000 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2001 Scope.Exit();
2002
Douglas Gregordda7ced2009-06-30 17:20:14 +00002003 if (Recursive) {
2004 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00002005 // instantiation of this template.
Douglas Gregordda7ced2009-06-30 17:20:14 +00002006 PerformPendingImplicitInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00002007
Douglas Gregordda7ced2009-06-30 17:20:14 +00002008 // Restore the set of pending implicit instantiations.
2009 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2010 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002011}
2012
2013/// \brief Instantiate the definition of the given variable from its
2014/// template.
2015///
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002016/// \param PointOfInstantiation the point at which the instantiation was
2017/// required. Note that this is not precisely a "point of instantiation"
2018/// for the function, but it's close.
2019///
2020/// \param Var the already-instantiated declaration of a static member
2021/// variable of a class template specialization.
2022///
2023/// \param Recursive if true, recursively instantiates any functions that
2024/// are required by this instantiation.
Douglas Gregora8b89d22009-10-15 14:05:49 +00002025///
2026/// \param DefinitionRequired if true, then we are performing an explicit
2027/// instantiation where an out-of-line definition of the member variable
2028/// is required. Complain if there is no such definition.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002029void Sema::InstantiateStaticDataMemberDefinition(
2030 SourceLocation PointOfInstantiation,
2031 VarDecl *Var,
Douglas Gregora8b89d22009-10-15 14:05:49 +00002032 bool Recursive,
2033 bool DefinitionRequired) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002034 if (Var->isInvalidDecl())
2035 return;
Mike Stump11289f42009-09-09 15:08:12 +00002036
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002037 // Find the out-of-line definition of this static data member.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002038 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002039 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor1d957a32009-10-27 18:42:08 +00002040 assert(Def->isStaticDataMember() && "Not a static data member?");
2041 Def = Def->getOutOfLineDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00002042
Douglas Gregor1d957a32009-10-27 18:42:08 +00002043 if (!Def) {
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002044 // We did not find an out-of-line definition of this static data member,
2045 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump11289f42009-09-09 15:08:12 +00002046 // instantiate this definition (or provide a specialization for it) in
2047 // another translation unit.
Douglas Gregora8b89d22009-10-15 14:05:49 +00002048 if (DefinitionRequired) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002049 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregora8b89d22009-10-15 14:05:49 +00002050 Diag(PointOfInstantiation,
2051 diag::err_explicit_instantiation_undefined_member)
2052 << 2 << Var->getDeclName() << Var->getDeclContext();
2053 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2054 }
2055
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002056 return;
2057 }
2058
Douglas Gregor86d142a2009-10-08 07:24:58 +00002059 // Never instantiate an explicit specialization.
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002060 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor86d142a2009-10-08 07:24:58 +00002061 return;
2062
2063 // C++0x [temp.explicit]p9:
2064 // Except for inline functions, other explicit instantiation declarations
2065 // have the effect of suppressing the implicit instantiation of the entity
2066 // to which they refer.
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002067 if (Var->getTemplateSpecializationKind()
Douglas Gregor86d142a2009-10-08 07:24:58 +00002068 == TSK_ExplicitInstantiationDeclaration)
2069 return;
Mike Stump11289f42009-09-09 15:08:12 +00002070
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002071 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2072 if (Inst)
2073 return;
Mike Stump11289f42009-09-09 15:08:12 +00002074
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002075 // If we're performing recursive template instantiation, create our own
2076 // queue of pending implicit instantiations that we will instantiate later,
2077 // while we're still within our own instantiation context.
2078 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2079 if (Recursive)
2080 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00002081
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002082 // Enter the scope of this instantiation. We don't use
2083 // PushDeclContext because we don't have a scope.
2084 DeclContext *PreviousContext = CurContext;
2085 CurContext = Var->getDeclContext();
Mike Stump11289f42009-09-09 15:08:12 +00002086
Douglas Gregor3cc3cde2009-10-14 21:29:40 +00002087 VarDecl *OldVar = Var;
John McCall76d824f2009-08-25 22:02:44 +00002088 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002089 getTemplateInstantiationArgs(Var)));
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002090 CurContext = PreviousContext;
2091
2092 if (Var) {
Douglas Gregor8f003d02009-10-15 18:07:02 +00002093 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2094 assert(MSInfo && "Missing member specialization information?");
2095 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2096 MSInfo->getPointOfInstantiation());
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002097 DeclGroupRef DG(Var);
2098 Consumer.HandleTopLevelDecl(DG);
2099 }
Mike Stump11289f42009-09-09 15:08:12 +00002100
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002101 if (Recursive) {
2102 // Instantiate any pending implicit instantiations found during the
Mike Stump11289f42009-09-09 15:08:12 +00002103 // instantiation of this template.
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002104 PerformPendingImplicitInstantiations();
Mike Stump11289f42009-09-09 15:08:12 +00002105
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002106 // Restore the set of pending implicit instantiations.
2107 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump11289f42009-09-09 15:08:12 +00002108 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002109}
Douglas Gregor51783312009-05-27 05:35:12 +00002110
Anders Carlsson70553942009-08-29 05:16:22 +00002111void
2112Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2113 const CXXConstructorDecl *Tmpl,
2114 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00002115
Anders Carlsson70553942009-08-29 05:16:22 +00002116 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002117 bool AnyErrors = false;
2118
Anders Carlsson70553942009-08-29 05:16:22 +00002119 // Instantiate all the initializers.
2120 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregora3a3f6f2009-09-01 21:04:42 +00002121 InitsEnd = Tmpl->init_end();
2122 Inits != InitsEnd; ++Inits) {
Anders Carlsson70553942009-08-29 05:16:22 +00002123 CXXBaseOrMemberInitializer *Init = *Inits;
2124
Douglas Gregorb30f22b2010-03-02 07:38:39 +00002125 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson70553942009-08-29 05:16:22 +00002126 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002127 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump11289f42009-09-09 15:08:12 +00002128
Douglas Gregorb30f22b2010-03-02 07:38:39 +00002129 // Instantiate the initializer.
2130 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2131 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2132 AnyErrors = true;
2133 continue;
Anders Carlsson70553942009-08-29 05:16:22 +00002134 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002135
Anders Carlsson70553942009-08-29 05:16:22 +00002136 MemInitResult NewInit;
Anders Carlsson70553942009-08-29 05:16:22 +00002137 if (Init->isBaseInitializer()) {
John McCallbcd03502009-12-07 02:54:59 +00002138 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002139 TemplateArgs,
2140 Init->getSourceLocation(),
2141 New->getDeclName());
John McCallbcd03502009-12-07 02:54:59 +00002142 if (!BaseTInfo) {
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002143 AnyErrors = true;
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002144 New->setInvalidDecl();
2145 continue;
2146 }
2147
John McCallbcd03502009-12-07 02:54:59 +00002148 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump11289f42009-09-09 15:08:12 +00002149 (Expr **)NewArgs.data(),
Anders Carlsson70553942009-08-29 05:16:22 +00002150 NewArgs.size(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002151 Init->getLParenLoc(),
Anders Carlsson70553942009-08-29 05:16:22 +00002152 Init->getRParenLoc(),
2153 New->getParent());
2154 } else if (Init->isMemberInitializer()) {
Anders Carlsson17dc7e22009-09-01 04:31:02 +00002155 FieldDecl *Member;
Mike Stump11289f42009-09-09 15:08:12 +00002156
Anders Carlsson17dc7e22009-09-01 04:31:02 +00002157 // Is this an anonymous union?
2158 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002159 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2160 UnionInit, TemplateArgs));
Anders Carlsson17dc7e22009-09-01 04:31:02 +00002161 else
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002162 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2163 Init->getMember(),
Douglas Gregor64621e62009-09-16 18:34:49 +00002164 TemplateArgs));
Mike Stump11289f42009-09-09 15:08:12 +00002165
2166 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson70553942009-08-29 05:16:22 +00002167 NewArgs.size(),
2168 Init->getSourceLocation(),
Douglas Gregorc8c44b5d2009-12-02 22:36:29 +00002169 Init->getLParenLoc(),
Anders Carlsson70553942009-08-29 05:16:22 +00002170 Init->getRParenLoc());
2171 }
2172
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002173 if (NewInit.isInvalid()) {
2174 AnyErrors = true;
Anders Carlsson70553942009-08-29 05:16:22 +00002175 New->setInvalidDecl();
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002176 } else {
Anders Carlsson70553942009-08-29 05:16:22 +00002177 // FIXME: It would be nice if ASTOwningVector had a release function.
2178 NewArgs.take();
Mike Stump11289f42009-09-09 15:08:12 +00002179
Anders Carlsson70553942009-08-29 05:16:22 +00002180 NewInits.push_back((MemInitTy *)NewInit.get());
2181 }
2182 }
Mike Stump11289f42009-09-09 15:08:12 +00002183
Anders Carlsson70553942009-08-29 05:16:22 +00002184 // Assign all the initializers to the new constructor.
Mike Stump11289f42009-09-09 15:08:12 +00002185 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson70553942009-08-29 05:16:22 +00002186 /*FIXME: ColonLoc */
2187 SourceLocation(),
Douglas Gregor7ae2d772010-01-31 09:12:51 +00002188 NewInits.data(), NewInits.size(),
2189 AnyErrors);
Anders Carlsson70553942009-08-29 05:16:22 +00002190}
2191
John McCall59660882009-08-29 08:11:13 +00002192// TODO: this could be templated if the various decl types used the
2193// same method name.
2194static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2195 ClassTemplateDecl *Instance) {
2196 Pattern = Pattern->getCanonicalDecl();
2197
2198 do {
2199 Instance = Instance->getCanonicalDecl();
2200 if (Pattern == Instance) return true;
2201 Instance = Instance->getInstantiatedFromMemberTemplate();
2202 } while (Instance);
2203
2204 return false;
2205}
2206
Douglas Gregor14d1bf42009-09-28 06:34:35 +00002207static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2208 FunctionTemplateDecl *Instance) {
2209 Pattern = Pattern->getCanonicalDecl();
2210
2211 do {
2212 Instance = Instance->getCanonicalDecl();
2213 if (Pattern == Instance) return true;
2214 Instance = Instance->getInstantiatedFromMemberTemplate();
2215 } while (Instance);
2216
2217 return false;
2218}
2219
Douglas Gregor21610382009-10-29 00:04:11 +00002220static bool
2221isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2222 ClassTemplatePartialSpecializationDecl *Instance) {
2223 Pattern
2224 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2225 do {
2226 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2227 Instance->getCanonicalDecl());
2228 if (Pattern == Instance)
2229 return true;
2230 Instance = Instance->getInstantiatedFromMember();
2231 } while (Instance);
2232
2233 return false;
2234}
2235
John McCall59660882009-08-29 08:11:13 +00002236static bool isInstantiationOf(CXXRecordDecl *Pattern,
2237 CXXRecordDecl *Instance) {
2238 Pattern = Pattern->getCanonicalDecl();
2239
2240 do {
2241 Instance = Instance->getCanonicalDecl();
2242 if (Pattern == Instance) return true;
2243 Instance = Instance->getInstantiatedFromMemberClass();
2244 } while (Instance);
2245
2246 return false;
2247}
2248
2249static bool isInstantiationOf(FunctionDecl *Pattern,
2250 FunctionDecl *Instance) {
2251 Pattern = Pattern->getCanonicalDecl();
2252
2253 do {
2254 Instance = Instance->getCanonicalDecl();
2255 if (Pattern == Instance) return true;
2256 Instance = Instance->getInstantiatedFromMemberFunction();
2257 } while (Instance);
2258
2259 return false;
2260}
2261
2262static bool isInstantiationOf(EnumDecl *Pattern,
2263 EnumDecl *Instance) {
2264 Pattern = Pattern->getCanonicalDecl();
2265
2266 do {
2267 Instance = Instance->getCanonicalDecl();
2268 if (Pattern == Instance) return true;
2269 Instance = Instance->getInstantiatedFromMemberEnum();
2270 } while (Instance);
2271
2272 return false;
2273}
2274
John McCallb96ec562009-12-04 22:46:56 +00002275static bool isInstantiationOf(UsingShadowDecl *Pattern,
2276 UsingShadowDecl *Instance,
2277 ASTContext &C) {
2278 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2279}
2280
2281static bool isInstantiationOf(UsingDecl *Pattern,
2282 UsingDecl *Instance,
2283 ASTContext &C) {
2284 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2285}
2286
John McCalle61f2ba2009-11-18 02:36:19 +00002287static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2288 UsingDecl *Instance,
2289 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00002290 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCalle61f2ba2009-11-18 02:36:19 +00002291}
2292
2293static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002294 UsingDecl *Instance,
2295 ASTContext &C) {
John McCallb96ec562009-12-04 22:46:56 +00002296 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002297}
2298
John McCall59660882009-08-29 08:11:13 +00002299static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2300 VarDecl *Instance) {
2301 assert(Instance->isStaticDataMember());
2302
2303 Pattern = Pattern->getCanonicalDecl();
2304
2305 do {
2306 Instance = Instance->getCanonicalDecl();
2307 if (Pattern == Instance) return true;
2308 Instance = Instance->getInstantiatedFromStaticDataMember();
2309 } while (Instance);
2310
2311 return false;
2312}
2313
John McCallb96ec562009-12-04 22:46:56 +00002314// Other is the prospective instantiation
2315// D is the prospective pattern
Douglas Gregor51783312009-05-27 05:35:12 +00002316static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002317 if (D->getKind() != Other->getKind()) {
John McCalle61f2ba2009-11-18 02:36:19 +00002318 if (UnresolvedUsingTypenameDecl *UUD
2319 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2320 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2321 return isInstantiationOf(UUD, UD, Ctx);
2322 }
2323 }
2324
2325 if (UnresolvedUsingValueDecl *UUD
2326 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002327 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2328 return isInstantiationOf(UUD, UD, Ctx);
2329 }
2330 }
Douglas Gregor51783312009-05-27 05:35:12 +00002331
Anders Carlsson4bb87ce2009-08-29 19:37:28 +00002332 return false;
2333 }
Mike Stump11289f42009-09-09 15:08:12 +00002334
John McCall59660882009-08-29 08:11:13 +00002335 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2336 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump11289f42009-09-09 15:08:12 +00002337
John McCall59660882009-08-29 08:11:13 +00002338 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2339 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor51783312009-05-27 05:35:12 +00002340
John McCall59660882009-08-29 08:11:13 +00002341 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2342 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor51783312009-05-27 05:35:12 +00002343
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002344 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall59660882009-08-29 08:11:13 +00002345 if (Var->isStaticDataMember())
2346 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2347
2348 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2349 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregorf3db0032009-08-28 22:03:51 +00002350
Douglas Gregor14d1bf42009-09-28 06:34:35 +00002351 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2352 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2353
Douglas Gregor21610382009-10-29 00:04:11 +00002354 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2355 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2356 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2357 PartialSpec);
2358
Anders Carlsson5da84842009-09-01 04:26:58 +00002359 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2360 if (!Field->getDeclName()) {
2361 // This is an unnamed field.
Mike Stump11289f42009-09-09 15:08:12 +00002362 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlsson5da84842009-09-01 04:26:58 +00002363 cast<FieldDecl>(D);
2364 }
2365 }
Mike Stump11289f42009-09-09 15:08:12 +00002366
John McCallb96ec562009-12-04 22:46:56 +00002367 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2368 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2369
2370 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2371 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2372
Douglas Gregor51783312009-05-27 05:35:12 +00002373 return D->getDeclName() && isa<NamedDecl>(Other) &&
2374 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2375}
2376
2377template<typename ForwardIterator>
Mike Stump11289f42009-09-09 15:08:12 +00002378static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor51783312009-05-27 05:35:12 +00002379 NamedDecl *D,
2380 ForwardIterator first,
2381 ForwardIterator last) {
2382 for (; first != last; ++first)
2383 if (isInstantiationOf(Ctx, D, *first))
2384 return cast<NamedDecl>(*first);
2385
2386 return 0;
2387}
2388
John McCallaa74a0c2009-08-28 07:59:38 +00002389/// \brief Finds the instantiation of the given declaration context
2390/// within the current instantiation.
2391///
2392/// \returns NULL if there was an error
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002393DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregor64621e62009-09-16 18:34:49 +00002394 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCallaa74a0c2009-08-28 07:59:38 +00002395 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002396 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCallaa74a0c2009-08-28 07:59:38 +00002397 return cast_or_null<DeclContext>(ID);
2398 } else return DC;
2399}
2400
Douglas Gregorcd3a0972009-05-27 17:54:46 +00002401/// \brief Find the instantiation of the given declaration within the
2402/// current instantiation.
Douglas Gregor51783312009-05-27 05:35:12 +00002403///
2404/// This routine is intended to be used when \p D is a declaration
2405/// referenced from within a template, that needs to mapped into the
2406/// corresponding declaration within an instantiation. For example,
2407/// given:
2408///
2409/// \code
2410/// template<typename T>
2411/// struct X {
2412/// enum Kind {
2413/// KnownValue = sizeof(T)
2414/// };
2415///
2416/// bool getKind() const { return KnownValue; }
2417/// };
2418///
2419/// template struct X<int>;
2420/// \endcode
2421///
2422/// In the instantiation of X<int>::getKind(), we need to map the
2423/// EnumConstantDecl for KnownValue (which refers to
2424/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregorcd3a0972009-05-27 17:54:46 +00002425/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2426/// this mapping from within the instantiation of X<int>.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002427NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregor64621e62009-09-16 18:34:49 +00002428 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor51783312009-05-27 05:35:12 +00002429 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor954de172009-10-31 17:21:17 +00002430 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregorb93971082010-02-05 19:54:12 +00002431 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor954de172009-10-31 17:21:17 +00002432 ParentDC->isFunctionOrMethod()) {
Douglas Gregorf98d9b62009-05-27 17:07:49 +00002433 // D is a local of some kind. Look into the map of local
2434 // declarations to their instantiations.
2435 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2436 }
Douglas Gregor51783312009-05-27 05:35:12 +00002437
Douglas Gregor64621e62009-09-16 18:34:49 +00002438 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2439 if (!Record->isDependentContext())
2440 return D;
2441
Douglas Gregord225fa02010-02-05 22:40:03 +00002442 // If the RecordDecl is actually the injected-class-name or a
2443 // "templated" declaration for a class template, class template
2444 // partial specialization, or a member class of a class template,
2445 // substitute into the injected-class-name of the class template
2446 // or partial specialization to find the new DeclContext.
Douglas Gregor64621e62009-09-16 18:34:49 +00002447 QualType T;
2448 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2449
2450 if (ClassTemplate) {
John McCalle78aac42010-03-10 03:28:59 +00002451 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregor64621e62009-09-16 18:34:49 +00002452 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2453 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregor64621e62009-09-16 18:34:49 +00002454 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCalle78aac42010-03-10 03:28:59 +00002455
2456 // If we call SubstType with an InjectedClassNameType here we
2457 // can end up in an infinite loop.
2458 T = Context.getTypeDeclType(Record);
2459 assert(isa<InjectedClassNameType>(T) &&
2460 "type of partial specialization is not an InjectedClassNameType");
2461 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2462 }
Douglas Gregor64621e62009-09-16 18:34:49 +00002463
2464 if (!T.isNull()) {
Douglas Gregord225fa02010-02-05 22:40:03 +00002465 // Substitute into the injected-class-name to get the type
2466 // corresponding to the instantiation we want, which may also be
2467 // the current instantiation (if we're in a template
2468 // definition). This substitution should never fail, since we
2469 // know we can instantiate the injected-class-name or we
2470 // wouldn't have gotten to the injected-class-name!
2471
2472 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2473 // extra instantiation in the common case?
Douglas Gregor64621e62009-09-16 18:34:49 +00002474 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2475 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2476
2477 if (!T->isDependentType()) {
2478 assert(T->isRecordType() && "Instantiation must produce a record type");
2479 return T->getAs<RecordType>()->getDecl();
2480 }
2481
Douglas Gregord225fa02010-02-05 22:40:03 +00002482 // We are performing "partial" template instantiation to create
2483 // the member declarations for the members of a class template
2484 // specialization. Therefore, D is actually referring to something
2485 // in the current instantiation. Look through the current
2486 // context, which contains actual instantiations, to find the
2487 // instantiation of the "current instantiation" that D refers
2488 // to.
2489 bool SawNonDependentContext = false;
Mike Stump11289f42009-09-09 15:08:12 +00002490 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall59660882009-08-29 08:11:13 +00002491 DC = DC->getParent()) {
Mike Stump11289f42009-09-09 15:08:12 +00002492 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord225fa02010-02-05 22:40:03 +00002493 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregor64621e62009-09-16 18:34:49 +00002494 if (isInstantiationOf(ClassTemplate,
2495 Spec->getSpecializedTemplate()))
John McCall59660882009-08-29 08:11:13 +00002496 return Spec;
Douglas Gregord225fa02010-02-05 22:40:03 +00002497
2498 if (!DC->isDependentContext())
2499 SawNonDependentContext = true;
John McCall59660882009-08-29 08:11:13 +00002500 }
2501
Douglas Gregord225fa02010-02-05 22:40:03 +00002502 // We're performing "instantiation" of a member of the current
2503 // instantiation while we are type-checking the
2504 // definition. Compute the declaration context and return that.
2505 assert(!SawNonDependentContext &&
2506 "No dependent context while instantiating record");
2507 DeclContext *DC = computeDeclContext(T);
2508 assert(DC &&
John McCall59660882009-08-29 08:11:13 +00002509 "Unable to find declaration for the current instantiation");
Douglas Gregord225fa02010-02-05 22:40:03 +00002510 return cast<CXXRecordDecl>(DC);
John McCall59660882009-08-29 08:11:13 +00002511 }
Douglas Gregord225fa02010-02-05 22:40:03 +00002512
Douglas Gregor64621e62009-09-16 18:34:49 +00002513 // Fall through to deal with other dependent record types (e.g.,
2514 // anonymous unions in class templates).
2515 }
John McCall59660882009-08-29 08:11:13 +00002516
Douglas Gregor64621e62009-09-16 18:34:49 +00002517 if (!ParentDC->isDependentContext())
2518 return D;
2519
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002520 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00002521 if (!ParentDC)
Douglas Gregor2ffd9652009-09-01 17:53:10 +00002522 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002523
Douglas Gregor51783312009-05-27 05:35:12 +00002524 if (ParentDC != D->getDeclContext()) {
2525 // We performed some kind of instantiation in the parent context,
2526 // so now we need to look into the instantiated parent context to
2527 // find the instantiation of the declaration D.
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002528
John McCalle78aac42010-03-10 03:28:59 +00002529 // If our context used to be dependent, we may need to instantiate
2530 // it before performing lookup into that context.
2531 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002532 if (!Spec->isDependentContext()) {
2533 QualType T = Context.getTypeDeclType(Spec);
John McCalle78aac42010-03-10 03:28:59 +00002534 const RecordType *Tag = T->getAs<RecordType>();
2535 assert(Tag && "type of non-dependent record is not a RecordType");
2536 if (!Tag->isBeingDefined() &&
2537 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2538 return 0;
Douglas Gregora04f2ca2010-03-01 15:56:25 +00002539 }
2540 }
2541
Douglas Gregor51783312009-05-27 05:35:12 +00002542 NamedDecl *Result = 0;
2543 if (D->getDeclName()) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002544 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor51783312009-05-27 05:35:12 +00002545 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2546 } else {
2547 // Since we don't have a name for the entity we're looking for,
2548 // our only option is to walk through all of the declarations to
2549 // find that name. This will occur in a few cases:
2550 //
2551 // - anonymous struct/union within a template
2552 // - unnamed class/struct/union/enum within a template
2553 //
2554 // FIXME: Find a better way to find these instantiations!
Mike Stump11289f42009-09-09 15:08:12 +00002555 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002556 ParentDC->decls_begin(),
2557 ParentDC->decls_end());
Douglas Gregor51783312009-05-27 05:35:12 +00002558 }
Mike Stump11289f42009-09-09 15:08:12 +00002559
John McCall84d87672009-12-10 09:41:52 +00002560 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor604c3022010-03-01 18:27:54 +00002561 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2562 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall84d87672009-12-10 09:41:52 +00002563 && "Unable to find instantiation of declaration!");
2564
Douglas Gregor51783312009-05-27 05:35:12 +00002565 D = Result;
2566 }
2567
Douglas Gregor51783312009-05-27 05:35:12 +00002568 return D;
2569}
Douglas Gregor77b50e12009-06-22 23:06:13 +00002570
Mike Stump11289f42009-09-09 15:08:12 +00002571/// \brief Performs template instantiation for all implicit template
Douglas Gregor77b50e12009-06-22 23:06:13 +00002572/// instantiations we have seen until this point.
Douglas Gregor7f792cf2010-01-16 22:29:39 +00002573void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2574 while (!PendingLocalImplicitInstantiations.empty() ||
2575 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2576 PendingImplicitInstantiation Inst;
2577
2578 if (PendingLocalImplicitInstantiations.empty()) {
2579 Inst = PendingImplicitInstantiations.front();
2580 PendingImplicitInstantiations.pop_front();
2581 } else {
2582 Inst = PendingLocalImplicitInstantiations.front();
2583 PendingLocalImplicitInstantiations.pop_front();
2584 }
Mike Stump11289f42009-09-09 15:08:12 +00002585
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002586 // Instantiate function definitions
2587 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump11289f42009-09-09 15:08:12 +00002588 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlsson62215c42009-09-01 05:12:24 +00002589 Function->getLocation(), *this,
2590 Context.getSourceManager(),
2591 "instantiating function definition");
Mike Stump11289f42009-09-09 15:08:12 +00002592
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00002593 if (!Function->getBody())
Douglas Gregordda7ced2009-06-30 17:20:14 +00002594 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002595 continue;
2596 }
Mike Stump11289f42009-09-09 15:08:12 +00002597
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002598 // Instantiate static data member definitions.
2599 VarDecl *Var = cast<VarDecl>(Inst.first);
2600 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlsson62215c42009-09-01 05:12:24 +00002601
Chandler Carruth6b4756a2010-02-13 10:17:50 +00002602 // Don't try to instantiate declarations if the most recent redeclaration
2603 // is invalid.
2604 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2605 continue;
2606
2607 // Check if the most recent declaration has changed the specialization kind
2608 // and removed the need for implicit instantiation.
2609 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2610 case TSK_Undeclared:
2611 assert(false && "Cannot instantitiate an undeclared specialization.");
2612 case TSK_ExplicitInstantiationDeclaration:
2613 case TSK_ExplicitInstantiationDefinition:
2614 case TSK_ExplicitSpecialization:
2615 continue; // No longer need implicit instantiation.
2616 case TSK_ImplicitInstantiation:
2617 break;
2618 }
2619
Mike Stump11289f42009-09-09 15:08:12 +00002620 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlsson62215c42009-09-01 05:12:24 +00002621 Var->getLocation(), *this,
2622 Context.getSourceManager(),
2623 "instantiating static data member "
2624 "definition");
Mike Stump11289f42009-09-09 15:08:12 +00002625
Douglas Gregora6ef8f02009-07-24 20:34:43 +00002626 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregor77b50e12009-06-22 23:06:13 +00002627 }
2628}
John McCallc62bb642010-03-24 05:22:00 +00002629
2630void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2631 const MultiLevelTemplateArgumentList &TemplateArgs) {
2632 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2633 E = Pattern->ddiag_end(); I != E; ++I) {
2634 DependentDiagnostic *DD = *I;
2635
2636 switch (DD->getKind()) {
2637 case DependentDiagnostic::Access:
2638 HandleDependentAccessCheck(*DD, TemplateArgs);
2639 break;
2640 }
2641 }
2642}