blob: 665dd07b8f85cda2c526ab3c9a0003f5542e38c9 [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 &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000101 (Function->getTemplateSpecializationKind() ==
102 TSK_ExplicitSpecialization &&
103 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000104 break;
105
Douglas Gregord1102432009-08-28 17:37:35 +0000106 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000107 = Function->getTemplateSpecializationArgs()) {
108 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000109 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000110
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000111 // If this function was instantiated from a specialized member that is
112 // a function template, we're done.
113 assert(Function->getPrimaryTemplate() && "No function template?");
114 if (Function->getPrimaryTemplate()->isMemberSpecialization())
115 break;
Douglas Gregorc494f772011-03-05 17:54:25 +0000116 } else if (FunctionTemplateDecl *FunTmpl
117 = Function->getDescribedFunctionTemplate()) {
118 // Add the "injected" template arguments.
119 std::pair<const TemplateArgument *, unsigned>
120 Injected = FunTmpl->getInjectedTemplateArgs();
121 Result.addOuterTemplateArguments(Injected.first, Injected.second);
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000122 }
123
John McCallf181d8a2009-08-29 03:16:09 +0000124 // If this is a friend declaration and it declares an entity at
125 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000126 // instead of its semantic parent, unless of course the pattern we're
127 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000128 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000129 Function->getDeclContext()->isFileContext() &&
130 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000131 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000132 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000133 continue;
134 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000135 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
136 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
137 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
138 const TemplateSpecializationType *TST
139 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
140 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
141 if (ClassTemplate->isMemberSpecialization())
142 break;
143 }
Douglas Gregord1102432009-08-28 17:37:35 +0000144 }
John McCallf181d8a2009-08-29 03:16:09 +0000145
146 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000147 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000148 }
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregord1102432009-08-28 17:37:35 +0000150 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000151}
152
Douglas Gregorf35f8282009-11-11 21:54:23 +0000153bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
154 switch (Kind) {
155 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000156 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000157 case DefaultTemplateArgumentInstantiation:
158 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000159 case ExplicitTemplateArgumentSubstitution:
160 case DeducedTemplateArgumentSubstitution:
161 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000162 return true;
163
Douglas Gregorf35f8282009-11-11 21:54:23 +0000164 case DefaultTemplateArgumentChecking:
165 return false;
166 }
David Blaikie7530c032012-01-17 06:56:22 +0000167
168 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000169}
170
Douglas Gregor26dce442009-03-10 00:06:19 +0000171Sema::InstantiatingTemplate::
172InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000173 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000174 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000175 : SemaRef(SemaRef),
176 SavedInNonInstantiationSFINAEContext(
177 SemaRef.InNonInstantiationSFINAEContext)
178{
Douglas Gregordf667e72009-03-10 20:44:00 +0000179 Invalid = CheckInstantiationDepth(PointOfInstantiation,
180 InstantiationRange);
181 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000182 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000183 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000184 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregordf667e72009-03-10 20:44:00 +0000185 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor313a81d2009-03-12 18:36:18 +0000186 Inst.TemplateArgs = 0;
187 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000188 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000189 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000190 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000191 }
192}
193
Richard Smithe6975e92012-04-17 00:58:00 +0000194Sema::InstantiatingTemplate::
195InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
196 FunctionDecl *Entity, ExceptionSpecification,
197 SourceRange InstantiationRange)
198 : SemaRef(SemaRef),
199 SavedInNonInstantiationSFINAEContext(
200 SemaRef.InNonInstantiationSFINAEContext)
201{
202 Invalid = CheckInstantiationDepth(PointOfInstantiation,
203 InstantiationRange);
204 if (!Invalid) {
205 ActiveTemplateInstantiation Inst;
206 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
207 Inst.PointOfInstantiation = PointOfInstantiation;
208 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
209 Inst.TemplateArgs = 0;
210 Inst.NumTemplateArgs = 0;
211 Inst.InstantiationRange = InstantiationRange;
212 SemaRef.InNonInstantiationSFINAEContext = false;
213 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
214 }
215}
216
Richard Smith7e54fb52012-07-16 01:09:10 +0000217Sema::InstantiatingTemplate::
218InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
219 TemplateDecl *Template,
220 ArrayRef<TemplateArgument> TemplateArgs,
221 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000222 : SemaRef(SemaRef),
223 SavedInNonInstantiationSFINAEContext(
224 SemaRef.InNonInstantiationSFINAEContext)
225{
Douglas Gregordf667e72009-03-10 20:44:00 +0000226 Invalid = CheckInstantiationDepth(PointOfInstantiation,
227 InstantiationRange);
228 if (!Invalid) {
229 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000230 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000231 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
232 Inst.PointOfInstantiation = PointOfInstantiation;
233 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
Richard Smith7e54fb52012-07-16 01:09:10 +0000234 Inst.TemplateArgs = TemplateArgs.data();
235 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor26dce442009-03-10 00:06:19 +0000236 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000237 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000238 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000239 }
240}
241
Richard Smith7e54fb52012-07-16 01:09:10 +0000242Sema::InstantiatingTemplate::
243InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
244 FunctionTemplateDecl *FunctionTemplate,
245 ArrayRef<TemplateArgument> TemplateArgs,
246 ActiveTemplateInstantiation::InstantiationKind Kind,
247 sema::TemplateDeductionInfo &DeductionInfo,
248 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000249 : SemaRef(SemaRef),
250 SavedInNonInstantiationSFINAEContext(
251 SemaRef.InNonInstantiationSFINAEContext)
252{
Richard Smithab91ef12012-07-08 02:38:24 +0000253 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000254 if (!Invalid) {
255 ActiveTemplateInstantiation Inst;
256 Inst.Kind = Kind;
257 Inst.PointOfInstantiation = PointOfInstantiation;
258 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
Richard Smith7e54fb52012-07-16 01:09:10 +0000259 Inst.TemplateArgs = TemplateArgs.data();
260 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor9b623632010-10-12 23:32:35 +0000261 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000262 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000263 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000264 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000265
266 if (!Inst.isInstantiationRecord())
267 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000268 }
269}
270
Richard Smith7e54fb52012-07-16 01:09:10 +0000271Sema::InstantiatingTemplate::
272InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
273 ClassTemplatePartialSpecializationDecl *PartialSpec,
274 ArrayRef<TemplateArgument> TemplateArgs,
275 sema::TemplateDeductionInfo &DeductionInfo,
276 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000277 : SemaRef(SemaRef),
278 SavedInNonInstantiationSFINAEContext(
279 SemaRef.InNonInstantiationSFINAEContext)
280{
Richard Smithab91ef12012-07-08 02:38:24 +0000281 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
282 if (!Invalid) {
283 ActiveTemplateInstantiation Inst;
284 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
285 Inst.PointOfInstantiation = PointOfInstantiation;
286 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
Richard Smith7e54fb52012-07-16 01:09:10 +0000287 Inst.TemplateArgs = TemplateArgs.data();
288 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000289 Inst.DeductionInfo = &DeductionInfo;
290 Inst.InstantiationRange = InstantiationRange;
291 SemaRef.InNonInstantiationSFINAEContext = false;
292 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
293 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000294}
295
Richard Smith7e54fb52012-07-16 01:09:10 +0000296Sema::InstantiatingTemplate::
297InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
298 ParmVarDecl *Param,
299 ArrayRef<TemplateArgument> TemplateArgs,
300 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000301 : SemaRef(SemaRef),
302 SavedInNonInstantiationSFINAEContext(
303 SemaRef.InNonInstantiationSFINAEContext)
304{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000305 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000306 if (!Invalid) {
307 ActiveTemplateInstantiation Inst;
308 Inst.Kind
309 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000310 Inst.PointOfInstantiation = PointOfInstantiation;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000311 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
Richard Smith7e54fb52012-07-16 01:09:10 +0000312 Inst.TemplateArgs = TemplateArgs.data();
313 Inst.NumTemplateArgs = TemplateArgs.size();
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000314 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000315 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000316 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000317 }
318}
319
320Sema::InstantiatingTemplate::
321InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000322 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
323 ArrayRef<TemplateArgument> TemplateArgs,
324 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000325 : SemaRef(SemaRef),
326 SavedInNonInstantiationSFINAEContext(
327 SemaRef.InNonInstantiationSFINAEContext)
328{
Richard Smithab91ef12012-07-08 02:38:24 +0000329 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
330 if (!Invalid) {
331 ActiveTemplateInstantiation Inst;
332 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
333 Inst.PointOfInstantiation = PointOfInstantiation;
334 Inst.Template = Template;
335 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
Richard Smith7e54fb52012-07-16 01:09:10 +0000336 Inst.TemplateArgs = TemplateArgs.data();
337 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000338 Inst.InstantiationRange = InstantiationRange;
339 SemaRef.InNonInstantiationSFINAEContext = false;
340 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
341 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000342}
343
344Sema::InstantiatingTemplate::
345InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000346 NamedDecl *Template, TemplateTemplateParmDecl *Param,
347 ArrayRef<TemplateArgument> TemplateArgs,
348 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000349 : SemaRef(SemaRef),
350 SavedInNonInstantiationSFINAEContext(
351 SemaRef.InNonInstantiationSFINAEContext)
352{
Richard Smithab91ef12012-07-08 02:38:24 +0000353 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
354 if (!Invalid) {
355 ActiveTemplateInstantiation Inst;
356 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
357 Inst.PointOfInstantiation = PointOfInstantiation;
358 Inst.Template = Template;
359 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
Richard Smith7e54fb52012-07-16 01:09:10 +0000360 Inst.TemplateArgs = TemplateArgs.data();
361 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000362 Inst.InstantiationRange = InstantiationRange;
363 SemaRef.InNonInstantiationSFINAEContext = false;
364 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
365 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000366}
367
368Sema::InstantiatingTemplate::
369InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000370 TemplateDecl *Template, NamedDecl *Param,
371 ArrayRef<TemplateArgument> TemplateArgs,
372 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000373 : SemaRef(SemaRef),
374 SavedInNonInstantiationSFINAEContext(
375 SemaRef.InNonInstantiationSFINAEContext)
376{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000377 Invalid = false;
378
379 ActiveTemplateInstantiation Inst;
380 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
381 Inst.PointOfInstantiation = PointOfInstantiation;
382 Inst.Template = Template;
383 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
Richard Smith7e54fb52012-07-16 01:09:10 +0000384 Inst.TemplateArgs = TemplateArgs.data();
385 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregorf35f8282009-11-11 21:54:23 +0000386 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000387 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000388 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
389
390 assert(!Inst.isInstantiationRecord());
391 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000392}
393
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000394void Sema::InstantiatingTemplate::Clear() {
395 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000396 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
397 assert(SemaRef.NonInstantiationEntries > 0);
398 --SemaRef.NonInstantiationEntries;
399 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000400 SemaRef.InNonInstantiationSFINAEContext
401 = SavedInNonInstantiationSFINAEContext;
Douglas Gregor26dce442009-03-10 00:06:19 +0000402 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000403 Invalid = true;
404 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000405}
406
Douglas Gregordf667e72009-03-10 20:44:00 +0000407bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
408 SourceLocation PointOfInstantiation,
409 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000410 assert(SemaRef.NonInstantiationEntries <=
411 SemaRef.ActiveTemplateInstantiations.size());
412 if ((SemaRef.ActiveTemplateInstantiations.size() -
413 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000414 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000415 return false;
416
Mike Stump1eb44332009-09-09 15:08:12 +0000417 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000418 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000419 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000420 << InstantiationRange;
421 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000422 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000423 return true;
424}
425
Douglas Gregoree1828a2009-03-10 18:03:33 +0000426/// \brief Prints the current instantiation stack through a series of
427/// notes.
428void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000429 // Determine which template instantiations to skip, if any.
430 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
431 unsigned Limit = Diags.getTemplateBacktraceLimit();
432 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
433 SkipStart = Limit / 2 + Limit % 2;
434 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
435 }
436
Douglas Gregorcca9e962009-07-01 22:01:06 +0000437 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000438 unsigned InstantiationIdx = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000439 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000440 Active = ActiveTemplateInstantiations.rbegin(),
441 ActiveEnd = ActiveTemplateInstantiations.rend();
442 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000443 ++Active, ++InstantiationIdx) {
444 // Skip this instantiation?
445 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
446 if (InstantiationIdx == SkipStart) {
447 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000448 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000449 diag::note_instantiation_contexts_suppressed)
450 << unsigned(ActiveTemplateInstantiations.size() - Limit);
451 }
452 continue;
453 }
454
Douglas Gregordf667e72009-03-10 20:44:00 +0000455 switch (Active->Kind) {
456 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000457 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
458 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
459 unsigned DiagID = diag::note_template_member_class_here;
460 if (isa<ClassTemplateSpecializationDecl>(Record))
461 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000462 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000463 << Context.getTypeDeclType(Record)
464 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000465 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000466 unsigned DiagID;
467 if (Function->getPrimaryTemplate())
468 DiagID = diag::note_function_template_spec_here;
469 else
470 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000471 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000472 << Function
473 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000474 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000475 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000476 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000477 << VD
478 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000479 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
480 Diags.Report(Active->PointOfInstantiation,
481 diag::note_template_enum_def_here)
482 << ED
483 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000484 } else {
485 Diags.Report(Active->PointOfInstantiation,
486 diag::note_template_type_alias_instantiation_here)
487 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000488 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000489 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000490 break;
491 }
492
493 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
494 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
495 std::string TemplateArgsStr
Douglas Gregor7532dc62009-03-30 22:58:21 +0000496 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000497 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000498 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000499 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000500 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000501 diag::note_default_arg_instantiation_here)
502 << (Template->getNameAsString() + TemplateArgsStr)
503 << Active->InstantiationRange;
504 break;
505 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000506
Douglas Gregorcca9e962009-07-01 22:01:06 +0000507 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Mike Stump1eb44332009-09-09 15:08:12 +0000508 FunctionTemplateDecl *FnTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +0000509 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000510 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000511 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000512 << FnTmpl
513 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
514 Active->TemplateArgs,
515 Active->NumTemplateArgs)
516 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000517 break;
518 }
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Douglas Gregorcca9e962009-07-01 22:01:06 +0000520 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
521 if (ClassTemplatePartialSpecializationDecl *PartialSpec
522 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
523 (Decl *)Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000524 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000525 diag::note_partial_spec_deduct_instantiation_here)
526 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000527 << getTemplateArgumentBindingsText(
528 PartialSpec->getTemplateParameters(),
529 Active->TemplateArgs,
530 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000531 << Active->InstantiationRange;
532 } else {
533 FunctionTemplateDecl *FnTmpl
534 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000535 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000536 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000537 << FnTmpl
538 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
539 Active->TemplateArgs,
540 Active->NumTemplateArgs)
541 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000542 }
543 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000544
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000545 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
546 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
547 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000549 std::string TemplateArgsStr
550 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000551 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000552 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000553 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000554 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000555 diag::note_default_function_arg_instantiation_here)
Anders Carlsson6bc107b2009-09-05 05:38:54 +0000556 << (FD->getNameAsString() + TemplateArgsStr)
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000557 << Active->InstantiationRange;
558 break;
559 }
Mike Stump1eb44332009-09-09 15:08:12 +0000560
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000561 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
562 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
563 std::string Name;
564 if (!Parm->getName().empty())
565 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000566
567 TemplateParameterList *TemplateParams = 0;
568 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
569 TemplateParams = Template->getTemplateParameters();
570 else
571 TemplateParams =
572 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
573 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000574 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000575 diag::note_prior_template_arg_substitution)
576 << isa<TemplateTemplateParmDecl>(Parm)
577 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000578 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000579 Active->TemplateArgs,
580 Active->NumTemplateArgs)
581 << Active->InstantiationRange;
582 break;
583 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000584
585 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000586 TemplateParameterList *TemplateParams = 0;
587 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
588 TemplateParams = Template->getTemplateParameters();
589 else
590 TemplateParams =
591 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
592 ->getTemplateParameters();
593
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000594 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000595 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000596 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000597 Active->TemplateArgs,
598 Active->NumTemplateArgs)
599 << Active->InstantiationRange;
600 break;
601 }
Richard Smithe6975e92012-04-17 00:58:00 +0000602
603 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
604 Diags.Report(Active->PointOfInstantiation,
605 diag::note_template_exception_spec_instantiation_here)
606 << cast<FunctionDecl>((Decl *)Active->Entity)
607 << Active->InstantiationRange;
608 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000609 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000610 }
611}
612
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000613llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000614 if (InNonInstantiationSFINAEContext)
615 return llvm::Optional<TemplateDeductionInfo *>(0);
616
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000617 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
618 Active = ActiveTemplateInstantiations.rbegin(),
619 ActiveEnd = ActiveTemplateInstantiations.rend();
620 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000621 ++Active)
622 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000623 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000624 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000625 // An instantiation of an alias template may or may not be a SFINAE
626 // context, depending on what else is on the stack.
627 if (isa<TypeAliasTemplateDecl>(reinterpret_cast<Decl *>(Active->Entity)))
628 break;
629 // Fall through.
630 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000631 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000632 // This is a template instantiation, so there is no SFINAE.
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000633 return llvm::Optional<TemplateDeductionInfo *>();
Mike Stump1eb44332009-09-09 15:08:12 +0000634
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000635 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000636 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000637 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000638 // A default template argument instantiation and substitution into
639 // template parameters with arguments for prior parameters may or may
640 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000641 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Douglas Gregorcca9e962009-07-01 22:01:06 +0000643 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
644 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
645 // We're either substitution explicitly-specified template arguments
646 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000647 assert(Active->DeductionInfo && "Missing deduction info pointer");
648 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000649 }
650 }
651
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000652 return llvm::Optional<TemplateDeductionInfo *>();
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000653}
654
Douglas Gregord3731192011-01-10 07:32:04 +0000655/// \brief Retrieve the depth and index of a parameter pack.
656static std::pair<unsigned, unsigned>
657getDepthAndIndex(NamedDecl *ND) {
658 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
659 return std::make_pair(TTP->getDepth(), TTP->getIndex());
660
661 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
662 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
663
664 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
665 return std::make_pair(TTP->getDepth(), TTP->getIndex());
666}
667
Douglas Gregor99ebf652009-02-27 19:31:52 +0000668//===----------------------------------------------------------------------===/
669// Template Instantiation for Types
670//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000671namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000672 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000673 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000674 SourceLocation Loc;
675 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000676
Douglas Gregorcd281c32009-02-28 00:25:32 +0000677 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000678 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000679
680 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000681 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000682 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000683 DeclarationName Entity)
684 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000685 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000686
Mike Stump1eb44332009-09-09 15:08:12 +0000687 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000688 /// transformed.
689 ///
690 /// For the purposes of template instantiation, a type has already been
691 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000692 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000693
Douglas Gregor577f75a2009-08-04 16:50:30 +0000694 /// \brief Returns the location of the entity being instantiated, if known.
695 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000696
Douglas Gregor577f75a2009-08-04 16:50:30 +0000697 /// \brief Returns the name of the entity being instantiated, if any.
698 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000699
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000700 /// \brief Sets the "base" location and entity when that
701 /// information is known based on another transformation.
702 void setBase(SourceLocation Loc, DeclarationName Entity) {
703 this->Loc = Loc;
704 this->Entity = Entity;
705 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000706
707 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
708 SourceRange PatternRange,
David Blaikiea71f9d02011-09-22 02:34:54 +0000709 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000710 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000711 bool &RetainExpansion,
Douglas Gregorcded4f62011-01-14 17:04:44 +0000712 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000713 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
714 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000715 TemplateArgs,
716 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000717 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000718 NumExpansions);
719 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000720
Douglas Gregor12c9c002011-01-07 16:43:16 +0000721 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
722 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
723 }
724
Douglas Gregord3731192011-01-10 07:32:04 +0000725 TemplateArgument ForgetPartiallySubstitutedPack() {
726 TemplateArgument Result;
727 if (NamedDecl *PartialPack
728 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
729 MultiLevelTemplateArgumentList &TemplateArgs
730 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
731 unsigned Depth, Index;
732 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
733 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
734 Result = TemplateArgs(Depth, Index);
735 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
736 }
737 }
738
739 return Result;
740 }
741
742 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
743 if (Arg.isNull())
744 return;
745
746 if (NamedDecl *PartialPack
747 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
748 MultiLevelTemplateArgumentList &TemplateArgs
749 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
750 unsigned Depth, Index;
751 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
752 TemplateArgs.setArgument(Depth, Index, Arg);
753 }
754 }
755
Douglas Gregor577f75a2009-08-04 16:50:30 +0000756 /// \brief Transform the given declaration by instantiating a reference to
757 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000758 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000759
Douglas Gregordfca6f52012-02-13 22:00:16 +0000760 void transformAttrs(Decl *Old, Decl *New) {
761 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
762 }
763
764 void transformedLocalDecl(Decl *Old, Decl *New) {
765 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
766 }
767
Mike Stump1eb44332009-09-09 15:08:12 +0000768 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000769 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000770 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000772 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000773 /// declaration.
774 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
775
Douglas Gregor43959a92009-08-20 07:17:43 +0000776 /// \brief Rebuild the exception declaration and register the declaration
777 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000778 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000779 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000780 SourceLocation StartLoc,
781 SourceLocation NameLoc,
782 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Douglas Gregorbe270a02010-04-26 17:57:08 +0000784 /// \brief Rebuild the Objective-C exception declaration and register the
785 /// declaration as an instantiated local.
786 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
787 TypeSourceInfo *TSInfo, QualType T);
788
John McCallc4e70192009-09-11 04:59:25 +0000789 /// \brief Check for tag mismatches when instantiating an
790 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000791 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
792 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000793 NestedNameSpecifierLoc QualifierLoc,
794 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000795
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000796 TemplateName TransformTemplateName(CXXScopeSpec &SS,
797 TemplateName Name,
798 SourceLocation NameLoc,
799 QualType ObjectType = QualType(),
800 NamedDecl *FirstQualifierInScope = 0);
801
John McCall60d7b3a2010-08-24 06:29:42 +0000802 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
803 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
804 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000805
John McCall60d7b3a2010-08-24 06:29:42 +0000806 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000807 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000808 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
809 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000810
811 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
812 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
813
814 /// \brief Transform a reference to a function parameter pack.
815 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
816 ParmVarDecl *PD);
817
818 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
819 /// expand a function parameter pack reference which refers to an expanded
820 /// pack.
821 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
822
Douglas Gregor895162d2010-04-30 18:55:50 +0000823 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000824 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000825 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
826 FunctionProtoTypeLoc TL,
827 CXXRecordDecl *ThisContext,
828 unsigned ThisTypeQuals);
829
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000830 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000831 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000832 llvm::Optional<unsigned> NumExpansions,
833 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000834
Mike Stump1eb44332009-09-09 15:08:12 +0000835 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000836 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000837 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000838 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000839
Douglas Gregorc3069d62011-01-14 02:55:32 +0000840 /// \brief Transforms an already-substituted template type parameter pack
841 /// into either itself (if we aren't substituting into its pack expansion)
842 /// or the appropriate substituted argument.
843 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
844 SubstTemplateTypeParmPackTypeLoc TL);
845
John McCall60d7b3a2010-08-24 06:29:42 +0000846 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000847 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000848 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000849 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
850 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000851 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000852 }
John McCall91a57552011-07-15 05:09:51 +0000853
Richard Smith612409e2012-07-25 03:56:55 +0000854 ExprResult TransformLambdaExpr(LambdaExpr *E) {
855 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
856 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
857 }
858
859 ExprResult TransformLambdaScope(LambdaExpr *E,
860 CXXMethodDecl *CallOperator) {
861 CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
862 TSK_ImplicitInstantiation);
863 return TreeTransform<TemplateInstantiator>::
864 TransformLambdaScope(E, CallOperator);
865 }
866
John McCall91a57552011-07-15 05:09:51 +0000867 private:
868 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
869 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000870 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000871 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000872}
873
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000874bool TemplateInstantiator::AlreadyTransformed(QualType T) {
875 if (T.isNull())
876 return true;
877
Douglas Gregor561f8122011-07-01 01:22:09 +0000878 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000879 return false;
880
881 getSema().MarkDeclarationsReferencedInType(Loc, T);
882 return true;
883}
884
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000885Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000886 if (!D)
887 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Douglas Gregorc68afe22009-09-03 21:38:09 +0000889 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000890 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000891 // If the corresponding template argument is NULL or non-existent, it's
892 // because we are performing instantiation from explicitly-specified
893 // template arguments in a function template, but there were some
894 // arguments left unspecified.
895 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
896 TTP->getPosition()))
897 return D;
898
Douglas Gregor61c4d282011-01-05 15:48:55 +0000899 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
900
901 if (TTP->isParameterPack()) {
902 assert(Arg.getKind() == TemplateArgument::Pack &&
903 "Missing argument pack");
904
Douglas Gregor1aee05d2011-01-15 06:45:20 +0000905 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregord3731192011-01-10 07:32:04 +0000906 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000907 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
908 }
909
910 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000911 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000912 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000913 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000914 }
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregor788cd062009-11-11 01:00:40 +0000916 // Fall through to find the instantiated declaration for this template
917 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000918 }
Mike Stump1eb44332009-09-09 15:08:12 +0000919
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000920 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000921}
922
Douglas Gregoraac571c2010-03-01 17:25:41 +0000923Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000924 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000925 if (!Inst)
926 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregor43959a92009-08-20 07:17:43 +0000928 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
929 return Inst;
930}
931
Douglas Gregor6cd21982009-10-20 05:58:46 +0000932NamedDecl *
933TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
934 SourceLocation Loc) {
935 // If the first part of the nested-name-specifier was a template type
936 // parameter, instantiate that type parameter down to a tag type.
937 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
938 const TemplateTypeParmType *TTP
939 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000940
Douglas Gregor6cd21982009-10-20 05:58:46 +0000941 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000942 // FIXME: This needs testing w/ member access expressions.
943 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
944
945 if (TTP->isParameterPack()) {
946 assert(Arg.getKind() == TemplateArgument::Pack &&
947 "Missing argument pack");
948
Douglas Gregor2be29f42011-01-14 23:41:42 +0000949 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000950 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000951
Douglas Gregord3731192011-01-10 07:32:04 +0000952 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor984a58b2010-12-20 22:48:17 +0000953 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
954 }
955
956 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000957 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000958 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000959
960 if (const TagType *Tag = T->getAs<TagType>())
961 return Tag->getDecl();
962
963 // The resulting type is not a tag; complain.
964 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
965 return 0;
966 }
967 }
968
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000969 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000970}
971
Douglas Gregor43959a92009-08-20 07:17:43 +0000972VarDecl *
973TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000974 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000975 SourceLocation StartLoc,
976 SourceLocation NameLoc,
977 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000978 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000979 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000980 if (Var)
981 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
982 return Var;
983}
984
985VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
986 TypeSourceInfo *TSInfo,
987 QualType T) {
988 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
989 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000990 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
991 return Var;
992}
993
John McCallc4e70192009-09-11 04:59:25 +0000994QualType
John McCall21e413f2010-11-04 19:04:38 +0000995TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
996 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000997 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000998 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +0000999 if (const TagType *TT = T->getAs<TagType>()) {
1000 TagDecl* TD = TT->getDecl();
1001
John McCall21e413f2010-11-04 19:04:38 +00001002 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001003
John McCallc4e70192009-09-11 04:59:25 +00001004 IdentifierInfo *Id = TD->getIdentifier();
1005
1006 // TODO: should we even warn on struct/class mismatches for this? Seems
1007 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001008 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001009 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001010 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1011 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001012 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1013 << Id
1014 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1015 TD->getKindName());
1016 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1017 }
John McCallc4e70192009-09-11 04:59:25 +00001018 }
1019 }
1020
John McCall21e413f2010-11-04 19:04:38 +00001021 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1022 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001023 QualifierLoc,
1024 T);
John McCallc4e70192009-09-11 04:59:25 +00001025}
1026
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001027TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1028 TemplateName Name,
1029 SourceLocation NameLoc,
1030 QualType ObjectType,
1031 NamedDecl *FirstQualifierInScope) {
1032 if (TemplateTemplateParmDecl *TTP
1033 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1034 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1035 // If the corresponding template argument is NULL or non-existent, it's
1036 // because we are performing instantiation from explicitly-specified
1037 // template arguments in a function template, but there were some
1038 // arguments left unspecified.
1039 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1040 TTP->getPosition()))
1041 return Name;
1042
1043 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1044
1045 if (TTP->isParameterPack()) {
1046 assert(Arg.getKind() == TemplateArgument::Pack &&
1047 "Missing argument pack");
1048
1049 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1050 // We have the template argument pack to substitute, but we're not
1051 // actually expanding the enclosing pack expansion yet. So, just
1052 // keep the entire argument pack.
1053 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1054 }
1055
1056 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1057 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1058 }
1059
1060 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001061 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001062
Douglas Gregor58750382011-03-05 20:06:51 +00001063 // We don't ever want to substitute for a qualified template name, since
1064 // the qualifier is handled separately. So, look through the qualified
1065 // template name to its underlying declaration.
1066 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1067 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001068
1069 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001070 return Template;
1071 }
1072 }
1073
1074 if (SubstTemplateTemplateParmPackStorage *SubstPack
1075 = Name.getAsSubstTemplateTemplateParmPack()) {
1076 if (getSema().ArgumentPackSubstitutionIndex == -1)
1077 return Name;
1078
1079 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1080 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1081 "Pack substitution index out-of-range");
1082 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1083 .getAsTemplate();
1084 }
1085
1086 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1087 FirstQualifierInScope);
1088}
1089
John McCall60d7b3a2010-08-24 06:29:42 +00001090ExprResult
John McCall454feb92009-12-08 09:21:05 +00001091TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001092 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001093 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001094
1095 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1096 assert(currentDecl && "Must have current function declaration when "
1097 "instantiating.");
1098
1099 PredefinedExpr::IdentType IT = E->getIdentType();
1100
Anders Carlsson848fa642010-02-11 18:20:28 +00001101 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001102
1103 llvm::APInt LengthI(32, Length + 1);
Nico Weberb4e80082012-06-25 22:34:48 +00001104 QualType ResTy;
1105 if (IT == PredefinedExpr::LFunction)
1106 ResTy = getSema().Context.WCharTy.withConst();
1107 else
1108 ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001109 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1110 ArrayType::Normal, 0);
1111 PredefinedExpr *PE =
1112 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1113 return getSema().Owned(PE);
1114}
1115
John McCall60d7b3a2010-08-24 06:29:42 +00001116ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001117TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001118 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001119 // If the corresponding template argument is NULL or non-existent, it's
1120 // because we are performing instantiation from explicitly-specified
1121 // template arguments in a function template, but there were some
1122 // arguments left unspecified.
1123 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1124 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001125 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Douglas Gregor56bc9832010-12-24 00:15:10 +00001127 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1128 if (NTTP->isParameterPack()) {
1129 assert(Arg.getKind() == TemplateArgument::Pack &&
1130 "Missing argument pack");
1131
1132 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001133 // We have an argument pack, but we can't select a particular argument
1134 // out of it yet. Therefore, we'll build an expression to hold on to that
1135 // argument pack.
1136 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1137 E->getLocation(),
1138 NTTP->getDeclName());
1139 if (TargetType.isNull())
1140 return ExprError();
1141
1142 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1143 NTTP,
1144 E->getLocation(),
1145 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001146 }
1147
Douglas Gregord3731192011-01-10 07:32:04 +00001148 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor56bc9832010-12-24 00:15:10 +00001149 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1150 }
Mike Stump1eb44332009-09-09 15:08:12 +00001151
John McCall91a57552011-07-15 05:09:51 +00001152 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1153}
1154
1155ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1156 NonTypeTemplateParmDecl *parm,
1157 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001158 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001159 ExprResult result;
1160 QualType type;
1161
Richard Smith60983812012-07-09 03:07:20 +00001162 // If the argument is a pack expansion, the parameter must actually be a
1163 // parameter pack, and we should substitute the pattern itself, producing
1164 // an expression which contains an unexpanded parameter pack.
1165 if (arg.isPackExpansion()) {
1166 assert(parm->isParameterPack() && "pack expansion for non-pack");
1167 arg = arg.getPackExpansionPattern();
1168 }
1169
John McCallb8fc0532010-02-06 08:42:39 +00001170 // The template argument itself might be an expression, in which
1171 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001172 if (arg.getKind() == TemplateArgument::Expression) {
1173 Expr *argExpr = arg.getAsExpr();
1174 result = SemaRef.Owned(argExpr);
1175 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Eli Friedmand7a6b162012-09-26 02:36:12 +00001177 } else if (arg.getKind() == TemplateArgument::Declaration ||
1178 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001179 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001180 if (arg.getKind() == TemplateArgument::Declaration) {
1181 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Douglas Gregord2008e22012-04-06 22:40:38 +00001183 // Find the instantiation of the template argument. This is
1184 // required for nested templates.
1185 VD = cast_or_null<ValueDecl>(
1186 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1187 if (!VD)
1188 return ExprError();
1189 } else {
1190 // Propagate NULL template argument.
1191 VD = 0;
1192 }
1193
John McCall645cf442010-02-06 10:23:53 +00001194 // Derive the type we want the substituted decl to have. This had
1195 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001196 if (parm->isExpandedParameterPack()) {
1197 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1198 } else if (parm->isParameterPack() &&
1199 isa<PackExpansionType>(parm->getType())) {
1200 type = SemaRef.SubstType(
1201 cast<PackExpansionType>(parm->getType())->getPattern(),
1202 TemplateArgs, loc, parm->getDeclName());
1203 } else {
1204 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1205 loc, parm->getDeclName());
1206 }
1207 assert(!type.isNull() && "type substitution failed for param type");
1208 assert(!type->isDependentType() && "param type still dependent");
1209 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001210
John McCall91a57552011-07-15 05:09:51 +00001211 if (!result.isInvalid()) type = result.get()->getType();
1212 } else {
1213 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1214
1215 // Note that this type can be different from the type of 'result',
1216 // e.g. if it's an enum type.
1217 type = arg.getIntegralType();
1218 }
1219 if (result.isInvalid()) return ExprError();
1220
1221 Expr *resultExpr = result.take();
1222 return SemaRef.Owned(new (SemaRef.Context)
1223 SubstNonTypeTemplateParmExpr(type,
1224 resultExpr->getValueKind(),
1225 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001226}
1227
Douglas Gregorc7793c72011-01-15 01:15:58 +00001228ExprResult
1229TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1230 SubstNonTypeTemplateParmPackExpr *E) {
1231 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1232 // We aren't expanding the parameter pack, so just return ourselves.
1233 return getSema().Owned(E);
1234 }
1235
Douglas Gregorc7793c72011-01-15 01:15:58 +00001236 const TemplateArgument &ArgPack = E->getArgumentPack();
1237 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1238 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1239
1240 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
John McCall91a57552011-07-15 05:09:51 +00001241 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1242 E->getParameterPackLocation(),
1243 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001244}
John McCallb8fc0532010-02-06 08:42:39 +00001245
John McCall60d7b3a2010-08-24 06:29:42 +00001246ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001247TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1248 SourceLocation Loc) {
1249 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1250 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1251}
1252
1253ExprResult
1254TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1255 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1256 // We can expand this parameter pack now.
1257 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1258 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1259 if (!VD)
1260 return ExprError();
1261 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1262 }
1263
1264 QualType T = TransformType(E->getType());
1265 if (T.isNull())
1266 return ExprError();
1267
1268 // Transform each of the parameter expansions into the corresponding
1269 // parameters in the instantiation of the function decl.
1270 llvm::SmallVector<Decl*, 8> Parms;
1271 Parms.reserve(E->getNumExpansions());
1272 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1273 I != End; ++I) {
1274 ParmVarDecl *D =
1275 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1276 if (!D)
1277 return ExprError();
1278 Parms.push_back(D);
1279 }
1280
1281 return FunctionParmPackExpr::Create(getSema().Context, T,
1282 E->getParameterPack(),
1283 E->getParameterPackLocation(), Parms);
1284}
1285
1286ExprResult
1287TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1288 ParmVarDecl *PD) {
1289 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1290 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1291 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1292 assert(Found && "no instantiation for parameter pack");
1293
1294 Decl *TransformedDecl;
1295 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1296 // If this is a reference to a function parameter pack which we can substitute
1297 // but can't yet expand, build a FunctionParmPackExpr for it.
1298 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1299 QualType T = TransformType(E->getType());
1300 if (T.isNull())
1301 return ExprError();
1302 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1303 E->getExprLoc(), *Pack);
1304 }
1305
1306 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1307 } else {
1308 TransformedDecl = Found->get<Decl*>();
1309 }
1310
1311 // We have either an unexpanded pack or a specific expansion.
1312 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1313 E->getExprLoc());
1314}
1315
1316ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001317TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1318 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001319
1320 // Handle references to non-type template parameters and non-type template
1321 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001322 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1323 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1324 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001325
1326 // We have a non-type template parameter that isn't fully substituted;
1327 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001328 }
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Richard Smith9a4db032012-09-12 00:56:43 +00001330 // Handle references to function parameter packs.
1331 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1332 if (PD->isParameterPack())
1333 return TransformFunctionParmPackRefExpr(E, PD);
1334
John McCall454feb92009-12-08 09:21:05 +00001335 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001336}
1337
John McCall60d7b3a2010-08-24 06:29:42 +00001338ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001339 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001340 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1341 getDescribedFunctionTemplate() &&
1342 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001343 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1344 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1345 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001346}
1347
Douglas Gregor895162d2010-04-30 18:55:50 +00001348QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001349 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001350 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001351 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001352 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001353}
1354
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001355QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1356 FunctionProtoTypeLoc TL,
1357 CXXRecordDecl *ThisContext,
1358 unsigned ThisTypeQuals) {
1359 // We need a local instantiation scope for this function prototype.
1360 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1361 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1362 ThisTypeQuals);
1363}
1364
John McCall21ef0fa2010-03-11 09:03:00 +00001365ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001366TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001367 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001368 llvm::Optional<unsigned> NumExpansions,
1369 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001370 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001371 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001372}
1373
Mike Stump1eb44332009-09-09 15:08:12 +00001374QualType
John McCalla2becad2009-10-21 00:40:46 +00001375TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001376 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001377 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001378 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001379 // Replace the template type parameter with its corresponding
1380 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001381
1382 // If the corresponding template argument is NULL or doesn't exist, it's
1383 // because we are performing instantiation from explicitly-specified
1384 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001385 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001386 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1387 TemplateTypeParmTypeLoc NewTL
1388 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1389 NewTL.setNameLoc(TL.getNameLoc());
1390 return TL.getType();
1391 }
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001393 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1394
1395 if (T->isParameterPack()) {
1396 assert(Arg.getKind() == TemplateArgument::Pack &&
1397 "Missing argument pack");
1398
1399 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001400 // We have the template argument pack, but we're not expanding the
1401 // enclosing pack expansion yet. Just save the template argument
1402 // pack for later substitution.
1403 QualType Result
1404 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1405 SubstTemplateTypeParmPackTypeLoc NewTL
1406 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1407 NewTL.setNameLoc(TL.getNameLoc());
1408 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001409 }
1410
Douglas Gregord3731192011-01-10 07:32:04 +00001411 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001412 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1413 }
1414
1415 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001416 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001417
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001418 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001419
1420 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001421 QualType Result
1422 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1423 SubstTemplateTypeParmTypeLoc NewTL
1424 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1425 NewTL.setNameLoc(TL.getNameLoc());
1426 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001427 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001428
1429 // The template type parameter comes from an inner template (e.g.,
1430 // the template parameter list of a member template inside the
1431 // template we are instantiating). Create a new template type
1432 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001433 TemplateTypeParmDecl *NewTTPDecl = 0;
1434 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1435 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1436 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1437
John McCalla2becad2009-10-21 00:40:46 +00001438 QualType Result
1439 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1440 - TemplateArgs.getNumLevels(),
1441 T->getIndex(),
1442 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001443 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001444 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1445 NewTL.setNameLoc(TL.getNameLoc());
1446 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001447}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001448
Douglas Gregorc3069d62011-01-14 02:55:32 +00001449QualType
1450TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1451 TypeLocBuilder &TLB,
1452 SubstTemplateTypeParmPackTypeLoc TL) {
1453 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1454 // We aren't expanding the parameter pack, so just return ourselves.
1455 SubstTemplateTypeParmPackTypeLoc NewTL
1456 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1457 NewTL.setNameLoc(TL.getNameLoc());
1458 return TL.getType();
1459 }
1460
1461 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1462 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1463 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1464
1465 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1466 Result = getSema().Context.getSubstTemplateTypeParmType(
1467 TL.getTypePtr()->getReplacedParameter(),
1468 Result);
1469 SubstTemplateTypeParmTypeLoc NewTL
1470 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1471 NewTL.setNameLoc(TL.getNameLoc());
1472 return Result;
1473}
1474
John McCallce3ff2b2009-08-25 22:02:44 +00001475/// \brief Perform substitution on the type T with a given set of template
1476/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001477///
1478/// This routine substitutes the given template arguments into the
1479/// type T and produces the instantiated type.
1480///
1481/// \param T the type into which the template arguments will be
1482/// substituted. If this type is not dependent, it will be returned
1483/// immediately.
1484///
James Dennett1dfbd922012-06-14 21:40:34 +00001485/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001486/// substituted for the top-level template parameters within T.
1487///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001488/// \param Loc the location in the source code where this substitution
1489/// is being performed. It will typically be the location of the
1490/// declarator (if we're instantiating the type of some declaration)
1491/// or the location of the type in the source code (if, e.g., we're
1492/// instantiating the type of a cast expression).
1493///
1494/// \param Entity the name of the entity associated with a declaration
1495/// being instantiated (if any). May be empty to indicate that there
1496/// is no such entity (if, e.g., this is a type that occurs as part of
1497/// a cast expression) or that the entity has no name (e.g., an
1498/// unnamed function parameter).
1499///
1500/// \returns If the instantiation succeeds, the instantiated
1501/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001502TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001503 const MultiLevelTemplateArgumentList &Args,
1504 SourceLocation Loc,
1505 DeclarationName Entity) {
1506 assert(!ActiveTemplateInstantiations.empty() &&
1507 "Cannot perform an instantiation without some context on the "
1508 "instantiation stack");
1509
Douglas Gregor561f8122011-07-01 01:22:09 +00001510 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001511 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001512 return T;
1513
1514 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1515 return Instantiator.TransformType(T);
1516}
1517
Douglas Gregor603cfb42011-01-05 23:12:31 +00001518TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1519 const MultiLevelTemplateArgumentList &Args,
1520 SourceLocation Loc,
1521 DeclarationName Entity) {
1522 assert(!ActiveTemplateInstantiations.empty() &&
1523 "Cannot perform an instantiation without some context on the "
1524 "instantiation stack");
1525
1526 if (TL.getType().isNull())
1527 return 0;
1528
Douglas Gregor561f8122011-07-01 01:22:09 +00001529 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001530 !TL.getType()->isVariablyModifiedType()) {
1531 // FIXME: Make a copy of the TypeLoc data here, so that we can
1532 // return a new TypeSourceInfo. Inefficient!
1533 TypeLocBuilder TLB;
1534 TLB.pushFullCopy(TL);
1535 return TLB.getTypeSourceInfo(Context, TL.getType());
1536 }
1537
1538 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1539 TypeLocBuilder TLB;
1540 TLB.reserve(TL.getFullDataSize());
1541 QualType Result = Instantiator.TransformType(TLB, TL);
1542 if (Result.isNull())
1543 return 0;
1544
1545 return TLB.getTypeSourceInfo(Context, Result);
1546}
1547
John McCallcd7ba1c2009-10-21 00:58:09 +00001548/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001549QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001550 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001551 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001552 assert(!ActiveTemplateInstantiations.empty() &&
1553 "Cannot perform an instantiation without some context on the "
1554 "instantiation stack");
1555
Douglas Gregor836adf62010-05-24 17:22:01 +00001556 // If T is not a dependent type or a variably-modified type, there
1557 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001558 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001559 return T;
1560
Douglas Gregor577f75a2009-08-04 16:50:30 +00001561 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1562 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001563}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001564
John McCall6cd3b9f2010-04-09 17:38:44 +00001565static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001566 if (T->getType()->isInstantiationDependentType() ||
1567 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001568 return true;
1569
Abramo Bagnara723df242010-12-14 22:11:44 +00001570 TypeLoc TL = T->getTypeLoc().IgnoreParens();
John McCall6cd3b9f2010-04-09 17:38:44 +00001571 if (!isa<FunctionProtoTypeLoc>(TL))
1572 return false;
1573
1574 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1575 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1576 ParmVarDecl *P = FP.getArg(I);
1577
Douglas Gregorc056c172011-05-09 20:45:16 +00001578 // The parameter's type as written might be dependent even if the
1579 // decayed type was not dependent.
1580 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001581 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001582 return true;
1583
John McCall6cd3b9f2010-04-09 17:38:44 +00001584 // TODO: currently we always rebuild expressions. When we
1585 // properly get lazier about this, we should use the same
1586 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001587 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001588 return true;
1589 }
1590
1591 return false;
1592}
1593
1594/// A form of SubstType intended specifically for instantiating the
1595/// type of a FunctionDecl. Its purpose is solely to force the
1596/// instantiation of default-argument expressions.
1597TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1598 const MultiLevelTemplateArgumentList &Args,
1599 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001600 DeclarationName Entity,
1601 CXXRecordDecl *ThisContext,
1602 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001603 assert(!ActiveTemplateInstantiations.empty() &&
1604 "Cannot perform an instantiation without some context on the "
1605 "instantiation stack");
1606
1607 if (!NeedsInstantiationAsFunctionType(T))
1608 return T;
1609
1610 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1611
1612 TypeLocBuilder TLB;
1613
1614 TypeLoc TL = T->getTypeLoc();
1615 TLB.reserve(TL.getFullDataSize());
1616
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001617 QualType Result;
1618
1619 if (FunctionProtoTypeLoc *Proto = dyn_cast<FunctionProtoTypeLoc>(&TL)) {
1620 Result = Instantiator.TransformFunctionProtoType(TLB, *Proto, ThisContext,
1621 ThisTypeQuals);
1622 } else {
1623 Result = Instantiator.TransformType(TLB, TL);
1624 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001625 if (Result.isNull())
1626 return 0;
1627
1628 return TLB.getTypeSourceInfo(Context, Result);
1629}
1630
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001631ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001632 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001633 int indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001634 llvm::Optional<unsigned> NumExpansions,
1635 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001636 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001637 TypeSourceInfo *NewDI = 0;
1638
Douglas Gregor603cfb42011-01-05 23:12:31 +00001639 TypeLoc OldTL = OldDI->getTypeLoc();
1640 if (isa<PackExpansionTypeLoc>(OldTL)) {
1641 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
Douglas Gregor603cfb42011-01-05 23:12:31 +00001642
1643 // We have a function parameter pack. Substitute into the pattern of the
1644 // expansion.
1645 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1646 OldParm->getLocation(), OldParm->getDeclName());
1647 if (!NewDI)
1648 return 0;
1649
1650 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1651 // We still have unexpanded parameter packs, which means that
1652 // our function parameter is still a function parameter pack.
1653 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001654 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001655 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001656 } else if (ExpectParameterPack) {
1657 // We expected to get a parameter pack but didn't (because the type
1658 // itself is not a pack expansion type), so complain. This can occur when
1659 // the substitution goes through an alias template that "loses" the
1660 // pack expansion.
1661 Diag(OldParm->getLocation(),
1662 diag::err_function_parameter_pack_without_parameter_packs)
1663 << NewDI->getType();
1664 return 0;
1665 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001666 } else {
1667 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1668 OldParm->getDeclName());
1669 }
1670
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001671 if (!NewDI)
1672 return 0;
1673
1674 if (NewDI->getType()->isVoidType()) {
1675 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1676 return 0;
1677 }
1678
1679 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001680 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001681 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001682 OldParm->getIdentifier(),
1683 NewDI->getType(), NewDI,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001684 OldParm->getStorageClass(),
1685 OldParm->getStorageClassAsWritten());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001686 if (!NewParm)
1687 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001688
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001689 // Mark the (new) default argument as uninstantiated (if any).
1690 if (OldParm->hasUninstantiatedDefaultArg()) {
1691 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1692 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001693 } else if (OldParm->hasUnparsedDefaultArg()) {
1694 NewParm->setUnparsedDefaultArg();
1695 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001696 } else if (Expr *Arg = OldParm->getDefaultArg())
1697 // FIXME: if we non-lazily instantiated non-dependent default args for
1698 // non-dependent parameter types we could remove a bunch of duplicate
1699 // conversion warnings for such arguments.
1700 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001701
1702 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001703
Douglas Gregor12c9c002011-01-07 16:43:16 +00001704 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001705 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001706 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1707 } else {
1708 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001709 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001710 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001711
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001712 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1713 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001714 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001715
1716 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1717 OldParm->getFunctionScopeIndex() + indexAdjustment);
Fariborz Jahaniane7ffbe22010-07-13 20:05:58 +00001718
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001719 return NewParm;
1720}
1721
Douglas Gregora009b592011-01-07 00:20:55 +00001722/// \brief Substitute the given template arguments into the given set of
1723/// parameters, producing the set of parameter types that would be generated
1724/// from such a substitution.
1725bool Sema::SubstParmTypes(SourceLocation Loc,
1726 ParmVarDecl **Params, unsigned NumParams,
1727 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001728 SmallVectorImpl<QualType> &ParamTypes,
1729 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001730 assert(!ActiveTemplateInstantiations.empty() &&
1731 "Cannot perform an instantiation without some context on the "
1732 "instantiation stack");
1733
1734 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1735 DeclarationName());
1736 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001737 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001738}
1739
John McCallce3ff2b2009-08-25 22:02:44 +00001740/// \brief Perform substitution on the base class specifiers of the
1741/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001742///
1743/// Produces a diagnostic and returns true on error, returns false and
1744/// attaches the instantiated base classes to the class template
1745/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001746bool
John McCallce3ff2b2009-08-25 22:02:44 +00001747Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1748 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001749 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001750 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001751 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001752 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001753 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001754 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001755 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001756 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001757 continue;
1758 }
1759
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001760 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001761 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001762 if (Base->isPackExpansion()) {
1763 // This is a pack expansion. See whether we should expand it now, or
1764 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001765 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001766 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1767 Unexpanded);
1768 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001769 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00001770 llvm::Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001771 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1772 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001773 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001774 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001775 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001776 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001777 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001778 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001779 }
1780
1781 // If we should expand this pack expansion now, do so.
1782 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001783 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001784 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1785
1786 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1787 TemplateArgs,
1788 Base->getSourceRange().getBegin(),
1789 DeclarationName());
1790 if (!BaseTypeLoc) {
1791 Invalid = true;
1792 continue;
1793 }
1794
1795 if (CXXBaseSpecifier *InstantiatedBase
1796 = CheckBaseSpecifier(Instantiation,
1797 Base->getSourceRange(),
1798 Base->isVirtual(),
1799 Base->getAccessSpecifierAsWritten(),
1800 BaseTypeLoc,
1801 SourceLocation()))
1802 InstantiatedBases.push_back(InstantiatedBase);
1803 else
1804 Invalid = true;
1805 }
1806
1807 continue;
1808 }
1809
1810 // The resulting base specifier will (still) be a pack expansion.
1811 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001812 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1813 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1814 TemplateArgs,
1815 Base->getSourceRange().getBegin(),
1816 DeclarationName());
1817 } else {
1818 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1819 TemplateArgs,
1820 Base->getSourceRange().getBegin(),
1821 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001822 }
1823
Nick Lewycky56062202010-07-26 16:56:01 +00001824 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001825 Invalid = true;
1826 continue;
1827 }
1828
1829 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001830 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001831 Base->getSourceRange(),
1832 Base->isVirtual(),
1833 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001834 BaseTypeLoc,
1835 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001836 InstantiatedBases.push_back(InstantiatedBase);
1837 else
1838 Invalid = true;
1839 }
1840
Douglas Gregor27b152f2009-03-10 18:52:44 +00001841 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001842 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001843 InstantiatedBases.size()))
1844 Invalid = true;
1845
1846 return Invalid;
1847}
1848
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001849// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001850namespace clang {
1851 namespace sema {
1852 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1853 const MultiLevelTemplateArgumentList &TemplateArgs);
1854 }
1855}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001856
Richard Smithf1c66b42012-03-14 23:13:10 +00001857/// Determine whether we would be unable to instantiate this template (because
1858/// it either has no definition, or is in the process of being instantiated).
1859static bool DiagnoseUninstantiableTemplate(Sema &S,
1860 SourceLocation PointOfInstantiation,
1861 TagDecl *Instantiation,
1862 bool InstantiatedFromMember,
1863 TagDecl *Pattern,
1864 TagDecl *PatternDef,
1865 TemplateSpecializationKind TSK,
1866 bool Complain = true) {
1867 if (PatternDef && !PatternDef->isBeingDefined())
1868 return false;
1869
1870 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1871 // Say nothing
1872 } else if (PatternDef) {
1873 assert(PatternDef->isBeingDefined());
1874 S.Diag(PointOfInstantiation,
1875 diag::err_template_instantiate_within_definition)
1876 << (TSK != TSK_ImplicitInstantiation)
1877 << S.Context.getTypeDeclType(Instantiation);
1878 // Not much point in noting the template declaration here, since
1879 // we're lexically inside it.
1880 Instantiation->setInvalidDecl();
1881 } else if (InstantiatedFromMember) {
1882 S.Diag(PointOfInstantiation,
1883 diag::err_implicit_instantiate_member_undefined)
1884 << S.Context.getTypeDeclType(Instantiation);
1885 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1886 } else {
1887 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1888 << (TSK != TSK_ImplicitInstantiation)
1889 << S.Context.getTypeDeclType(Instantiation);
1890 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1891 }
1892
1893 // In general, Instantiation isn't marked invalid to get more than one
1894 // error for multiple undefined instantiations. But the code that does
1895 // explicit declaration -> explicit definition conversion can't handle
1896 // invalid declarations, so mark as invalid in that case.
1897 if (TSK == TSK_ExplicitInstantiationDeclaration)
1898 Instantiation->setInvalidDecl();
1899 return true;
1900}
1901
Douglas Gregord475b8d2009-03-25 21:17:03 +00001902/// \brief Instantiate the definition of a class from a given pattern.
1903///
1904/// \param PointOfInstantiation The point of instantiation within the
1905/// source code.
1906///
1907/// \param Instantiation is the declaration whose definition is being
1908/// instantiated. This will be either a class template specialization
1909/// or a member class of a class template specialization.
1910///
1911/// \param Pattern is the pattern from which the instantiation
1912/// occurs. This will be either the declaration of a class template or
1913/// the declaration of a member class of a class template.
1914///
1915/// \param TemplateArgs The template arguments to be substituted into
1916/// the pattern.
1917///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001918/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001919///
1920/// \param Complain whether to complain if the class cannot be instantiated due
1921/// to the lack of a definition.
1922///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001923/// \returns true if an error occurred, false otherwise.
1924bool
1925Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1926 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001927 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001928 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001929 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001930 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001931 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001932 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1933 Instantiation->getInstantiatedFromMemberClass(),
1934 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001935 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001936 Pattern = PatternDef;
1937
Douglas Gregor454885e2009-10-15 15:54:05 +00001938 // \brief Record the point of instantiation.
1939 if (MemberSpecializationInfo *MSInfo
1940 = Instantiation->getMemberSpecializationInfo()) {
1941 MSInfo->setTemplateSpecializationKind(TSK);
1942 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001943 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001944 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001945 Spec->setTemplateSpecializationKind(TSK);
1946 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001947 }
1948
Douglas Gregord048bb72009-03-25 21:23:52 +00001949 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001950 if (Inst)
1951 return true;
1952
1953 // Enter the scope of this instantiation. We don't use
1954 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001955 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001956 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001957 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001958
Douglas Gregor05030bb2010-03-24 01:33:17 +00001959 // If this is an instantiation of a local class, merge this local
1960 // instantiation scope with the enclosing scope. Otherwise, every
1961 // instantiation of a class has its own local instantiation scope.
1962 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001963 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001964
John McCall1d8d1cc2010-08-01 02:01:53 +00001965 // Pull attributes from the pattern onto the instantiation.
1966 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1967
Douglas Gregord475b8d2009-03-25 21:17:03 +00001968 // Start the definition of this instantiation.
1969 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001970
1971 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001972
John McCallce3ff2b2009-08-25 22:02:44 +00001973 // Do substitution on the base class specifiers.
1974 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001975 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001976
Douglas Gregord65587f2010-11-10 19:44:59 +00001977 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001978 SmallVector<Decl*, 4> Fields;
1979 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001980 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001981 // Delay instantiation of late parsed attributes.
1982 LateInstantiatedAttrVec LateAttrs;
1983 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1984
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001985 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001986 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001987 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001988 // Don't instantiate members not belonging in this semantic context.
1989 // e.g. for:
1990 // @code
1991 // template <int i> class A {
1992 // class B *g;
1993 // };
1994 // @endcode
1995 // 'class B' has the template as lexical context but semantically it is
1996 // introduced in namespace scope.
1997 if ((*Member)->getDeclContext() != Pattern)
1998 continue;
1999
Douglas Gregord65587f2010-11-10 19:44:59 +00002000 if ((*Member)->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00002001 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002002 continue;
2003 }
2004
2005 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002006 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002007 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002008 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00002009 FieldDecl *OldField = cast<FieldDecl>(*Member);
2010 if (OldField->getInClassInitializer())
2011 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2012 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00002013 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2014 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2015 // specialization causes the implicit instantiation of the definitions
2016 // of unscoped member enumerations.
2017 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002018 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2019 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002020 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2021 assert(MSInfo && "no spec info for member enum specialization");
2022 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2023 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2024 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002025 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2026 if (SA->isFailed()) {
2027 // A static_assert failed. Bail out; instantiating this
2028 // class is probably not meaningful.
2029 Instantiation->setInvalidDecl();
2030 break;
2031 }
Richard Smith1af83c42012-03-23 03:33:32 +00002032 }
2033
2034 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002035 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002036 } else {
2037 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002038 // instantiations was a semantic disaster, and we'll want to mark the
2039 // declaration invalid.
2040 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002041 }
2042 }
2043
2044 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00002045 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2046 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002047 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002048
2049 // Attach any in-class member initializers now the class is complete.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002050 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002051 // C++11 [expr.prim.general]p4:
2052 // Otherwise, if a member-declarator declares a non-static data member
2053 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2054 // to X" within the optional brace-or-equal-initializer. It shall not
2055 // appear elsewhere in the member-declarator.
2056 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2057
2058 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2059 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2060 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2061 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002062
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002063 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2064 /*CXXDirectInit=*/false);
2065 if (NewInit.isInvalid())
2066 NewField->setInvalidDecl();
2067 else {
2068 Expr *Init = NewInit.take();
2069 assert(Init && "no-argument initializer in class");
2070 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
Richard Smithca523302012-06-10 03:12:00 +00002071 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002072 }
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002073 }
Richard Smith7a614d82011-06-11 17:19:42 +00002074 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002075 // Instantiate late parsed attributes, and attach them to their decls.
2076 // See Sema::InstantiateAttrs
2077 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2078 E = LateAttrs.end(); I != E; ++I) {
2079 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2080 CurrentInstantiationScope = I->Scope;
2081 Attr *NewAttr =
2082 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2083 I->NewDecl->addAttr(NewAttr);
2084 LocalInstantiationScope::deleteScopes(I->Scope,
2085 Instantiator.getStartingScope());
2086 }
2087 Instantiator.disableLateAttributeInstantiation();
2088 LateAttrs.clear();
2089
Richard Smithb9d0b762012-07-27 04:22:15 +00002090 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002091
Abramo Bagnarae9946242011-11-18 08:08:52 +00002092 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002093 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002094 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002095 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002096 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002097
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002098 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002099 // Perform any dependent diagnostics from the pattern.
2100 PerformDependentDiagnostics(Pattern, TemplateArgs);
2101
Douglas Gregord65587f2010-11-10 19:44:59 +00002102 // Instantiate any out-of-line class template partial
2103 // specializations now.
2104 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2105 P = Instantiator.delayed_partial_spec_begin(),
2106 PEnd = Instantiator.delayed_partial_spec_end();
2107 P != PEnd; ++P) {
2108 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2109 P->first,
2110 P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002111 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002112 break;
2113 }
2114 }
2115 }
2116
Douglas Gregord475b8d2009-03-25 21:17:03 +00002117 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002118 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002119
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002120 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002121 Consumer.HandleTagDeclDefinition(Instantiation);
2122
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002123 // Always emit the vtable for an explicit instantiation definition
2124 // of a polymorphic class template specialization.
2125 if (TSK == TSK_ExplicitInstantiationDefinition)
2126 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2127 }
2128
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002129 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002130}
2131
Richard Smithf1c66b42012-03-14 23:13:10 +00002132/// \brief Instantiate the definition of an enum from a given pattern.
2133///
2134/// \param PointOfInstantiation The point of instantiation within the
2135/// source code.
2136/// \param Instantiation is the declaration whose definition is being
2137/// instantiated. This will be a member enumeration of a class
2138/// temploid specialization, or a local enumeration within a
2139/// function temploid specialization.
2140/// \param Pattern The templated declaration from which the instantiation
2141/// occurs.
2142/// \param TemplateArgs The template arguments to be substituted into
2143/// the pattern.
2144/// \param TSK The kind of implicit or explicit instantiation to perform.
2145///
2146/// \return \c true if an error occurred, \c false otherwise.
2147bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2148 EnumDecl *Instantiation, EnumDecl *Pattern,
2149 const MultiLevelTemplateArgumentList &TemplateArgs,
2150 TemplateSpecializationKind TSK) {
2151 EnumDecl *PatternDef = Pattern->getDefinition();
2152 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2153 Instantiation->getInstantiatedFromMemberEnum(),
2154 Pattern, PatternDef, TSK,/*Complain*/true))
2155 return true;
2156 Pattern = PatternDef;
2157
2158 // Record the point of instantiation.
2159 if (MemberSpecializationInfo *MSInfo
2160 = Instantiation->getMemberSpecializationInfo()) {
2161 MSInfo->setTemplateSpecializationKind(TSK);
2162 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2163 }
2164
2165 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2166 if (Inst)
2167 return true;
2168
2169 // Enter the scope of this instantiation. We don't use
2170 // PushDeclContext because we don't have a scope.
2171 ContextRAII SavedContext(*this, Instantiation);
2172 EnterExpressionEvaluationContext EvalContext(*this,
2173 Sema::PotentiallyEvaluated);
2174
2175 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2176
2177 // Pull attributes from the pattern onto the instantiation.
2178 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2179
2180 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2181 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2182
2183 // Exit the scope of this instantiation.
2184 SavedContext.pop();
2185
2186 return Instantiation->isInvalidDecl();
2187}
2188
Douglas Gregor9b623632010-10-12 23:32:35 +00002189namespace {
2190 /// \brief A partial specialization whose template arguments have matched
2191 /// a given template-id.
2192 struct PartialSpecMatchResult {
2193 ClassTemplatePartialSpecializationDecl *Partial;
2194 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002195 };
2196}
2197
Mike Stump1eb44332009-09-09 15:08:12 +00002198bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00002199Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002200 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00002201 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002202 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002203 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002204 // Perform the actual instantiation on the canonical declaration.
2205 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002206 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002207
Douglas Gregor52604ab2009-09-11 21:19:12 +00002208 // Check whether we have already instantiated or specialized this class
2209 // template specialization.
2210 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2211 if (ClassTemplateSpec->getSpecializationKind() ==
2212 TSK_ExplicitInstantiationDeclaration &&
2213 TSK == TSK_ExplicitInstantiationDefinition) {
2214 // An explicit instantiation definition follows an explicit instantiation
2215 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2216 // explicit instantiation.
2217 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002218
2219 // If this is an explicit instantiation definition, mark the
2220 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002221 if (TSK == TSK_ExplicitInstantiationDefinition &&
2222 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002223 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2224
Douglas Gregor52604ab2009-09-11 21:19:12 +00002225 return false;
2226 }
2227
2228 // We can only instantiate something that hasn't already been
2229 // instantiated or specialized. Fail without any diagnostics: our
2230 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002231 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002232 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002233
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002234 if (ClassTemplateSpec->isInvalidDecl())
2235 return true;
2236
Douglas Gregor2943aed2009-03-03 04:44:36 +00002237 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002238 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002239
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002240 // C++ [temp.class.spec.match]p1:
2241 // When a class template is used in a context that requires an
2242 // instantiation of the class, it is necessary to determine
2243 // whether the instantiation is to be generated using the primary
2244 // template or one of the partial specializations. This is done by
2245 // matching the template arguments of the class template
2246 // specialization with the template argument lists of the partial
2247 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002248 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002249 SmallVector<MatchResult, 4> Matched;
2250 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002251 Template->getPartialSpecializations(PartialSpecs);
2252 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2253 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Craig Topper93e45992012-09-19 02:26:47 +00002254 TemplateDeductionInfo Info(PointOfInstantiation);
Douglas Gregorf67875d2009-06-12 18:26:56 +00002255 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002256 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002257 ClassTemplateSpec->getTemplateArgs(),
2258 Info)) {
2259 // FIXME: Store the failed-deduction information for use in
2260 // diagnostics, later.
2261 (void)Result;
2262 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002263 Matched.push_back(PartialSpecMatchResult());
2264 Matched.back().Partial = Partial;
2265 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002266 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002267 }
2268
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002269 // If we're dealing with a member template where the template parameters
2270 // have been instantiated, this provides the original template parameters
2271 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002272 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002273
Douglas Gregored9c0f92009-10-29 00:04:11 +00002274 if (Matched.size() >= 1) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002275 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002276 if (Matched.size() == 1) {
2277 // -- If exactly one matching specialization is found, the
2278 // instantiation is generated from that specialization.
2279 // We don't need to do anything for this.
2280 } else {
2281 // -- If more than one matching specialization is found, the
2282 // partial order rules (14.5.4.2) are used to determine
2283 // whether one of the specializations is more specialized
2284 // than the others. If none of the specializations is more
2285 // specialized than all of the other matching
2286 // specializations, then the use of the class template is
2287 // ambiguous and the program is ill-formed.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002288 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002289 PEnd = Matched.end();
2290 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002291 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002292 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002293 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002294 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002295 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002296
Douglas Gregored9c0f92009-10-29 00:04:11 +00002297 // Determine if the best partial specialization is more specialized than
2298 // the others.
2299 bool Ambiguous = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002300 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002301 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002302 P != PEnd; ++P) {
2303 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002304 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002305 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002306 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002307 Ambiguous = true;
2308 break;
2309 }
2310 }
2311
2312 if (Ambiguous) {
2313 // Partial ordering did not produce a clear winner. Complain.
2314 ClassTemplateSpec->setInvalidDecl();
2315 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2316 << ClassTemplateSpec;
2317
2318 // Print the matching partial specializations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002319 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002320 PEnd = Matched.end();
2321 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002322 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2323 << getTemplateArgumentBindingsText(
2324 P->Partial->getTemplateParameters(),
2325 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002326
Douglas Gregored9c0f92009-10-29 00:04:11 +00002327 return true;
2328 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002329 }
2330
2331 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002332 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002333 while (OrigPartialSpec->getInstantiatedFromMember()) {
2334 // If we've found an explicit specialization of this class template,
2335 // stop here and use that as the pattern.
2336 if (OrigPartialSpec->isMemberSpecialization())
2337 break;
2338
2339 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2340 }
2341
2342 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002343 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002344 } else {
2345 // -- If no matches are found, the instantiation is generated
2346 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002347 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002348 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2349 // If we've found an explicit specialization of this class template,
2350 // stop here and use that as the pattern.
2351 if (OrigTemplate->isMemberSpecialization())
2352 break;
2353
Douglas Gregord6350ae2009-08-28 20:31:08 +00002354 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002355 }
2356
Douglas Gregord6350ae2009-08-28 20:31:08 +00002357 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002358 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002359
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002360 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2361 Pattern,
2362 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002363 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002364 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002365
Douglas Gregor199d9912009-06-05 00:53:49 +00002366 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002367}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002368
John McCallce3ff2b2009-08-25 22:02:44 +00002369/// \brief Instantiates the definitions of all of the member
2370/// of the given class, which is an instantiation of a class template
2371/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002372void
2373Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002374 CXXRecordDecl *Instantiation,
2375 const MultiLevelTemplateArgumentList &TemplateArgs,
2376 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002377 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2378 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002379 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002380 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002381 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002382 if (FunctionDecl *Pattern
2383 = Function->getInstantiatedFromMemberFunction()) {
2384 MemberSpecializationInfo *MSInfo
2385 = Function->getMemberSpecializationInfo();
2386 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002387 if (MSInfo->getTemplateSpecializationKind()
2388 == TSK_ExplicitSpecialization)
2389 continue;
2390
Douglas Gregor0d035142009-10-27 18:42:08 +00002391 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2392 Function,
2393 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002394 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002395 SuppressNew) ||
2396 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002397 continue;
2398
Sean Hunt10620eb2011-05-06 20:44:56 +00002399 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002400 continue;
2401
2402 if (TSK == TSK_ExplicitInstantiationDefinition) {
2403 // C++0x [temp.explicit]p8:
2404 // An explicit instantiation definition that names a class template
2405 // specialization explicitly instantiates the class template
2406 // specialization and is only an explicit instantiation definition
2407 // of members whose definition is visible at the point of
2408 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002409 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002410 continue;
2411
2412 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2413
2414 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2415 } else {
2416 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2417 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002418 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002419 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002420 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002421 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2422 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002423 if (MSInfo->getTemplateSpecializationKind()
2424 == TSK_ExplicitSpecialization)
2425 continue;
2426
Douglas Gregor0d035142009-10-27 18:42:08 +00002427 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2428 Var,
2429 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002430 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002431 SuppressNew) ||
2432 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002433 continue;
2434
Douglas Gregor0d035142009-10-27 18:42:08 +00002435 if (TSK == TSK_ExplicitInstantiationDefinition) {
2436 // C++0x [temp.explicit]p8:
2437 // An explicit instantiation definition that names a class template
2438 // specialization explicitly instantiates the class template
2439 // specialization and is only an explicit instantiation definition
2440 // of members whose definition is visible at the point of
2441 // instantiation.
2442 if (!Var->getInstantiatedFromStaticDataMember()
2443 ->getOutOfLineDefinition())
2444 continue;
2445
2446 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002447 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002448 } else {
2449 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2450 }
2451 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002452 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002453 // Always skip the injected-class-name, along with any
2454 // redeclarations of nested classes, since both would cause us
2455 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002456 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002457 continue;
2458
Douglas Gregor0d035142009-10-27 18:42:08 +00002459 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2460 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002461
2462 if (MSInfo->getTemplateSpecializationKind()
2463 == TSK_ExplicitSpecialization)
2464 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002465
Douglas Gregor0d035142009-10-27 18:42:08 +00002466 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2467 Record,
2468 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002469 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002470 SuppressNew) ||
2471 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002472 continue;
2473
Douglas Gregor0d035142009-10-27 18:42:08 +00002474 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2475 assert(Pattern && "Missing instantiated-from-template information");
2476
Douglas Gregor952b0172010-02-11 01:04:33 +00002477 if (!Record->getDefinition()) {
2478 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002479 // C++0x [temp.explicit]p8:
2480 // An explicit instantiation definition that names a class template
2481 // specialization explicitly instantiates the class template
2482 // specialization and is only an explicit instantiation definition
2483 // of members whose definition is visible at the point of
2484 // instantiation.
2485 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2486 MSInfo->setTemplateSpecializationKind(TSK);
2487 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2488 }
2489
2490 continue;
2491 }
2492
2493 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002494 TemplateArgs,
2495 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002496 } else {
2497 if (TSK == TSK_ExplicitInstantiationDefinition &&
2498 Record->getTemplateSpecializationKind() ==
2499 TSK_ExplicitInstantiationDeclaration) {
2500 Record->setTemplateSpecializationKind(TSK);
2501 MarkVTableUsed(PointOfInstantiation, Record, true);
2502 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002503 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002504
Douglas Gregor952b0172010-02-11 01:04:33 +00002505 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002506 if (Pattern)
2507 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2508 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002509 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2510 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2511 assert(MSInfo && "No member specialization information?");
2512
2513 if (MSInfo->getTemplateSpecializationKind()
2514 == TSK_ExplicitSpecialization)
2515 continue;
2516
2517 if (CheckSpecializationInstantiationRedecl(
2518 PointOfInstantiation, TSK, Enum,
2519 MSInfo->getTemplateSpecializationKind(),
2520 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2521 SuppressNew)
2522 continue;
2523
2524 if (Enum->getDefinition())
2525 continue;
2526
2527 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2528 assert(Pattern && "Missing instantiated-from-template information");
2529
2530 if (TSK == TSK_ExplicitInstantiationDefinition) {
2531 if (!Pattern->getDefinition())
2532 continue;
2533
2534 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2535 } else {
2536 MSInfo->setTemplateSpecializationKind(TSK);
2537 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2538 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002539 }
2540 }
2541}
2542
2543/// \brief Instantiate the definitions of all of the members of the
2544/// given class template specialization, which was named as part of an
2545/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002546void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002547Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002548 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002549 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2550 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002551 // C++0x [temp.explicit]p7:
2552 // An explicit instantiation that names a class template
2553 // specialization is an explicit instantion of the same kind
2554 // (declaration or definition) of each of its members (not
2555 // including members inherited from base classes) that has not
2556 // been previously explicitly specialized in the translation unit
2557 // containing the explicit instantiation, except as described
2558 // below.
2559 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002560 getTemplateInstantiationArgs(ClassTemplateSpec),
2561 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002562}
2563
John McCall60d7b3a2010-08-24 06:29:42 +00002564StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002565Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002566 if (!S)
2567 return Owned(S);
2568
2569 TemplateInstantiator Instantiator(*this, TemplateArgs,
2570 SourceLocation(),
2571 DeclarationName());
2572 return Instantiator.TransformStmt(S);
2573}
2574
John McCall60d7b3a2010-08-24 06:29:42 +00002575ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002576Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002577 if (!E)
2578 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002579
Douglas Gregorb98b1992009-08-11 05:31:07 +00002580 TemplateInstantiator Instantiator(*this, TemplateArgs,
2581 SourceLocation(),
2582 DeclarationName());
2583 return Instantiator.TransformExpr(E);
2584}
2585
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002586bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2587 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002588 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002589 if (NumExprs == 0)
2590 return false;
2591
2592 TemplateInstantiator Instantiator(*this, TemplateArgs,
2593 SourceLocation(),
2594 DeclarationName());
2595 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2596}
2597
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002598NestedNameSpecifierLoc
2599Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2600 const MultiLevelTemplateArgumentList &TemplateArgs) {
2601 if (!NNS)
2602 return NestedNameSpecifierLoc();
2603
2604 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2605 DeclarationName());
2606 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2607}
2608
Abramo Bagnara25777432010-08-11 22:01:17 +00002609/// \brief Do template substitution on declaration name info.
2610DeclarationNameInfo
2611Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2612 const MultiLevelTemplateArgumentList &TemplateArgs) {
2613 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2614 NameInfo.getName());
2615 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2616}
2617
Douglas Gregorde650ae2009-03-31 18:38:02 +00002618TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002619Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2620 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002621 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002622 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2623 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002624 CXXScopeSpec SS;
2625 SS.Adopt(QualifierLoc);
2626 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002627}
Douglas Gregor91333002009-06-11 00:06:24 +00002628
Douglas Gregore02e2622010-12-22 21:19:48 +00002629bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2630 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002631 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002632 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2633 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002634
2635 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002636}
Douglas Gregor895162d2010-04-30 18:55:50 +00002637
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002638
2639static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2640 // When storing ParmVarDecls in the local instantiation scope, we always
2641 // want to use the ParmVarDecl from the canonical function declaration,
2642 // since the map is then valid for any redeclaration or definition of that
2643 // function.
2644 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2645 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2646 unsigned i = PV->getFunctionScopeIndex();
2647 return FD->getCanonicalDecl()->getParamDecl(i);
2648 }
2649 }
2650 return D;
2651}
2652
2653
Douglas Gregor12c9c002011-01-07 16:43:16 +00002654llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2655LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002656 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002657 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002658 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002659
Douglas Gregor895162d2010-04-30 18:55:50 +00002660 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002661 const Decl *CheckD = D;
2662 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002663 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002664 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002665 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002666
2667 // If this is a tag declaration, it's possible that we need to look for
2668 // a previous declaration.
2669 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002670 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002671 else
2672 CheckD = 0;
2673 } while (CheckD);
2674
Douglas Gregor895162d2010-04-30 18:55:50 +00002675 // If we aren't combined with our outer scope, we're done.
2676 if (!Current->CombineWithOuterScope)
2677 break;
2678 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002679
2680 // If we didn't find the decl, then we either have a sema bug, or we have a
2681 // forward reference to a label declaration. Return null to indicate that
2682 // we have an uninstantiated label.
2683 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002684 return 0;
2685}
2686
John McCall2a7fb272010-08-25 05:32:35 +00002687void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002688 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002689 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002690 if (Stored.isNull())
2691 Stored = Inst;
2692 else if (Stored.is<Decl *>()) {
2693 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2694 Stored = Inst;
2695 } else
2696 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
Douglas Gregor895162d2010-04-30 18:55:50 +00002697}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002698
2699void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2700 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002701 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002702 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2703 Pack->push_back(Inst);
2704}
2705
2706void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002707 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002708 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2709 assert(Stored.isNull() && "Already instantiated this local");
2710 DeclArgumentPack *Pack = new DeclArgumentPack;
2711 Stored = Pack;
2712 ArgumentPacks.push_back(Pack);
2713}
2714
Douglas Gregord3731192011-01-10 07:32:04 +00002715void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2716 const TemplateArgument *ExplicitArgs,
2717 unsigned NumExplicitArgs) {
2718 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2719 "Already have a partially-substituted pack");
2720 assert((!PartiallySubstitutedPack
2721 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2722 "Wrong number of arguments in partially-substituted pack");
2723 PartiallySubstitutedPack = Pack;
2724 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2725 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2726}
2727
2728NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2729 const TemplateArgument **ExplicitArgs,
2730 unsigned *NumExplicitArgs) const {
2731 if (ExplicitArgs)
2732 *ExplicitArgs = 0;
2733 if (NumExplicitArgs)
2734 *NumExplicitArgs = 0;
2735
2736 for (const LocalInstantiationScope *Current = this; Current;
2737 Current = Current->Outer) {
2738 if (Current->PartiallySubstitutedPack) {
2739 if (ExplicitArgs)
2740 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2741 if (NumExplicitArgs)
2742 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2743
2744 return Current->PartiallySubstitutedPack;
2745 }
2746
2747 if (!Current->CombineWithOuterScope)
2748 break;
2749 }
2750
2751 return 0;
2752}