blob: 82270451cbcc419e8bf7a7180552432e0b4d7453 [file] [log] [blame]
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl Instantiation ===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation for declarations.
10//
11//===----------------------------------------------------------------------===/
12#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000013#include "Lookup.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000014#include "clang/AST/ASTConsumer.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
John McCall0c01d182010-03-24 05:22:00 +000018#include "clang/AST/DependentDiagnostic.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000019#include "clang/AST/Expr.h"
Douglas Gregora88cfbf2009-12-12 18:16:41 +000020#include "clang/AST/ExprCXX.h"
John McCall21ef0fa2010-03-11 09:03:00 +000021#include "clang/AST/TypeLoc.h"
Anders Carlssonc17fb7b2009-09-01 05:12:24 +000022#include "clang/Basic/PrettyStackTrace.h"
Douglas Gregor83ddad32009-08-26 21:14:46 +000023#include "clang/Lex/Preprocessor.h"
Douglas Gregor8dbc2692009-03-17 21:15:40 +000024
25using namespace clang;
26
27namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000028 class TemplateDeclInstantiator
Chris Lattnerb28317a2009-03-28 19:18:32 +000029 : public DeclVisitor<TemplateDeclInstantiator, Decl *> {
Douglas Gregor8dbc2692009-03-17 21:15:40 +000030 Sema &SemaRef;
31 DeclContext *Owner;
Douglas Gregord6350ae2009-08-28 20:31:08 +000032 const MultiLevelTemplateArgumentList &TemplateArgs;
Mike Stump1eb44332009-09-09 15:08:12 +000033
Anders Carlssond8fe2d52009-11-07 06:07:58 +000034 void InstantiateAttrs(Decl *Tmpl, Decl *New);
35
Douglas Gregor8dbc2692009-03-17 21:15:40 +000036 public:
37 typedef Sema::OwningExprResult OwningExprResult;
38
39 TemplateDeclInstantiator(Sema &SemaRef, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +000040 const MultiLevelTemplateArgumentList &TemplateArgs)
Douglas Gregor7e063902009-05-11 23:53:27 +000041 : SemaRef(SemaRef), Owner(Owner), TemplateArgs(TemplateArgs) { }
Mike Stump1eb44332009-09-09 15:08:12 +000042
Mike Stump390b4cc2009-05-16 07:39:55 +000043 // FIXME: Once we get closer to completion, replace these manually-written
44 // declarations with automatically-generated ones from
45 // clang/AST/DeclNodes.def.
Douglas Gregor4f722be2009-03-25 15:45:12 +000046 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
47 Decl *VisitNamespaceDecl(NamespaceDecl *D);
John McCall3dbd3d52010-02-16 06:53:13 +000048 Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000049 Decl *VisitTypedefDecl(TypedefDecl *D);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +000050 Decl *VisitVarDecl(VarDecl *D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +000051 Decl *VisitFieldDecl(FieldDecl *D);
52 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
53 Decl *VisitEnumDecl(EnumDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000054 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
John McCall02cace72009-08-28 07:59:38 +000055 Decl *VisitFriendDecl(FriendDecl *D);
Douglas Gregora735b202009-10-13 14:39:41 +000056 Decl *VisitFunctionDecl(FunctionDecl *D,
57 TemplateParameterList *TemplateParams = 0);
Douglas Gregord475b8d2009-03-25 21:17:03 +000058 Decl *VisitCXXRecordDecl(CXXRecordDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000059 Decl *VisitCXXMethodDecl(CXXMethodDecl *D,
60 TemplateParameterList *TemplateParams = 0);
Douglas Gregor615c5d42009-03-24 16:43:20 +000061 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
Douglas Gregor03b2b072009-03-24 00:15:49 +000062 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +000063 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
Douglas Gregor6477b692009-03-25 15:04:13 +000064 ParmVarDecl *VisitParmVarDecl(ParmVarDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000065 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor7974c3b2009-10-07 17:21:34 +000066 Decl *VisitClassTemplatePartialSpecializationDecl(
67 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregord60e1052009-08-27 16:57:43 +000068 Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
John McCalle29ba202009-08-20 01:44:21 +000069 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Douglas Gregor33642df2009-10-23 23:25:44 +000070 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregor9106ef72009-11-11 16:58:32 +000071 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Douglas Gregor48c32a72009-11-17 06:07:40 +000072 Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
John McCalled976492009-12-04 22:46:56 +000073 Decl *VisitUsingDecl(UsingDecl *D);
74 Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
John McCall7ba107a2009-11-18 02:36:19 +000075 Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
76 Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregor8dbc2692009-03-17 21:15:40 +000078 // Base case. FIXME: Remove once we can instantiate everything.
Douglas Gregor48c32a72009-11-17 06:07:40 +000079 Decl *VisitDecl(Decl *D) {
80 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
81 Diagnostic::Error,
82 "cannot instantiate %0 yet");
83 SemaRef.Diag(D->getLocation(), DiagID)
84 << D->getDeclKindName();
85
Douglas Gregor8dbc2692009-03-17 21:15:40 +000086 return 0;
87 }
Douglas Gregor5545e162009-03-24 00:38:23 +000088
John McCallfd810b12009-08-14 02:03:10 +000089 const LangOptions &getLangOptions() {
90 return SemaRef.getLangOptions();
91 }
92
Douglas Gregor5545e162009-03-24 00:38:23 +000093 // Helper functions for instantiating methods.
John McCall21ef0fa2010-03-11 09:03:00 +000094 TypeSourceInfo *SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +000095 llvm::SmallVectorImpl<ParmVarDecl *> &Params);
Douglas Gregore53060f2009-06-25 22:08:12 +000096 bool InitFunctionInstantiation(FunctionDecl *New, FunctionDecl *Tmpl);
Douglas Gregor5545e162009-03-24 00:38:23 +000097 bool InitMethodInstantiation(CXXMethodDecl *New, CXXMethodDecl *Tmpl);
John McCalle29ba202009-08-20 01:44:21 +000098
99 TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +0000100 SubstTemplateParams(TemplateParameterList *List);
John McCallb6217662010-03-15 10:12:16 +0000101
102 bool SubstQualifier(const DeclaratorDecl *OldDecl,
103 DeclaratorDecl *NewDecl);
104 bool SubstQualifier(const TagDecl *OldDecl,
105 TagDecl *NewDecl);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000106
107 bool InstantiateClassTemplatePartialSpecialization(
108 ClassTemplateDecl *ClassTemplate,
109 ClassTemplatePartialSpecializationDecl *PartialSpec);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000110 };
111}
112
John McCallb6217662010-03-15 10:12:16 +0000113bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
114 DeclaratorDecl *NewDecl) {
115 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
116 if (!OldQual) return false;
117
118 SourceRange QualRange = OldDecl->getQualifierRange();
119
120 NestedNameSpecifier *NewQual
121 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
122 if (!NewQual)
123 return true;
124
125 NewDecl->setQualifierInfo(NewQual, QualRange);
126 return false;
127}
128
129bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
130 TagDecl *NewDecl) {
131 NestedNameSpecifier *OldQual = OldDecl->getQualifier();
132 if (!OldQual) return false;
133
134 SourceRange QualRange = OldDecl->getQualifierRange();
135
136 NestedNameSpecifier *NewQual
137 = SemaRef.SubstNestedNameSpecifier(OldQual, QualRange, TemplateArgs);
138 if (!NewQual)
139 return true;
140
141 NewDecl->setQualifierInfo(NewQual, QualRange);
142 return false;
143}
144
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000145// FIXME: Is this too simple?
146void TemplateDeclInstantiator::InstantiateAttrs(Decl *Tmpl, Decl *New) {
147 for (const Attr *TmplAttr = Tmpl->getAttrs(); TmplAttr;
148 TmplAttr = TmplAttr->getNext()) {
149
150 // FIXME: Is cloning correct for all attributes?
151 Attr *NewAttr = TmplAttr->clone(SemaRef.Context);
152
153 New->addAttr(NewAttr);
154 }
155}
156
Douglas Gregor4f722be2009-03-25 15:45:12 +0000157Decl *
158TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
159 assert(false && "Translation units cannot be instantiated");
160 return D;
161}
162
163Decl *
164TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
165 assert(false && "Namespaces cannot be instantiated");
166 return D;
167}
168
John McCall3dbd3d52010-02-16 06:53:13 +0000169Decl *
170TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
171 NamespaceAliasDecl *Inst
172 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
173 D->getNamespaceLoc(),
174 D->getAliasLoc(),
175 D->getNamespace()->getIdentifier(),
176 D->getQualifierRange(),
177 D->getQualifier(),
178 D->getTargetNameLoc(),
179 D->getNamespace());
180 Owner->addDecl(Inst);
181 return Inst;
182}
183
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000184Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
185 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000186 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCallba6a9bd2009-10-24 08:00:42 +0000187 if (DI->getType()->isDependentType()) {
188 DI = SemaRef.SubstType(DI, TemplateArgs,
189 D->getLocation(), D->getDeclName());
190 if (!DI) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000191 Invalid = true;
John McCalla93c9342009-12-07 02:54:59 +0000192 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000193 }
194 }
Mike Stump1eb44332009-09-09 15:08:12 +0000195
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000196 // Create the new typedef
197 TypedefDecl *Typedef
198 = TypedefDecl::Create(SemaRef.Context, Owner, D->getLocation(),
John McCallba6a9bd2009-10-24 08:00:42 +0000199 D->getIdentifier(), DI);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000200 if (Invalid)
201 Typedef->setInvalidDecl();
202
John McCall5126fd02009-12-30 00:31:22 +0000203 if (TypedefDecl *Prev = D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000204 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
205 TemplateArgs);
John McCall5126fd02009-12-30 00:31:22 +0000206 Typedef->setPreviousDeclaration(cast<TypedefDecl>(InstPrev));
207 }
208
John McCall46460a62010-01-20 21:53:11 +0000209 Typedef->setAccess(D->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000210 Owner->addDecl(Typedef);
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000212 return Typedef;
213}
214
Douglas Gregor6eef5192009-12-14 19:27:10 +0000215/// \brief Instantiate the arguments provided as part of initialization.
216///
217/// \returns true if an error occurred, false otherwise.
218static bool InstantiateInitializationArguments(Sema &SemaRef,
219 Expr **Args, unsigned NumArgs,
220 const MultiLevelTemplateArgumentList &TemplateArgs,
221 llvm::SmallVectorImpl<SourceLocation> &FakeCommaLocs,
222 ASTOwningVector<&ActionBase::DeleteExpr> &InitArgs) {
223 for (unsigned I = 0; I != NumArgs; ++I) {
224 // When we hit the first defaulted argument, break out of the loop:
225 // we don't pass those default arguments on.
226 if (Args[I]->isDefaultArgument())
227 break;
228
229 Sema::OwningExprResult Arg = SemaRef.SubstExpr(Args[I], TemplateArgs);
230 if (Arg.isInvalid())
231 return true;
232
233 Expr *ArgExpr = (Expr *)Arg.get();
234 InitArgs.push_back(Arg.release());
235
236 // FIXME: We're faking all of the comma locations. Do we need them?
237 FakeCommaLocs.push_back(
238 SemaRef.PP.getLocForEndOfToken(ArgExpr->getLocEnd()));
239 }
240
241 return false;
242}
243
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000244/// \brief Instantiate an initializer, breaking it into separate
245/// initialization arguments.
246///
247/// \param S The semantic analysis object.
248///
249/// \param Init The initializer to instantiate.
250///
251/// \param TemplateArgs Template arguments to be substituted into the
252/// initializer.
253///
254/// \param NewArgs Will be filled in with the instantiation arguments.
255///
256/// \returns true if an error occurred, false otherwise
257static bool InstantiateInitializer(Sema &S, Expr *Init,
258 const MultiLevelTemplateArgumentList &TemplateArgs,
259 SourceLocation &LParenLoc,
260 llvm::SmallVector<SourceLocation, 4> &CommaLocs,
261 ASTOwningVector<&ActionBase::DeleteExpr> &NewArgs,
262 SourceLocation &RParenLoc) {
263 NewArgs.clear();
264 LParenLoc = SourceLocation();
265 RParenLoc = SourceLocation();
266
267 if (!Init)
268 return false;
269
270 if (CXXExprWithTemporaries *ExprTemp = dyn_cast<CXXExprWithTemporaries>(Init))
271 Init = ExprTemp->getSubExpr();
272
273 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
274 Init = Binder->getSubExpr();
275
276 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
277 Init = ICE->getSubExprAsWritten();
278
279 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
280 LParenLoc = ParenList->getLParenLoc();
281 RParenLoc = ParenList->getRParenLoc();
282 return InstantiateInitializationArguments(S, ParenList->getExprs(),
283 ParenList->getNumExprs(),
284 TemplateArgs, CommaLocs,
285 NewArgs);
286 }
287
288 if (CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) {
Douglas Gregor28329e52010-03-24 21:22:47 +0000289 if (!isa<CXXTemporaryObjectExpr>(Construct)) {
290 if (InstantiateInitializationArguments(S,
291 Construct->getArgs(),
292 Construct->getNumArgs(),
293 TemplateArgs,
294 CommaLocs, NewArgs))
295 return true;
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000296
Douglas Gregor28329e52010-03-24 21:22:47 +0000297 // FIXME: Fake locations!
298 LParenLoc = S.PP.getLocForEndOfToken(Init->getLocStart());
299 RParenLoc = CommaLocs.empty()? LParenLoc : CommaLocs.back();
300 return false;
301 }
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000302 }
303
304 Sema::OwningExprResult Result = S.SubstExpr(Init, TemplateArgs);
305 if (Result.isInvalid())
306 return true;
307
308 NewArgs.push_back(Result.takeAs<Expr>());
309 return false;
310}
311
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000312Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000313 // Do substitution on the type of the declaration
John McCalla93c9342009-12-07 02:54:59 +0000314 TypeSourceInfo *DI = SemaRef.SubstType(D->getTypeSourceInfo(),
John McCall0a5fa062009-10-21 02:39:02 +0000315 TemplateArgs,
316 D->getTypeSpecStartLoc(),
317 D->getDeclName());
318 if (!DI)
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000319 return 0;
320
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +0000321 // Build the instantiated declaration
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000322 VarDecl *Var = VarDecl::Create(SemaRef.Context, Owner,
323 D->getLocation(), D->getIdentifier(),
John McCall0a5fa062009-10-21 02:39:02 +0000324 DI->getType(), DI,
Argyrios Kyrtzidisa5d82002009-08-21 00:31:54 +0000325 D->getStorageClass());
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000326 Var->setThreadSpecified(D->isThreadSpecified());
327 Var->setCXXDirectInitializer(D->hasCXXDirectInitializer());
328 Var->setDeclaredInCondition(D->isDeclaredInCondition());
Mike Stump1eb44332009-09-09 15:08:12 +0000329
John McCallb6217662010-03-15 10:12:16 +0000330 // Substitute the nested name specifier, if any.
331 if (SubstQualifier(D, Var))
332 return 0;
333
Mike Stump1eb44332009-09-09 15:08:12 +0000334 // If we are instantiating a static data member defined
Douglas Gregor7caa6822009-07-24 20:34:43 +0000335 // out-of-line, the instantiation will have the same lexical
336 // context (which will be a namespace scope) as the template.
337 if (D->isOutOfLine())
338 Var->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000339
John McCall46460a62010-01-20 21:53:11 +0000340 Var->setAccess(D->getAccess());
341
Mike Stump390b4cc2009-05-16 07:39:55 +0000342 // FIXME: In theory, we could have a previous declaration for variables that
343 // are not static data members.
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000344 bool Redeclaration = false;
John McCall68263142009-11-18 22:49:29 +0000345 // FIXME: having to fake up a LookupResult is dumb.
346 LookupResult Previous(SemaRef, Var->getDeclName(), Var->getLocation(),
Douglas Gregor449d0a82010-03-01 19:11:54 +0000347 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Douglas Gregor60c93c92010-02-09 07:26:29 +0000348 if (D->isStaticDataMember())
349 SemaRef.LookupQualifiedName(Previous, Owner, false);
John McCall68263142009-11-18 22:49:29 +0000350 SemaRef.CheckVariableDeclaration(Var, Previous, Redeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +0000351
Douglas Gregor7caa6822009-07-24 20:34:43 +0000352 if (D->isOutOfLine()) {
353 D->getLexicalDeclContext()->addDecl(Var);
354 Owner->makeDeclVisibleInContext(Var);
355 } else {
356 Owner->addDecl(Var);
357 }
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000359 // Link instantiations of static data members back to the template from
360 // which they were instantiated.
361 if (Var->isStaticDataMember())
362 SemaRef.Context.setInstantiatedFromStaticDataMember(Var, D,
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000363 TSK_ImplicitInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +0000364
Douglas Gregor60c93c92010-02-09 07:26:29 +0000365 if (Var->getAnyInitializer()) {
366 // We already have an initializer in the class.
367 } else if (D->getInit()) {
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000368 if (Var->isStaticDataMember() && !D->isOutOfLine())
369 SemaRef.PushExpressionEvaluationContext(Sema::Unevaluated);
370 else
371 SemaRef.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
372
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000373 // Instantiate the initializer.
374 SourceLocation LParenLoc, RParenLoc;
375 llvm::SmallVector<SourceLocation, 4> CommaLocs;
376 ASTOwningVector<&ActionBase::DeleteExpr> InitArgs(SemaRef);
377 if (!InstantiateInitializer(SemaRef, D->getInit(), TemplateArgs, LParenLoc,
378 CommaLocs, InitArgs, RParenLoc)) {
379 // Attach the initializer to the declaration.
380 if (D->hasCXXDirectInitializer()) {
Douglas Gregor6eef5192009-12-14 19:27:10 +0000381 // Add the direct initializer to the declaration.
Douglas Gregora88cfbf2009-12-12 18:16:41 +0000382 SemaRef.AddCXXDirectInitializerToDecl(Sema::DeclPtrTy::make(Var),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000383 LParenLoc,
Douglas Gregor6eef5192009-12-14 19:27:10 +0000384 move_arg(InitArgs),
385 CommaLocs.data(),
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000386 RParenLoc);
387 } else if (InitArgs.size() == 1) {
388 Expr *Init = (Expr*)(InitArgs.take()[0]);
389 SemaRef.AddInitializerToDecl(Sema::DeclPtrTy::make(Var),
390 SemaRef.Owned(Init),
391 false);
392 } else {
393 assert(InitArgs.size() == 0);
394 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor6eef5192009-12-14 19:27:10 +0000395 }
Douglas Gregor6eef5192009-12-14 19:27:10 +0000396 } else {
Douglas Gregor6b98b2e2010-03-02 07:38:39 +0000397 // FIXME: Not too happy about invalidating the declaration
398 // because of a bogus initializer.
399 Var->setInvalidDecl();
Douglas Gregor6eef5192009-12-14 19:27:10 +0000400 }
401
Douglas Gregor1f5f3a42009-12-03 17:10:37 +0000402 SemaRef.PopExpressionEvaluationContext();
Douglas Gregor65b90052009-07-27 17:43:39 +0000403 } else if (!Var->isStaticDataMember() || Var->isOutOfLine())
404 SemaRef.ActOnUninitializedDecl(Sema::DeclPtrTy::make(Var), false);
Douglas Gregor3d7a12a2009-03-25 23:32:15 +0000405
406 return Var;
407}
408
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000409Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
410 bool Invalid = false;
John McCalla93c9342009-12-07 02:54:59 +0000411 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000412 if (DI->getType()->isDependentType()) {
413 DI = SemaRef.SubstType(DI, TemplateArgs,
414 D->getLocation(), D->getDeclName());
415 if (!DI) {
John McCalla93c9342009-12-07 02:54:59 +0000416 DI = D->getTypeSourceInfo();
John McCall07fb6be2009-10-22 23:33:21 +0000417 Invalid = true;
418 } else if (DI->getType()->isFunctionType()) {
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000419 // C++ [temp.arg.type]p3:
420 // If a declaration acquires a function type through a type
421 // dependent on a template-parameter and this causes a
422 // declaration that does not use the syntactic form of a
423 // function declarator to have function type, the program is
424 // ill-formed.
425 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
John McCall07fb6be2009-10-22 23:33:21 +0000426 << DI->getType();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000427 Invalid = true;
428 }
429 }
430
431 Expr *BitWidth = D->getBitWidth();
432 if (Invalid)
433 BitWidth = 0;
434 else if (BitWidth) {
Douglas Gregorac7610d2009-06-22 20:57:11 +0000435 // The bit-width expression is not potentially evaluated.
436 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000438 OwningExprResult InstantiatedBitWidth
John McCallce3ff2b2009-08-25 22:02:44 +0000439 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000440 if (InstantiatedBitWidth.isInvalid()) {
441 Invalid = true;
442 BitWidth = 0;
443 } else
Anders Carlssone9146f22009-05-01 19:49:17 +0000444 BitWidth = InstantiatedBitWidth.takeAs<Expr>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000445 }
446
John McCall07fb6be2009-10-22 23:33:21 +0000447 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
448 DI->getType(), DI,
Mike Stump1eb44332009-09-09 15:08:12 +0000449 cast<RecordDecl>(Owner),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000450 D->getLocation(),
451 D->isMutable(),
452 BitWidth,
Steve Naroffea218b82009-07-14 14:58:18 +0000453 D->getTypeSpecStartLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000454 D->getAccess(),
455 0);
Douglas Gregor663b5a02009-10-14 20:14:33 +0000456 if (!Field) {
457 cast<Decl>(Owner)->setInvalidDecl();
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000458 return 0;
Douglas Gregor663b5a02009-10-14 20:14:33 +0000459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Anders Carlssond8fe2d52009-11-07 06:07:58 +0000461 InstantiateAttrs(D, Field);
462
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000463 if (Invalid)
464 Field->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000466 if (!Field->getDeclName()) {
467 // Keep track of where this decl came from.
468 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000469 }
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000471 Field->setImplicit(D->isImplicit());
John McCall46460a62010-01-20 21:53:11 +0000472 Field->setAccess(D->getAccess());
Anders Carlssonf4b5f5c2009-09-02 19:17:55 +0000473 Owner->addDecl(Field);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000474
475 return Field;
476}
477
John McCall02cace72009-08-28 07:59:38 +0000478Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
John McCall02cace72009-08-28 07:59:38 +0000479 // Handle friend type expressions by simply substituting template
Douglas Gregor06245bf2010-04-07 17:57:12 +0000480 // parameters into the pattern type and checking the result.
John McCall32f2fb52010-03-25 18:04:51 +0000481 if (TypeSourceInfo *Ty = D->getFriendType()) {
482 TypeSourceInfo *InstTy =
483 SemaRef.SubstType(Ty, TemplateArgs,
484 D->getLocation(), DeclarationName());
Douglas Gregor06245bf2010-04-07 17:57:12 +0000485 if (!InstTy)
Douglas Gregor7557a132009-12-24 20:56:24 +0000486 return 0;
John McCall02cace72009-08-28 07:59:38 +0000487
Douglas Gregor06245bf2010-04-07 17:57:12 +0000488 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getFriendLoc(), InstTy);
489 if (!FD)
490 return 0;
491
492 FD->setAccess(AS_public);
493 Owner->addDecl(FD);
494 return FD;
495 }
496
497 NamedDecl *ND = D->getFriendDecl();
498 assert(ND && "friend decl must be a decl or a type!");
499
John McCallaf2094e2010-04-08 09:05:18 +0000500 // All of the Visit implementations for the various potential friend
501 // declarations have to be carefully written to work for friend
502 // objects, with the most important detail being that the target
503 // decl should almost certainly not be placed in Owner.
504 Decl *NewND = Visit(ND);
Douglas Gregor06245bf2010-04-07 17:57:12 +0000505 if (!NewND) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000506
John McCall02cace72009-08-28 07:59:38 +0000507 FriendDecl *FD =
Douglas Gregor06245bf2010-04-07 17:57:12 +0000508 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
509 cast<NamedDecl>(NewND), D->getFriendLoc());
John McCall5fee1102009-08-29 03:50:18 +0000510 FD->setAccess(AS_public);
John McCall02cace72009-08-28 07:59:38 +0000511 Owner->addDecl(FD);
512 return FD;
John McCallfd810b12009-08-14 02:03:10 +0000513}
514
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000515Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
516 Expr *AssertExpr = D->getAssertExpr();
Mike Stump1eb44332009-09-09 15:08:12 +0000517
Douglas Gregorac7610d2009-06-22 20:57:11 +0000518 // The expression in a static assertion is not potentially evaluated.
519 EnterExpressionEvaluationContext Unevaluated(SemaRef, Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000521 OwningExprResult InstantiatedAssertExpr
John McCallce3ff2b2009-08-25 22:02:44 +0000522 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000523 if (InstantiatedAssertExpr.isInvalid())
524 return 0;
525
Douglas Gregor43d9d922009-08-08 01:41:12 +0000526 OwningExprResult Message(SemaRef, D->getMessage());
527 D->getMessage()->Retain();
Mike Stump1eb44332009-09-09 15:08:12 +0000528 Decl *StaticAssert
529 = SemaRef.ActOnStaticAssertDeclaration(D->getLocation(),
Chris Lattnerb28317a2009-03-28 19:18:32 +0000530 move(InstantiatedAssertExpr),
531 move(Message)).getAs<Decl>();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000532 return StaticAssert;
533}
534
535Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +0000536 EnumDecl *Enum = EnumDecl::Create(SemaRef.Context, Owner,
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000537 D->getLocation(), D->getIdentifier(),
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000538 D->getTagKeywordLoc(),
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000539 /*PrevDecl=*/0);
Douglas Gregor8dbc3c62009-05-27 17:20:35 +0000540 Enum->setInstantiationOfMemberEnum(D);
Douglas Gregor06c0fec2009-03-25 22:00:53 +0000541 Enum->setAccess(D->getAccess());
John McCallb6217662010-03-15 10:12:16 +0000542 if (SubstQualifier(D, Enum)) return 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000543 Owner->addDecl(Enum);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000544 Enum->startDefinition();
545
Douglas Gregor96084f12010-03-01 19:00:07 +0000546 if (D->getDeclContext()->isFunctionOrMethod())
547 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
548
Douglas Gregor0ca20ac2009-05-29 18:27:38 +0000549 llvm::SmallVector<Sema::DeclPtrTy, 4> Enumerators;
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000550
551 EnumConstantDecl *LastEnumConst = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000552 for (EnumDecl::enumerator_iterator EC = D->enumerator_begin(),
553 ECEnd = D->enumerator_end();
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000554 EC != ECEnd; ++EC) {
555 // The specified value for the enumerator.
556 OwningExprResult Value = SemaRef.Owned((Expr *)0);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000557 if (Expr *UninstValue = EC->getInitExpr()) {
558 // The enumerator's value expression is not potentially evaluated.
Mike Stump1eb44332009-09-09 15:08:12 +0000559 EnterExpressionEvaluationContext Unevaluated(SemaRef,
Douglas Gregorac7610d2009-06-22 20:57:11 +0000560 Action::Unevaluated);
Mike Stump1eb44332009-09-09 15:08:12 +0000561
John McCallce3ff2b2009-08-25 22:02:44 +0000562 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
Douglas Gregorac7610d2009-06-22 20:57:11 +0000563 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000564
565 // Drop the initial value and continue.
566 bool isInvalid = false;
567 if (Value.isInvalid()) {
568 Value = SemaRef.Owned((Expr *)0);
569 isInvalid = true;
570 }
571
Mike Stump1eb44332009-09-09 15:08:12 +0000572 EnumConstantDecl *EnumConst
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000573 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
574 EC->getLocation(), EC->getIdentifier(),
575 move(Value));
576
577 if (isInvalid) {
578 if (EnumConst)
579 EnumConst->setInvalidDecl();
580 Enum->setInvalidDecl();
581 }
582
583 if (EnumConst) {
John McCall3b85ecf2010-01-23 22:37:59 +0000584 EnumConst->setAccess(Enum->getAccess());
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000585 Enum->addDecl(EnumConst);
Chris Lattnerb28317a2009-03-28 19:18:32 +0000586 Enumerators.push_back(Sema::DeclPtrTy::make(EnumConst));
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000587 LastEnumConst = EnumConst;
Douglas Gregor96084f12010-03-01 19:00:07 +0000588
589 if (D->getDeclContext()->isFunctionOrMethod()) {
590 // If the enumeration is within a function or method, record the enum
591 // constant as a local.
592 SemaRef.CurrentInstantiationScope->InstantiatedLocal(*EC, EnumConst);
593 }
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000594 }
595 }
Mike Stump1eb44332009-09-09 15:08:12 +0000596
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000597 // FIXME: Fixup LBraceLoc and RBraceLoc
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000598 // FIXME: Empty Scope and AttributeList (required to handle attribute packed).
Mike Stumpc6e35aa2009-05-16 07:06:02 +0000599 SemaRef.ActOnEnumBody(Enum->getLocation(), SourceLocation(), SourceLocation(),
600 Sema::DeclPtrTy::make(Enum),
Edward O'Callaghanfee13812009-08-08 14:36:57 +0000601 &Enumerators[0], Enumerators.size(),
602 0, 0);
Douglas Gregor8dbc2692009-03-17 21:15:40 +0000603
604 return Enum;
605}
606
Douglas Gregor6477b692009-03-25 15:04:13 +0000607Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
608 assert(false && "EnumConstantDecls can only occur within EnumDecls.");
609 return 0;
610}
611
Douglas Gregored9c0f92009-10-29 00:04:11 +0000612namespace {
613 class SortDeclByLocation {
614 SourceManager &SourceMgr;
615
616 public:
617 explicit SortDeclByLocation(SourceManager &SourceMgr)
618 : SourceMgr(SourceMgr) { }
619
620 bool operator()(const Decl *X, const Decl *Y) const {
621 return SourceMgr.isBeforeInTranslationUnit(X->getLocation(),
622 Y->getLocation());
623 }
624 };
625}
626
John McCalle29ba202009-08-20 01:44:21 +0000627Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
John McCall93ba8572010-03-25 06:39:04 +0000628 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
629
Douglas Gregor550d9b22009-10-31 17:21:17 +0000630 // Create a local instantiation scope for this class template, which
631 // will contain the instantiations of the template parameters.
632 Sema::LocalInstantiationScope Scope(SemaRef);
John McCalle29ba202009-08-20 01:44:21 +0000633 TemplateParameterList *TempParams = D->getTemplateParameters();
John McCallce3ff2b2009-08-25 22:02:44 +0000634 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000635 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000636 return NULL;
John McCalle29ba202009-08-20 01:44:21 +0000637
638 CXXRecordDecl *Pattern = D->getTemplatedDecl();
John McCall93ba8572010-03-25 06:39:04 +0000639
640 // Instantiate the qualifier. We have to do this first in case
641 // we're a friend declaration, because if we are then we need to put
642 // the new declaration in the appropriate context.
643 NestedNameSpecifier *Qualifier = Pattern->getQualifier();
644 if (Qualifier) {
645 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
646 Pattern->getQualifierRange(),
647 TemplateArgs);
648 if (!Qualifier) return 0;
649 }
650
651 CXXRecordDecl *PrevDecl = 0;
652 ClassTemplateDecl *PrevClassTemplate = 0;
653
654 // If this isn't a friend, then it's a member template, in which
655 // case we just want to build the instantiation in the
656 // specialization. If it is a friend, we want to build it in
657 // the appropriate context.
658 DeclContext *DC = Owner;
659 if (isFriend) {
660 if (Qualifier) {
661 CXXScopeSpec SS;
662 SS.setScopeRep(Qualifier);
663 SS.setRange(Pattern->getQualifierRange());
664 DC = SemaRef.computeDeclContext(SS);
665 if (!DC) return 0;
666 } else {
667 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
668 Pattern->getDeclContext(),
669 TemplateArgs);
670 }
671
672 // Look for a previous declaration of the template in the owning
673 // context.
674 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
675 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
676 SemaRef.LookupQualifiedName(R, DC);
677
678 if (R.isSingleResult()) {
679 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
680 if (PrevClassTemplate)
681 PrevDecl = PrevClassTemplate->getTemplatedDecl();
682 }
683
684 if (!PrevClassTemplate && Qualifier) {
685 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
Douglas Gregor1eabb7d2010-03-31 23:17:41 +0000686 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
687 << Pattern->getQualifierRange();
John McCall93ba8572010-03-25 06:39:04 +0000688 return 0;
689 }
690
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000691 bool AdoptedPreviousTemplateParams = false;
John McCall93ba8572010-03-25 06:39:04 +0000692 if (PrevClassTemplate) {
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000693 bool Complain = true;
694
695 // HACK: libstdc++ 4.2.1 contains an ill-formed friend class
696 // template for struct std::tr1::__detail::_Map_base, where the
697 // template parameters of the friend declaration don't match the
698 // template parameters of the original declaration. In this one
699 // case, we don't complain about the ill-formed friend
700 // declaration.
701 if (isFriend && Pattern->getIdentifier() &&
702 Pattern->getIdentifier()->isStr("_Map_base") &&
703 DC->isNamespace() &&
704 cast<NamespaceDecl>(DC)->getIdentifier() &&
705 cast<NamespaceDecl>(DC)->getIdentifier()->isStr("__detail")) {
706 DeclContext *DCParent = DC->getParent();
707 if (DCParent->isNamespace() &&
708 cast<NamespaceDecl>(DCParent)->getIdentifier() &&
709 cast<NamespaceDecl>(DCParent)->getIdentifier()->isStr("tr1")) {
710 DeclContext *DCParent2 = DCParent->getParent();
711 if (DCParent2->isNamespace() &&
712 cast<NamespaceDecl>(DCParent2)->getIdentifier() &&
713 cast<NamespaceDecl>(DCParent2)->getIdentifier()->isStr("std") &&
714 DCParent2->getParent()->isTranslationUnit())
715 Complain = false;
716 }
717 }
718
John McCall93ba8572010-03-25 06:39:04 +0000719 TemplateParameterList *PrevParams
720 = PrevClassTemplate->getTemplateParameters();
721
722 // Make sure the parameter lists match.
723 if (!SemaRef.TemplateParameterListsAreEqual(InstParams, PrevParams,
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000724 Complain,
725 Sema::TPL_TemplateMatch)) {
726 if (Complain)
727 return 0;
728
729 AdoptedPreviousTemplateParams = true;
730 InstParams = PrevParams;
731 }
John McCall93ba8572010-03-25 06:39:04 +0000732
733 // Do some additional validation, then merge default arguments
734 // from the existing declarations.
Douglas Gregorc53d0d72010-04-08 18:16:15 +0000735 if (!AdoptedPreviousTemplateParams &&
736 SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
John McCall93ba8572010-03-25 06:39:04 +0000737 Sema::TPC_ClassTemplate))
738 return 0;
739 }
740 }
741
John McCalle29ba202009-08-20 01:44:21 +0000742 CXXRecordDecl *RecordInst
John McCall93ba8572010-03-25 06:39:04 +0000743 = CXXRecordDecl::Create(SemaRef.Context, Pattern->getTagKind(), DC,
John McCalle29ba202009-08-20 01:44:21 +0000744 Pattern->getLocation(), Pattern->getIdentifier(),
John McCall93ba8572010-03-25 06:39:04 +0000745 Pattern->getTagKeywordLoc(), PrevDecl,
Douglas Gregorf0510d42009-10-12 23:11:44 +0000746 /*DelayTypeCreation=*/true);
John McCalle29ba202009-08-20 01:44:21 +0000747
John McCall93ba8572010-03-25 06:39:04 +0000748 if (Qualifier)
749 RecordInst->setQualifierInfo(Qualifier, Pattern->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000750
John McCalle29ba202009-08-20 01:44:21 +0000751 ClassTemplateDecl *Inst
John McCall93ba8572010-03-25 06:39:04 +0000752 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
753 D->getIdentifier(), InstParams, RecordInst,
754 PrevClassTemplate);
John McCalle29ba202009-08-20 01:44:21 +0000755 RecordInst->setDescribedClassTemplate(Inst);
John McCallea7390c2010-04-08 20:25:50 +0000756
John McCall93ba8572010-03-25 06:39:04 +0000757 if (isFriend) {
John McCallea7390c2010-04-08 20:25:50 +0000758 if (PrevClassTemplate)
759 Inst->setAccess(PrevClassTemplate->getAccess());
760 else
761 Inst->setAccess(D->getAccess());
762
John McCall93ba8572010-03-25 06:39:04 +0000763 Inst->setObjectOfFriendDecl(PrevClassTemplate != 0);
764 // TODO: do we want to track the instantiation progeny of this
765 // friend target decl?
766 } else {
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000767 Inst->setAccess(D->getAccess());
John McCall93ba8572010-03-25 06:39:04 +0000768 Inst->setInstantiatedFromMemberTemplate(D);
769 }
Douglas Gregorf0510d42009-10-12 23:11:44 +0000770
771 // Trigger creation of the type for the instantiation.
John McCall3cb0ebd2010-03-10 03:28:59 +0000772 SemaRef.Context.getInjectedClassNameType(RecordInst,
773 Inst->getInjectedClassNameSpecialization(SemaRef.Context));
John McCallea7390c2010-04-08 20:25:50 +0000774
Douglas Gregor259571e2009-10-30 22:42:42 +0000775 // Finish handling of friends.
John McCall93ba8572010-03-25 06:39:04 +0000776 if (isFriend) {
777 DC->makeDeclVisibleInContext(Inst, /*Recoverable*/ false);
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000778 return Inst;
Douglas Gregor259571e2009-10-30 22:42:42 +0000779 }
Douglas Gregore8c01bd2009-10-30 21:07:27 +0000780
John McCalle29ba202009-08-20 01:44:21 +0000781 Owner->addDecl(Inst);
Douglas Gregored9c0f92009-10-29 00:04:11 +0000782
783 // First, we sort the partial specializations by location, so
784 // that we instantiate them in the order they were declared.
785 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
786 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
787 P = D->getPartialSpecializations().begin(),
788 PEnd = D->getPartialSpecializations().end();
789 P != PEnd; ++P)
790 PartialSpecs.push_back(&*P);
791 std::sort(PartialSpecs.begin(), PartialSpecs.end(),
792 SortDeclByLocation(SemaRef.SourceMgr));
793
794 // Instantiate all of the partial specializations of this member class
795 // template.
796 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
797 InstantiateClassTemplatePartialSpecialization(Inst, PartialSpecs[I]);
798
John McCalle29ba202009-08-20 01:44:21 +0000799 return Inst;
800}
801
Douglas Gregord60e1052009-08-27 16:57:43 +0000802Decl *
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000803TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
804 ClassTemplatePartialSpecializationDecl *D) {
Douglas Gregored9c0f92009-10-29 00:04:11 +0000805 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
806
807 // Lookup the already-instantiated declaration in the instantiation
808 // of the class template and return that.
809 DeclContext::lookup_result Found
810 = Owner->lookup(ClassTemplate->getDeclName());
811 if (Found.first == Found.second)
812 return 0;
813
814 ClassTemplateDecl *InstClassTemplate
815 = dyn_cast<ClassTemplateDecl>(*Found.first);
816 if (!InstClassTemplate)
817 return 0;
818
819 Decl *DCanon = D->getCanonicalDecl();
820 for (llvm::FoldingSet<ClassTemplatePartialSpecializationDecl>::iterator
821 P = InstClassTemplate->getPartialSpecializations().begin(),
822 PEnd = InstClassTemplate->getPartialSpecializations().end();
823 P != PEnd; ++P) {
824 if (P->getInstantiatedFromMember()->getCanonicalDecl() == DCanon)
825 return &*P;
826 }
827
Douglas Gregor7974c3b2009-10-07 17:21:34 +0000828 return 0;
829}
830
831Decl *
Douglas Gregord60e1052009-08-27 16:57:43 +0000832TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
Douglas Gregor550d9b22009-10-31 17:21:17 +0000833 // Create a local instantiation scope for this function template, which
834 // will contain the instantiations of the template parameters and then get
835 // merged with the local instantiation scope for the function template
836 // itself.
837 Sema::LocalInstantiationScope Scope(SemaRef);
838
Douglas Gregord60e1052009-08-27 16:57:43 +0000839 TemplateParameterList *TempParams = D->getTemplateParameters();
840 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
Mike Stump1eb44332009-09-09 15:08:12 +0000841 if (!InstParams)
Douglas Gregord60e1052009-08-27 16:57:43 +0000842 return NULL;
Douglas Gregored9c0f92009-10-29 00:04:11 +0000843
Douglas Gregora735b202009-10-13 14:39:41 +0000844 FunctionDecl *Instantiated = 0;
845 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
846 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
847 InstParams));
848 else
849 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
850 D->getTemplatedDecl(),
851 InstParams));
852
853 if (!Instantiated)
Douglas Gregord60e1052009-08-27 16:57:43 +0000854 return 0;
855
John McCall46460a62010-01-20 21:53:11 +0000856 Instantiated->setAccess(D->getAccess());
857
Mike Stump1eb44332009-09-09 15:08:12 +0000858 // Link the instantiated function template declaration to the function
Douglas Gregord60e1052009-08-27 16:57:43 +0000859 // template from which it was instantiated.
Douglas Gregor37d681852009-10-12 22:27:17 +0000860 FunctionTemplateDecl *InstTemplate
Douglas Gregora735b202009-10-13 14:39:41 +0000861 = Instantiated->getDescribedFunctionTemplate();
Douglas Gregor37d681852009-10-12 22:27:17 +0000862 InstTemplate->setAccess(D->getAccess());
Douglas Gregora735b202009-10-13 14:39:41 +0000863 assert(InstTemplate &&
864 "VisitFunctionDecl/CXXMethodDecl didn't create a template!");
John McCalle976ffe2009-12-14 23:19:40 +0000865
John McCallb1a56e72010-03-26 23:10:15 +0000866 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
867
John McCalle976ffe2009-12-14 23:19:40 +0000868 // Link the instantiation back to the pattern *unless* this is a
869 // non-definition friend declaration.
870 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
John McCallb1a56e72010-03-26 23:10:15 +0000871 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
Douglas Gregora735b202009-10-13 14:39:41 +0000872 InstTemplate->setInstantiatedFromMemberTemplate(D);
873
John McCallb1a56e72010-03-26 23:10:15 +0000874 // Make declarations visible in the appropriate context.
875 if (!isFriend)
Douglas Gregora735b202009-10-13 14:39:41 +0000876 Owner->addDecl(InstTemplate);
John McCallb1a56e72010-03-26 23:10:15 +0000877
Douglas Gregord60e1052009-08-27 16:57:43 +0000878 return InstTemplate;
879}
880
Douglas Gregord475b8d2009-03-25 21:17:03 +0000881Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
882 CXXRecordDecl *PrevDecl = 0;
883 if (D->isInjectedClassName())
884 PrevDecl = cast<CXXRecordDecl>(Owner);
John McCall6c1c1b82009-12-15 22:29:06 +0000885 else if (D->getPreviousDeclaration()) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000886 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
887 D->getPreviousDeclaration(),
John McCall6c1c1b82009-12-15 22:29:06 +0000888 TemplateArgs);
889 if (!Prev) return 0;
890 PrevDecl = cast<CXXRecordDecl>(Prev);
891 }
Douglas Gregord475b8d2009-03-25 21:17:03 +0000892
893 CXXRecordDecl *Record
Mike Stump1eb44332009-09-09 15:08:12 +0000894 = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
Douglas Gregor741dd9a2009-07-21 14:46:17 +0000895 D->getLocation(), D->getIdentifier(),
896 D->getTagKeywordLoc(), PrevDecl);
John McCallb6217662010-03-15 10:12:16 +0000897
898 // Substitute the nested name specifier, if any.
899 if (SubstQualifier(D, Record))
900 return 0;
901
Douglas Gregord475b8d2009-03-25 21:17:03 +0000902 Record->setImplicit(D->isImplicit());
Eli Friedmaneaba1af2009-08-27 19:11:42 +0000903 // FIXME: Check against AS_none is an ugly hack to work around the issue that
904 // the tag decls introduced by friend class declarations don't have an access
905 // specifier. Remove once this area of the code gets sorted out.
906 if (D->getAccess() != AS_none)
907 Record->setAccess(D->getAccess());
Douglas Gregord475b8d2009-03-25 21:17:03 +0000908 if (!D->isInjectedClassName())
Douglas Gregorf6b11852009-10-08 15:14:33 +0000909 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000910
John McCall02cace72009-08-28 07:59:38 +0000911 // If the original function was part of a friend declaration,
912 // inherit its namespace state.
913 if (Decl::FriendObjectKind FOK = D->getFriendObjectKind())
914 Record->setObjectOfFriendDecl(FOK == Decl::FOK_Declared);
915
Anders Carlssond8b285f2009-09-01 04:26:58 +0000916 Record->setAnonymousStructOrUnion(D->isAnonymousStructOrUnion());
917
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000918 Owner->addDecl(Record);
Douglas Gregord475b8d2009-03-25 21:17:03 +0000919 return Record;
920}
921
John McCall02cace72009-08-28 07:59:38 +0000922/// Normal class members are of more specific types and therefore
923/// don't make it here. This function serves two purposes:
924/// 1) instantiating function templates
925/// 2) substituting friend declarations
926/// FIXME: preserve function definitions in case #2
Douglas Gregor7557a132009-12-24 20:56:24 +0000927Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D,
Douglas Gregora735b202009-10-13 14:39:41 +0000928 TemplateParameterList *TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000929 // Check whether there is already a function template specialization for
930 // this declaration.
931 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
932 void *InsertPos = 0;
John McCallb0cb0222010-03-27 05:57:59 +0000933 if (FunctionTemplate && !TemplateParams) {
Douglas Gregor127102b2009-06-29 20:59:39 +0000934 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +0000935 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000936 TemplateArgs.getInnermost().getFlatArgumentList(),
937 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor828e2262009-07-29 16:09:57 +0000938 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000939
940 FunctionTemplateSpecializationInfo *Info
941 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor127102b2009-06-29 20:59:39 +0000942 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +0000943
Douglas Gregor127102b2009-06-29 20:59:39 +0000944 // If we already have a function template specialization, return it.
945 if (Info)
946 return Info->Function;
947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
John McCallb0cb0222010-03-27 05:57:59 +0000949 bool isFriend;
950 if (FunctionTemplate)
951 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
952 else
953 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
954
Douglas Gregor79c22782010-01-16 20:21:20 +0000955 bool MergeWithParentScope = (TemplateParams != 0) ||
956 !(isa<Decl>(Owner) &&
957 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
958 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000959
Douglas Gregore53060f2009-06-25 22:08:12 +0000960 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +0000961 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
962 TInfo = SubstFunctionType(D, Params);
963 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +0000964 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +0000965 QualType T = TInfo->getType();
John McCallfd810b12009-08-14 02:03:10 +0000966
John McCalld325daa2010-03-26 04:53:08 +0000967 NestedNameSpecifier *Qualifier = D->getQualifier();
968 if (Qualifier) {
969 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
970 D->getQualifierRange(),
971 TemplateArgs);
972 if (!Qualifier) return 0;
973 }
974
John McCall68b6b872010-02-06 01:50:47 +0000975 // If we're instantiating a local function declaration, put the result
976 // in the owner; otherwise we need to find the instantiated context.
977 DeclContext *DC;
978 if (D->getDeclContext()->isFunctionOrMethod())
979 DC = Owner;
John McCalld325daa2010-03-26 04:53:08 +0000980 else if (isFriend && Qualifier) {
981 CXXScopeSpec SS;
982 SS.setScopeRep(Qualifier);
983 SS.setRange(D->getQualifierRange());
984 DC = SemaRef.computeDeclContext(SS);
985 if (!DC) return 0;
986 } else {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000987 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
988 TemplateArgs);
John McCalld325daa2010-03-26 04:53:08 +0000989 }
John McCall68b6b872010-02-06 01:50:47 +0000990
John McCall02cace72009-08-28 07:59:38 +0000991 FunctionDecl *Function =
Mike Stump1eb44332009-09-09 15:08:12 +0000992 FunctionDecl::Create(SemaRef.Context, DC, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +0000993 D->getDeclName(), T, TInfo,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +0000994 D->getStorageClass(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +0000995 D->isInlineSpecified(), D->hasWrittenPrototype());
John McCallb6217662010-03-15 10:12:16 +0000996
John McCalld325daa2010-03-26 04:53:08 +0000997 if (Qualifier)
998 Function->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +0000999
John McCallb1a56e72010-03-26 23:10:15 +00001000 DeclContext *LexicalDC = Owner;
1001 if (!isFriend && D->isOutOfLine()) {
1002 assert(D->getDeclContext()->isFileContext());
1003 LexicalDC = D->getDeclContext();
1004 }
1005
1006 Function->setLexicalDeclContext(LexicalDC);
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Douglas Gregore53060f2009-06-25 22:08:12 +00001008 // Attach the parameters
1009 for (unsigned P = 0; P < Params.size(); ++P)
1010 Params[P]->setOwningFunction(Function);
Douglas Gregor838db382010-02-11 01:19:42 +00001011 Function->setParams(Params.data(), Params.size());
John McCall02cace72009-08-28 07:59:38 +00001012
Douglas Gregora735b202009-10-13 14:39:41 +00001013 if (TemplateParams) {
1014 // Our resulting instantiation is actually a function template, since we
1015 // are substituting only the outer template parameters. For example, given
1016 //
1017 // template<typename T>
1018 // struct X {
1019 // template<typename U> friend void f(T, U);
1020 // };
1021 //
1022 // X<int> x;
1023 //
1024 // We are instantiating the friend function template "f" within X<int>,
1025 // which means substituting int for T, but leaving "f" as a friend function
1026 // template.
1027 // Build the function template itself.
John McCalld325daa2010-03-26 04:53:08 +00001028 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
Douglas Gregora735b202009-10-13 14:39:41 +00001029 Function->getLocation(),
1030 Function->getDeclName(),
1031 TemplateParams, Function);
1032 Function->setDescribedFunctionTemplate(FunctionTemplate);
John McCallb1a56e72010-03-26 23:10:15 +00001033
1034 FunctionTemplate->setLexicalDeclContext(LexicalDC);
John McCalld325daa2010-03-26 04:53:08 +00001035
1036 if (isFriend && D->isThisDeclarationADefinition()) {
1037 // TODO: should we remember this connection regardless of whether
1038 // the friend declaration provided a body?
1039 FunctionTemplate->setInstantiatedFromMemberTemplate(
1040 D->getDescribedFunctionTemplate());
1041 }
Douglas Gregor66724ea2009-11-14 01:20:54 +00001042 } else if (FunctionTemplate) {
1043 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001044 Function->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001045 &TemplateArgs.getInnermost(),
1046 InsertPos);
John McCalld325daa2010-03-26 04:53:08 +00001047 } else if (isFriend && D->isThisDeclarationADefinition()) {
1048 // TODO: should we remember this connection regardless of whether
1049 // the friend declaration provided a body?
1050 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
John McCall02cace72009-08-28 07:59:38 +00001051 }
Douglas Gregora735b202009-10-13 14:39:41 +00001052
Douglas Gregore53060f2009-06-25 22:08:12 +00001053 if (InitFunctionInstantiation(Function, D))
1054 Function->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregore53060f2009-06-25 22:08:12 +00001056 bool Redeclaration = false;
1057 bool OverloadableAttrRequired = false;
John McCallaf2094e2010-04-08 09:05:18 +00001058 bool isExplicitSpecialization = false;
Douglas Gregora735b202009-10-13 14:39:41 +00001059
John McCall68263142009-11-18 22:49:29 +00001060 LookupResult Previous(SemaRef, Function->getDeclName(), SourceLocation(),
1061 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
1062
John McCallaf2094e2010-04-08 09:05:18 +00001063 if (DependentFunctionTemplateSpecializationInfo *Info
1064 = D->getDependentSpecializationInfo()) {
1065 assert(isFriend && "non-friend has dependent specialization info?");
1066
1067 // This needs to be set now for future sanity.
1068 Function->setObjectOfFriendDecl(/*HasPrevious*/ true);
1069
1070 // Instantiate the explicit template arguments.
1071 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
1072 Info->getRAngleLoc());
1073 for (unsigned I = 0, E = Info->getNumTemplateArgs(); I != E; ++I) {
1074 TemplateArgumentLoc Loc;
1075 if (SemaRef.Subst(Info->getTemplateArg(I), Loc, TemplateArgs))
1076 return 0;
1077
1078 ExplicitArgs.addArgument(Loc);
1079 }
1080
1081 // Map the candidate templates to their instantiations.
1082 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
1083 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
1084 Info->getTemplate(I),
1085 TemplateArgs);
1086 if (!Temp) return 0;
1087
1088 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
1089 }
1090
1091 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
1092 &ExplicitArgs,
1093 Previous))
1094 Function->setInvalidDecl();
1095
1096 isExplicitSpecialization = true;
1097
1098 } else if (TemplateParams || !FunctionTemplate) {
Douglas Gregora735b202009-10-13 14:39:41 +00001099 // Look only into the namespace where the friend would be declared to
1100 // find a previous declaration. This is the innermost enclosing namespace,
1101 // as described in ActOnFriendFunctionDecl.
John McCall68263142009-11-18 22:49:29 +00001102 SemaRef.LookupQualifiedName(Previous, DC);
Douglas Gregora735b202009-10-13 14:39:41 +00001103
Douglas Gregora735b202009-10-13 14:39:41 +00001104 // In C++, the previous declaration we find might be a tag type
1105 // (class or enum). In this case, the new declaration will hide the
1106 // tag type. Note that this does does not apply if we're declaring a
1107 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001108 if (Previous.isSingleTagDecl())
1109 Previous.clear();
Douglas Gregora735b202009-10-13 14:39:41 +00001110 }
1111
John McCall9f54ad42009-12-10 09:41:52 +00001112 SemaRef.CheckFunctionDeclaration(/*Scope*/ 0, Function, Previous,
John McCallaf2094e2010-04-08 09:05:18 +00001113 isExplicitSpecialization, Redeclaration,
Douglas Gregore53060f2009-06-25 22:08:12 +00001114 /*FIXME:*/OverloadableAttrRequired);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001115
Douglas Gregora735b202009-10-13 14:39:41 +00001116 // If the original function was part of a friend declaration,
1117 // inherit its namespace state and add it to the owner.
John McCalld325daa2010-03-26 04:53:08 +00001118 if (isFriend) {
Douglas Gregora735b202009-10-13 14:39:41 +00001119 NamedDecl *ToFriendD = 0;
John McCall68263142009-11-18 22:49:29 +00001120 NamedDecl *PrevDecl;
Douglas Gregora735b202009-10-13 14:39:41 +00001121 if (TemplateParams) {
1122 ToFriendD = cast<NamedDecl>(FunctionTemplate);
1123 PrevDecl = FunctionTemplate->getPreviousDeclaration();
1124 } else {
1125 ToFriendD = Function;
1126 PrevDecl = Function->getPreviousDeclaration();
1127 }
1128 ToFriendD->setObjectOfFriendDecl(PrevDecl != NULL);
John McCalld325daa2010-03-26 04:53:08 +00001129 DC->makeDeclVisibleInContext(ToFriendD, /*Recoverable=*/ false);
Douglas Gregora735b202009-10-13 14:39:41 +00001130 }
1131
Douglas Gregore53060f2009-06-25 22:08:12 +00001132 return Function;
1133}
1134
Douglas Gregord60e1052009-08-27 16:57:43 +00001135Decl *
1136TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D,
1137 TemplateParameterList *TemplateParams) {
Douglas Gregor6b906862009-08-21 00:16:32 +00001138 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
1139 void *InsertPos = 0;
Douglas Gregord60e1052009-08-27 16:57:43 +00001140 if (FunctionTemplate && !TemplateParams) {
Mike Stump1eb44332009-09-09 15:08:12 +00001141 // We are creating a function template specialization from a function
1142 // template. Check whether there is already a function template
Douglas Gregord60e1052009-08-27 16:57:43 +00001143 // specialization for this particular set of template arguments.
Douglas Gregor6b906862009-08-21 00:16:32 +00001144 llvm::FoldingSetNodeID ID;
Mike Stump1eb44332009-09-09 15:08:12 +00001145 FunctionTemplateSpecializationInfo::Profile(ID,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001146 TemplateArgs.getInnermost().getFlatArgumentList(),
1147 TemplateArgs.getInnermost().flat_size(),
Douglas Gregor6b906862009-08-21 00:16:32 +00001148 SemaRef.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001149
1150 FunctionTemplateSpecializationInfo *Info
1151 = FunctionTemplate->getSpecializations().FindNodeOrInsertPos(ID,
Douglas Gregor6b906862009-08-21 00:16:32 +00001152 InsertPos);
Mike Stump1eb44332009-09-09 15:08:12 +00001153
Douglas Gregor6b906862009-08-21 00:16:32 +00001154 // If we already have a function template specialization, return it.
1155 if (Info)
1156 return Info->Function;
1157 }
1158
John McCallb0cb0222010-03-27 05:57:59 +00001159 bool isFriend;
1160 if (FunctionTemplate)
1161 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
1162 else
1163 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1164
Douglas Gregor79c22782010-01-16 20:21:20 +00001165 bool MergeWithParentScope = (TemplateParams != 0) ||
1166 !(isa<Decl>(Owner) &&
1167 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
1168 Sema::LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001169
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001170 llvm::SmallVector<ParmVarDecl *, 4> Params;
John McCall21ef0fa2010-03-11 09:03:00 +00001171 TypeSourceInfo *TInfo = D->getTypeSourceInfo();
1172 TInfo = SubstFunctionType(D, Params);
1173 if (!TInfo)
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001174 return 0;
John McCall21ef0fa2010-03-11 09:03:00 +00001175 QualType T = TInfo->getType();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001176
John McCallb0cb0222010-03-27 05:57:59 +00001177 NestedNameSpecifier *Qualifier = D->getQualifier();
1178 if (Qualifier) {
1179 Qualifier = SemaRef.SubstNestedNameSpecifier(Qualifier,
1180 D->getQualifierRange(),
1181 TemplateArgs);
1182 if (!Qualifier) return 0;
1183 }
1184
1185 DeclContext *DC = Owner;
1186 if (isFriend) {
1187 if (Qualifier) {
1188 CXXScopeSpec SS;
1189 SS.setScopeRep(Qualifier);
1190 SS.setRange(D->getQualifierRange());
1191 DC = SemaRef.computeDeclContext(SS);
1192 } else {
1193 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
1194 D->getDeclContext(),
1195 TemplateArgs);
1196 }
1197 if (!DC) return 0;
1198 }
1199
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001200 // Build the instantiated method declaration.
John McCallb0cb0222010-03-27 05:57:59 +00001201 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Douglas Gregordec06662009-08-21 18:42:58 +00001202 CXXMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregordec06662009-08-21 18:42:58 +00001204 DeclarationName Name = D->getDeclName();
Douglas Gregor17e32f32009-08-21 22:43:28 +00001205 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001206 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1207 Name = SemaRef.Context.DeclarationNames.getCXXConstructorName(
1208 SemaRef.Context.getCanonicalType(ClassTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001209 Method = CXXConstructorDecl::Create(SemaRef.Context, Record,
1210 Constructor->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001211 Name, T, TInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00001212 Constructor->isExplicit(),
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001213 Constructor->isInlineSpecified(), false);
Douglas Gregor17e32f32009-08-21 22:43:28 +00001214 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
1215 QualType ClassTy = SemaRef.Context.getTypeDeclType(Record);
1216 Name = SemaRef.Context.DeclarationNames.getCXXDestructorName(
1217 SemaRef.Context.getCanonicalType(ClassTy));
1218 Method = CXXDestructorDecl::Create(SemaRef.Context, Record,
1219 Destructor->getLocation(), Name,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001220 T, Destructor->isInlineSpecified(), false);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001221 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001222 CanQualType ConvTy
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001223 = SemaRef.Context.getCanonicalType(
John McCall183700f2009-09-21 23:43:11 +00001224 T->getAs<FunctionType>()->getResultType());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001225 Name = SemaRef.Context.DeclarationNames.getCXXConversionFunctionName(
1226 ConvTy);
1227 Method = CXXConversionDecl::Create(SemaRef.Context, Record,
1228 Conversion->getLocation(), Name,
John McCall21ef0fa2010-03-11 09:03:00 +00001229 T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001230 Conversion->isInlineSpecified(),
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001231 Conversion->isExplicit());
Douglas Gregordec06662009-08-21 18:42:58 +00001232 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001233 Method = CXXMethodDecl::Create(SemaRef.Context, Record, D->getLocation(),
John McCall21ef0fa2010-03-11 09:03:00 +00001234 D->getDeclName(), T, TInfo,
Douglas Gregor0130f3c2009-10-27 21:01:01 +00001235 D->isStatic(), D->isInlineSpecified());
Douglas Gregordec06662009-08-21 18:42:58 +00001236 }
Douglas Gregor6b906862009-08-21 00:16:32 +00001237
John McCallb0cb0222010-03-27 05:57:59 +00001238 if (Qualifier)
1239 Method->setQualifierInfo(Qualifier, D->getQualifierRange());
John McCallb6217662010-03-15 10:12:16 +00001240
Douglas Gregord60e1052009-08-27 16:57:43 +00001241 if (TemplateParams) {
1242 // Our resulting instantiation is actually a function template, since we
1243 // are substituting only the outer template parameters. For example, given
Mike Stump1eb44332009-09-09 15:08:12 +00001244 //
Douglas Gregord60e1052009-08-27 16:57:43 +00001245 // template<typename T>
1246 // struct X {
1247 // template<typename U> void f(T, U);
1248 // };
1249 //
1250 // X<int> x;
1251 //
1252 // We are instantiating the member template "f" within X<int>, which means
1253 // substituting int for T, but leaving "f" as a member function template.
1254 // Build the function template itself.
1255 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
1256 Method->getLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00001257 Method->getDeclName(),
Douglas Gregord60e1052009-08-27 16:57:43 +00001258 TemplateParams, Method);
John McCallb0cb0222010-03-27 05:57:59 +00001259 if (isFriend) {
1260 FunctionTemplate->setLexicalDeclContext(Owner);
1261 FunctionTemplate->setObjectOfFriendDecl(true);
1262 } else if (D->isOutOfLine())
Mike Stump1eb44332009-09-09 15:08:12 +00001263 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
Douglas Gregord60e1052009-08-27 16:57:43 +00001264 Method->setDescribedFunctionTemplate(FunctionTemplate);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001265 } else if (FunctionTemplate) {
1266 // Record this function template specialization.
Douglas Gregor838db382010-02-11 01:19:42 +00001267 Method->setFunctionTemplateSpecialization(FunctionTemplate,
Douglas Gregor66724ea2009-11-14 01:20:54 +00001268 &TemplateArgs.getInnermost(),
1269 InsertPos);
John McCallb0cb0222010-03-27 05:57:59 +00001270 } else if (!isFriend) {
Douglas Gregor66724ea2009-11-14 01:20:54 +00001271 // Record that this is an instantiation of a member function.
Douglas Gregor2db32322009-10-07 23:56:10 +00001272 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001273 }
1274
Mike Stump1eb44332009-09-09 15:08:12 +00001275 // If we are instantiating a member function defined
Douglas Gregor7caa6822009-07-24 20:34:43 +00001276 // out-of-line, the instantiation will have the same lexical
1277 // context (which will be a namespace scope) as the template.
John McCallb0cb0222010-03-27 05:57:59 +00001278 if (isFriend) {
1279 Method->setLexicalDeclContext(Owner);
1280 Method->setObjectOfFriendDecl(true);
1281 } else if (D->isOutOfLine())
Douglas Gregor7caa6822009-07-24 20:34:43 +00001282 Method->setLexicalDeclContext(D->getLexicalDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Douglas Gregor5545e162009-03-24 00:38:23 +00001284 // Attach the parameters
1285 for (unsigned P = 0; P < Params.size(); ++P)
1286 Params[P]->setOwningFunction(Method);
Douglas Gregor838db382010-02-11 01:19:42 +00001287 Method->setParams(Params.data(), Params.size());
Douglas Gregor5545e162009-03-24 00:38:23 +00001288
1289 if (InitMethodInstantiation(Method, D))
1290 Method->setInvalidDecl();
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001291
John McCall68263142009-11-18 22:49:29 +00001292 LookupResult Previous(SemaRef, Name, SourceLocation(),
1293 Sema::LookupOrdinaryName, Sema::ForRedeclaration);
Mike Stump1eb44332009-09-09 15:08:12 +00001294
John McCallb0cb0222010-03-27 05:57:59 +00001295 if (!FunctionTemplate || TemplateParams || isFriend) {
1296 SemaRef.LookupQualifiedName(Previous, Record);
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Douglas Gregordec06662009-08-21 18:42:58 +00001298 // In C++, the previous declaration we find might be a tag type
1299 // (class or enum). In this case, the new declaration will hide the
1300 // tag type. Note that this does does not apply if we're declaring a
1301 // typedef (C++ [dcl.typedef]p4).
John McCall68263142009-11-18 22:49:29 +00001302 if (Previous.isSingleTagDecl())
1303 Previous.clear();
Douglas Gregordec06662009-08-21 18:42:58 +00001304 }
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001305
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001306 bool Redeclaration = false;
1307 bool OverloadableAttrRequired = false;
John McCall9f54ad42009-12-10 09:41:52 +00001308 SemaRef.CheckFunctionDeclaration(0, Method, Previous, false, Redeclaration,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001309 /*FIXME:*/OverloadableAttrRequired);
1310
Douglas Gregor4ba31362009-12-01 17:24:26 +00001311 if (D->isPure())
1312 SemaRef.CheckPureMethod(Method, SourceRange());
1313
John McCall46460a62010-01-20 21:53:11 +00001314 Method->setAccess(D->getAccess());
1315
John McCallb0cb0222010-03-27 05:57:59 +00001316 if (FunctionTemplate) {
1317 // If there's a function template, let our caller handle it.
1318 } else if (Method->isInvalidDecl() && !Previous.empty()) {
1319 // Don't hide a (potentially) valid declaration with an invalid one.
1320 } else {
1321 NamedDecl *DeclToAdd = (TemplateParams
1322 ? cast<NamedDecl>(FunctionTemplate)
1323 : Method);
1324 if (isFriend)
1325 Record->makeDeclVisibleInContext(DeclToAdd);
1326 else
1327 Owner->addDecl(DeclToAdd);
1328 }
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001330 return Method;
1331}
1332
Douglas Gregor615c5d42009-03-24 16:43:20 +00001333Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
Douglas Gregordec06662009-08-21 18:42:58 +00001334 return VisitCXXMethodDecl(D);
Douglas Gregor615c5d42009-03-24 16:43:20 +00001335}
1336
Douglas Gregor03b2b072009-03-24 00:15:49 +00001337Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
Douglas Gregor17e32f32009-08-21 22:43:28 +00001338 return VisitCXXMethodDecl(D);
Douglas Gregor03b2b072009-03-24 00:15:49 +00001339}
1340
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001341Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00001342 return VisitCXXMethodDecl(D);
Douglas Gregorbb969ed2009-03-25 00:34:44 +00001343}
1344
Douglas Gregor6477b692009-03-25 15:04:13 +00001345ParmVarDecl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
John McCall58e46772009-10-23 21:48:59 +00001346 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001347 TypeSourceInfo *DI = D->getTypeSourceInfo();
John McCall58e46772009-10-23 21:48:59 +00001348 if (DI) {
1349 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1350 D->getDeclName());
1351 if (DI) T = DI->getType();
1352 } else {
1353 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1354 D->getDeclName());
1355 DI = 0;
1356 }
1357
1358 if (T.isNull())
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001359 return 0;
1360
John McCall58e46772009-10-23 21:48:59 +00001361 T = SemaRef.adjustParameterType(T);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001362
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001363 // Allocate the parameter
John McCall58e46772009-10-23 21:48:59 +00001364 ParmVarDecl *Param
John McCall7a9813c2010-01-22 00:28:27 +00001365 = ParmVarDecl::Create(SemaRef.Context,
1366 SemaRef.Context.getTranslationUnitDecl(),
1367 D->getLocation(),
John McCall58e46772009-10-23 21:48:59 +00001368 D->getIdentifier(), T, DI, D->getStorageClass(), 0);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001369
Anders Carlsson9351c172009-08-25 03:18:48 +00001370 // Mark the default argument as being uninstantiated.
Douglas Gregorf43d0b32009-09-25 06:56:31 +00001371 if (D->hasUninstantiatedDefaultArg())
1372 Param->setUninstantiatedDefaultArg(D->getUninstantiatedDefaultArg());
Douglas Gregor0ed09302009-09-25 07:03:22 +00001373 else if (Expr *Arg = D->getDefaultArg())
1374 Param->setUninstantiatedDefaultArg(Arg);
1375
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001376 // Note: we don't try to instantiate function parameters until after
1377 // we've instantiated the function's type. Therefore, we don't have
1378 // to check for 'void' parameter types here.
Douglas Gregor48dd19b2009-05-14 21:44:34 +00001379 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor2dc0e642009-03-23 23:06:20 +00001380 return Param;
1381}
1382
John McCalle29ba202009-08-20 01:44:21 +00001383Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
1384 TemplateTypeParmDecl *D) {
1385 // TODO: don't always clone when decls are refcounted.
1386 const Type* T = D->getTypeForDecl();
1387 assert(T->isTemplateTypeParmType());
1388 const TemplateTypeParmType *TTPT = T->getAs<TemplateTypeParmType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001389
John McCalle29ba202009-08-20 01:44:21 +00001390 TemplateTypeParmDecl *Inst =
1391 TemplateTypeParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
Douglas Gregor550d9b22009-10-31 17:21:17 +00001392 TTPT->getDepth() - 1, TTPT->getIndex(),
John McCalle29ba202009-08-20 01:44:21 +00001393 TTPT->getName(),
1394 D->wasDeclaredWithTypename(),
1395 D->isParameterPack());
1396
Douglas Gregor0f8716b2009-11-09 19:17:50 +00001397 if (D->hasDefaultArgument())
1398 Inst->setDefaultArgument(D->getDefaultArgumentInfo(), false);
John McCalle29ba202009-08-20 01:44:21 +00001399
Douglas Gregor550d9b22009-10-31 17:21:17 +00001400 // Introduce this template parameter's instantiation into the instantiation
1401 // scope.
1402 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1403
John McCalle29ba202009-08-20 01:44:21 +00001404 return Inst;
1405}
1406
Douglas Gregor33642df2009-10-23 23:25:44 +00001407Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
1408 NonTypeTemplateParmDecl *D) {
1409 // Substitute into the type of the non-type template parameter.
1410 QualType T;
John McCalla93c9342009-12-07 02:54:59 +00001411 TypeSourceInfo *DI = D->getTypeSourceInfo();
Douglas Gregor33642df2009-10-23 23:25:44 +00001412 if (DI) {
1413 DI = SemaRef.SubstType(DI, TemplateArgs, D->getLocation(),
1414 D->getDeclName());
1415 if (DI) T = DI->getType();
1416 } else {
1417 T = SemaRef.SubstType(D->getType(), TemplateArgs, D->getLocation(),
1418 D->getDeclName());
1419 DI = 0;
1420 }
1421 if (T.isNull())
1422 return 0;
1423
1424 // Check that this type is acceptable for a non-type template parameter.
1425 bool Invalid = false;
1426 T = SemaRef.CheckNonTypeTemplateParameterType(T, D->getLocation());
1427 if (T.isNull()) {
1428 T = SemaRef.Context.IntTy;
1429 Invalid = true;
1430 }
1431
1432 NonTypeTemplateParmDecl *Param
1433 = NonTypeTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1434 D->getDepth() - 1, D->getPosition(),
1435 D->getIdentifier(), T, DI);
1436 if (Invalid)
1437 Param->setInvalidDecl();
1438
1439 Param->setDefaultArgument(D->getDefaultArgument());
Douglas Gregor550d9b22009-10-31 17:21:17 +00001440
1441 // Introduce this template parameter's instantiation into the instantiation
1442 // scope.
1443 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
Douglas Gregor33642df2009-10-23 23:25:44 +00001444 return Param;
1445}
1446
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001447Decl *
Douglas Gregor9106ef72009-11-11 16:58:32 +00001448TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
1449 TemplateTemplateParmDecl *D) {
1450 // Instantiate the template parameter list of the template template parameter.
1451 TemplateParameterList *TempParams = D->getTemplateParameters();
1452 TemplateParameterList *InstParams;
1453 {
1454 // Perform the actual substitution of template parameters within a new,
1455 // local instantiation scope.
1456 Sema::LocalInstantiationScope Scope(SemaRef);
1457 InstParams = SubstTemplateParams(TempParams);
1458 if (!InstParams)
1459 return NULL;
1460 }
1461
1462 // Build the template template parameter.
1463 TemplateTemplateParmDecl *Param
1464 = TemplateTemplateParmDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1465 D->getDepth() - 1, D->getPosition(),
1466 D->getIdentifier(), InstParams);
1467 Param->setDefaultArgument(D->getDefaultArgument());
1468
1469 // Introduce this template parameter's instantiation into the instantiation
1470 // scope.
1471 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
1472
1473 return Param;
1474}
1475
Douglas Gregor48c32a72009-11-17 06:07:40 +00001476Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1477 // Using directives are never dependent, so they require no explicit
1478
1479 UsingDirectiveDecl *Inst
1480 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1481 D->getNamespaceKeyLocation(),
1482 D->getQualifierRange(), D->getQualifier(),
1483 D->getIdentLocation(),
1484 D->getNominatedNamespace(),
1485 D->getCommonAncestor());
1486 Owner->addDecl(Inst);
1487 return Inst;
1488}
1489
John McCalled976492009-12-04 22:46:56 +00001490Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
1491 // The nested name specifier is non-dependent, so no transformation
1492 // is required.
1493
John McCall9f54ad42009-12-10 09:41:52 +00001494 // We only need to do redeclaration lookups if we're in a class
1495 // scope (in fact, it's not really even possible in non-class
1496 // scopes).
1497 bool CheckRedeclaration = Owner->isRecord();
1498
1499 LookupResult Prev(SemaRef, D->getDeclName(), D->getLocation(),
1500 Sema::LookupUsingDeclName, Sema::ForRedeclaration);
1501
John McCalled976492009-12-04 22:46:56 +00001502 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
1503 D->getLocation(),
1504 D->getNestedNameRange(),
1505 D->getUsingLocation(),
1506 D->getTargetNestedNameDecl(),
1507 D->getDeclName(),
1508 D->isTypeName());
1509
1510 CXXScopeSpec SS;
1511 SS.setScopeRep(D->getTargetNestedNameDecl());
1512 SS.setRange(D->getNestedNameRange());
John McCall9f54ad42009-12-10 09:41:52 +00001513
1514 if (CheckRedeclaration) {
1515 Prev.setHideTags(false);
1516 SemaRef.LookupQualifiedName(Prev, Owner);
1517
1518 // Check for invalid redeclarations.
1519 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLocation(),
1520 D->isTypeName(), SS,
1521 D->getLocation(), Prev))
1522 NewUD->setInvalidDecl();
1523
1524 }
1525
1526 if (!NewUD->isInvalidDecl() &&
1527 SemaRef.CheckUsingDeclQualifier(D->getUsingLocation(), SS,
John McCalled976492009-12-04 22:46:56 +00001528 D->getLocation()))
1529 NewUD->setInvalidDecl();
John McCall9f54ad42009-12-10 09:41:52 +00001530
John McCalled976492009-12-04 22:46:56 +00001531 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
1532 NewUD->setAccess(D->getAccess());
1533 Owner->addDecl(NewUD);
1534
John McCall9f54ad42009-12-10 09:41:52 +00001535 // Don't process the shadow decls for an invalid decl.
1536 if (NewUD->isInvalidDecl())
1537 return NewUD;
1538
John McCall323c3102009-12-22 22:26:37 +00001539 bool isFunctionScope = Owner->isFunctionOrMethod();
1540
John McCall9f54ad42009-12-10 09:41:52 +00001541 // Process the shadow decls.
1542 for (UsingDecl::shadow_iterator I = D->shadow_begin(), E = D->shadow_end();
1543 I != E; ++I) {
1544 UsingShadowDecl *Shadow = *I;
1545 NamedDecl *InstTarget =
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001546 cast<NamedDecl>(SemaRef.FindInstantiatedDecl(Shadow->getLocation(),
1547 Shadow->getTargetDecl(),
John McCall9f54ad42009-12-10 09:41:52 +00001548 TemplateArgs));
1549
1550 if (CheckRedeclaration &&
1551 SemaRef.CheckUsingShadowDecl(NewUD, InstTarget, Prev))
1552 continue;
1553
1554 UsingShadowDecl *InstShadow
1555 = SemaRef.BuildUsingShadowDecl(/*Scope*/ 0, NewUD, InstTarget);
1556 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
John McCall323c3102009-12-22 22:26:37 +00001557
1558 if (isFunctionScope)
1559 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
John McCall9f54ad42009-12-10 09:41:52 +00001560 }
John McCalled976492009-12-04 22:46:56 +00001561
1562 return NewUD;
1563}
1564
1565Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
John McCall9f54ad42009-12-10 09:41:52 +00001566 // Ignore these; we handle them in bulk when processing the UsingDecl.
1567 return 0;
John McCalled976492009-12-04 22:46:56 +00001568}
1569
John McCall7ba107a2009-11-18 02:36:19 +00001570Decl * TemplateDeclInstantiator
1571 ::VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00001572 NestedNameSpecifier *NNS =
1573 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1574 D->getTargetNestedNameRange(),
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001575 TemplateArgs);
1576 if (!NNS)
1577 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001579 CXXScopeSpec SS;
1580 SS.setRange(D->getTargetNestedNameRange());
1581 SS.setScopeRep(NNS);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
1583 NamedDecl *UD =
John McCall9488ea12009-11-17 05:59:44 +00001584 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
John McCall7ba107a2009-11-18 02:36:19 +00001585 D->getUsingLoc(), SS, D->getLocation(),
1586 D->getDeclName(), 0,
1587 /*instantiation*/ true,
1588 /*typename*/ true, D->getTypenameLoc());
1589 if (UD)
John McCalled976492009-12-04 22:46:56 +00001590 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1591
John McCall7ba107a2009-11-18 02:36:19 +00001592 return UD;
1593}
1594
1595Decl * TemplateDeclInstantiator
1596 ::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1597 NestedNameSpecifier *NNS =
1598 SemaRef.SubstNestedNameSpecifier(D->getTargetNestedNameSpecifier(),
1599 D->getTargetNestedNameRange(),
1600 TemplateArgs);
1601 if (!NNS)
1602 return 0;
1603
1604 CXXScopeSpec SS;
1605 SS.setRange(D->getTargetNestedNameRange());
1606 SS.setScopeRep(NNS);
1607
1608 NamedDecl *UD =
1609 SemaRef.BuildUsingDeclaration(/*Scope*/ 0, D->getAccess(),
1610 D->getUsingLoc(), SS, D->getLocation(),
1611 D->getDeclName(), 0,
1612 /*instantiation*/ true,
1613 /*typename*/ false, SourceLocation());
Anders Carlsson0d8df782009-08-29 19:37:28 +00001614 if (UD)
John McCalled976492009-12-04 22:46:56 +00001615 SemaRef.Context.setInstantiatedFromUsingDecl(cast<UsingDecl>(UD), D);
1616
Anders Carlsson0d8df782009-08-29 19:37:28 +00001617 return UD;
Anders Carlsson0dde18e2009-08-28 15:18:15 +00001618}
1619
John McCallce3ff2b2009-08-25 22:02:44 +00001620Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001621 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor7e063902009-05-11 23:53:27 +00001622 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
Douglas Gregor2fa98002010-02-16 19:28:15 +00001623 if (D->isInvalidDecl())
1624 return 0;
1625
Douglas Gregor8dbc2692009-03-17 21:15:40 +00001626 return Instantiator.Visit(D);
1627}
1628
John McCalle29ba202009-08-20 01:44:21 +00001629/// \brief Instantiates a nested template parameter list in the current
1630/// instantiation context.
1631///
1632/// \param L The parameter list to instantiate
1633///
1634/// \returns NULL if there was an error
1635TemplateParameterList *
John McCallce3ff2b2009-08-25 22:02:44 +00001636TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
John McCalle29ba202009-08-20 01:44:21 +00001637 // Get errors for all the parameters before bailing out.
1638 bool Invalid = false;
1639
1640 unsigned N = L->size();
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001641 typedef llvm::SmallVector<NamedDecl *, 8> ParamVector;
John McCalle29ba202009-08-20 01:44:21 +00001642 ParamVector Params;
1643 Params.reserve(N);
1644 for (TemplateParameterList::iterator PI = L->begin(), PE = L->end();
1645 PI != PE; ++PI) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001646 NamedDecl *D = cast_or_null<NamedDecl>(Visit(*PI));
John McCalle29ba202009-08-20 01:44:21 +00001647 Params.push_back(D);
Douglas Gregor9148c3f2009-11-11 19:13:48 +00001648 Invalid = Invalid || !D || D->isInvalidDecl();
John McCalle29ba202009-08-20 01:44:21 +00001649 }
1650
1651 // Clean up if we had an error.
1652 if (Invalid) {
1653 for (ParamVector::iterator PI = Params.begin(), PE = Params.end();
1654 PI != PE; ++PI)
1655 if (*PI)
1656 (*PI)->Destroy(SemaRef.Context);
1657 return NULL;
1658 }
1659
1660 TemplateParameterList *InstL
1661 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
1662 L->getLAngleLoc(), &Params.front(), N,
1663 L->getRAngleLoc());
1664 return InstL;
Mike Stump1eb44332009-09-09 15:08:12 +00001665}
John McCalle29ba202009-08-20 01:44:21 +00001666
Douglas Gregored9c0f92009-10-29 00:04:11 +00001667/// \brief Instantiate the declaration of a class template partial
1668/// specialization.
1669///
1670/// \param ClassTemplate the (instantiated) class template that is partially
1671// specialized by the instantiation of \p PartialSpec.
1672///
1673/// \param PartialSpec the (uninstantiated) class template partial
1674/// specialization that we are instantiating.
1675///
1676/// \returns true if there was an error, false otherwise.
1677bool
1678TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
1679 ClassTemplateDecl *ClassTemplate,
1680 ClassTemplatePartialSpecializationDecl *PartialSpec) {
Douglas Gregor550d9b22009-10-31 17:21:17 +00001681 // Create a local instantiation scope for this class template partial
1682 // specialization, which will contain the instantiations of the template
1683 // parameters.
1684 Sema::LocalInstantiationScope Scope(SemaRef);
1685
Douglas Gregored9c0f92009-10-29 00:04:11 +00001686 // Substitute into the template parameters of the class template partial
1687 // specialization.
1688 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
1689 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1690 if (!InstParams)
1691 return true;
1692
1693 // Substitute into the template arguments of the class template partial
1694 // specialization.
John McCall833ca992009-10-29 08:12:44 +00001695 const TemplateArgumentLoc *PartialSpecTemplateArgs
1696 = PartialSpec->getTemplateArgsAsWritten();
1697 unsigned N = PartialSpec->getNumTemplateArgsAsWritten();
1698
John McCalld5532b62009-11-23 01:53:49 +00001699 TemplateArgumentListInfo InstTemplateArgs; // no angle locations
John McCall833ca992009-10-29 08:12:44 +00001700 for (unsigned I = 0; I != N; ++I) {
John McCalld5532b62009-11-23 01:53:49 +00001701 TemplateArgumentLoc Loc;
1702 if (SemaRef.Subst(PartialSpecTemplateArgs[I], Loc, TemplateArgs))
Douglas Gregored9c0f92009-10-29 00:04:11 +00001703 return true;
John McCalld5532b62009-11-23 01:53:49 +00001704 InstTemplateArgs.addArgument(Loc);
Douglas Gregored9c0f92009-10-29 00:04:11 +00001705 }
1706
1707
1708 // Check that the template argument list is well-formed for this
1709 // class template.
1710 TemplateArgumentListBuilder Converted(ClassTemplate->getTemplateParameters(),
1711 InstTemplateArgs.size());
1712 if (SemaRef.CheckTemplateArgumentList(ClassTemplate,
1713 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001714 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001715 false,
1716 Converted))
1717 return true;
1718
1719 // Figure out where to insert this class template partial specialization
1720 // in the member template's set of class template partial specializations.
1721 llvm::FoldingSetNodeID ID;
1722 ClassTemplatePartialSpecializationDecl::Profile(ID,
1723 Converted.getFlatArguments(),
1724 Converted.flatSize(),
1725 SemaRef.Context);
1726 void *InsertPos = 0;
1727 ClassTemplateSpecializationDecl *PrevDecl
1728 = ClassTemplate->getPartialSpecializations().FindNodeOrInsertPos(ID,
1729 InsertPos);
1730
1731 // Build the canonical type that describes the converted template
1732 // arguments of the class template partial specialization.
1733 QualType CanonType
1734 = SemaRef.Context.getTemplateSpecializationType(TemplateName(ClassTemplate),
1735 Converted.getFlatArguments(),
1736 Converted.flatSize());
1737
1738 // Build the fully-sugared type for this class template
1739 // specialization as the user wrote in the specialization
1740 // itself. This means that we'll pretty-print the type retrieved
1741 // from the specialization's declaration the way that the user
1742 // actually wrote the specialization, rather than formatting the
1743 // name based on the "canonical" representation used to store the
1744 // template arguments in the specialization.
John McCall3cb0ebd2010-03-10 03:28:59 +00001745 TypeSourceInfo *WrittenTy
1746 = SemaRef.Context.getTemplateSpecializationTypeInfo(
1747 TemplateName(ClassTemplate),
1748 PartialSpec->getLocation(),
John McCalld5532b62009-11-23 01:53:49 +00001749 InstTemplateArgs,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001750 CanonType);
1751
1752 if (PrevDecl) {
1753 // We've already seen a partial specialization with the same template
1754 // parameters and template arguments. This can happen, for example, when
1755 // substituting the outer template arguments ends up causing two
1756 // class template partial specializations of a member class template
1757 // to have identical forms, e.g.,
1758 //
1759 // template<typename T, typename U>
1760 // struct Outer {
1761 // template<typename X, typename Y> struct Inner;
1762 // template<typename Y> struct Inner<T, Y>;
1763 // template<typename Y> struct Inner<U, Y>;
1764 // };
1765 //
1766 // Outer<int, int> outer; // error: the partial specializations of Inner
1767 // // have the same signature.
1768 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
1769 << WrittenTy;
1770 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
1771 << SemaRef.Context.getTypeDeclType(PrevDecl);
1772 return true;
1773 }
1774
1775
1776 // Create the class template partial specialization declaration.
1777 ClassTemplatePartialSpecializationDecl *InstPartialSpec
1778 = ClassTemplatePartialSpecializationDecl::Create(SemaRef.Context, Owner,
1779 PartialSpec->getLocation(),
1780 InstParams,
1781 ClassTemplate,
1782 Converted,
John McCalld5532b62009-11-23 01:53:49 +00001783 InstTemplateArgs,
John McCall3cb0ebd2010-03-10 03:28:59 +00001784 CanonType,
Douglas Gregored9c0f92009-10-29 00:04:11 +00001785 0);
John McCallb6217662010-03-15 10:12:16 +00001786 // Substitute the nested name specifier, if any.
1787 if (SubstQualifier(PartialSpec, InstPartialSpec))
1788 return 0;
1789
Douglas Gregored9c0f92009-10-29 00:04:11 +00001790 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
1791 InstPartialSpec->setTypeAsWritten(WrittenTy);
1792
1793 // Add this partial specialization to the set of class template partial
1794 // specializations.
1795 ClassTemplate->getPartialSpecializations().InsertNode(InstPartialSpec,
1796 InsertPos);
1797 return false;
1798}
1799
John McCall21ef0fa2010-03-11 09:03:00 +00001800bool
1801Sema::CheckInstantiatedParams(llvm::SmallVectorImpl<ParmVarDecl*> &Params) {
1802 bool Invalid = false;
1803 for (unsigned i = 0, i_end = Params.size(); i != i_end; ++i)
1804 if (ParmVarDecl *PInst = Params[i]) {
1805 if (PInst->isInvalidDecl())
1806 Invalid = true;
1807 else if (PInst->getType()->isVoidType()) {
1808 Diag(PInst->getLocation(), diag::err_param_with_void_type);
1809 PInst->setInvalidDecl();
1810 Invalid = true;
1811 }
1812 else if (RequireNonAbstractType(PInst->getLocation(),
1813 PInst->getType(),
1814 diag::err_abstract_type_in_decl,
1815 Sema::AbstractParamType)) {
1816 PInst->setInvalidDecl();
1817 Invalid = true;
1818 }
1819 }
1820 return Invalid;
1821}
Douglas Gregor5545e162009-03-24 00:38:23 +00001822
John McCall21ef0fa2010-03-11 09:03:00 +00001823TypeSourceInfo*
John McCallce3ff2b2009-08-25 22:02:44 +00001824TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
Douglas Gregor5545e162009-03-24 00:38:23 +00001825 llvm::SmallVectorImpl<ParmVarDecl *> &Params) {
John McCall21ef0fa2010-03-11 09:03:00 +00001826 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
1827 assert(OldTInfo && "substituting function without type source info");
1828 assert(Params.empty() && "parameter vector is non-empty at start");
John McCall6cd3b9f2010-04-09 17:38:44 +00001829 TypeSourceInfo *NewTInfo
1830 = SemaRef.SubstFunctionDeclType(OldTInfo, TemplateArgs,
1831 D->getTypeSpecStartLoc(),
1832 D->getDeclName());
John McCall21ef0fa2010-03-11 09:03:00 +00001833 if (!NewTInfo)
1834 return 0;
Douglas Gregor5545e162009-03-24 00:38:23 +00001835
John McCall21ef0fa2010-03-11 09:03:00 +00001836 // Get parameters from the new type info.
1837 TypeLoc NewTL = NewTInfo->getTypeLoc();
1838 FunctionProtoTypeLoc *NewProtoLoc = cast<FunctionProtoTypeLoc>(&NewTL);
1839 assert(NewProtoLoc && "Missing prototype?");
1840 for (unsigned i = 0, i_end = NewProtoLoc->getNumArgs(); i != i_end; ++i)
1841 Params.push_back(NewProtoLoc->getArg(i));
Douglas Gregor5545e162009-03-24 00:38:23 +00001842
John McCall21ef0fa2010-03-11 09:03:00 +00001843 return NewTInfo;
Douglas Gregor5545e162009-03-24 00:38:23 +00001844}
1845
Mike Stump1eb44332009-09-09 15:08:12 +00001846/// \brief Initializes the common fields of an instantiation function
Douglas Gregore53060f2009-06-25 22:08:12 +00001847/// declaration (New) from the corresponding fields of its template (Tmpl).
1848///
1849/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001850bool
1851TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
Douglas Gregore53060f2009-06-25 22:08:12 +00001852 FunctionDecl *Tmpl) {
1853 if (Tmpl->isDeleted())
1854 New->setDeleted();
Mike Stump1eb44332009-09-09 15:08:12 +00001855
Douglas Gregorcca9e962009-07-01 22:01:06 +00001856 // If we are performing substituting explicitly-specified template arguments
1857 // or deduced template arguments into a function template and we reach this
1858 // point, we are now past the point where SFINAE applies and have committed
Mike Stump1eb44332009-09-09 15:08:12 +00001859 // to keeping the new function template specialization. We therefore
1860 // convert the active template instantiation for the function template
Douglas Gregorcca9e962009-07-01 22:01:06 +00001861 // into a template instantiation for this specific function template
1862 // specialization, which is not a SFINAE context, so that we diagnose any
1863 // further errors in the declaration itself.
1864 typedef Sema::ActiveTemplateInstantiation ActiveInstType;
1865 ActiveInstType &ActiveInst = SemaRef.ActiveTemplateInstantiations.back();
1866 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
1867 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
Mike Stump1eb44332009-09-09 15:08:12 +00001868 if (FunctionTemplateDecl *FunTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +00001869 = dyn_cast<FunctionTemplateDecl>((Decl *)ActiveInst.Entity)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001870 assert(FunTmpl->getTemplatedDecl() == Tmpl &&
Douglas Gregorcca9e962009-07-01 22:01:06 +00001871 "Deduction from the wrong function template?");
Daniel Dunbarbcbb8bd2009-07-16 22:10:11 +00001872 (void) FunTmpl;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001873 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
1874 ActiveInst.Entity = reinterpret_cast<uintptr_t>(New);
Douglas Gregorf35f8282009-11-11 21:54:23 +00001875 --SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +00001876 }
1877 }
Mike Stump1eb44332009-09-09 15:08:12 +00001878
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001879 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
1880 assert(Proto && "Function template without prototype?");
1881
1882 if (Proto->hasExceptionSpec() || Proto->hasAnyExceptionSpec() ||
1883 Proto->getNoReturnAttr()) {
1884 // The function has an exception specification or a "noreturn"
1885 // attribute. Substitute into each of the exception types.
1886 llvm::SmallVector<QualType, 4> Exceptions;
1887 for (unsigned I = 0, N = Proto->getNumExceptions(); I != N; ++I) {
1888 // FIXME: Poor location information!
1889 QualType T
1890 = SemaRef.SubstType(Proto->getExceptionType(I), TemplateArgs,
1891 New->getLocation(), New->getDeclName());
1892 if (T.isNull() ||
1893 SemaRef.CheckSpecifiedExceptionType(T, New->getLocation()))
1894 continue;
1895
1896 Exceptions.push_back(T);
1897 }
1898
1899 // Rebuild the function type
1900
1901 const FunctionProtoType *NewProto
1902 = New->getType()->getAs<FunctionProtoType>();
1903 assert(NewProto && "Template instantiation without function prototype?");
1904 New->setType(SemaRef.Context.getFunctionType(NewProto->getResultType(),
1905 NewProto->arg_type_begin(),
1906 NewProto->getNumArgs(),
1907 NewProto->isVariadic(),
1908 NewProto->getTypeQuals(),
1909 Proto->hasExceptionSpec(),
1910 Proto->hasAnyExceptionSpec(),
1911 Exceptions.size(),
1912 Exceptions.data(),
Rafael Espindola264ba482010-03-30 20:24:48 +00001913 Proto->getExtInfo()));
Douglas Gregor0ae7b3f2009-12-08 17:45:32 +00001914 }
1915
Douglas Gregore53060f2009-06-25 22:08:12 +00001916 return false;
1917}
1918
Douglas Gregor5545e162009-03-24 00:38:23 +00001919/// \brief Initializes common fields of an instantiated method
1920/// declaration (New) from the corresponding fields of its template
1921/// (Tmpl).
1922///
1923/// \returns true if there was an error
Mike Stump1eb44332009-09-09 15:08:12 +00001924bool
1925TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
Douglas Gregor5545e162009-03-24 00:38:23 +00001926 CXXMethodDecl *Tmpl) {
Douglas Gregore53060f2009-06-25 22:08:12 +00001927 if (InitFunctionInstantiation(New, Tmpl))
1928 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00001929
Douglas Gregor5545e162009-03-24 00:38:23 +00001930 CXXRecordDecl *Record = cast<CXXRecordDecl>(Owner);
1931 New->setAccess(Tmpl->getAccess());
Fariborz Jahaniane7184df2009-12-03 18:44:40 +00001932 if (Tmpl->isVirtualAsWritten())
1933 Record->setMethodAsVirtual(New);
Douglas Gregor5545e162009-03-24 00:38:23 +00001934
1935 // FIXME: attributes
1936 // FIXME: New needs a pointer to Tmpl
1937 return false;
1938}
Douglas Gregora58861f2009-05-13 20:28:22 +00001939
1940/// \brief Instantiate the definition of the given function from its
1941/// template.
1942///
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001943/// \param PointOfInstantiation the point at which the instantiation was
1944/// required. Note that this is not precisely a "point of instantiation"
1945/// for the function, but it's close.
1946///
Douglas Gregora58861f2009-05-13 20:28:22 +00001947/// \param Function the already-instantiated declaration of a
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001948/// function template specialization or member function of a class template
1949/// specialization.
1950///
1951/// \param Recursive if true, recursively instantiates any functions that
1952/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001953///
1954/// \param DefinitionRequired if true, then we are performing an explicit
1955/// instantiation where the body of the function is required. Complain if
1956/// there is no such body.
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00001957void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00001958 FunctionDecl *Function,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001959 bool Recursive,
1960 bool DefinitionRequired) {
Douglas Gregor54dabfc2009-05-14 23:26:13 +00001961 if (Function->isInvalidDecl())
1962 return;
1963
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001964 assert(!Function->getBody() && "Already instantiated!");
Mike Stump1eb44332009-09-09 15:08:12 +00001965
Douglas Gregor251b4ff2009-10-08 07:24:58 +00001966 // Never instantiate an explicit specialization.
1967 if (Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1968 return;
1969
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001970 // Find the function body that we'll be substituting.
Douglas Gregor3b846b62009-10-27 20:53:28 +00001971 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001972 Stmt *Pattern = 0;
1973 if (PatternDecl)
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001974 Pattern = PatternDecl->getBody(PatternDecl);
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001975
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001976 if (!Pattern) {
1977 if (DefinitionRequired) {
1978 if (Function->getPrimaryTemplate())
1979 Diag(PointOfInstantiation,
1980 diag::err_explicit_instantiation_undefined_func_template)
1981 << Function->getPrimaryTemplate();
1982 else
1983 Diag(PointOfInstantiation,
1984 diag::err_explicit_instantiation_undefined_member)
1985 << 1 << Function->getDeclName() << Function->getDeclContext();
1986
1987 if (PatternDecl)
1988 Diag(PatternDecl->getLocation(),
1989 diag::note_explicit_instantiation_here);
1990 }
1991
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001992 return;
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00001993 }
Douglas Gregor1eee0e72009-05-14 21:06:31 +00001994
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001995 // C++0x [temp.explicit]p9:
1996 // Except for inline functions, other explicit instantiation declarations
Mike Stump1eb44332009-09-09 15:08:12 +00001997 // have the effect of suppressing the implicit instantiation of the entity
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001998 // to which they refer.
Mike Stump1eb44332009-09-09 15:08:12 +00001999 if (Function->getTemplateSpecializationKind()
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002000 == TSK_ExplicitInstantiationDeclaration &&
Douglas Gregor7ced9c82009-10-27 21:11:48 +00002001 !PatternDecl->isInlined())
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002002 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002003
Douglas Gregorf3e7ce42009-05-18 17:01:57 +00002004 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
2005 if (Inst)
2006 return;
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002007
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002008 // If we're performing recursive template instantiation, create our own
2009 // queue of pending implicit instantiations that we will instantiate later,
2010 // while we're still within our own instantiation context.
2011 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2012 if (Recursive)
2013 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002015 ActOnStartOfFunctionDef(0, DeclPtrTy::make(Function));
2016
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002017 // Introduce a new scope where local variable instantiations will be
Douglas Gregor60406be2010-01-16 22:29:39 +00002018 // recorded, unless we're actually a member function within a local
2019 // class, in which case we need to merge our results with the parent
2020 // scope (of the enclosing function).
2021 bool MergeWithParentScope = false;
2022 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
2023 MergeWithParentScope = Rec->isLocalClass();
2024
2025 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002027 // Introduce the instantiated function parameters into the local
2028 // instantiation scope.
2029 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I)
2030 Scope.InstantiatedLocal(PatternDecl->getParamDecl(I),
2031 Function->getParamDecl(I));
2032
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002033 // Enter the scope of this instantiation. We don't use
2034 // PushDeclContext because we don't have a scope.
2035 DeclContext *PreviousContext = CurContext;
2036 CurContext = Function;
2037
Mike Stump1eb44332009-09-09 15:08:12 +00002038 MultiLevelTemplateArgumentList TemplateArgs =
Anders Carlsson09025312009-08-29 05:16:22 +00002039 getTemplateInstantiationArgs(Function);
2040
2041 // If this is a constructor, instantiate the member initializers.
Mike Stump1eb44332009-09-09 15:08:12 +00002042 if (const CXXConstructorDecl *Ctor =
Anders Carlsson09025312009-08-29 05:16:22 +00002043 dyn_cast<CXXConstructorDecl>(PatternDecl)) {
2044 InstantiateMemInitializers(cast<CXXConstructorDecl>(Function), Ctor,
2045 TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002046 }
2047
Douglas Gregor54dabfc2009-05-14 23:26:13 +00002048 // Instantiate the function body.
Anders Carlsson09025312009-08-29 05:16:22 +00002049 OwningStmtResult Body = SubstStmt(Pattern, TemplateArgs);
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002050
Douglas Gregor52604ab2009-09-11 21:19:12 +00002051 if (Body.isInvalid())
2052 Function->setInvalidDecl();
2053
Mike Stump1eb44332009-09-09 15:08:12 +00002054 ActOnFinishFunctionBody(DeclPtrTy::make(Function), move(Body),
Douglas Gregore2c31ff2009-05-15 17:59:04 +00002055 /*IsInstantiation=*/true);
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002056
John McCall0c01d182010-03-24 05:22:00 +00002057 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
2058
Douglas Gregorb9f1b8d2009-05-15 00:01:03 +00002059 CurContext = PreviousContext;
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002060
2061 DeclGroupRef DG(Function);
2062 Consumer.HandleTopLevelDecl(DG);
Mike Stump1eb44332009-09-09 15:08:12 +00002063
Douglas Gregor60406be2010-01-16 22:29:39 +00002064 // This class may have local implicit instantiations that need to be
2065 // instantiation within this scope.
2066 PerformPendingImplicitInstantiations(/*LocalOnly=*/true);
2067 Scope.Exit();
2068
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002069 if (Recursive) {
2070 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002071 // instantiation of this template.
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002072 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002074 // Restore the set of pending implicit instantiations.
2075 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
2076 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002077}
2078
2079/// \brief Instantiate the definition of the given variable from its
2080/// template.
2081///
Douglas Gregor7caa6822009-07-24 20:34:43 +00002082/// \param PointOfInstantiation the point at which the instantiation was
2083/// required. Note that this is not precisely a "point of instantiation"
2084/// for the function, but it's close.
2085///
2086/// \param Var the already-instantiated declaration of a static member
2087/// variable of a class template specialization.
2088///
2089/// \param Recursive if true, recursively instantiates any functions that
2090/// are required by this instantiation.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002091///
2092/// \param DefinitionRequired if true, then we are performing an explicit
2093/// instantiation where an out-of-line definition of the member variable
2094/// is required. Complain if there is no such definition.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002095void Sema::InstantiateStaticDataMemberDefinition(
2096 SourceLocation PointOfInstantiation,
2097 VarDecl *Var,
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002098 bool Recursive,
2099 bool DefinitionRequired) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002100 if (Var->isInvalidDecl())
2101 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Douglas Gregor7caa6822009-07-24 20:34:43 +00002103 // Find the out-of-line definition of this static data member.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002104 VarDecl *Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregor7caa6822009-07-24 20:34:43 +00002105 assert(Def && "This data member was not instantiated from a template?");
Douglas Gregor0d035142009-10-27 18:42:08 +00002106 assert(Def->isStaticDataMember() && "Not a static data member?");
2107 Def = Def->getOutOfLineDefinition();
Mike Stump1eb44332009-09-09 15:08:12 +00002108
Douglas Gregor0d035142009-10-27 18:42:08 +00002109 if (!Def) {
Douglas Gregor7caa6822009-07-24 20:34:43 +00002110 // We did not find an out-of-line definition of this static data member,
2111 // so we won't perform any instantiation. Rather, we rely on the user to
Mike Stump1eb44332009-09-09 15:08:12 +00002112 // instantiate this definition (or provide a specialization for it) in
2113 // another translation unit.
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002114 if (DefinitionRequired) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002115 Def = Var->getInstantiatedFromStaticDataMember();
Douglas Gregore2d3a3d2009-10-15 14:05:49 +00002116 Diag(PointOfInstantiation,
2117 diag::err_explicit_instantiation_undefined_member)
2118 << 2 << Var->getDeclName() << Var->getDeclContext();
2119 Diag(Def->getLocation(), diag::note_explicit_instantiation_here);
2120 }
2121
Douglas Gregor7caa6822009-07-24 20:34:43 +00002122 return;
2123 }
2124
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002125 // Never instantiate an explicit specialization.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002126 if (Var->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002127 return;
2128
2129 // C++0x [temp.explicit]p9:
2130 // Except for inline functions, other explicit instantiation declarations
2131 // have the effect of suppressing the implicit instantiation of the entity
2132 // to which they refer.
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002133 if (Var->getTemplateSpecializationKind()
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002134 == TSK_ExplicitInstantiationDeclaration)
2135 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Douglas Gregor7caa6822009-07-24 20:34:43 +00002137 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
2138 if (Inst)
2139 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002140
Douglas Gregor7caa6822009-07-24 20:34:43 +00002141 // If we're performing recursive template instantiation, create our own
2142 // queue of pending implicit instantiations that we will instantiate later,
2143 // while we're still within our own instantiation context.
2144 std::deque<PendingImplicitInstantiation> SavedPendingImplicitInstantiations;
2145 if (Recursive)
2146 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002147
Douglas Gregor7caa6822009-07-24 20:34:43 +00002148 // Enter the scope of this instantiation. We don't use
2149 // PushDeclContext because we don't have a scope.
2150 DeclContext *PreviousContext = CurContext;
2151 CurContext = Var->getDeclContext();
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Douglas Gregor1028c9f2009-10-14 21:29:40 +00002153 VarDecl *OldVar = Var;
John McCallce3ff2b2009-08-25 22:02:44 +00002154 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
Douglas Gregor7caa6822009-07-24 20:34:43 +00002155 getTemplateInstantiationArgs(Var)));
Douglas Gregor7caa6822009-07-24 20:34:43 +00002156 CurContext = PreviousContext;
2157
2158 if (Var) {
Douglas Gregor583f33b2009-10-15 18:07:02 +00002159 MemberSpecializationInfo *MSInfo = OldVar->getMemberSpecializationInfo();
2160 assert(MSInfo && "Missing member specialization information?");
2161 Var->setTemplateSpecializationKind(MSInfo->getTemplateSpecializationKind(),
2162 MSInfo->getPointOfInstantiation());
Douglas Gregor7caa6822009-07-24 20:34:43 +00002163 DeclGroupRef DG(Var);
2164 Consumer.HandleTopLevelDecl(DG);
2165 }
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregor7caa6822009-07-24 20:34:43 +00002167 if (Recursive) {
2168 // Instantiate any pending implicit instantiations found during the
Mike Stump1eb44332009-09-09 15:08:12 +00002169 // instantiation of this template.
Douglas Gregor7caa6822009-07-24 20:34:43 +00002170 PerformPendingImplicitInstantiations();
Mike Stump1eb44332009-09-09 15:08:12 +00002171
Douglas Gregor7caa6822009-07-24 20:34:43 +00002172 // Restore the set of pending implicit instantiations.
2173 PendingImplicitInstantiations.swap(SavedPendingImplicitInstantiations);
Mike Stump1eb44332009-09-09 15:08:12 +00002174 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002175}
Douglas Gregor815215d2009-05-27 05:35:12 +00002176
Anders Carlsson09025312009-08-29 05:16:22 +00002177void
2178Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
2179 const CXXConstructorDecl *Tmpl,
2180 const MultiLevelTemplateArgumentList &TemplateArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00002181
Anders Carlsson09025312009-08-29 05:16:22 +00002182 llvm::SmallVector<MemInitTy*, 4> NewInits;
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002183 bool AnyErrors = false;
2184
Anders Carlsson09025312009-08-29 05:16:22 +00002185 // Instantiate all the initializers.
2186 for (CXXConstructorDecl::init_const_iterator Inits = Tmpl->init_begin(),
Douglas Gregor72f6d672009-09-01 21:04:42 +00002187 InitsEnd = Tmpl->init_end();
2188 Inits != InitsEnd; ++Inits) {
Anders Carlsson09025312009-08-29 05:16:22 +00002189 CXXBaseOrMemberInitializer *Init = *Inits;
2190
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002191 SourceLocation LParenLoc, RParenLoc;
Anders Carlsson09025312009-08-29 05:16:22 +00002192 ASTOwningVector<&ActionBase::DeleteExpr> NewArgs(*this);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002193 llvm::SmallVector<SourceLocation, 4> CommaLocs;
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Douglas Gregor6b98b2e2010-03-02 07:38:39 +00002195 // Instantiate the initializer.
2196 if (InstantiateInitializer(*this, Init->getInit(), TemplateArgs,
2197 LParenLoc, CommaLocs, NewArgs, RParenLoc)) {
2198 AnyErrors = true;
2199 continue;
Anders Carlsson09025312009-08-29 05:16:22 +00002200 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002201
Anders Carlsson09025312009-08-29 05:16:22 +00002202 MemInitResult NewInit;
Anders Carlsson09025312009-08-29 05:16:22 +00002203 if (Init->isBaseInitializer()) {
John McCalla93c9342009-12-07 02:54:59 +00002204 TypeSourceInfo *BaseTInfo = SubstType(Init->getBaseClassInfo(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002205 TemplateArgs,
2206 Init->getSourceLocation(),
2207 New->getDeclName());
John McCalla93c9342009-12-07 02:54:59 +00002208 if (!BaseTInfo) {
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002209 AnyErrors = true;
Douglas Gregor802ab452009-12-02 22:36:29 +00002210 New->setInvalidDecl();
2211 continue;
2212 }
2213
John McCalla93c9342009-12-07 02:54:59 +00002214 NewInit = BuildBaseInitializer(BaseTInfo->getType(), BaseTInfo,
Mike Stump1eb44332009-09-09 15:08:12 +00002215 (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002216 NewArgs.size(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002217 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002218 Init->getRParenLoc(),
2219 New->getParent());
2220 } else if (Init->isMemberInitializer()) {
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002221 FieldDecl *Member;
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002223 // Is this an anonymous union?
2224 if (FieldDecl *UnionInit = Init->getAnonUnionMember())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002225 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2226 UnionInit, TemplateArgs));
Anders Carlsson9988d5d2009-09-01 04:31:02 +00002227 else
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002228 Member = cast<FieldDecl>(FindInstantiatedDecl(Init->getMemberLocation(),
2229 Init->getMember(),
Douglas Gregore95b4092009-09-16 18:34:49 +00002230 TemplateArgs));
Mike Stump1eb44332009-09-09 15:08:12 +00002231
2232 NewInit = BuildMemberInitializer(Member, (Expr **)NewArgs.data(),
Anders Carlsson09025312009-08-29 05:16:22 +00002233 NewArgs.size(),
2234 Init->getSourceLocation(),
Douglas Gregor802ab452009-12-02 22:36:29 +00002235 Init->getLParenLoc(),
Anders Carlsson09025312009-08-29 05:16:22 +00002236 Init->getRParenLoc());
2237 }
2238
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002239 if (NewInit.isInvalid()) {
2240 AnyErrors = true;
Anders Carlsson09025312009-08-29 05:16:22 +00002241 New->setInvalidDecl();
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002242 } else {
Anders Carlsson09025312009-08-29 05:16:22 +00002243 // FIXME: It would be nice if ASTOwningVector had a release function.
2244 NewArgs.take();
Mike Stump1eb44332009-09-09 15:08:12 +00002245
Anders Carlsson09025312009-08-29 05:16:22 +00002246 NewInits.push_back((MemInitTy *)NewInit.get());
2247 }
2248 }
Mike Stump1eb44332009-09-09 15:08:12 +00002249
Anders Carlsson09025312009-08-29 05:16:22 +00002250 // Assign all the initializers to the new constructor.
Mike Stump1eb44332009-09-09 15:08:12 +00002251 ActOnMemInitializers(DeclPtrTy::make(New),
Anders Carlsson09025312009-08-29 05:16:22 +00002252 /*FIXME: ColonLoc */
2253 SourceLocation(),
Douglas Gregor9db7dbb2010-01-31 09:12:51 +00002254 NewInits.data(), NewInits.size(),
2255 AnyErrors);
Anders Carlsson09025312009-08-29 05:16:22 +00002256}
2257
John McCall52a575a2009-08-29 08:11:13 +00002258// TODO: this could be templated if the various decl types used the
2259// same method name.
2260static bool isInstantiationOf(ClassTemplateDecl *Pattern,
2261 ClassTemplateDecl *Instance) {
2262 Pattern = Pattern->getCanonicalDecl();
2263
2264 do {
2265 Instance = Instance->getCanonicalDecl();
2266 if (Pattern == Instance) return true;
2267 Instance = Instance->getInstantiatedFromMemberTemplate();
2268 } while (Instance);
2269
2270 return false;
2271}
2272
Douglas Gregor0d696532009-09-28 06:34:35 +00002273static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
2274 FunctionTemplateDecl *Instance) {
2275 Pattern = Pattern->getCanonicalDecl();
2276
2277 do {
2278 Instance = Instance->getCanonicalDecl();
2279 if (Pattern == Instance) return true;
2280 Instance = Instance->getInstantiatedFromMemberTemplate();
2281 } while (Instance);
2282
2283 return false;
2284}
2285
Douglas Gregored9c0f92009-10-29 00:04:11 +00002286static bool
2287isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
2288 ClassTemplatePartialSpecializationDecl *Instance) {
2289 Pattern
2290 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
2291 do {
2292 Instance = cast<ClassTemplatePartialSpecializationDecl>(
2293 Instance->getCanonicalDecl());
2294 if (Pattern == Instance)
2295 return true;
2296 Instance = Instance->getInstantiatedFromMember();
2297 } while (Instance);
2298
2299 return false;
2300}
2301
John McCall52a575a2009-08-29 08:11:13 +00002302static bool isInstantiationOf(CXXRecordDecl *Pattern,
2303 CXXRecordDecl *Instance) {
2304 Pattern = Pattern->getCanonicalDecl();
2305
2306 do {
2307 Instance = Instance->getCanonicalDecl();
2308 if (Pattern == Instance) return true;
2309 Instance = Instance->getInstantiatedFromMemberClass();
2310 } while (Instance);
2311
2312 return false;
2313}
2314
2315static bool isInstantiationOf(FunctionDecl *Pattern,
2316 FunctionDecl *Instance) {
2317 Pattern = Pattern->getCanonicalDecl();
2318
2319 do {
2320 Instance = Instance->getCanonicalDecl();
2321 if (Pattern == Instance) return true;
2322 Instance = Instance->getInstantiatedFromMemberFunction();
2323 } while (Instance);
2324
2325 return false;
2326}
2327
2328static bool isInstantiationOf(EnumDecl *Pattern,
2329 EnumDecl *Instance) {
2330 Pattern = Pattern->getCanonicalDecl();
2331
2332 do {
2333 Instance = Instance->getCanonicalDecl();
2334 if (Pattern == Instance) return true;
2335 Instance = Instance->getInstantiatedFromMemberEnum();
2336 } while (Instance);
2337
2338 return false;
2339}
2340
John McCalled976492009-12-04 22:46:56 +00002341static bool isInstantiationOf(UsingShadowDecl *Pattern,
2342 UsingShadowDecl *Instance,
2343 ASTContext &C) {
2344 return C.getInstantiatedFromUsingShadowDecl(Instance) == Pattern;
2345}
2346
2347static bool isInstantiationOf(UsingDecl *Pattern,
2348 UsingDecl *Instance,
2349 ASTContext &C) {
2350 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
2351}
2352
John McCall7ba107a2009-11-18 02:36:19 +00002353static bool isInstantiationOf(UnresolvedUsingValueDecl *Pattern,
2354 UsingDecl *Instance,
2355 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002356 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
John McCall7ba107a2009-11-18 02:36:19 +00002357}
2358
2359static bool isInstantiationOf(UnresolvedUsingTypenameDecl *Pattern,
Anders Carlsson0d8df782009-08-29 19:37:28 +00002360 UsingDecl *Instance,
2361 ASTContext &C) {
John McCalled976492009-12-04 22:46:56 +00002362 return C.getInstantiatedFromUsingDecl(Instance) == Pattern;
Anders Carlsson0d8df782009-08-29 19:37:28 +00002363}
2364
John McCall52a575a2009-08-29 08:11:13 +00002365static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
2366 VarDecl *Instance) {
2367 assert(Instance->isStaticDataMember());
2368
2369 Pattern = Pattern->getCanonicalDecl();
2370
2371 do {
2372 Instance = Instance->getCanonicalDecl();
2373 if (Pattern == Instance) return true;
2374 Instance = Instance->getInstantiatedFromStaticDataMember();
2375 } while (Instance);
2376
2377 return false;
2378}
2379
John McCalled976492009-12-04 22:46:56 +00002380// Other is the prospective instantiation
2381// D is the prospective pattern
Douglas Gregor815215d2009-05-27 05:35:12 +00002382static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002383 if (D->getKind() != Other->getKind()) {
John McCall7ba107a2009-11-18 02:36:19 +00002384 if (UnresolvedUsingTypenameDecl *UUD
2385 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
2386 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2387 return isInstantiationOf(UUD, UD, Ctx);
2388 }
2389 }
2390
2391 if (UnresolvedUsingValueDecl *UUD
2392 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
Anders Carlsson0d8df782009-08-29 19:37:28 +00002393 if (UsingDecl *UD = dyn_cast<UsingDecl>(Other)) {
2394 return isInstantiationOf(UUD, UD, Ctx);
2395 }
2396 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002397
Anders Carlsson0d8df782009-08-29 19:37:28 +00002398 return false;
2399 }
Mike Stump1eb44332009-09-09 15:08:12 +00002400
John McCall52a575a2009-08-29 08:11:13 +00002401 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Other))
2402 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
Mike Stump1eb44332009-09-09 15:08:12 +00002403
John McCall52a575a2009-08-29 08:11:13 +00002404 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Other))
2405 return isInstantiationOf(cast<FunctionDecl>(D), Function);
Douglas Gregor815215d2009-05-27 05:35:12 +00002406
John McCall52a575a2009-08-29 08:11:13 +00002407 if (EnumDecl *Enum = dyn_cast<EnumDecl>(Other))
2408 return isInstantiationOf(cast<EnumDecl>(D), Enum);
Douglas Gregor815215d2009-05-27 05:35:12 +00002409
Douglas Gregor7caa6822009-07-24 20:34:43 +00002410 if (VarDecl *Var = dyn_cast<VarDecl>(Other))
John McCall52a575a2009-08-29 08:11:13 +00002411 if (Var->isStaticDataMember())
2412 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
2413
2414 if (ClassTemplateDecl *Temp = dyn_cast<ClassTemplateDecl>(Other))
2415 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
Douglas Gregora5bf7f12009-08-28 22:03:51 +00002416
Douglas Gregor0d696532009-09-28 06:34:35 +00002417 if (FunctionTemplateDecl *Temp = dyn_cast<FunctionTemplateDecl>(Other))
2418 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
2419
Douglas Gregored9c0f92009-10-29 00:04:11 +00002420 if (ClassTemplatePartialSpecializationDecl *PartialSpec
2421 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
2422 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
2423 PartialSpec);
2424
Anders Carlssond8b285f2009-09-01 04:26:58 +00002425 if (FieldDecl *Field = dyn_cast<FieldDecl>(Other)) {
2426 if (!Field->getDeclName()) {
2427 // This is an unnamed field.
Mike Stump1eb44332009-09-09 15:08:12 +00002428 return Ctx.getInstantiatedFromUnnamedFieldDecl(Field) ==
Anders Carlssond8b285f2009-09-01 04:26:58 +00002429 cast<FieldDecl>(D);
2430 }
2431 }
Mike Stump1eb44332009-09-09 15:08:12 +00002432
John McCalled976492009-12-04 22:46:56 +00002433 if (UsingDecl *Using = dyn_cast<UsingDecl>(Other))
2434 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
2435
2436 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Other))
2437 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
2438
Douglas Gregor815215d2009-05-27 05:35:12 +00002439 return D->getDeclName() && isa<NamedDecl>(Other) &&
2440 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
2441}
2442
2443template<typename ForwardIterator>
Mike Stump1eb44332009-09-09 15:08:12 +00002444static NamedDecl *findInstantiationOf(ASTContext &Ctx,
Douglas Gregor815215d2009-05-27 05:35:12 +00002445 NamedDecl *D,
2446 ForwardIterator first,
2447 ForwardIterator last) {
2448 for (; first != last; ++first)
2449 if (isInstantiationOf(Ctx, D, *first))
2450 return cast<NamedDecl>(*first);
2451
2452 return 0;
2453}
2454
John McCall02cace72009-08-28 07:59:38 +00002455/// \brief Finds the instantiation of the given declaration context
2456/// within the current instantiation.
2457///
2458/// \returns NULL if there was an error
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002459DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
Douglas Gregore95b4092009-09-16 18:34:49 +00002460 const MultiLevelTemplateArgumentList &TemplateArgs) {
John McCall02cace72009-08-28 07:59:38 +00002461 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002462 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs);
John McCall02cace72009-08-28 07:59:38 +00002463 return cast_or_null<DeclContext>(ID);
2464 } else return DC;
2465}
2466
Douglas Gregored961e72009-05-27 17:54:46 +00002467/// \brief Find the instantiation of the given declaration within the
2468/// current instantiation.
Douglas Gregor815215d2009-05-27 05:35:12 +00002469///
2470/// This routine is intended to be used when \p D is a declaration
2471/// referenced from within a template, that needs to mapped into the
2472/// corresponding declaration within an instantiation. For example,
2473/// given:
2474///
2475/// \code
2476/// template<typename T>
2477/// struct X {
2478/// enum Kind {
2479/// KnownValue = sizeof(T)
2480/// };
2481///
2482/// bool getKind() const { return KnownValue; }
2483/// };
2484///
2485/// template struct X<int>;
2486/// \endcode
2487///
2488/// In the instantiation of X<int>::getKind(), we need to map the
2489/// EnumConstantDecl for KnownValue (which refers to
2490/// X<T>::<Kind>::KnownValue) to its instantiation
Douglas Gregored961e72009-05-27 17:54:46 +00002491/// (X<int>::<Kind>::KnownValue). InstantiateCurrentDeclRef() performs
2492/// this mapping from within the instantiation of X<int>.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002493NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
Douglas Gregore95b4092009-09-16 18:34:49 +00002494 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor815215d2009-05-27 05:35:12 +00002495 DeclContext *ParentDC = D->getDeclContext();
Douglas Gregor550d9b22009-10-31 17:21:17 +00002496 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
Douglas Gregor6d3e6272010-02-05 19:54:12 +00002497 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
Douglas Gregor550d9b22009-10-31 17:21:17 +00002498 ParentDC->isFunctionOrMethod()) {
Douglas Gregor2bba76b2009-05-27 17:07:49 +00002499 // D is a local of some kind. Look into the map of local
2500 // declarations to their instantiations.
2501 return cast<NamedDecl>(CurrentInstantiationScope->getInstantiationOf(D));
2502 }
Douglas Gregor815215d2009-05-27 05:35:12 +00002503
Douglas Gregore95b4092009-09-16 18:34:49 +00002504 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
2505 if (!Record->isDependentContext())
2506 return D;
2507
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002508 // If the RecordDecl is actually the injected-class-name or a
2509 // "templated" declaration for a class template, class template
2510 // partial specialization, or a member class of a class template,
2511 // substitute into the injected-class-name of the class template
2512 // or partial specialization to find the new DeclContext.
Douglas Gregore95b4092009-09-16 18:34:49 +00002513 QualType T;
2514 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
2515
2516 if (ClassTemplate) {
John McCall3cb0ebd2010-03-10 03:28:59 +00002517 T = ClassTemplate->getInjectedClassNameSpecialization(Context);
Douglas Gregore95b4092009-09-16 18:34:49 +00002518 } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
2519 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record)) {
Douglas Gregore95b4092009-09-16 18:34:49 +00002520 ClassTemplate = PartialSpec->getSpecializedTemplate();
John McCall3cb0ebd2010-03-10 03:28:59 +00002521
2522 // If we call SubstType with an InjectedClassNameType here we
2523 // can end up in an infinite loop.
2524 T = Context.getTypeDeclType(Record);
2525 assert(isa<InjectedClassNameType>(T) &&
2526 "type of partial specialization is not an InjectedClassNameType");
2527 T = cast<InjectedClassNameType>(T)->getUnderlyingType();
2528 }
Douglas Gregore95b4092009-09-16 18:34:49 +00002529
2530 if (!T.isNull()) {
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002531 // Substitute into the injected-class-name to get the type
2532 // corresponding to the instantiation we want, which may also be
2533 // the current instantiation (if we're in a template
2534 // definition). This substitution should never fail, since we
2535 // know we can instantiate the injected-class-name or we
2536 // wouldn't have gotten to the injected-class-name!
2537
2538 // FIXME: Can we use the CurrentInstantiationScope to avoid this
2539 // extra instantiation in the common case?
Douglas Gregore95b4092009-09-16 18:34:49 +00002540 T = SubstType(T, TemplateArgs, SourceLocation(), DeclarationName());
2541 assert(!T.isNull() && "Instantiation of injected-class-name cannot fail.");
2542
2543 if (!T->isDependentType()) {
2544 assert(T->isRecordType() && "Instantiation must produce a record type");
2545 return T->getAs<RecordType>()->getDecl();
2546 }
2547
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002548 // We are performing "partial" template instantiation to create
2549 // the member declarations for the members of a class template
2550 // specialization. Therefore, D is actually referring to something
2551 // in the current instantiation. Look through the current
2552 // context, which contains actual instantiations, to find the
2553 // instantiation of the "current instantiation" that D refers
2554 // to.
2555 bool SawNonDependentContext = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002556 for (DeclContext *DC = CurContext; !DC->isFileContext();
John McCall52a575a2009-08-29 08:11:13 +00002557 DC = DC->getParent()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002558 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002559 = dyn_cast<ClassTemplateSpecializationDecl>(DC))
Douglas Gregore95b4092009-09-16 18:34:49 +00002560 if (isInstantiationOf(ClassTemplate,
2561 Spec->getSpecializedTemplate()))
John McCall52a575a2009-08-29 08:11:13 +00002562 return Spec;
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002563
2564 if (!DC->isDependentContext())
2565 SawNonDependentContext = true;
John McCall52a575a2009-08-29 08:11:13 +00002566 }
2567
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002568 // We're performing "instantiation" of a member of the current
2569 // instantiation while we are type-checking the
2570 // definition. Compute the declaration context and return that.
2571 assert(!SawNonDependentContext &&
2572 "No dependent context while instantiating record");
2573 DeclContext *DC = computeDeclContext(T);
2574 assert(DC &&
John McCall52a575a2009-08-29 08:11:13 +00002575 "Unable to find declaration for the current instantiation");
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002576 return cast<CXXRecordDecl>(DC);
John McCall52a575a2009-08-29 08:11:13 +00002577 }
Douglas Gregor8b013bd2010-02-05 22:40:03 +00002578
Douglas Gregore95b4092009-09-16 18:34:49 +00002579 // Fall through to deal with other dependent record types (e.g.,
2580 // anonymous unions in class templates).
2581 }
John McCall52a575a2009-08-29 08:11:13 +00002582
Douglas Gregore95b4092009-09-16 18:34:49 +00002583 if (!ParentDC->isDependentContext())
2584 return D;
2585
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002586 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00002587 if (!ParentDC)
Douglas Gregor44c73842009-09-01 17:53:10 +00002588 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002589
Douglas Gregor815215d2009-05-27 05:35:12 +00002590 if (ParentDC != D->getDeclContext()) {
2591 // We performed some kind of instantiation in the parent context,
2592 // so now we need to look into the instantiated parent context to
2593 // find the instantiation of the declaration D.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002594
John McCall3cb0ebd2010-03-10 03:28:59 +00002595 // If our context used to be dependent, we may need to instantiate
2596 // it before performing lookup into that context.
2597 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002598 if (!Spec->isDependentContext()) {
2599 QualType T = Context.getTypeDeclType(Spec);
John McCall3cb0ebd2010-03-10 03:28:59 +00002600 const RecordType *Tag = T->getAs<RecordType>();
2601 assert(Tag && "type of non-dependent record is not a RecordType");
2602 if (!Tag->isBeingDefined() &&
2603 RequireCompleteType(Loc, T, diag::err_incomplete_type))
2604 return 0;
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00002605 }
2606 }
2607
Douglas Gregor815215d2009-05-27 05:35:12 +00002608 NamedDecl *Result = 0;
2609 if (D->getDeclName()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002610 DeclContext::lookup_result Found = ParentDC->lookup(D->getDeclName());
Douglas Gregor815215d2009-05-27 05:35:12 +00002611 Result = findInstantiationOf(Context, D, Found.first, Found.second);
2612 } else {
2613 // Since we don't have a name for the entity we're looking for,
2614 // our only option is to walk through all of the declarations to
2615 // find that name. This will occur in a few cases:
2616 //
2617 // - anonymous struct/union within a template
2618 // - unnamed class/struct/union/enum within a template
2619 //
2620 // FIXME: Find a better way to find these instantiations!
Mike Stump1eb44332009-09-09 15:08:12 +00002621 Result = findInstantiationOf(Context, D,
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002622 ParentDC->decls_begin(),
2623 ParentDC->decls_end());
Douglas Gregor815215d2009-05-27 05:35:12 +00002624 }
Mike Stump1eb44332009-09-09 15:08:12 +00002625
John McCall9f54ad42009-12-10 09:41:52 +00002626 // UsingShadowDecls can instantiate to nothing because of using hiding.
Douglas Gregor00225542010-03-01 18:27:54 +00002627 assert((Result || isa<UsingShadowDecl>(D) || D->isInvalidDecl() ||
2628 cast<Decl>(ParentDC)->isInvalidDecl())
John McCall9f54ad42009-12-10 09:41:52 +00002629 && "Unable to find instantiation of declaration!");
2630
Douglas Gregor815215d2009-05-27 05:35:12 +00002631 D = Result;
2632 }
2633
Douglas Gregor815215d2009-05-27 05:35:12 +00002634 return D;
2635}
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002636
Mike Stump1eb44332009-09-09 15:08:12 +00002637/// \brief Performs template instantiation for all implicit template
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002638/// instantiations we have seen until this point.
Douglas Gregor60406be2010-01-16 22:29:39 +00002639void Sema::PerformPendingImplicitInstantiations(bool LocalOnly) {
2640 while (!PendingLocalImplicitInstantiations.empty() ||
2641 (!LocalOnly && !PendingImplicitInstantiations.empty())) {
2642 PendingImplicitInstantiation Inst;
2643
2644 if (PendingLocalImplicitInstantiations.empty()) {
2645 Inst = PendingImplicitInstantiations.front();
2646 PendingImplicitInstantiations.pop_front();
2647 } else {
2648 Inst = PendingLocalImplicitInstantiations.front();
2649 PendingLocalImplicitInstantiations.pop_front();
2650 }
Mike Stump1eb44332009-09-09 15:08:12 +00002651
Douglas Gregor7caa6822009-07-24 20:34:43 +00002652 // Instantiate function definitions
2653 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002654 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Function),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002655 Function->getLocation(), *this,
2656 Context.getSourceManager(),
2657 "instantiating function definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002658
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002659 if (!Function->getBody())
Douglas Gregorb33fe2f2009-06-30 17:20:14 +00002660 InstantiateFunctionDefinition(/*FIXME:*/Inst.second, Function, true);
Douglas Gregor7caa6822009-07-24 20:34:43 +00002661 continue;
2662 }
Mike Stump1eb44332009-09-09 15:08:12 +00002663
Douglas Gregor7caa6822009-07-24 20:34:43 +00002664 // Instantiate static data member definitions.
2665 VarDecl *Var = cast<VarDecl>(Inst.first);
2666 assert(Var->isStaticDataMember() && "Not a static data member?");
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002667
Chandler Carruth291b4412010-02-13 10:17:50 +00002668 // Don't try to instantiate declarations if the most recent redeclaration
2669 // is invalid.
2670 if (Var->getMostRecentDeclaration()->isInvalidDecl())
2671 continue;
2672
2673 // Check if the most recent declaration has changed the specialization kind
2674 // and removed the need for implicit instantiation.
2675 switch (Var->getMostRecentDeclaration()->getTemplateSpecializationKind()) {
2676 case TSK_Undeclared:
2677 assert(false && "Cannot instantitiate an undeclared specialization.");
2678 case TSK_ExplicitInstantiationDeclaration:
2679 case TSK_ExplicitInstantiationDefinition:
2680 case TSK_ExplicitSpecialization:
2681 continue; // No longer need implicit instantiation.
2682 case TSK_ImplicitInstantiation:
2683 break;
2684 }
2685
Mike Stump1eb44332009-09-09 15:08:12 +00002686 PrettyStackTraceActionsDecl CrashInfo(DeclPtrTy::make(Var),
Anders Carlssonc17fb7b2009-09-01 05:12:24 +00002687 Var->getLocation(), *this,
2688 Context.getSourceManager(),
2689 "instantiating static data member "
2690 "definition");
Mike Stump1eb44332009-09-09 15:08:12 +00002691
Douglas Gregor7caa6822009-07-24 20:34:43 +00002692 InstantiateStaticDataMemberDefinition(/*FIXME:*/Inst.second, Var, true);
Douglas Gregord7f37bf2009-06-22 23:06:13 +00002693 }
2694}
John McCall0c01d182010-03-24 05:22:00 +00002695
2696void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
2697 const MultiLevelTemplateArgumentList &TemplateArgs) {
2698 for (DeclContext::ddiag_iterator I = Pattern->ddiag_begin(),
2699 E = Pattern->ddiag_end(); I != E; ++I) {
2700 DependentDiagnostic *DD = *I;
2701
2702 switch (DD->getKind()) {
2703 case DependentDiagnostic::Access:
2704 HandleDependentAccessCheck(*DD, TemplateArgs);
2705 break;
2706 }
2707 }
2708}