blob: c452e26a403b6daa17911d50e709db5ee2c6ab52 [file] [log] [blame]
Douglas Gregor99ebf652009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template 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.
10//
11//===----------------------------------------------------------------------===/
12
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregor577f75a2009-08-04 16:50:30 +000014#include "TreeTransform.h"
John McCall19510852010-08-20 18:27:03 +000015#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000016#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000018#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000019#include "clang/Sema/TemplateDeduction.h"
Douglas Gregoraba43bb2009-05-26 20:50:29 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000021#include "clang/AST/ASTContext.h"
22#include "clang/AST/Expr.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000024#include "clang/Basic/LangOptions.h"
25
26using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000027using namespace sema;
Douglas Gregor99ebf652009-02-27 19:31:52 +000028
Douglas Gregoree1828a2009-03-10 18:03:33 +000029//===----------------------------------------------------------------------===/
30// Template Instantiation Support
31//===----------------------------------------------------------------------===/
32
Douglas Gregord6350ae2009-08-28 20:31:08 +000033/// \brief Retrieve the template argument list(s) that should be used to
34/// instantiate the definition of the given declaration.
Douglas Gregor0f8716b2009-11-09 19:17:50 +000035///
36/// \param D the declaration for which we are computing template instantiation
37/// arguments.
38///
39/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor525f96c2010-02-05 07:33:43 +000040///
41/// \param RelativeToPrimary true if we should get the template
42/// arguments relative to the primary template, even when we're
43/// dealing with a specialization. This is only relevant for function
44/// template specializations.
Douglas Gregore7089b02010-05-03 23:29:10 +000045///
46/// \param Pattern If non-NULL, indicates the pattern from which we will be
47/// instantiating the definition of the given declaration, \p D. This is
48/// used to determine the proper set of template instantiation arguments for
49/// friend function template specializations.
Douglas Gregord1102432009-08-28 17:37:35 +000050MultiLevelTemplateArgumentList
Douglas Gregor0f8716b2009-11-09 19:17:50 +000051Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor525f96c2010-02-05 07:33:43 +000052 const TemplateArgumentList *Innermost,
Douglas Gregore7089b02010-05-03 23:29:10 +000053 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
Douglas Gregord1102432009-08-28 17:37:35 +000055 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor0f8716b2009-11-09 19:17:50 +000058 if (Innermost)
59 Result.addOuterTemplateArguments(Innermost);
60
Douglas Gregord1102432009-08-28 17:37:35 +000061 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregor93104c12011-05-22 00:21:10 +000062 if (!Ctx) {
Douglas Gregord1102432009-08-28 17:37:35 +000063 Ctx = D->getDeclContext();
Douglas Gregor93104c12011-05-22 00:21:10 +000064
Douglas Gregor383041d2011-06-15 14:20:42 +000065 // If we have a template template parameter with translation unit context,
66 // then we're performing substitution into a default template argument of
67 // this template template parameter before we've constructed the template
68 // that will own this template template parameter. In this case, we
69 // use empty template parameter lists for all of the outer templates
70 // to avoid performing any substitutions.
71 if (Ctx->isTranslationUnit()) {
72 if (TemplateTemplateParmDecl *TTP
73 = dyn_cast<TemplateTemplateParmDecl>(D)) {
74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
75 Result.addOuterTemplateArguments(0, 0);
76 return Result;
77 }
78 }
Douglas Gregor93104c12011-05-22 00:21:10 +000079 }
80
John McCallf181d8a2009-08-29 03:16:09 +000081 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +000082 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +000083 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +000084 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +000086 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +000088 break;
Mike Stump1eb44332009-09-09 15:08:12 +000089
Douglas Gregord1102432009-08-28 17:37:35 +000090 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +000091
92 // If this class template specialization was instantiated from a
93 // specialized member that is a class template, we're done.
94 assert(Spec->getSpecializedTemplate() && "No class template?");
95 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
96 break;
Mike Stump1eb44332009-09-09 15:08:12 +000097 }
Douglas Gregord1102432009-08-28 17:37:35 +000098 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +000099 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000100 if (!RelativeToPrimary &&
101 Function->getTemplateSpecializationKind()
102 == TSK_ExplicitSpecialization)
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000103 break;
104
Douglas Gregord1102432009-08-28 17:37:35 +0000105 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000106 = Function->getTemplateSpecializationArgs()) {
107 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000108 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000109
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000110 // If this function was instantiated from a specialized member that is
111 // a function template, we're done.
112 assert(Function->getPrimaryTemplate() && "No function template?");
113 if (Function->getPrimaryTemplate()->isMemberSpecialization())
114 break;
Douglas Gregorc494f772011-03-05 17:54:25 +0000115 } else if (FunctionTemplateDecl *FunTmpl
116 = Function->getDescribedFunctionTemplate()) {
117 // Add the "injected" template arguments.
118 std::pair<const TemplateArgument *, unsigned>
119 Injected = FunTmpl->getInjectedTemplateArgs();
120 Result.addOuterTemplateArguments(Injected.first, Injected.second);
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000121 }
122
John McCallf181d8a2009-08-29 03:16:09 +0000123 // If this is a friend declaration and it declares an entity at
124 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000125 // instead of its semantic parent, unless of course the pattern we're
126 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000127 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000128 Function->getDeclContext()->isFileContext() &&
129 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000130 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000131 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000132 continue;
133 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000134 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
135 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
136 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
137 const TemplateSpecializationType *TST
138 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
139 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
140 if (ClassTemplate->isMemberSpecialization())
141 break;
142 }
Douglas Gregord1102432009-08-28 17:37:35 +0000143 }
John McCallf181d8a2009-08-29 03:16:09 +0000144
145 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000146 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000147 }
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Douglas Gregord1102432009-08-28 17:37:35 +0000149 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000150}
151
Douglas Gregorf35f8282009-11-11 21:54:23 +0000152bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
153 switch (Kind) {
154 case TemplateInstantiation:
155 case DefaultTemplateArgumentInstantiation:
156 case DefaultFunctionArgumentInstantiation:
157 return true;
158
159 case ExplicitTemplateArgumentSubstitution:
160 case DeducedTemplateArgumentSubstitution:
161 case PriorTemplateArgumentSubstitution:
162 case DefaultTemplateArgumentChecking:
163 return false;
164 }
165
166 return true;
167}
168
Douglas Gregor26dce442009-03-10 00:06:19 +0000169Sema::InstantiatingTemplate::
170InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000171 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000172 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000173 : SemaRef(SemaRef),
174 SavedInNonInstantiationSFINAEContext(
175 SemaRef.InNonInstantiationSFINAEContext)
176{
Douglas Gregordf667e72009-03-10 20:44:00 +0000177 Invalid = CheckInstantiationDepth(PointOfInstantiation,
178 InstantiationRange);
179 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000180 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000181 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000182 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregordf667e72009-03-10 20:44:00 +0000183 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor313a81d2009-03-12 18:36:18 +0000184 Inst.TemplateArgs = 0;
185 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000186 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000187 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000188 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000189 }
190}
191
Mike Stump1eb44332009-09-09 15:08:12 +0000192Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregordf667e72009-03-10 20:44:00 +0000193 SourceLocation PointOfInstantiation,
194 TemplateDecl *Template,
195 const TemplateArgument *TemplateArgs,
196 unsigned NumTemplateArgs,
197 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000198 : SemaRef(SemaRef),
199 SavedInNonInstantiationSFINAEContext(
200 SemaRef.InNonInstantiationSFINAEContext)
201{
Douglas Gregordf667e72009-03-10 20:44:00 +0000202 Invalid = CheckInstantiationDepth(PointOfInstantiation,
203 InstantiationRange);
204 if (!Invalid) {
205 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000206 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000207 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
208 Inst.PointOfInstantiation = PointOfInstantiation;
209 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
210 Inst.TemplateArgs = TemplateArgs;
211 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor26dce442009-03-10 00:06:19 +0000212 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000213 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000214 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000215 }
216}
217
Mike Stump1eb44332009-09-09 15:08:12 +0000218Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor637a4092009-06-10 23:47:09 +0000219 SourceLocation PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000220 FunctionTemplateDecl *FunctionTemplate,
221 const TemplateArgument *TemplateArgs,
222 unsigned NumTemplateArgs,
223 ActiveTemplateInstantiation::InstantiationKind Kind,
Douglas Gregor9b623632010-10-12 23:32:35 +0000224 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000225 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000226 : SemaRef(SemaRef),
227 SavedInNonInstantiationSFINAEContext(
228 SemaRef.InNonInstantiationSFINAEContext)
229{
Douglas Gregorcca9e962009-07-01 22:01:06 +0000230 Invalid = CheckInstantiationDepth(PointOfInstantiation,
231 InstantiationRange);
232 if (!Invalid) {
233 ActiveTemplateInstantiation Inst;
234 Inst.Kind = Kind;
235 Inst.PointOfInstantiation = PointOfInstantiation;
236 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
237 Inst.TemplateArgs = TemplateArgs;
238 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor9b623632010-10-12 23:32:35 +0000239 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000240 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000241 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000242 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000243
244 if (!Inst.isInstantiationRecord())
245 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000246 }
247}
248
Mike Stump1eb44332009-09-09 15:08:12 +0000249Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000250 SourceLocation PointOfInstantiation,
Douglas Gregor637a4092009-06-10 23:47:09 +0000251 ClassTemplatePartialSpecializationDecl *PartialSpec,
252 const TemplateArgument *TemplateArgs,
253 unsigned NumTemplateArgs,
Douglas Gregor9b623632010-10-12 23:32:35 +0000254 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregor637a4092009-06-10 23:47:09 +0000255 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000256 : SemaRef(SemaRef),
257 SavedInNonInstantiationSFINAEContext(
258 SemaRef.InNonInstantiationSFINAEContext)
259{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000260 Invalid = false;
261
262 ActiveTemplateInstantiation Inst;
263 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
264 Inst.PointOfInstantiation = PointOfInstantiation;
265 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
266 Inst.TemplateArgs = TemplateArgs;
267 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor9b623632010-10-12 23:32:35 +0000268 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000269 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000270 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000271 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
272
273 assert(!Inst.isInstantiationRecord());
274 ++SemaRef.NonInstantiationEntries;
Douglas Gregor637a4092009-06-10 23:47:09 +0000275}
276
Mike Stump1eb44332009-09-09 15:08:12 +0000277Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000278 SourceLocation PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000279 ParmVarDecl *Param,
280 const TemplateArgument *TemplateArgs,
281 unsigned NumTemplateArgs,
282 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000283 : SemaRef(SemaRef),
284 SavedInNonInstantiationSFINAEContext(
285 SemaRef.InNonInstantiationSFINAEContext)
286{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000287 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000288
289 if (!Invalid) {
290 ActiveTemplateInstantiation Inst;
291 Inst.Kind
292 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000293 Inst.PointOfInstantiation = PointOfInstantiation;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000294 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
295 Inst.TemplateArgs = TemplateArgs;
296 Inst.NumTemplateArgs = NumTemplateArgs;
297 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000298 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000299 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000300 }
301}
302
303Sema::InstantiatingTemplate::
304InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000305 NamedDecl *Template,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000306 NonTypeTemplateParmDecl *Param,
307 const TemplateArgument *TemplateArgs,
308 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000309 SourceRange InstantiationRange)
310 : SemaRef(SemaRef),
311 SavedInNonInstantiationSFINAEContext(
312 SemaRef.InNonInstantiationSFINAEContext)
313{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000314 Invalid = false;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000315
Douglas Gregorf35f8282009-11-11 21:54:23 +0000316 ActiveTemplateInstantiation Inst;
317 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
318 Inst.PointOfInstantiation = PointOfInstantiation;
319 Inst.Template = Template;
320 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
321 Inst.TemplateArgs = TemplateArgs;
322 Inst.NumTemplateArgs = NumTemplateArgs;
323 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000324 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000325 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
326
327 assert(!Inst.isInstantiationRecord());
328 ++SemaRef.NonInstantiationEntries;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000329}
330
331Sema::InstantiatingTemplate::
332InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000333 NamedDecl *Template,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000334 TemplateTemplateParmDecl *Param,
335 const TemplateArgument *TemplateArgs,
336 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000337 SourceRange InstantiationRange)
338 : SemaRef(SemaRef),
339 SavedInNonInstantiationSFINAEContext(
340 SemaRef.InNonInstantiationSFINAEContext)
341{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000342 Invalid = false;
343 ActiveTemplateInstantiation Inst;
344 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
345 Inst.PointOfInstantiation = PointOfInstantiation;
346 Inst.Template = Template;
347 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
348 Inst.TemplateArgs = TemplateArgs;
349 Inst.NumTemplateArgs = NumTemplateArgs;
350 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000351 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000352 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000353
Douglas Gregorf35f8282009-11-11 21:54:23 +0000354 assert(!Inst.isInstantiationRecord());
355 ++SemaRef.NonInstantiationEntries;
356}
357
358Sema::InstantiatingTemplate::
359InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
360 TemplateDecl *Template,
361 NamedDecl *Param,
362 const TemplateArgument *TemplateArgs,
363 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000364 SourceRange InstantiationRange)
365 : SemaRef(SemaRef),
366 SavedInNonInstantiationSFINAEContext(
367 SemaRef.InNonInstantiationSFINAEContext)
368{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000369 Invalid = false;
370
371 ActiveTemplateInstantiation Inst;
372 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
373 Inst.PointOfInstantiation = PointOfInstantiation;
374 Inst.Template = Template;
375 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
376 Inst.TemplateArgs = TemplateArgs;
377 Inst.NumTemplateArgs = NumTemplateArgs;
378 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000379 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000380 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
381
382 assert(!Inst.isInstantiationRecord());
383 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000384}
385
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000386void Sema::InstantiatingTemplate::Clear() {
387 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000388 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
389 assert(SemaRef.NonInstantiationEntries > 0);
390 --SemaRef.NonInstantiationEntries;
391 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000392 SemaRef.InNonInstantiationSFINAEContext
393 = SavedInNonInstantiationSFINAEContext;
Douglas Gregor26dce442009-03-10 00:06:19 +0000394 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000395 Invalid = true;
396 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000397}
398
Douglas Gregordf667e72009-03-10 20:44:00 +0000399bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
400 SourceLocation PointOfInstantiation,
401 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000402 assert(SemaRef.NonInstantiationEntries <=
403 SemaRef.ActiveTemplateInstantiations.size());
404 if ((SemaRef.ActiveTemplateInstantiations.size() -
405 SemaRef.NonInstantiationEntries)
406 <= SemaRef.getLangOptions().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000407 return false;
408
Mike Stump1eb44332009-09-09 15:08:12 +0000409 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000410 diag::err_template_recursion_depth_exceeded)
411 << SemaRef.getLangOptions().InstantiationDepth
412 << InstantiationRange;
413 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
414 << SemaRef.getLangOptions().InstantiationDepth;
415 return true;
416}
417
Douglas Gregoree1828a2009-03-10 18:03:33 +0000418/// \brief Prints the current instantiation stack through a series of
419/// notes.
420void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000421 // Determine which template instantiations to skip, if any.
422 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
423 unsigned Limit = Diags.getTemplateBacktraceLimit();
424 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
425 SkipStart = Limit / 2 + Limit % 2;
426 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
427 }
428
Douglas Gregorcca9e962009-07-01 22:01:06 +0000429 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000430 unsigned InstantiationIdx = 0;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000431 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
432 Active = ActiveTemplateInstantiations.rbegin(),
433 ActiveEnd = ActiveTemplateInstantiations.rend();
434 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000435 ++Active, ++InstantiationIdx) {
436 // Skip this instantiation?
437 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
438 if (InstantiationIdx == SkipStart) {
439 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000440 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000441 diag::note_instantiation_contexts_suppressed)
442 << unsigned(ActiveTemplateInstantiations.size() - Limit);
443 }
444 continue;
445 }
446
Douglas Gregordf667e72009-03-10 20:44:00 +0000447 switch (Active->Kind) {
448 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000449 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
450 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
451 unsigned DiagID = diag::note_template_member_class_here;
452 if (isa<ClassTemplateSpecializationDecl>(Record))
453 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000454 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000455 << Context.getTypeDeclType(Record)
456 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000457 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000458 unsigned DiagID;
459 if (Function->getPrimaryTemplate())
460 DiagID = diag::note_function_template_spec_here;
461 else
462 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000463 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000464 << Function
465 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000466 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000467 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000468 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000469 << VD
470 << Active->InstantiationRange;
471 } else {
472 Diags.Report(Active->PointOfInstantiation,
473 diag::note_template_type_alias_instantiation_here)
474 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000475 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000476 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000477 break;
478 }
479
480 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
481 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
482 std::string TemplateArgsStr
Douglas Gregor7532dc62009-03-30 22:58:21 +0000483 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000484 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000485 Active->NumTemplateArgs,
486 Context.PrintingPolicy);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000487 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000488 diag::note_default_arg_instantiation_here)
489 << (Template->getNameAsString() + TemplateArgsStr)
490 << Active->InstantiationRange;
491 break;
492 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000493
Douglas Gregorcca9e962009-07-01 22:01:06 +0000494 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 FunctionTemplateDecl *FnTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +0000496 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000497 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000498 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000499 << FnTmpl
500 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
501 Active->TemplateArgs,
502 Active->NumTemplateArgs)
503 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000504 break;
505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Douglas Gregorcca9e962009-07-01 22:01:06 +0000507 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
508 if (ClassTemplatePartialSpecializationDecl *PartialSpec
509 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
510 (Decl *)Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000511 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000512 diag::note_partial_spec_deduct_instantiation_here)
513 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000514 << getTemplateArgumentBindingsText(
515 PartialSpec->getTemplateParameters(),
516 Active->TemplateArgs,
517 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000518 << Active->InstantiationRange;
519 } else {
520 FunctionTemplateDecl *FnTmpl
521 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000522 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000523 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000524 << FnTmpl
525 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
526 Active->TemplateArgs,
527 Active->NumTemplateArgs)
528 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000529 }
530 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000531
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000532 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
533 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
534 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000536 std::string TemplateArgsStr
537 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000538 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000539 Active->NumTemplateArgs,
540 Context.PrintingPolicy);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000541 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000542 diag::note_default_function_arg_instantiation_here)
Anders Carlsson6bc107b2009-09-05 05:38:54 +0000543 << (FD->getNameAsString() + TemplateArgsStr)
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000544 << Active->InstantiationRange;
545 break;
546 }
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000548 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
549 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
550 std::string Name;
551 if (!Parm->getName().empty())
552 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000553
554 TemplateParameterList *TemplateParams = 0;
555 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
556 TemplateParams = Template->getTemplateParameters();
557 else
558 TemplateParams =
559 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
560 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000561 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000562 diag::note_prior_template_arg_substitution)
563 << isa<TemplateTemplateParmDecl>(Parm)
564 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000565 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000566 Active->TemplateArgs,
567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
569 break;
570 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000571
572 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000573 TemplateParameterList *TemplateParams = 0;
574 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
575 TemplateParams = Template->getTemplateParameters();
576 else
577 TemplateParams =
578 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
579 ->getTemplateParameters();
580
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000581 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000582 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000583 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000584 Active->TemplateArgs,
585 Active->NumTemplateArgs)
586 << Active->InstantiationRange;
587 break;
588 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000589 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000590 }
591}
592
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000593llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000594 using llvm::SmallVector;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000595 if (InNonInstantiationSFINAEContext)
596 return llvm::Optional<TemplateDeductionInfo *>(0);
597
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000598 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
599 Active = ActiveTemplateInstantiations.rbegin(),
600 ActiveEnd = ActiveTemplateInstantiations.rend();
601 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000602 ++Active)
603 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000604 switch(Active->Kind) {
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000605 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000606 case ActiveTemplateInstantiation::TemplateInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000607 // This is a template instantiation, so there is no SFINAE.
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000608 return llvm::Optional<TemplateDeductionInfo *>();
Mike Stump1eb44332009-09-09 15:08:12 +0000609
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000610 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000611 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000612 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000613 // A default template argument instantiation and substitution into
614 // template parameters with arguments for prior parameters may or may
615 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000616 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000617
Douglas Gregorcca9e962009-07-01 22:01:06 +0000618 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
619 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
620 // We're either substitution explicitly-specified template arguments
621 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000622 assert(Active->DeductionInfo && "Missing deduction info pointer");
623 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000624 }
625 }
626
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000627 return llvm::Optional<TemplateDeductionInfo *>();
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000628}
629
Douglas Gregord3731192011-01-10 07:32:04 +0000630/// \brief Retrieve the depth and index of a parameter pack.
631static std::pair<unsigned, unsigned>
632getDepthAndIndex(NamedDecl *ND) {
633 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
634 return std::make_pair(TTP->getDepth(), TTP->getIndex());
635
636 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
637 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
638
639 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
640 return std::make_pair(TTP->getDepth(), TTP->getIndex());
641}
642
Douglas Gregor99ebf652009-02-27 19:31:52 +0000643//===----------------------------------------------------------------------===/
644// Template Instantiation for Types
645//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000646namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000647 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000648 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000649 SourceLocation Loc;
650 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000651
Douglas Gregorcd281c32009-02-28 00:25:32 +0000652 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000653 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000654
655 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000656 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000657 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000658 DeclarationName Entity)
659 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000660 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000661
Mike Stump1eb44332009-09-09 15:08:12 +0000662 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000663 /// transformed.
664 ///
665 /// For the purposes of template instantiation, a type has already been
666 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000667 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Douglas Gregor577f75a2009-08-04 16:50:30 +0000669 /// \brief Returns the location of the entity being instantiated, if known.
670 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Douglas Gregor577f75a2009-08-04 16:50:30 +0000672 /// \brief Returns the name of the entity being instantiated, if any.
673 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000674
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000675 /// \brief Sets the "base" location and entity when that
676 /// information is known based on another transformation.
677 void setBase(SourceLocation Loc, DeclarationName Entity) {
678 this->Loc = Loc;
679 this->Entity = Entity;
680 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000681
682 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
683 SourceRange PatternRange,
684 const UnexpandedParameterPack *Unexpanded,
685 unsigned NumUnexpanded,
686 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000687 bool &RetainExpansion,
Douglas Gregorcded4f62011-01-14 17:04:44 +0000688 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000689 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
690 PatternRange, Unexpanded,
691 NumUnexpanded,
692 TemplateArgs,
693 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000694 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000695 NumExpansions);
696 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000697
Douglas Gregor12c9c002011-01-07 16:43:16 +0000698 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
699 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
700 }
701
Douglas Gregord3731192011-01-10 07:32:04 +0000702 TemplateArgument ForgetPartiallySubstitutedPack() {
703 TemplateArgument Result;
704 if (NamedDecl *PartialPack
705 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
706 MultiLevelTemplateArgumentList &TemplateArgs
707 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
708 unsigned Depth, Index;
709 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
710 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
711 Result = TemplateArgs(Depth, Index);
712 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
713 }
714 }
715
716 return Result;
717 }
718
719 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
720 if (Arg.isNull())
721 return;
722
723 if (NamedDecl *PartialPack
724 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
725 MultiLevelTemplateArgumentList &TemplateArgs
726 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
727 unsigned Depth, Index;
728 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
729 TemplateArgs.setArgument(Depth, Index, Arg);
730 }
731 }
732
Douglas Gregor577f75a2009-08-04 16:50:30 +0000733 /// \brief Transform the given declaration by instantiating a reference to
734 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000735 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000736
Mike Stump1eb44332009-09-09 15:08:12 +0000737 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000738 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000739 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Douglas Gregor6cd21982009-10-20 05:58:46 +0000741 /// \bried Transform the first qualifier within a scope by instantiating the
742 /// declaration.
743 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
744
Douglas Gregor43959a92009-08-20 07:17:43 +0000745 /// \brief Rebuild the exception declaration and register the declaration
746 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000747 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000748 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000749 SourceLocation StartLoc,
750 SourceLocation NameLoc,
751 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Douglas Gregorbe270a02010-04-26 17:57:08 +0000753 /// \brief Rebuild the Objective-C exception declaration and register the
754 /// declaration as an instantiated local.
755 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
756 TypeSourceInfo *TSInfo, QualType T);
757
John McCallc4e70192009-09-11 04:59:25 +0000758 /// \brief Check for tag mismatches when instantiating an
759 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000760 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
761 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000762 NestedNameSpecifierLoc QualifierLoc,
763 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000764
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000765 TemplateName TransformTemplateName(CXXScopeSpec &SS,
766 TemplateName Name,
767 SourceLocation NameLoc,
768 QualType ObjectType = QualType(),
769 NamedDecl *FirstQualifierInScope = 0);
770
John McCall60d7b3a2010-08-24 06:29:42 +0000771 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
772 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
773 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
774 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000775 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000776 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
777 SubstNonTypeTemplateParmPackExpr *E);
778
Douglas Gregor895162d2010-04-30 18:55:50 +0000779 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000780 FunctionProtoTypeLoc TL);
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000781 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000782 int indexAdjustment,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000783 llvm::Optional<unsigned> NumExpansions);
John McCall21ef0fa2010-03-11 09:03:00 +0000784
Mike Stump1eb44332009-09-09 15:08:12 +0000785 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000786 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000787 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000788 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000789
Douglas Gregorc3069d62011-01-14 02:55:32 +0000790 /// \brief Transforms an already-substituted template type parameter pack
791 /// into either itself (if we aren't substituting into its pack expansion)
792 /// or the appropriate substituted argument.
793 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
794 SubstTemplateTypeParmPackTypeLoc TL);
795
John McCall60d7b3a2010-08-24 06:29:42 +0000796 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000797 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000798 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000799 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
800 getSema().CallsUndergoingInstantiation.pop_back();
801 return move(Result);
802 }
Douglas Gregor577f75a2009-08-04 16:50:30 +0000803 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000804}
805
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000806bool TemplateInstantiator::AlreadyTransformed(QualType T) {
807 if (T.isNull())
808 return true;
809
Douglas Gregor836adf62010-05-24 17:22:01 +0000810 if (T->isDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000811 return false;
812
813 getSema().MarkDeclarationsReferencedInType(Loc, T);
814 return true;
815}
816
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000817Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000818 if (!D)
819 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Douglas Gregorc68afe22009-09-03 21:38:09 +0000821 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000822 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000823 // If the corresponding template argument is NULL or non-existent, it's
824 // because we are performing instantiation from explicitly-specified
825 // template arguments in a function template, but there were some
826 // arguments left unspecified.
827 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
828 TTP->getPosition()))
829 return D;
830
Douglas Gregor61c4d282011-01-05 15:48:55 +0000831 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
832
833 if (TTP->isParameterPack()) {
834 assert(Arg.getKind() == TemplateArgument::Pack &&
835 "Missing argument pack");
836
Douglas Gregor1aee05d2011-01-15 06:45:20 +0000837 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregord3731192011-01-10 07:32:04 +0000838 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000839 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
840 }
841
842 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000843 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000844 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000845 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000846 }
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregor788cd062009-11-11 01:00:40 +0000848 // Fall through to find the instantiated declaration for this template
849 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000850 }
Mike Stump1eb44332009-09-09 15:08:12 +0000851
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000852 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000853}
854
Douglas Gregoraac571c2010-03-01 17:25:41 +0000855Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000856 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000857 if (!Inst)
858 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000859
Douglas Gregor43959a92009-08-20 07:17:43 +0000860 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
861 return Inst;
862}
863
Douglas Gregor6cd21982009-10-20 05:58:46 +0000864NamedDecl *
865TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
866 SourceLocation Loc) {
867 // If the first part of the nested-name-specifier was a template type
868 // parameter, instantiate that type parameter down to a tag type.
869 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
870 const TemplateTypeParmType *TTP
871 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000872
Douglas Gregor6cd21982009-10-20 05:58:46 +0000873 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000874 // FIXME: This needs testing w/ member access expressions.
875 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
876
877 if (TTP->isParameterPack()) {
878 assert(Arg.getKind() == TemplateArgument::Pack &&
879 "Missing argument pack");
880
Douglas Gregor2be29f42011-01-14 23:41:42 +0000881 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000882 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000883
Douglas Gregord3731192011-01-10 07:32:04 +0000884 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor984a58b2010-12-20 22:48:17 +0000885 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
886 }
887
888 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000889 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000890 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000891
892 if (const TagType *Tag = T->getAs<TagType>())
893 return Tag->getDecl();
894
895 // The resulting type is not a tag; complain.
896 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
897 return 0;
898 }
899 }
900
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000901 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000902}
903
Douglas Gregor43959a92009-08-20 07:17:43 +0000904VarDecl *
905TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000906 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000907 SourceLocation StartLoc,
908 SourceLocation NameLoc,
909 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000910 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000911 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000912 if (Var)
913 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
914 return Var;
915}
916
917VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
918 TypeSourceInfo *TSInfo,
919 QualType T) {
920 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
921 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000922 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
923 return Var;
924}
925
John McCallc4e70192009-09-11 04:59:25 +0000926QualType
John McCall21e413f2010-11-04 19:04:38 +0000927TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
928 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000929 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000930 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +0000931 if (const TagType *TT = T->getAs<TagType>()) {
932 TagDecl* TD = TT->getDecl();
933
John McCall21e413f2010-11-04 19:04:38 +0000934 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +0000935
936 // FIXME: type might be anonymous.
937 IdentifierInfo *Id = TD->getIdentifier();
938
939 // TODO: should we even warn on struct/class mismatches for this? Seems
940 // like it's likely to produce a lot of spurious errors.
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000941 if (Keyword != ETK_None && Keyword != ETK_Typename) {
942 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +0000943 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
944 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000945 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
946 << Id
947 << FixItHint::CreateReplacement(SourceRange(TagLocation),
948 TD->getKindName());
949 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
950 }
John McCallc4e70192009-09-11 04:59:25 +0000951 }
952 }
953
John McCall21e413f2010-11-04 19:04:38 +0000954 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
955 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000956 QualifierLoc,
957 T);
John McCallc4e70192009-09-11 04:59:25 +0000958}
959
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000960TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
961 TemplateName Name,
962 SourceLocation NameLoc,
963 QualType ObjectType,
964 NamedDecl *FirstQualifierInScope) {
965 if (TemplateTemplateParmDecl *TTP
966 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
967 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
968 // If the corresponding template argument is NULL or non-existent, it's
969 // because we are performing instantiation from explicitly-specified
970 // template arguments in a function template, but there were some
971 // arguments left unspecified.
972 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
973 TTP->getPosition()))
974 return Name;
975
976 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
977
978 if (TTP->isParameterPack()) {
979 assert(Arg.getKind() == TemplateArgument::Pack &&
980 "Missing argument pack");
981
982 if (getSema().ArgumentPackSubstitutionIndex == -1) {
983 // We have the template argument pack to substitute, but we're not
984 // actually expanding the enclosing pack expansion yet. So, just
985 // keep the entire argument pack.
986 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
987 }
988
989 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
990 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
991 }
992
993 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +0000994 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +0000995
Douglas Gregor58750382011-03-05 20:06:51 +0000996 // We don't ever want to substitute for a qualified template name, since
997 // the qualifier is handled separately. So, look through the qualified
998 // template name to its underlying declaration.
999 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1000 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001001
1002 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001003 return Template;
1004 }
1005 }
1006
1007 if (SubstTemplateTemplateParmPackStorage *SubstPack
1008 = Name.getAsSubstTemplateTemplateParmPack()) {
1009 if (getSema().ArgumentPackSubstitutionIndex == -1)
1010 return Name;
1011
1012 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1013 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1014 "Pack substitution index out-of-range");
1015 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1016 .getAsTemplate();
1017 }
1018
1019 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1020 FirstQualifierInScope);
1021}
1022
John McCall60d7b3a2010-08-24 06:29:42 +00001023ExprResult
John McCall454feb92009-12-08 09:21:05 +00001024TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001025 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001026 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001027
1028 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1029 assert(currentDecl && "Must have current function declaration when "
1030 "instantiating.");
1031
1032 PredefinedExpr::IdentType IT = E->getIdentType();
1033
Anders Carlsson848fa642010-02-11 18:20:28 +00001034 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001035
1036 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001037 QualType ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001038 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1039 ArrayType::Normal, 0);
1040 PredefinedExpr *PE =
1041 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1042 return getSema().Owned(PE);
1043}
1044
John McCall60d7b3a2010-08-24 06:29:42 +00001045ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001046TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001047 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001048 // If the corresponding template argument is NULL or non-existent, it's
1049 // because we are performing instantiation from explicitly-specified
1050 // template arguments in a function template, but there were some
1051 // arguments left unspecified.
1052 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1053 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001054 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Douglas Gregor56bc9832010-12-24 00:15:10 +00001056 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1057 if (NTTP->isParameterPack()) {
1058 assert(Arg.getKind() == TemplateArgument::Pack &&
1059 "Missing argument pack");
1060
1061 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001062 // We have an argument pack, but we can't select a particular argument
1063 // out of it yet. Therefore, we'll build an expression to hold on to that
1064 // argument pack.
1065 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1066 E->getLocation(),
1067 NTTP->getDeclName());
1068 if (TargetType.isNull())
1069 return ExprError();
1070
1071 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1072 NTTP,
1073 E->getLocation(),
1074 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001075 }
1076
Douglas Gregord3731192011-01-10 07:32:04 +00001077 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor56bc9832010-12-24 00:15:10 +00001078 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1079 }
Mike Stump1eb44332009-09-09 15:08:12 +00001080
John McCallb8fc0532010-02-06 08:42:39 +00001081 // The template argument itself might be an expression, in which
1082 // case we just return that expression.
1083 if (Arg.getKind() == TemplateArgument::Expression)
John McCall3fa5cae2010-10-26 07:05:15 +00001084 return SemaRef.Owned(Arg.getAsExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001085
John McCallb8fc0532010-02-06 08:42:39 +00001086 if (Arg.getKind() == TemplateArgument::Declaration) {
1087 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001088
John McCall645cf442010-02-06 10:23:53 +00001089 // Find the instantiation of the template argument. This is
1090 // required for nested templates.
John McCallb8fc0532010-02-06 08:42:39 +00001091 VD = cast_or_null<ValueDecl>(
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001092 getSema().FindInstantiatedDecl(E->getLocation(),
1093 VD, TemplateArgs));
John McCallb8fc0532010-02-06 08:42:39 +00001094 if (!VD)
John McCallf312b1e2010-08-26 23:41:50 +00001095 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001096
John McCall645cf442010-02-06 10:23:53 +00001097 // Derive the type we want the substituted decl to have. This had
1098 // better be non-dependent, or these checks will have serious problems.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001099 QualType TargetType;
1100 if (NTTP->isExpandedParameterPack())
1101 TargetType = NTTP->getExpansionType(
1102 getSema().ArgumentPackSubstitutionIndex);
1103 else if (NTTP->isParameterPack() &&
1104 isa<PackExpansionType>(NTTP->getType())) {
1105 TargetType = SemaRef.SubstType(
1106 cast<PackExpansionType>(NTTP->getType())->getPattern(),
1107 TemplateArgs, E->getLocation(),
1108 NTTP->getDeclName());
1109 } else
1110 TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1111 E->getLocation(), NTTP->getDeclName());
John McCall645cf442010-02-06 10:23:53 +00001112 assert(!TargetType.isNull() && "type substitution failed for param type");
1113 assert(!TargetType->isDependentType() && "param type still dependent");
Douglas Gregor02024a92010-03-28 02:42:43 +00001114 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg,
1115 TargetType,
1116 E->getLocation());
John McCallb8fc0532010-02-06 08:42:39 +00001117 }
1118
Douglas Gregor02024a92010-03-28 02:42:43 +00001119 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1120 E->getSourceRange().getBegin());
John McCallb8fc0532010-02-06 08:42:39 +00001121}
1122
Douglas Gregorc7793c72011-01-15 01:15:58 +00001123ExprResult
1124TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1125 SubstNonTypeTemplateParmPackExpr *E) {
1126 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1127 // We aren't expanding the parameter pack, so just return ourselves.
1128 return getSema().Owned(E);
1129 }
1130
Douglas Gregorc7793c72011-01-15 01:15:58 +00001131 const TemplateArgument &ArgPack = E->getArgumentPack();
1132 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1133 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1134
1135 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1136 if (Arg.getKind() == TemplateArgument::Expression)
1137 return SemaRef.Owned(Arg.getAsExpr());
1138
1139 if (Arg.getKind() == TemplateArgument::Declaration) {
1140 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
1141
1142 // Find the instantiation of the template argument. This is
1143 // required for nested templates.
1144 VD = cast_or_null<ValueDecl>(
1145 getSema().FindInstantiatedDecl(E->getParameterPackLocation(),
1146 VD, TemplateArgs));
1147 if (!VD)
1148 return ExprError();
1149
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001150 QualType T;
1151 NonTypeTemplateParmDecl *NTTP = E->getParameterPack();
1152 if (NTTP->isExpandedParameterPack())
1153 T = NTTP->getExpansionType(getSema().ArgumentPackSubstitutionIndex);
1154 else if (const PackExpansionType *Expansion
1155 = dyn_cast<PackExpansionType>(NTTP->getType()))
1156 T = SemaRef.SubstType(Expansion->getPattern(), TemplateArgs,
1157 E->getParameterPackLocation(), NTTP->getDeclName());
1158 else
1159 T = E->getType();
1160 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg, T,
Douglas Gregorc7793c72011-01-15 01:15:58 +00001161 E->getParameterPackLocation());
1162 }
1163
1164 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1165 E->getParameterPackLocation());
1166}
John McCallb8fc0532010-02-06 08:42:39 +00001167
John McCall60d7b3a2010-08-24 06:29:42 +00001168ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001169TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1170 NamedDecl *D = E->getDecl();
1171 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1172 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1173 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001174
1175 // We have a non-type template parameter that isn't fully substituted;
1176 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001177 }
Mike Stump1eb44332009-09-09 15:08:12 +00001178
John McCall454feb92009-12-08 09:21:05 +00001179 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001180}
1181
John McCall60d7b3a2010-08-24 06:29:42 +00001182ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001183 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001184 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1185 getDescribedFunctionTemplate() &&
1186 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001187 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1188 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1189 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001190}
1191
Douglas Gregor895162d2010-04-30 18:55:50 +00001192QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001193 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001194 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001195 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001196 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001197}
1198
1199ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001200TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001201 int indexAdjustment,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001202 llvm::Optional<unsigned> NumExpansions) {
John McCallfb44de92011-05-01 22:35:37 +00001203 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001204 NumExpansions);
John McCall21ef0fa2010-03-11 09:03:00 +00001205}
1206
Mike Stump1eb44332009-09-09 15:08:12 +00001207QualType
John McCalla2becad2009-10-21 00:40:46 +00001208TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001209 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001210 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001211 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001212 // Replace the template type parameter with its corresponding
1213 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001214
1215 // If the corresponding template argument is NULL or doesn't exist, it's
1216 // because we are performing instantiation from explicitly-specified
1217 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001218 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001219 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1220 TemplateTypeParmTypeLoc NewTL
1221 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1222 NewTL.setNameLoc(TL.getNameLoc());
1223 return TL.getType();
1224 }
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001226 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1227
1228 if (T->isParameterPack()) {
1229 assert(Arg.getKind() == TemplateArgument::Pack &&
1230 "Missing argument pack");
1231
1232 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001233 // We have the template argument pack, but we're not expanding the
1234 // enclosing pack expansion yet. Just save the template argument
1235 // pack for later substitution.
1236 QualType Result
1237 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1238 SubstTemplateTypeParmPackTypeLoc NewTL
1239 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1240 NewTL.setNameLoc(TL.getNameLoc());
1241 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001242 }
1243
Douglas Gregord3731192011-01-10 07:32:04 +00001244 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001245 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1246 }
1247
1248 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001249 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001250
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001251 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001252
1253 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001254 QualType Result
1255 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1256 SubstTemplateTypeParmTypeLoc NewTL
1257 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1258 NewTL.setNameLoc(TL.getNameLoc());
1259 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001260 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001261
1262 // The template type parameter comes from an inner template (e.g.,
1263 // the template parameter list of a member template inside the
1264 // template we are instantiating). Create a new template type
1265 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001266 TemplateTypeParmDecl *NewTTPDecl = 0;
1267 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1268 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1269 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1270
John McCalla2becad2009-10-21 00:40:46 +00001271 QualType Result
1272 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1273 - TemplateArgs.getNumLevels(),
1274 T->getIndex(),
1275 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001276 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001277 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1278 NewTL.setNameLoc(TL.getNameLoc());
1279 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001280}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001281
Douglas Gregorc3069d62011-01-14 02:55:32 +00001282QualType
1283TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1284 TypeLocBuilder &TLB,
1285 SubstTemplateTypeParmPackTypeLoc TL) {
1286 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1287 // We aren't expanding the parameter pack, so just return ourselves.
1288 SubstTemplateTypeParmPackTypeLoc NewTL
1289 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1290 NewTL.setNameLoc(TL.getNameLoc());
1291 return TL.getType();
1292 }
1293
1294 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1295 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1296 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1297
1298 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1299 Result = getSema().Context.getSubstTemplateTypeParmType(
1300 TL.getTypePtr()->getReplacedParameter(),
1301 Result);
1302 SubstTemplateTypeParmTypeLoc NewTL
1303 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1304 NewTL.setNameLoc(TL.getNameLoc());
1305 return Result;
1306}
1307
John McCallce3ff2b2009-08-25 22:02:44 +00001308/// \brief Perform substitution on the type T with a given set of template
1309/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001310///
1311/// This routine substitutes the given template arguments into the
1312/// type T and produces the instantiated type.
1313///
1314/// \param T the type into which the template arguments will be
1315/// substituted. If this type is not dependent, it will be returned
1316/// immediately.
1317///
1318/// \param TemplateArgs the template arguments that will be
1319/// substituted for the top-level template parameters within T.
1320///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001321/// \param Loc the location in the source code where this substitution
1322/// is being performed. It will typically be the location of the
1323/// declarator (if we're instantiating the type of some declaration)
1324/// or the location of the type in the source code (if, e.g., we're
1325/// instantiating the type of a cast expression).
1326///
1327/// \param Entity the name of the entity associated with a declaration
1328/// being instantiated (if any). May be empty to indicate that there
1329/// is no such entity (if, e.g., this is a type that occurs as part of
1330/// a cast expression) or that the entity has no name (e.g., an
1331/// unnamed function parameter).
1332///
1333/// \returns If the instantiation succeeds, the instantiated
1334/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001335TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001336 const MultiLevelTemplateArgumentList &Args,
1337 SourceLocation Loc,
1338 DeclarationName Entity) {
1339 assert(!ActiveTemplateInstantiations.empty() &&
1340 "Cannot perform an instantiation without some context on the "
1341 "instantiation stack");
1342
Douglas Gregor836adf62010-05-24 17:22:01 +00001343 if (!T->getType()->isDependentType() &&
1344 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001345 return T;
1346
1347 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1348 return Instantiator.TransformType(T);
1349}
1350
Douglas Gregor603cfb42011-01-05 23:12:31 +00001351TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1352 const MultiLevelTemplateArgumentList &Args,
1353 SourceLocation Loc,
1354 DeclarationName Entity) {
1355 assert(!ActiveTemplateInstantiations.empty() &&
1356 "Cannot perform an instantiation without some context on the "
1357 "instantiation stack");
1358
1359 if (TL.getType().isNull())
1360 return 0;
1361
1362 if (!TL.getType()->isDependentType() &&
1363 !TL.getType()->isVariablyModifiedType()) {
1364 // FIXME: Make a copy of the TypeLoc data here, so that we can
1365 // return a new TypeSourceInfo. Inefficient!
1366 TypeLocBuilder TLB;
1367 TLB.pushFullCopy(TL);
1368 return TLB.getTypeSourceInfo(Context, TL.getType());
1369 }
1370
1371 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1372 TypeLocBuilder TLB;
1373 TLB.reserve(TL.getFullDataSize());
1374 QualType Result = Instantiator.TransformType(TLB, TL);
1375 if (Result.isNull())
1376 return 0;
1377
1378 return TLB.getTypeSourceInfo(Context, Result);
1379}
1380
John McCallcd7ba1c2009-10-21 00:58:09 +00001381/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001382QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001383 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001384 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001385 assert(!ActiveTemplateInstantiations.empty() &&
1386 "Cannot perform an instantiation without some context on the "
1387 "instantiation stack");
1388
Douglas Gregor836adf62010-05-24 17:22:01 +00001389 // If T is not a dependent type or a variably-modified type, there
1390 // is nothing to do.
1391 if (!T->isDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001392 return T;
1393
Douglas Gregor577f75a2009-08-04 16:50:30 +00001394 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1395 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001396}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001397
John McCall6cd3b9f2010-04-09 17:38:44 +00001398static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor836adf62010-05-24 17:22:01 +00001399 if (T->getType()->isDependentType() || T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001400 return true;
1401
Abramo Bagnara723df242010-12-14 22:11:44 +00001402 TypeLoc TL = T->getTypeLoc().IgnoreParens();
John McCall6cd3b9f2010-04-09 17:38:44 +00001403 if (!isa<FunctionProtoTypeLoc>(TL))
1404 return false;
1405
1406 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1407 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1408 ParmVarDecl *P = FP.getArg(I);
1409
Douglas Gregorc056c172011-05-09 20:45:16 +00001410 // The parameter's type as written might be dependent even if the
1411 // decayed type was not dependent.
1412 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1413 if (TSInfo->getType()->isDependentType())
1414 return true;
1415
John McCall6cd3b9f2010-04-09 17:38:44 +00001416 // TODO: currently we always rebuild expressions. When we
1417 // properly get lazier about this, we should use the same
1418 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001419 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001420 return true;
1421 }
1422
1423 return false;
1424}
1425
1426/// A form of SubstType intended specifically for instantiating the
1427/// type of a FunctionDecl. Its purpose is solely to force the
1428/// instantiation of default-argument expressions.
1429TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1430 const MultiLevelTemplateArgumentList &Args,
1431 SourceLocation Loc,
1432 DeclarationName Entity) {
1433 assert(!ActiveTemplateInstantiations.empty() &&
1434 "Cannot perform an instantiation without some context on the "
1435 "instantiation stack");
1436
1437 if (!NeedsInstantiationAsFunctionType(T))
1438 return T;
1439
1440 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1441
1442 TypeLocBuilder TLB;
1443
1444 TypeLoc TL = T->getTypeLoc();
1445 TLB.reserve(TL.getFullDataSize());
1446
John McCall43fed0d2010-11-12 08:19:04 +00001447 QualType Result = Instantiator.TransformType(TLB, TL);
John McCall6cd3b9f2010-04-09 17:38:44 +00001448 if (Result.isNull())
1449 return 0;
1450
1451 return TLB.getTypeSourceInfo(Context, Result);
1452}
1453
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001454ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001455 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001456 int indexAdjustment,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001457 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001458 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001459 TypeSourceInfo *NewDI = 0;
1460
Douglas Gregor603cfb42011-01-05 23:12:31 +00001461 TypeLoc OldTL = OldDI->getTypeLoc();
1462 if (isa<PackExpansionTypeLoc>(OldTL)) {
1463 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
Douglas Gregor603cfb42011-01-05 23:12:31 +00001464
1465 // We have a function parameter pack. Substitute into the pattern of the
1466 // expansion.
1467 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1468 OldParm->getLocation(), OldParm->getDeclName());
1469 if (!NewDI)
1470 return 0;
1471
1472 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1473 // We still have unexpanded parameter packs, which means that
1474 // our function parameter is still a function parameter pack.
1475 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001476 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001477 NumExpansions);
Douglas Gregor603cfb42011-01-05 23:12:31 +00001478 }
1479 } else {
1480 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1481 OldParm->getDeclName());
1482 }
1483
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001484 if (!NewDI)
1485 return 0;
1486
1487 if (NewDI->getType()->isVoidType()) {
1488 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1489 return 0;
1490 }
1491
1492 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001493 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001494 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001495 OldParm->getIdentifier(),
1496 NewDI->getType(), NewDI,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001497 OldParm->getStorageClass(),
1498 OldParm->getStorageClassAsWritten());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001499 if (!NewParm)
1500 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001501
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001502 // Mark the (new) default argument as uninstantiated (if any).
1503 if (OldParm->hasUninstantiatedDefaultArg()) {
1504 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1505 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001506 } else if (OldParm->hasUnparsedDefaultArg()) {
1507 NewParm->setUnparsedDefaultArg();
1508 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001509 } else if (Expr *Arg = OldParm->getDefaultArg())
1510 NewParm->setUninstantiatedDefaultArg(Arg);
1511
1512 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1513
Douglas Gregor603cfb42011-01-05 23:12:31 +00001514 // FIXME: When OldParm is a parameter pack and NewParm is not a parameter
1515 // pack, we actually have a set of instantiated locations. Maintain this set!
Douglas Gregor12c9c002011-01-07 16:43:16 +00001516 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1517 // Add the new parameter to
1518 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1519 } else {
1520 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001521 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001522 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001523
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001524 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1525 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001526 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001527
1528 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1529 OldParm->getFunctionScopeIndex() + indexAdjustment);
Fariborz Jahaniane7ffbe22010-07-13 20:05:58 +00001530
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001531 return NewParm;
1532}
1533
Douglas Gregora009b592011-01-07 00:20:55 +00001534/// \brief Substitute the given template arguments into the given set of
1535/// parameters, producing the set of parameter types that would be generated
1536/// from such a substitution.
1537bool Sema::SubstParmTypes(SourceLocation Loc,
1538 ParmVarDecl **Params, unsigned NumParams,
1539 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001540 llvm::SmallVectorImpl<QualType> &ParamTypes,
1541 llvm::SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001542 assert(!ActiveTemplateInstantiations.empty() &&
1543 "Cannot perform an instantiation without some context on the "
1544 "instantiation stack");
1545
1546 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1547 DeclarationName());
1548 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001549 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001550}
1551
John McCallce3ff2b2009-08-25 22:02:44 +00001552/// \brief Perform substitution on the base class specifiers of the
1553/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001554///
1555/// Produces a diagnostic and returns true on error, returns false and
1556/// attaches the instantiated base classes to the class template
1557/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001558bool
John McCallce3ff2b2009-08-25 22:02:44 +00001559Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1560 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001561 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001562 bool Invalid = false;
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001563 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001564 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001565 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001566 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001567 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001568 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001569 continue;
1570 }
1571
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001572 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001573 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001574 if (Base->isPackExpansion()) {
1575 // This is a pack expansion. See whether we should expand it now, or
1576 // wait until later.
1577 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1578 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1579 Unexpanded);
1580 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001581 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00001582 llvm::Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001583 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1584 Base->getSourceRange(),
1585 Unexpanded.data(), Unexpanded.size(),
1586 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001587 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001588 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001589 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001590 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001591 }
1592
1593 // If we should expand this pack expansion now, do so.
1594 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001595 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001596 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1597
1598 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1599 TemplateArgs,
1600 Base->getSourceRange().getBegin(),
1601 DeclarationName());
1602 if (!BaseTypeLoc) {
1603 Invalid = true;
1604 continue;
1605 }
1606
1607 if (CXXBaseSpecifier *InstantiatedBase
1608 = CheckBaseSpecifier(Instantiation,
1609 Base->getSourceRange(),
1610 Base->isVirtual(),
1611 Base->getAccessSpecifierAsWritten(),
1612 BaseTypeLoc,
1613 SourceLocation()))
1614 InstantiatedBases.push_back(InstantiatedBase);
1615 else
1616 Invalid = true;
1617 }
1618
1619 continue;
1620 }
1621
1622 // The resulting base specifier will (still) be a pack expansion.
1623 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001624 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1625 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1626 TemplateArgs,
1627 Base->getSourceRange().getBegin(),
1628 DeclarationName());
1629 } else {
1630 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1631 TemplateArgs,
1632 Base->getSourceRange().getBegin(),
1633 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001634 }
1635
Nick Lewycky56062202010-07-26 16:56:01 +00001636 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001637 Invalid = true;
1638 continue;
1639 }
1640
1641 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001642 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001643 Base->getSourceRange(),
1644 Base->isVirtual(),
1645 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001646 BaseTypeLoc,
1647 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001648 InstantiatedBases.push_back(InstantiatedBase);
1649 else
1650 Invalid = true;
1651 }
1652
Douglas Gregor27b152f2009-03-10 18:52:44 +00001653 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001654 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001655 InstantiatedBases.size()))
1656 Invalid = true;
1657
1658 return Invalid;
1659}
1660
Douglas Gregord475b8d2009-03-25 21:17:03 +00001661/// \brief Instantiate the definition of a class from a given pattern.
1662///
1663/// \param PointOfInstantiation The point of instantiation within the
1664/// source code.
1665///
1666/// \param Instantiation is the declaration whose definition is being
1667/// instantiated. This will be either a class template specialization
1668/// or a member class of a class template specialization.
1669///
1670/// \param Pattern is the pattern from which the instantiation
1671/// occurs. This will be either the declaration of a class template or
1672/// the declaration of a member class of a class template.
1673///
1674/// \param TemplateArgs The template arguments to be substituted into
1675/// the pattern.
1676///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001677/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001678///
1679/// \param Complain whether to complain if the class cannot be instantiated due
1680/// to the lack of a definition.
1681///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001682/// \returns true if an error occurred, false otherwise.
1683bool
1684Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1685 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001686 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001687 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001688 bool Complain) {
Douglas Gregord475b8d2009-03-25 21:17:03 +00001689 bool Invalid = false;
John McCalle29ba202009-08-20 01:44:21 +00001690
Mike Stump1eb44332009-09-09 15:08:12 +00001691 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001692 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
John McCalld46a1122011-04-27 06:46:31 +00001693 if (!PatternDef || PatternDef->isBeingDefined()) {
1694 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001695 // Say nothing
John McCalld46a1122011-04-27 06:46:31 +00001696 } else if (PatternDef) {
1697 assert(PatternDef->isBeingDefined());
1698 Diag(PointOfInstantiation,
1699 diag::err_template_instantiate_within_definition)
1700 << (TSK != TSK_ImplicitInstantiation)
1701 << Context.getTypeDeclType(Instantiation);
1702 // Not much point in noting the template declaration here, since
1703 // we're lexically inside it.
1704 Instantiation->setInvalidDecl();
Douglas Gregor5842ba92009-08-24 15:23:48 +00001705 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
Douglas Gregord475b8d2009-03-25 21:17:03 +00001706 Diag(PointOfInstantiation,
1707 diag::err_implicit_instantiate_member_undefined)
1708 << Context.getTypeDeclType(Instantiation);
1709 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1710 } else {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00001711 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001712 << (TSK != TSK_ImplicitInstantiation)
Douglas Gregord475b8d2009-03-25 21:17:03 +00001713 << Context.getTypeDeclType(Instantiation);
1714 Diag(Pattern->getLocation(), diag::note_template_decl_here);
1715 }
1716 return true;
1717 }
1718 Pattern = PatternDef;
1719
Douglas Gregor454885e2009-10-15 15:54:05 +00001720 // \brief Record the point of instantiation.
1721 if (MemberSpecializationInfo *MSInfo
1722 = Instantiation->getMemberSpecializationInfo()) {
1723 MSInfo->setTemplateSpecializationKind(TSK);
1724 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001725 } else if (ClassTemplateSpecializationDecl *Spec
1726 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1727 Spec->setTemplateSpecializationKind(TSK);
1728 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001729 }
1730
Douglas Gregord048bb72009-03-25 21:23:52 +00001731 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001732 if (Inst)
1733 return true;
1734
1735 // Enter the scope of this instantiation. We don't use
1736 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001737 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001738 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001739 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001740
Douglas Gregor05030bb2010-03-24 01:33:17 +00001741 // If this is an instantiation of a local class, merge this local
1742 // instantiation scope with the enclosing scope. Otherwise, every
1743 // instantiation of a class has its own local instantiation scope.
1744 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001745 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001746
John McCall1d8d1cc2010-08-01 02:01:53 +00001747 // Pull attributes from the pattern onto the instantiation.
1748 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1749
Douglas Gregord475b8d2009-03-25 21:17:03 +00001750 // Start the definition of this instantiation.
1751 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001752
1753 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001754
John McCallce3ff2b2009-08-25 22:02:44 +00001755 // Do substitution on the base class specifiers.
1756 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001757 Invalid = true;
1758
Douglas Gregord65587f2010-11-10 19:44:59 +00001759 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
John McCalld226f652010-08-21 09:40:31 +00001760 llvm::SmallVector<Decl*, 4> Fields;
Richard Smith7a614d82011-06-11 17:19:42 +00001761 llvm::SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
1762 FieldsWithMemberInitializers;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001763 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001764 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001765 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001766 // Don't instantiate members not belonging in this semantic context.
1767 // e.g. for:
1768 // @code
1769 // template <int i> class A {
1770 // class B *g;
1771 // };
1772 // @endcode
1773 // 'class B' has the template as lexical context but semantically it is
1774 // introduced in namespace scope.
1775 if ((*Member)->getDeclContext() != Pattern)
1776 continue;
1777
Douglas Gregord65587f2010-11-10 19:44:59 +00001778 if ((*Member)->isInvalidDecl()) {
1779 Invalid = true;
1780 continue;
1781 }
1782
1783 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001784 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00001785 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00001786 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00001787 FieldDecl *OldField = cast<FieldDecl>(*Member);
1788 if (OldField->getInClassInitializer())
1789 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1790 Field));
1791 } else if (NewMember->isInvalidDecl())
Eli Friedman721e77d2009-12-07 00:22:08 +00001792 Invalid = true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001793 } else {
1794 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump390b4cc2009-05-16 07:39:55 +00001795 // instantiations was a semantic disaster, and we'll want to set Invalid =
1796 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00001797 }
1798 }
1799
1800 // Finish checking fields.
John McCalld226f652010-08-21 09:40:31 +00001801 ActOnFields(0, Instantiation->getLocation(), Instantiation,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001802 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
Douglas Gregord475b8d2009-03-25 21:17:03 +00001803 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00001804 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00001805
1806 // Attach any in-class member initializers now the class is complete.
1807 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
1808 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
1809 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
1810 Expr *OldInit = OldField->getInClassInitializer();
1811 ExprResult NewInit = SubstExpr(OldInit, TemplateArgs);
1812
1813 // If the initialization is no longer dependent, check it now.
1814 if ((OldField->getType()->isDependentType() || OldInit->isTypeDependent())
1815 && !NewField->getType()->isDependentType()
1816 && !NewInit.get()->isTypeDependent()) {
1817 // FIXME: handle list-initialization
1818 SourceLocation EqualLoc = NewField->getLocation();
1819 NewInit = PerformCopyInitialization(
1820 InitializedEntity::InitializeMember(NewField), EqualLoc,
1821 NewInit.release());
1822
1823 if (!NewInit.isInvalid()) {
1824 CheckImplicitConversions(NewInit.get(), EqualLoc);
1825
1826 // C++0x [class.base.init]p7:
1827 // The initialization of each base and member constitutes a
1828 // full-expression.
1829 NewInit = MaybeCreateExprWithCleanups(NewInit);
1830 }
1831 }
1832
1833 if (NewInit.isInvalid())
1834 NewField->setInvalidDecl();
1835 else
1836 NewField->setInClassInitializer(NewInit.release());
1837 }
1838
1839 if (!FieldsWithMemberInitializers.empty())
1840 ActOnFinishDelayedMemberInitializers(Instantiation);
1841
Douglas Gregor663b5a02009-10-14 20:14:33 +00001842 if (Instantiation->isInvalidDecl())
1843 Invalid = true;
Douglas Gregord65587f2010-11-10 19:44:59 +00001844 else {
1845 // Instantiate any out-of-line class template partial
1846 // specializations now.
1847 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1848 P = Instantiator.delayed_partial_spec_begin(),
1849 PEnd = Instantiator.delayed_partial_spec_end();
1850 P != PEnd; ++P) {
1851 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1852 P->first,
1853 P->second)) {
1854 Invalid = true;
1855 break;
1856 }
1857 }
1858 }
1859
Douglas Gregord475b8d2009-03-25 21:17:03 +00001860 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00001861 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001862
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001863 if (!Invalid) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001864 Consumer.HandleTagDeclDefinition(Instantiation);
1865
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001866 // Always emit the vtable for an explicit instantiation definition
1867 // of a polymorphic class template specialization.
1868 if (TSK == TSK_ExplicitInstantiationDefinition)
1869 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1870 }
1871
Douglas Gregord475b8d2009-03-25 21:17:03 +00001872 return Invalid;
1873}
1874
Douglas Gregor9b623632010-10-12 23:32:35 +00001875namespace {
1876 /// \brief A partial specialization whose template arguments have matched
1877 /// a given template-id.
1878 struct PartialSpecMatchResult {
1879 ClassTemplatePartialSpecializationDecl *Partial;
1880 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00001881 };
1882}
1883
Mike Stump1eb44332009-09-09 15:08:12 +00001884bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00001885Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001886 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001887 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001888 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001889 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001890 // Perform the actual instantiation on the canonical declaration.
1891 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001892 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001893
Douglas Gregor52604ab2009-09-11 21:19:12 +00001894 // Check whether we have already instantiated or specialized this class
1895 // template specialization.
1896 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
1897 if (ClassTemplateSpec->getSpecializationKind() ==
1898 TSK_ExplicitInstantiationDeclaration &&
1899 TSK == TSK_ExplicitInstantiationDefinition) {
1900 // An explicit instantiation definition follows an explicit instantiation
1901 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
1902 // explicit instantiation.
1903 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001904
1905 // If this is an explicit instantiation definition, mark the
1906 // vtable as used.
1907 if (TSK == TSK_ExplicitInstantiationDefinition)
1908 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
1909
Douglas Gregor52604ab2009-09-11 21:19:12 +00001910 return false;
1911 }
1912
1913 // We can only instantiate something that hasn't already been
1914 // instantiated or specialized. Fail without any diagnostics: our
1915 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001916 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00001917 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001918
Douglas Gregor9eea08b2009-09-15 16:51:42 +00001919 if (ClassTemplateSpec->isInvalidDecl())
1920 return true;
1921
Douglas Gregor2943aed2009-03-03 04:44:36 +00001922 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001923 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00001924
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001925 // C++ [temp.class.spec.match]p1:
1926 // When a class template is used in a context that requires an
1927 // instantiation of the class, it is necessary to determine
1928 // whether the instantiation is to be generated using the primary
1929 // template or one of the partial specializations. This is done by
1930 // matching the template arguments of the class template
1931 // specialization with the template argument lists of the partial
1932 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00001933 typedef PartialSpecMatchResult MatchResult;
Douglas Gregor199d9912009-06-05 00:53:49 +00001934 llvm::SmallVector<MatchResult, 4> Matched;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001935 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1936 Template->getPartialSpecializations(PartialSpecs);
1937 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
1938 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
John McCall5769d612010-02-08 23:07:23 +00001939 TemplateDeductionInfo Info(Context, PointOfInstantiation);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001940 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001941 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001942 ClassTemplateSpec->getTemplateArgs(),
1943 Info)) {
1944 // FIXME: Store the failed-deduction information for use in
1945 // diagnostics, later.
1946 (void)Result;
1947 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00001948 Matched.push_back(PartialSpecMatchResult());
1949 Matched.back().Partial = Partial;
1950 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00001951 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00001952 }
1953
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001954 // If we're dealing with a member template where the template parameters
1955 // have been instantiated, this provides the original template parameters
1956 // from which the member template's parameters were instantiated.
1957 llvm::SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
1958
Douglas Gregored9c0f92009-10-29 00:04:11 +00001959 if (Matched.size() >= 1) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001960 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001961 if (Matched.size() == 1) {
1962 // -- If exactly one matching specialization is found, the
1963 // instantiation is generated from that specialization.
1964 // We don't need to do anything for this.
1965 } else {
1966 // -- If more than one matching specialization is found, the
1967 // partial order rules (14.5.4.2) are used to determine
1968 // whether one of the specializations is more specialized
1969 // than the others. If none of the specializations is more
1970 // specialized than all of the other matching
1971 // specializations, then the use of the class template is
1972 // ambiguous and the program is ill-formed.
1973 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1974 PEnd = Matched.end();
1975 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00001976 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00001977 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00001978 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00001979 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001980 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001981
Douglas Gregored9c0f92009-10-29 00:04:11 +00001982 // Determine if the best partial specialization is more specialized than
1983 // the others.
1984 bool Ambiguous = false;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001985 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1986 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001987 P != PEnd; ++P) {
1988 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00001989 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00001990 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00001991 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00001992 Ambiguous = true;
1993 break;
1994 }
1995 }
1996
1997 if (Ambiguous) {
1998 // Partial ordering did not produce a clear winner. Complain.
1999 ClassTemplateSpec->setInvalidDecl();
2000 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2001 << ClassTemplateSpec;
2002
2003 // Print the matching partial specializations.
2004 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
2005 PEnd = Matched.end();
2006 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002007 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2008 << getTemplateArgumentBindingsText(
2009 P->Partial->getTemplateParameters(),
2010 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002011
Douglas Gregored9c0f92009-10-29 00:04:11 +00002012 return true;
2013 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002014 }
2015
2016 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002017 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002018 while (OrigPartialSpec->getInstantiatedFromMember()) {
2019 // If we've found an explicit specialization of this class template,
2020 // stop here and use that as the pattern.
2021 if (OrigPartialSpec->isMemberSpecialization())
2022 break;
2023
2024 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2025 }
2026
2027 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002028 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002029 } else {
2030 // -- If no matches are found, the instantiation is generated
2031 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002032 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002033 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2034 // If we've found an explicit specialization of this class template,
2035 // stop here and use that as the pattern.
2036 if (OrigTemplate->isMemberSpecialization())
2037 break;
2038
Douglas Gregord6350ae2009-08-28 20:31:08 +00002039 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002040 }
2041
Douglas Gregord6350ae2009-08-28 20:31:08 +00002042 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002043 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002044
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002045 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2046 Pattern,
2047 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002048 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002049 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002050
Douglas Gregor199d9912009-06-05 00:53:49 +00002051 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002052}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002053
John McCallce3ff2b2009-08-25 22:02:44 +00002054/// \brief Instantiates the definitions of all of the member
2055/// of the given class, which is an instantiation of a class template
2056/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002057void
2058Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002059 CXXRecordDecl *Instantiation,
2060 const MultiLevelTemplateArgumentList &TemplateArgs,
2061 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002062 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2063 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002064 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002065 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002066 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002067 if (FunctionDecl *Pattern
2068 = Function->getInstantiatedFromMemberFunction()) {
2069 MemberSpecializationInfo *MSInfo
2070 = Function->getMemberSpecializationInfo();
2071 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002072 if (MSInfo->getTemplateSpecializationKind()
2073 == TSK_ExplicitSpecialization)
2074 continue;
2075
Douglas Gregor0d035142009-10-27 18:42:08 +00002076 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2077 Function,
2078 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002079 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002080 SuppressNew) ||
2081 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002082 continue;
2083
Sean Hunt10620eb2011-05-06 20:44:56 +00002084 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002085 continue;
2086
2087 if (TSK == TSK_ExplicitInstantiationDefinition) {
2088 // C++0x [temp.explicit]p8:
2089 // An explicit instantiation definition that names a class template
2090 // specialization explicitly instantiates the class template
2091 // specialization and is only an explicit instantiation definition
2092 // of members whose definition is visible at the point of
2093 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002094 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002095 continue;
2096
2097 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2098
2099 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2100 } else {
2101 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2102 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002103 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002104 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002105 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002106 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2107 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002108 if (MSInfo->getTemplateSpecializationKind()
2109 == TSK_ExplicitSpecialization)
2110 continue;
2111
Douglas Gregor0d035142009-10-27 18:42:08 +00002112 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2113 Var,
2114 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002115 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002116 SuppressNew) ||
2117 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002118 continue;
2119
Douglas Gregor0d035142009-10-27 18:42:08 +00002120 if (TSK == TSK_ExplicitInstantiationDefinition) {
2121 // C++0x [temp.explicit]p8:
2122 // An explicit instantiation definition that names a class template
2123 // specialization explicitly instantiates the class template
2124 // specialization and is only an explicit instantiation definition
2125 // of members whose definition is visible at the point of
2126 // instantiation.
2127 if (!Var->getInstantiatedFromStaticDataMember()
2128 ->getOutOfLineDefinition())
2129 continue;
2130
2131 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002132 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002133 } else {
2134 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2135 }
2136 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002137 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002138 // Always skip the injected-class-name, along with any
2139 // redeclarations of nested classes, since both would cause us
2140 // to try to instantiate the members of a class twice.
2141 if (Record->isInjectedClassName() || Record->getPreviousDeclaration())
Douglas Gregor2db32322009-10-07 23:56:10 +00002142 continue;
2143
Douglas Gregor0d035142009-10-27 18:42:08 +00002144 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2145 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002146
2147 if (MSInfo->getTemplateSpecializationKind()
2148 == TSK_ExplicitSpecialization)
2149 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002150
Douglas Gregor0d035142009-10-27 18:42:08 +00002151 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2152 Record,
2153 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002154 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002155 SuppressNew) ||
2156 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002157 continue;
2158
Douglas Gregor0d035142009-10-27 18:42:08 +00002159 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2160 assert(Pattern && "Missing instantiated-from-template information");
2161
Douglas Gregor952b0172010-02-11 01:04:33 +00002162 if (!Record->getDefinition()) {
2163 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002164 // C++0x [temp.explicit]p8:
2165 // An explicit instantiation definition that names a class template
2166 // specialization explicitly instantiates the class template
2167 // specialization and is only an explicit instantiation definition
2168 // of members whose definition is visible at the point of
2169 // instantiation.
2170 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2171 MSInfo->setTemplateSpecializationKind(TSK);
2172 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2173 }
2174
2175 continue;
2176 }
2177
2178 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002179 TemplateArgs,
2180 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002181 } else {
2182 if (TSK == TSK_ExplicitInstantiationDefinition &&
2183 Record->getTemplateSpecializationKind() ==
2184 TSK_ExplicitInstantiationDeclaration) {
2185 Record->setTemplateSpecializationKind(TSK);
2186 MarkVTableUsed(PointOfInstantiation, Record, true);
2187 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002188 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002189
Douglas Gregor952b0172010-02-11 01:04:33 +00002190 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002191 if (Pattern)
2192 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2193 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002194 }
2195 }
2196}
2197
2198/// \brief Instantiate the definitions of all of the members of the
2199/// given class template specialization, which was named as part of an
2200/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002201void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002202Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002203 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002204 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2205 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002206 // C++0x [temp.explicit]p7:
2207 // An explicit instantiation that names a class template
2208 // specialization is an explicit instantion of the same kind
2209 // (declaration or definition) of each of its members (not
2210 // including members inherited from base classes) that has not
2211 // been previously explicitly specialized in the translation unit
2212 // containing the explicit instantiation, except as described
2213 // below.
2214 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002215 getTemplateInstantiationArgs(ClassTemplateSpec),
2216 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002217}
2218
John McCall60d7b3a2010-08-24 06:29:42 +00002219StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002220Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002221 if (!S)
2222 return Owned(S);
2223
2224 TemplateInstantiator Instantiator(*this, TemplateArgs,
2225 SourceLocation(),
2226 DeclarationName());
2227 return Instantiator.TransformStmt(S);
2228}
2229
John McCall60d7b3a2010-08-24 06:29:42 +00002230ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002231Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002232 if (!E)
2233 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Douglas Gregorb98b1992009-08-11 05:31:07 +00002235 TemplateInstantiator Instantiator(*this, TemplateArgs,
2236 SourceLocation(),
2237 DeclarationName());
2238 return Instantiator.TransformExpr(E);
2239}
2240
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002241bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2242 const MultiLevelTemplateArgumentList &TemplateArgs,
2243 llvm::SmallVectorImpl<Expr *> &Outputs) {
2244 if (NumExprs == 0)
2245 return false;
2246
2247 TemplateInstantiator Instantiator(*this, TemplateArgs,
2248 SourceLocation(),
2249 DeclarationName());
2250 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2251}
2252
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002253NestedNameSpecifierLoc
2254Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2255 const MultiLevelTemplateArgumentList &TemplateArgs) {
2256 if (!NNS)
2257 return NestedNameSpecifierLoc();
2258
2259 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2260 DeclarationName());
2261 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2262}
2263
Abramo Bagnara25777432010-08-11 22:01:17 +00002264/// \brief Do template substitution on declaration name info.
2265DeclarationNameInfo
2266Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2267 const MultiLevelTemplateArgumentList &TemplateArgs) {
2268 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2269 NameInfo.getName());
2270 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2271}
2272
Douglas Gregorde650ae2009-03-31 18:38:02 +00002273TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002274Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2275 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002276 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002277 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2278 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002279 CXXScopeSpec SS;
2280 SS.Adopt(QualifierLoc);
2281 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002282}
Douglas Gregor91333002009-06-11 00:06:24 +00002283
Douglas Gregore02e2622010-12-22 21:19:48 +00002284bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2285 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002286 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002287 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2288 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002289
2290 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002291}
Douglas Gregor895162d2010-04-30 18:55:50 +00002292
Douglas Gregor12c9c002011-01-07 16:43:16 +00002293llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2294LocalInstantiationScope::findInstantiationOf(const Decl *D) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002295 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002296 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002297
Douglas Gregor895162d2010-04-30 18:55:50 +00002298 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002299 const Decl *CheckD = D;
2300 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002301 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002302 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002303 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002304
2305 // If this is a tag declaration, it's possible that we need to look for
2306 // a previous declaration.
2307 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2308 CheckD = Tag->getPreviousDeclaration();
2309 else
2310 CheckD = 0;
2311 } while (CheckD);
2312
Douglas Gregor895162d2010-04-30 18:55:50 +00002313 // If we aren't combined with our outer scope, we're done.
2314 if (!Current->CombineWithOuterScope)
2315 break;
2316 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002317
2318 // If we didn't find the decl, then we either have a sema bug, or we have a
2319 // forward reference to a label declaration. Return null to indicate that
2320 // we have an uninstantiated label.
2321 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002322 return 0;
2323}
2324
John McCall2a7fb272010-08-25 05:32:35 +00002325void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002326 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002327 if (Stored.isNull())
2328 Stored = Inst;
2329 else if (Stored.is<Decl *>()) {
2330 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2331 Stored = Inst;
2332 } else
2333 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
Douglas Gregor895162d2010-04-30 18:55:50 +00002334}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002335
2336void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2337 Decl *Inst) {
2338 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2339 Pack->push_back(Inst);
2340}
2341
2342void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2343 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2344 assert(Stored.isNull() && "Already instantiated this local");
2345 DeclArgumentPack *Pack = new DeclArgumentPack;
2346 Stored = Pack;
2347 ArgumentPacks.push_back(Pack);
2348}
2349
Douglas Gregord3731192011-01-10 07:32:04 +00002350void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2351 const TemplateArgument *ExplicitArgs,
2352 unsigned NumExplicitArgs) {
2353 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2354 "Already have a partially-substituted pack");
2355 assert((!PartiallySubstitutedPack
2356 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2357 "Wrong number of arguments in partially-substituted pack");
2358 PartiallySubstitutedPack = Pack;
2359 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2360 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2361}
2362
2363NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2364 const TemplateArgument **ExplicitArgs,
2365 unsigned *NumExplicitArgs) const {
2366 if (ExplicitArgs)
2367 *ExplicitArgs = 0;
2368 if (NumExplicitArgs)
2369 *NumExplicitArgs = 0;
2370
2371 for (const LocalInstantiationScope *Current = this; Current;
2372 Current = Current->Outer) {
2373 if (Current->PartiallySubstitutedPack) {
2374 if (ExplicitArgs)
2375 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2376 if (NumExplicitArgs)
2377 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2378
2379 return Current->PartiallySubstitutedPack;
2380 }
2381
2382 if (!Current->CombineWithOuterScope)
2383 break;
2384 }
2385
2386 return 0;
2387}