blob: 3c1964175b10422ef45950941695d8936aff80be [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
65 assert((!D->isTemplateParameter() || !Ctx->isTranslationUnit()) &&
66 "Template parameter doesn't have its context yet!");
67 }
68
John McCallf181d8a2009-08-29 03:16:09 +000069 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +000070 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +000071 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +000072 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
73 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +000074 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
75 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +000076 break;
Mike Stump1eb44332009-09-09 15:08:12 +000077
Douglas Gregord1102432009-08-28 17:37:35 +000078 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +000079
80 // If this class template specialization was instantiated from a
81 // specialized member that is a class template, we're done.
82 assert(Spec->getSpecializedTemplate() && "No class template?");
83 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
84 break;
Mike Stump1eb44332009-09-09 15:08:12 +000085 }
Douglas Gregord1102432009-08-28 17:37:35 +000086 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +000087 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +000088 if (!RelativeToPrimary &&
89 Function->getTemplateSpecializationKind()
90 == TSK_ExplicitSpecialization)
Douglas Gregorfd056bc2009-10-13 16:30:37 +000091 break;
92
Douglas Gregord1102432009-08-28 17:37:35 +000093 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +000094 = Function->getTemplateSpecializationArgs()) {
95 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +000096 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +000097
Douglas Gregorfd056bc2009-10-13 16:30:37 +000098 // If this function was instantiated from a specialized member that is
99 // a function template, we're done.
100 assert(Function->getPrimaryTemplate() && "No function template?");
101 if (Function->getPrimaryTemplate()->isMemberSpecialization())
102 break;
Douglas Gregorc494f772011-03-05 17:54:25 +0000103 } else if (FunctionTemplateDecl *FunTmpl
104 = Function->getDescribedFunctionTemplate()) {
105 // Add the "injected" template arguments.
106 std::pair<const TemplateArgument *, unsigned>
107 Injected = FunTmpl->getInjectedTemplateArgs();
108 Result.addOuterTemplateArguments(Injected.first, Injected.second);
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000109 }
110
John McCallf181d8a2009-08-29 03:16:09 +0000111 // If this is a friend declaration and it declares an entity at
112 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000113 // instead of its semantic parent, unless of course the pattern we're
114 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000115 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000116 Function->getDeclContext()->isFileContext() &&
117 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000118 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000119 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000120 continue;
121 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000122 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
123 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
124 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
125 const TemplateSpecializationType *TST
126 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
127 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
128 if (ClassTemplate->isMemberSpecialization())
129 break;
130 }
Douglas Gregord1102432009-08-28 17:37:35 +0000131 }
John McCallf181d8a2009-08-29 03:16:09 +0000132
133 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000134 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000135 }
Mike Stump1eb44332009-09-09 15:08:12 +0000136
Douglas Gregord1102432009-08-28 17:37:35 +0000137 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000138}
139
Douglas Gregorf35f8282009-11-11 21:54:23 +0000140bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
141 switch (Kind) {
142 case TemplateInstantiation:
143 case DefaultTemplateArgumentInstantiation:
144 case DefaultFunctionArgumentInstantiation:
145 return true;
146
147 case ExplicitTemplateArgumentSubstitution:
148 case DeducedTemplateArgumentSubstitution:
149 case PriorTemplateArgumentSubstitution:
150 case DefaultTemplateArgumentChecking:
151 return false;
152 }
153
154 return true;
155}
156
Douglas Gregor26dce442009-03-10 00:06:19 +0000157Sema::InstantiatingTemplate::
158InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000159 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000160 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000161 : SemaRef(SemaRef),
162 SavedInNonInstantiationSFINAEContext(
163 SemaRef.InNonInstantiationSFINAEContext)
164{
Douglas Gregordf667e72009-03-10 20:44:00 +0000165 Invalid = CheckInstantiationDepth(PointOfInstantiation,
166 InstantiationRange);
167 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000168 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000169 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000170 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregordf667e72009-03-10 20:44:00 +0000171 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregor313a81d2009-03-12 18:36:18 +0000172 Inst.TemplateArgs = 0;
173 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000174 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000175 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000176 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000177 }
178}
179
Mike Stump1eb44332009-09-09 15:08:12 +0000180Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregordf667e72009-03-10 20:44:00 +0000181 SourceLocation PointOfInstantiation,
182 TemplateDecl *Template,
183 const TemplateArgument *TemplateArgs,
184 unsigned NumTemplateArgs,
185 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000186 : SemaRef(SemaRef),
187 SavedInNonInstantiationSFINAEContext(
188 SemaRef.InNonInstantiationSFINAEContext)
189{
Douglas Gregordf667e72009-03-10 20:44:00 +0000190 Invalid = CheckInstantiationDepth(PointOfInstantiation,
191 InstantiationRange);
192 if (!Invalid) {
193 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000194 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000195 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
196 Inst.PointOfInstantiation = PointOfInstantiation;
197 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
198 Inst.TemplateArgs = TemplateArgs;
199 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor26dce442009-03-10 00:06:19 +0000200 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000201 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000202 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000203 }
204}
205
Mike Stump1eb44332009-09-09 15:08:12 +0000206Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor637a4092009-06-10 23:47:09 +0000207 SourceLocation PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000208 FunctionTemplateDecl *FunctionTemplate,
209 const TemplateArgument *TemplateArgs,
210 unsigned NumTemplateArgs,
211 ActiveTemplateInstantiation::InstantiationKind Kind,
Douglas Gregor9b623632010-10-12 23:32:35 +0000212 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000213 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000214 : SemaRef(SemaRef),
215 SavedInNonInstantiationSFINAEContext(
216 SemaRef.InNonInstantiationSFINAEContext)
217{
Douglas Gregorcca9e962009-07-01 22:01:06 +0000218 Invalid = CheckInstantiationDepth(PointOfInstantiation,
219 InstantiationRange);
220 if (!Invalid) {
221 ActiveTemplateInstantiation Inst;
222 Inst.Kind = Kind;
223 Inst.PointOfInstantiation = PointOfInstantiation;
224 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
225 Inst.TemplateArgs = TemplateArgs;
226 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor9b623632010-10-12 23:32:35 +0000227 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000228 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000229 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000230 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000231
232 if (!Inst.isInstantiationRecord())
233 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000234 }
235}
236
Mike Stump1eb44332009-09-09 15:08:12 +0000237Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000238 SourceLocation PointOfInstantiation,
Douglas Gregor637a4092009-06-10 23:47:09 +0000239 ClassTemplatePartialSpecializationDecl *PartialSpec,
240 const TemplateArgument *TemplateArgs,
241 unsigned NumTemplateArgs,
Douglas Gregor9b623632010-10-12 23:32:35 +0000242 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregor637a4092009-06-10 23:47:09 +0000243 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000244 : SemaRef(SemaRef),
245 SavedInNonInstantiationSFINAEContext(
246 SemaRef.InNonInstantiationSFINAEContext)
247{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000248 Invalid = false;
249
250 ActiveTemplateInstantiation Inst;
251 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
252 Inst.PointOfInstantiation = PointOfInstantiation;
253 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
254 Inst.TemplateArgs = TemplateArgs;
255 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor9b623632010-10-12 23:32:35 +0000256 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000257 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000258 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000259 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
260
261 assert(!Inst.isInstantiationRecord());
262 ++SemaRef.NonInstantiationEntries;
Douglas Gregor637a4092009-06-10 23:47:09 +0000263}
264
Mike Stump1eb44332009-09-09 15:08:12 +0000265Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000266 SourceLocation PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000267 ParmVarDecl *Param,
268 const TemplateArgument *TemplateArgs,
269 unsigned NumTemplateArgs,
270 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000271 : SemaRef(SemaRef),
272 SavedInNonInstantiationSFINAEContext(
273 SemaRef.InNonInstantiationSFINAEContext)
274{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000275 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000276
277 if (!Invalid) {
278 ActiveTemplateInstantiation Inst;
279 Inst.Kind
280 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000281 Inst.PointOfInstantiation = PointOfInstantiation;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000282 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
283 Inst.TemplateArgs = TemplateArgs;
284 Inst.NumTemplateArgs = NumTemplateArgs;
285 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000286 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000287 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000288 }
289}
290
291Sema::InstantiatingTemplate::
292InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000293 NamedDecl *Template,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000294 NonTypeTemplateParmDecl *Param,
295 const TemplateArgument *TemplateArgs,
296 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000297 SourceRange InstantiationRange)
298 : SemaRef(SemaRef),
299 SavedInNonInstantiationSFINAEContext(
300 SemaRef.InNonInstantiationSFINAEContext)
301{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000302 Invalid = false;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000303
Douglas Gregorf35f8282009-11-11 21:54:23 +0000304 ActiveTemplateInstantiation Inst;
305 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
306 Inst.PointOfInstantiation = PointOfInstantiation;
307 Inst.Template = Template;
308 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
309 Inst.TemplateArgs = TemplateArgs;
310 Inst.NumTemplateArgs = NumTemplateArgs;
311 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000312 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000313 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
314
315 assert(!Inst.isInstantiationRecord());
316 ++SemaRef.NonInstantiationEntries;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000317}
318
319Sema::InstantiatingTemplate::
320InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000321 NamedDecl *Template,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000322 TemplateTemplateParmDecl *Param,
323 const TemplateArgument *TemplateArgs,
324 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000325 SourceRange InstantiationRange)
326 : SemaRef(SemaRef),
327 SavedInNonInstantiationSFINAEContext(
328 SemaRef.InNonInstantiationSFINAEContext)
329{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000330 Invalid = false;
331 ActiveTemplateInstantiation Inst;
332 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
333 Inst.PointOfInstantiation = PointOfInstantiation;
334 Inst.Template = Template;
335 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
336 Inst.TemplateArgs = TemplateArgs;
337 Inst.NumTemplateArgs = NumTemplateArgs;
338 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000339 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000340 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000341
Douglas Gregorf35f8282009-11-11 21:54:23 +0000342 assert(!Inst.isInstantiationRecord());
343 ++SemaRef.NonInstantiationEntries;
344}
345
346Sema::InstantiatingTemplate::
347InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
348 TemplateDecl *Template,
349 NamedDecl *Param,
350 const TemplateArgument *TemplateArgs,
351 unsigned NumTemplateArgs,
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000352 SourceRange InstantiationRange)
353 : SemaRef(SemaRef),
354 SavedInNonInstantiationSFINAEContext(
355 SemaRef.InNonInstantiationSFINAEContext)
356{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000357 Invalid = false;
358
359 ActiveTemplateInstantiation Inst;
360 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
361 Inst.PointOfInstantiation = PointOfInstantiation;
362 Inst.Template = Template;
363 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
364 Inst.TemplateArgs = TemplateArgs;
365 Inst.NumTemplateArgs = NumTemplateArgs;
366 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000367 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000368 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
369
370 assert(!Inst.isInstantiationRecord());
371 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000372}
373
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000374void Sema::InstantiatingTemplate::Clear() {
375 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000376 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
377 assert(SemaRef.NonInstantiationEntries > 0);
378 --SemaRef.NonInstantiationEntries;
379 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000380 SemaRef.InNonInstantiationSFINAEContext
381 = SavedInNonInstantiationSFINAEContext;
Douglas Gregor26dce442009-03-10 00:06:19 +0000382 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000383 Invalid = true;
384 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000385}
386
Douglas Gregordf667e72009-03-10 20:44:00 +0000387bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
388 SourceLocation PointOfInstantiation,
389 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000390 assert(SemaRef.NonInstantiationEntries <=
391 SemaRef.ActiveTemplateInstantiations.size());
392 if ((SemaRef.ActiveTemplateInstantiations.size() -
393 SemaRef.NonInstantiationEntries)
394 <= SemaRef.getLangOptions().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000395 return false;
396
Mike Stump1eb44332009-09-09 15:08:12 +0000397 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000398 diag::err_template_recursion_depth_exceeded)
399 << SemaRef.getLangOptions().InstantiationDepth
400 << InstantiationRange;
401 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
402 << SemaRef.getLangOptions().InstantiationDepth;
403 return true;
404}
405
Douglas Gregoree1828a2009-03-10 18:03:33 +0000406/// \brief Prints the current instantiation stack through a series of
407/// notes.
408void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000409 // Determine which template instantiations to skip, if any.
410 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
411 unsigned Limit = Diags.getTemplateBacktraceLimit();
412 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
413 SkipStart = Limit / 2 + Limit % 2;
414 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
415 }
416
Douglas Gregorcca9e962009-07-01 22:01:06 +0000417 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000418 unsigned InstantiationIdx = 0;
Douglas Gregoree1828a2009-03-10 18:03:33 +0000419 for (llvm::SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
420 Active = ActiveTemplateInstantiations.rbegin(),
421 ActiveEnd = ActiveTemplateInstantiations.rend();
422 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000423 ++Active, ++InstantiationIdx) {
424 // Skip this instantiation?
425 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
426 if (InstantiationIdx == SkipStart) {
427 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000428 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000429 diag::note_instantiation_contexts_suppressed)
430 << unsigned(ActiveTemplateInstantiations.size() - Limit);
431 }
432 continue;
433 }
434
Douglas Gregordf667e72009-03-10 20:44:00 +0000435 switch (Active->Kind) {
436 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000437 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
438 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
439 unsigned DiagID = diag::note_template_member_class_here;
440 if (isa<ClassTemplateSpecializationDecl>(Record))
441 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000442 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000443 << Context.getTypeDeclType(Record)
444 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000445 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000446 unsigned DiagID;
447 if (Function->getPrimaryTemplate())
448 DiagID = diag::note_function_template_spec_here;
449 else
450 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000451 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000452 << Function
453 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000454 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000455 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000456 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000457 << VD
458 << Active->InstantiationRange;
459 } else {
460 Diags.Report(Active->PointOfInstantiation,
461 diag::note_template_type_alias_instantiation_here)
462 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000463 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000464 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000465 break;
466 }
467
468 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
469 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
470 std::string TemplateArgsStr
Douglas Gregor7532dc62009-03-30 22:58:21 +0000471 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000472 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000473 Active->NumTemplateArgs,
474 Context.PrintingPolicy);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000475 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000476 diag::note_default_arg_instantiation_here)
477 << (Template->getNameAsString() + TemplateArgsStr)
478 << Active->InstantiationRange;
479 break;
480 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000481
Douglas Gregorcca9e962009-07-01 22:01:06 +0000482 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Mike Stump1eb44332009-09-09 15:08:12 +0000483 FunctionTemplateDecl *FnTmpl
Douglas Gregorcca9e962009-07-01 22:01:06 +0000484 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000485 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000486 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000487 << FnTmpl
488 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
489 Active->TemplateArgs,
490 Active->NumTemplateArgs)
491 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000492 break;
493 }
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Douglas Gregorcca9e962009-07-01 22:01:06 +0000495 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
496 if (ClassTemplatePartialSpecializationDecl *PartialSpec
497 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
498 (Decl *)Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000499 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000500 diag::note_partial_spec_deduct_instantiation_here)
501 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000502 << getTemplateArgumentBindingsText(
503 PartialSpec->getTemplateParameters(),
504 Active->TemplateArgs,
505 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000506 << Active->InstantiationRange;
507 } else {
508 FunctionTemplateDecl *FnTmpl
509 = 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_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000512 << FnTmpl
513 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
514 Active->TemplateArgs,
515 Active->NumTemplateArgs)
516 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000517 }
518 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000519
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000520 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
521 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
522 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000524 std::string TemplateArgsStr
525 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump1eb44332009-09-09 15:08:12 +0000526 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000527 Active->NumTemplateArgs,
528 Context.PrintingPolicy);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000529 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000530 diag::note_default_function_arg_instantiation_here)
Anders Carlsson6bc107b2009-09-05 05:38:54 +0000531 << (FD->getNameAsString() + TemplateArgsStr)
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000532 << Active->InstantiationRange;
533 break;
534 }
Mike Stump1eb44332009-09-09 15:08:12 +0000535
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000536 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
537 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
538 std::string Name;
539 if (!Parm->getName().empty())
540 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000541
542 TemplateParameterList *TemplateParams = 0;
543 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
544 TemplateParams = Template->getTemplateParameters();
545 else
546 TemplateParams =
547 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
548 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000549 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000550 diag::note_prior_template_arg_substitution)
551 << isa<TemplateTemplateParmDecl>(Parm)
552 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000553 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000554 Active->TemplateArgs,
555 Active->NumTemplateArgs)
556 << Active->InstantiationRange;
557 break;
558 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000559
560 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000561 TemplateParameterList *TemplateParams = 0;
562 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
563 TemplateParams = Template->getTemplateParameters();
564 else
565 TemplateParams =
566 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
567 ->getTemplateParameters();
568
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000569 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000570 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000571 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000572 Active->TemplateArgs,
573 Active->NumTemplateArgs)
574 << Active->InstantiationRange;
575 break;
576 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000577 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000578 }
579}
580
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000581llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000582 using llvm::SmallVector;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000583 if (InNonInstantiationSFINAEContext)
584 return llvm::Optional<TemplateDeductionInfo *>(0);
585
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000586 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
587 Active = ActiveTemplateInstantiations.rbegin(),
588 ActiveEnd = ActiveTemplateInstantiations.rend();
589 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000590 ++Active)
591 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000592 switch(Active->Kind) {
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000593 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000594 case ActiveTemplateInstantiation::TemplateInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000595 // This is a template instantiation, so there is no SFINAE.
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000596 return llvm::Optional<TemplateDeductionInfo *>();
Mike Stump1eb44332009-09-09 15:08:12 +0000597
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000598 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000599 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000600 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000601 // A default template argument instantiation and substitution into
602 // template parameters with arguments for prior parameters may or may
603 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000604 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000605
Douglas Gregorcca9e962009-07-01 22:01:06 +0000606 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
607 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
608 // We're either substitution explicitly-specified template arguments
609 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000610 assert(Active->DeductionInfo && "Missing deduction info pointer");
611 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000612 }
613 }
614
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000615 return llvm::Optional<TemplateDeductionInfo *>();
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000616}
617
Douglas Gregord3731192011-01-10 07:32:04 +0000618/// \brief Retrieve the depth and index of a parameter pack.
619static std::pair<unsigned, unsigned>
620getDepthAndIndex(NamedDecl *ND) {
621 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
622 return std::make_pair(TTP->getDepth(), TTP->getIndex());
623
624 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
625 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
626
627 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
628 return std::make_pair(TTP->getDepth(), TTP->getIndex());
629}
630
Douglas Gregor99ebf652009-02-27 19:31:52 +0000631//===----------------------------------------------------------------------===/
632// Template Instantiation for Types
633//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000634namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000635 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000636 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000637 SourceLocation Loc;
638 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000639
Douglas Gregorcd281c32009-02-28 00:25:32 +0000640 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000641 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000642
643 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000644 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000645 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000646 DeclarationName Entity)
647 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000648 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000649
Mike Stump1eb44332009-09-09 15:08:12 +0000650 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000651 /// transformed.
652 ///
653 /// For the purposes of template instantiation, a type has already been
654 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000655 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Douglas Gregor577f75a2009-08-04 16:50:30 +0000657 /// \brief Returns the location of the entity being instantiated, if known.
658 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Douglas Gregor577f75a2009-08-04 16:50:30 +0000660 /// \brief Returns the name of the entity being instantiated, if any.
661 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000663 /// \brief Sets the "base" location and entity when that
664 /// information is known based on another transformation.
665 void setBase(SourceLocation Loc, DeclarationName Entity) {
666 this->Loc = Loc;
667 this->Entity = Entity;
668 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000669
670 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
671 SourceRange PatternRange,
672 const UnexpandedParameterPack *Unexpanded,
673 unsigned NumUnexpanded,
674 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000675 bool &RetainExpansion,
Douglas Gregorcded4f62011-01-14 17:04:44 +0000676 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000677 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
678 PatternRange, Unexpanded,
679 NumUnexpanded,
680 TemplateArgs,
681 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000682 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000683 NumExpansions);
684 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000685
Douglas Gregor12c9c002011-01-07 16:43:16 +0000686 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
687 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
688 }
689
Douglas Gregord3731192011-01-10 07:32:04 +0000690 TemplateArgument ForgetPartiallySubstitutedPack() {
691 TemplateArgument Result;
692 if (NamedDecl *PartialPack
693 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
694 MultiLevelTemplateArgumentList &TemplateArgs
695 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
696 unsigned Depth, Index;
697 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
698 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
699 Result = TemplateArgs(Depth, Index);
700 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
701 }
702 }
703
704 return Result;
705 }
706
707 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
708 if (Arg.isNull())
709 return;
710
711 if (NamedDecl *PartialPack
712 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
713 MultiLevelTemplateArgumentList &TemplateArgs
714 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
715 unsigned Depth, Index;
716 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
717 TemplateArgs.setArgument(Depth, Index, Arg);
718 }
719 }
720
Douglas Gregor577f75a2009-08-04 16:50:30 +0000721 /// \brief Transform the given declaration by instantiating a reference to
722 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000723 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000724
Mike Stump1eb44332009-09-09 15:08:12 +0000725 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000726 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000727 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Douglas Gregor6cd21982009-10-20 05:58:46 +0000729 /// \bried Transform the first qualifier within a scope by instantiating the
730 /// declaration.
731 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
732
Douglas Gregor43959a92009-08-20 07:17:43 +0000733 /// \brief Rebuild the exception declaration and register the declaration
734 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000735 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000736 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000737 SourceLocation StartLoc,
738 SourceLocation NameLoc,
739 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000740
Douglas Gregorbe270a02010-04-26 17:57:08 +0000741 /// \brief Rebuild the Objective-C exception declaration and register the
742 /// declaration as an instantiated local.
743 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
744 TypeSourceInfo *TSInfo, QualType T);
745
John McCallc4e70192009-09-11 04:59:25 +0000746 /// \brief Check for tag mismatches when instantiating an
747 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000748 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
749 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000750 NestedNameSpecifierLoc QualifierLoc,
751 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000752
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000753 TemplateName TransformTemplateName(CXXScopeSpec &SS,
754 TemplateName Name,
755 SourceLocation NameLoc,
756 QualType ObjectType = QualType(),
757 NamedDecl *FirstQualifierInScope = 0);
758
John McCall60d7b3a2010-08-24 06:29:42 +0000759 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
760 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
761 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
762 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000763 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000764 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
765 SubstNonTypeTemplateParmPackExpr *E);
766
Douglas Gregor895162d2010-04-30 18:55:50 +0000767 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000768 FunctionProtoTypeLoc TL);
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000769 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000770 int indexAdjustment,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000771 llvm::Optional<unsigned> NumExpansions);
John McCall21ef0fa2010-03-11 09:03:00 +0000772
Mike Stump1eb44332009-09-09 15:08:12 +0000773 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000774 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000775 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000776 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000777
Douglas Gregorc3069d62011-01-14 02:55:32 +0000778 /// \brief Transforms an already-substituted template type parameter pack
779 /// into either itself (if we aren't substituting into its pack expansion)
780 /// or the appropriate substituted argument.
781 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
782 SubstTemplateTypeParmPackTypeLoc TL);
783
John McCall60d7b3a2010-08-24 06:29:42 +0000784 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000785 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000786 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000787 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
788 getSema().CallsUndergoingInstantiation.pop_back();
789 return move(Result);
790 }
Douglas Gregor577f75a2009-08-04 16:50:30 +0000791 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000792}
793
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000794bool TemplateInstantiator::AlreadyTransformed(QualType T) {
795 if (T.isNull())
796 return true;
797
Douglas Gregor836adf62010-05-24 17:22:01 +0000798 if (T->isDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000799 return false;
800
801 getSema().MarkDeclarationsReferencedInType(Loc, T);
802 return true;
803}
804
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000805Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000806 if (!D)
807 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Douglas Gregorc68afe22009-09-03 21:38:09 +0000809 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000810 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000811 // If the corresponding template argument is NULL or non-existent, it's
812 // because we are performing instantiation from explicitly-specified
813 // template arguments in a function template, but there were some
814 // arguments left unspecified.
815 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
816 TTP->getPosition()))
817 return D;
818
Douglas Gregor61c4d282011-01-05 15:48:55 +0000819 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
820
821 if (TTP->isParameterPack()) {
822 assert(Arg.getKind() == TemplateArgument::Pack &&
823 "Missing argument pack");
824
Douglas Gregor1aee05d2011-01-15 06:45:20 +0000825 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregord3731192011-01-10 07:32:04 +0000826 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000827 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
828 }
829
830 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000831 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000832 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000833 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000834 }
Mike Stump1eb44332009-09-09 15:08:12 +0000835
Douglas Gregor788cd062009-11-11 01:00:40 +0000836 // Fall through to find the instantiated declaration for this template
837 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000838 }
Mike Stump1eb44332009-09-09 15:08:12 +0000839
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000840 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000841}
842
Douglas Gregoraac571c2010-03-01 17:25:41 +0000843Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000844 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000845 if (!Inst)
846 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000847
Douglas Gregor43959a92009-08-20 07:17:43 +0000848 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
849 return Inst;
850}
851
Douglas Gregor6cd21982009-10-20 05:58:46 +0000852NamedDecl *
853TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
854 SourceLocation Loc) {
855 // If the first part of the nested-name-specifier was a template type
856 // parameter, instantiate that type parameter down to a tag type.
857 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
858 const TemplateTypeParmType *TTP
859 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000860
Douglas Gregor6cd21982009-10-20 05:58:46 +0000861 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000862 // FIXME: This needs testing w/ member access expressions.
863 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
864
865 if (TTP->isParameterPack()) {
866 assert(Arg.getKind() == TemplateArgument::Pack &&
867 "Missing argument pack");
868
Douglas Gregor2be29f42011-01-14 23:41:42 +0000869 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000870 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000871
Douglas Gregord3731192011-01-10 07:32:04 +0000872 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor984a58b2010-12-20 22:48:17 +0000873 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
874 }
875
876 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000877 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000878 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000879
880 if (const TagType *Tag = T->getAs<TagType>())
881 return Tag->getDecl();
882
883 // The resulting type is not a tag; complain.
884 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
885 return 0;
886 }
887 }
888
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000889 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000890}
891
Douglas Gregor43959a92009-08-20 07:17:43 +0000892VarDecl *
893TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000894 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000895 SourceLocation StartLoc,
896 SourceLocation NameLoc,
897 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000898 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000899 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000900 if (Var)
901 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
902 return Var;
903}
904
905VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
906 TypeSourceInfo *TSInfo,
907 QualType T) {
908 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
909 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000910 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
911 return Var;
912}
913
John McCallc4e70192009-09-11 04:59:25 +0000914QualType
John McCall21e413f2010-11-04 19:04:38 +0000915TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
916 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000917 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000918 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +0000919 if (const TagType *TT = T->getAs<TagType>()) {
920 TagDecl* TD = TT->getDecl();
921
John McCall21e413f2010-11-04 19:04:38 +0000922 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +0000923
924 // FIXME: type might be anonymous.
925 IdentifierInfo *Id = TD->getIdentifier();
926
927 // TODO: should we even warn on struct/class mismatches for this? Seems
928 // like it's likely to produce a lot of spurious errors.
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000929 if (Keyword != ETK_None && Keyword != ETK_Typename) {
930 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +0000931 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
932 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000933 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
934 << Id
935 << FixItHint::CreateReplacement(SourceRange(TagLocation),
936 TD->getKindName());
937 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
938 }
John McCallc4e70192009-09-11 04:59:25 +0000939 }
940 }
941
John McCall21e413f2010-11-04 19:04:38 +0000942 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
943 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000944 QualifierLoc,
945 T);
John McCallc4e70192009-09-11 04:59:25 +0000946}
947
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000948TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
949 TemplateName Name,
950 SourceLocation NameLoc,
951 QualType ObjectType,
952 NamedDecl *FirstQualifierInScope) {
953 if (TemplateTemplateParmDecl *TTP
954 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
955 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
956 // If the corresponding template argument is NULL or non-existent, it's
957 // because we are performing instantiation from explicitly-specified
958 // template arguments in a function template, but there were some
959 // arguments left unspecified.
960 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
961 TTP->getPosition()))
962 return Name;
963
964 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
965
966 if (TTP->isParameterPack()) {
967 assert(Arg.getKind() == TemplateArgument::Pack &&
968 "Missing argument pack");
969
970 if (getSema().ArgumentPackSubstitutionIndex == -1) {
971 // We have the template argument pack to substitute, but we're not
972 // actually expanding the enclosing pack expansion yet. So, just
973 // keep the entire argument pack.
974 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
975 }
976
977 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
978 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
979 }
980
981 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +0000982 assert(!Template.isNull() && "Null template template argument");
Douglas Gregor58750382011-03-05 20:06:51 +0000983
984 // We don't ever want to substitute for a qualified template name, since
985 // the qualifier is handled separately. So, look through the qualified
986 // template name to its underlying declaration.
987 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
988 Template = TemplateName(QTN->getTemplateDecl());
989
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000990 return Template;
991 }
992 }
993
994 if (SubstTemplateTemplateParmPackStorage *SubstPack
995 = Name.getAsSubstTemplateTemplateParmPack()) {
996 if (getSema().ArgumentPackSubstitutionIndex == -1)
997 return Name;
998
999 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1000 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1001 "Pack substitution index out-of-range");
1002 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1003 .getAsTemplate();
1004 }
1005
1006 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1007 FirstQualifierInScope);
1008}
1009
John McCall60d7b3a2010-08-24 06:29:42 +00001010ExprResult
John McCall454feb92009-12-08 09:21:05 +00001011TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001012 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001013 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001014
1015 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1016 assert(currentDecl && "Must have current function declaration when "
1017 "instantiating.");
1018
1019 PredefinedExpr::IdentType IT = E->getIdentType();
1020
Anders Carlsson848fa642010-02-11 18:20:28 +00001021 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001022
1023 llvm::APInt LengthI(32, Length + 1);
John McCall0953e762009-09-24 19:53:00 +00001024 QualType ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001025 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1026 ArrayType::Normal, 0);
1027 PredefinedExpr *PE =
1028 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1029 return getSema().Owned(PE);
1030}
1031
John McCall60d7b3a2010-08-24 06:29:42 +00001032ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001033TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001034 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001035 // 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(NTTP->getDepth(),
1040 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001041 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001042
Douglas Gregor56bc9832010-12-24 00:15:10 +00001043 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1044 if (NTTP->isParameterPack()) {
1045 assert(Arg.getKind() == TemplateArgument::Pack &&
1046 "Missing argument pack");
1047
1048 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001049 // We have an argument pack, but we can't select a particular argument
1050 // out of it yet. Therefore, we'll build an expression to hold on to that
1051 // argument pack.
1052 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1053 E->getLocation(),
1054 NTTP->getDeclName());
1055 if (TargetType.isNull())
1056 return ExprError();
1057
1058 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1059 NTTP,
1060 E->getLocation(),
1061 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001062 }
1063
Douglas Gregord3731192011-01-10 07:32:04 +00001064 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor56bc9832010-12-24 00:15:10 +00001065 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1066 }
Mike Stump1eb44332009-09-09 15:08:12 +00001067
John McCallb8fc0532010-02-06 08:42:39 +00001068 // The template argument itself might be an expression, in which
1069 // case we just return that expression.
1070 if (Arg.getKind() == TemplateArgument::Expression)
John McCall3fa5cae2010-10-26 07:05:15 +00001071 return SemaRef.Owned(Arg.getAsExpr());
Mike Stump1eb44332009-09-09 15:08:12 +00001072
John McCallb8fc0532010-02-06 08:42:39 +00001073 if (Arg.getKind() == TemplateArgument::Declaration) {
1074 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001075
John McCall645cf442010-02-06 10:23:53 +00001076 // Find the instantiation of the template argument. This is
1077 // required for nested templates.
John McCallb8fc0532010-02-06 08:42:39 +00001078 VD = cast_or_null<ValueDecl>(
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001079 getSema().FindInstantiatedDecl(E->getLocation(),
1080 VD, TemplateArgs));
John McCallb8fc0532010-02-06 08:42:39 +00001081 if (!VD)
John McCallf312b1e2010-08-26 23:41:50 +00001082 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001083
John McCall645cf442010-02-06 10:23:53 +00001084 // Derive the type we want the substituted decl to have. This had
1085 // better be non-dependent, or these checks will have serious problems.
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001086 QualType TargetType;
1087 if (NTTP->isExpandedParameterPack())
1088 TargetType = NTTP->getExpansionType(
1089 getSema().ArgumentPackSubstitutionIndex);
1090 else if (NTTP->isParameterPack() &&
1091 isa<PackExpansionType>(NTTP->getType())) {
1092 TargetType = SemaRef.SubstType(
1093 cast<PackExpansionType>(NTTP->getType())->getPattern(),
1094 TemplateArgs, E->getLocation(),
1095 NTTP->getDeclName());
1096 } else
1097 TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1098 E->getLocation(), NTTP->getDeclName());
John McCall645cf442010-02-06 10:23:53 +00001099 assert(!TargetType.isNull() && "type substitution failed for param type");
1100 assert(!TargetType->isDependentType() && "param type still dependent");
Douglas Gregor02024a92010-03-28 02:42:43 +00001101 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg,
1102 TargetType,
1103 E->getLocation());
John McCallb8fc0532010-02-06 08:42:39 +00001104 }
1105
Douglas Gregor02024a92010-03-28 02:42:43 +00001106 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1107 E->getSourceRange().getBegin());
John McCallb8fc0532010-02-06 08:42:39 +00001108}
1109
Douglas Gregorc7793c72011-01-15 01:15:58 +00001110ExprResult
1111TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1112 SubstNonTypeTemplateParmPackExpr *E) {
1113 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1114 // We aren't expanding the parameter pack, so just return ourselves.
1115 return getSema().Owned(E);
1116 }
1117
Douglas Gregorc7793c72011-01-15 01:15:58 +00001118 const TemplateArgument &ArgPack = E->getArgumentPack();
1119 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1120 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1121
1122 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
1123 if (Arg.getKind() == TemplateArgument::Expression)
1124 return SemaRef.Owned(Arg.getAsExpr());
1125
1126 if (Arg.getKind() == TemplateArgument::Declaration) {
1127 ValueDecl *VD = cast<ValueDecl>(Arg.getAsDecl());
1128
1129 // Find the instantiation of the template argument. This is
1130 // required for nested templates.
1131 VD = cast_or_null<ValueDecl>(
1132 getSema().FindInstantiatedDecl(E->getParameterPackLocation(),
1133 VD, TemplateArgs));
1134 if (!VD)
1135 return ExprError();
1136
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001137 QualType T;
1138 NonTypeTemplateParmDecl *NTTP = E->getParameterPack();
1139 if (NTTP->isExpandedParameterPack())
1140 T = NTTP->getExpansionType(getSema().ArgumentPackSubstitutionIndex);
1141 else if (const PackExpansionType *Expansion
1142 = dyn_cast<PackExpansionType>(NTTP->getType()))
1143 T = SemaRef.SubstType(Expansion->getPattern(), TemplateArgs,
1144 E->getParameterPackLocation(), NTTP->getDeclName());
1145 else
1146 T = E->getType();
1147 return SemaRef.BuildExpressionFromDeclTemplateArgument(Arg, T,
Douglas Gregorc7793c72011-01-15 01:15:58 +00001148 E->getParameterPackLocation());
1149 }
1150
1151 return SemaRef.BuildExpressionFromIntegralTemplateArgument(Arg,
1152 E->getParameterPackLocation());
1153}
John McCallb8fc0532010-02-06 08:42:39 +00001154
John McCall60d7b3a2010-08-24 06:29:42 +00001155ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001156TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1157 NamedDecl *D = E->getDecl();
1158 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1159 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1160 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001161
1162 // We have a non-type template parameter that isn't fully substituted;
1163 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001164 }
Mike Stump1eb44332009-09-09 15:08:12 +00001165
John McCall454feb92009-12-08 09:21:05 +00001166 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001167}
1168
John McCall60d7b3a2010-08-24 06:29:42 +00001169ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001170 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001171 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1172 getDescribedFunctionTemplate() &&
1173 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001174 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1175 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1176 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001177}
1178
Douglas Gregor895162d2010-04-30 18:55:50 +00001179QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001180 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001181 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001182 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001183 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001184}
1185
1186ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001187TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001188 int indexAdjustment,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001189 llvm::Optional<unsigned> NumExpansions) {
John McCallfb44de92011-05-01 22:35:37 +00001190 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001191 NumExpansions);
John McCall21ef0fa2010-03-11 09:03:00 +00001192}
1193
Mike Stump1eb44332009-09-09 15:08:12 +00001194QualType
John McCalla2becad2009-10-21 00:40:46 +00001195TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001196 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001197 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001198 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001199 // Replace the template type parameter with its corresponding
1200 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001201
1202 // If the corresponding template argument is NULL or doesn't exist, it's
1203 // because we are performing instantiation from explicitly-specified
1204 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001205 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001206 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1207 TemplateTypeParmTypeLoc NewTL
1208 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1209 NewTL.setNameLoc(TL.getNameLoc());
1210 return TL.getType();
1211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001213 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1214
1215 if (T->isParameterPack()) {
1216 assert(Arg.getKind() == TemplateArgument::Pack &&
1217 "Missing argument pack");
1218
1219 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001220 // We have the template argument pack, but we're not expanding the
1221 // enclosing pack expansion yet. Just save the template argument
1222 // pack for later substitution.
1223 QualType Result
1224 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1225 SubstTemplateTypeParmPackTypeLoc NewTL
1226 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1227 NewTL.setNameLoc(TL.getNameLoc());
1228 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001229 }
1230
Douglas Gregord3731192011-01-10 07:32:04 +00001231 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001232 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1233 }
1234
1235 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001236 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001237
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001238 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001239
1240 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001241 QualType Result
1242 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1243 SubstTemplateTypeParmTypeLoc NewTL
1244 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1245 NewTL.setNameLoc(TL.getNameLoc());
1246 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001247 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001248
1249 // The template type parameter comes from an inner template (e.g.,
1250 // the template parameter list of a member template inside the
1251 // template we are instantiating). Create a new template type
1252 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001253 TemplateTypeParmDecl *NewTTPDecl = 0;
1254 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1255 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1256 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1257
John McCalla2becad2009-10-21 00:40:46 +00001258 QualType Result
1259 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1260 - TemplateArgs.getNumLevels(),
1261 T->getIndex(),
1262 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001263 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001264 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1265 NewTL.setNameLoc(TL.getNameLoc());
1266 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001267}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001268
Douglas Gregorc3069d62011-01-14 02:55:32 +00001269QualType
1270TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1271 TypeLocBuilder &TLB,
1272 SubstTemplateTypeParmPackTypeLoc TL) {
1273 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1274 // We aren't expanding the parameter pack, so just return ourselves.
1275 SubstTemplateTypeParmPackTypeLoc NewTL
1276 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1277 NewTL.setNameLoc(TL.getNameLoc());
1278 return TL.getType();
1279 }
1280
1281 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1282 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1283 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1284
1285 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1286 Result = getSema().Context.getSubstTemplateTypeParmType(
1287 TL.getTypePtr()->getReplacedParameter(),
1288 Result);
1289 SubstTemplateTypeParmTypeLoc NewTL
1290 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1291 NewTL.setNameLoc(TL.getNameLoc());
1292 return Result;
1293}
1294
John McCallce3ff2b2009-08-25 22:02:44 +00001295/// \brief Perform substitution on the type T with a given set of template
1296/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001297///
1298/// This routine substitutes the given template arguments into the
1299/// type T and produces the instantiated type.
1300///
1301/// \param T the type into which the template arguments will be
1302/// substituted. If this type is not dependent, it will be returned
1303/// immediately.
1304///
1305/// \param TemplateArgs the template arguments that will be
1306/// substituted for the top-level template parameters within T.
1307///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001308/// \param Loc the location in the source code where this substitution
1309/// is being performed. It will typically be the location of the
1310/// declarator (if we're instantiating the type of some declaration)
1311/// or the location of the type in the source code (if, e.g., we're
1312/// instantiating the type of a cast expression).
1313///
1314/// \param Entity the name of the entity associated with a declaration
1315/// being instantiated (if any). May be empty to indicate that there
1316/// is no such entity (if, e.g., this is a type that occurs as part of
1317/// a cast expression) or that the entity has no name (e.g., an
1318/// unnamed function parameter).
1319///
1320/// \returns If the instantiation succeeds, the instantiated
1321/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001322TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001323 const MultiLevelTemplateArgumentList &Args,
1324 SourceLocation Loc,
1325 DeclarationName Entity) {
1326 assert(!ActiveTemplateInstantiations.empty() &&
1327 "Cannot perform an instantiation without some context on the "
1328 "instantiation stack");
1329
Douglas Gregor836adf62010-05-24 17:22:01 +00001330 if (!T->getType()->isDependentType() &&
1331 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001332 return T;
1333
1334 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1335 return Instantiator.TransformType(T);
1336}
1337
Douglas Gregor603cfb42011-01-05 23:12:31 +00001338TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1339 const MultiLevelTemplateArgumentList &Args,
1340 SourceLocation Loc,
1341 DeclarationName Entity) {
1342 assert(!ActiveTemplateInstantiations.empty() &&
1343 "Cannot perform an instantiation without some context on the "
1344 "instantiation stack");
1345
1346 if (TL.getType().isNull())
1347 return 0;
1348
1349 if (!TL.getType()->isDependentType() &&
1350 !TL.getType()->isVariablyModifiedType()) {
1351 // FIXME: Make a copy of the TypeLoc data here, so that we can
1352 // return a new TypeSourceInfo. Inefficient!
1353 TypeLocBuilder TLB;
1354 TLB.pushFullCopy(TL);
1355 return TLB.getTypeSourceInfo(Context, TL.getType());
1356 }
1357
1358 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1359 TypeLocBuilder TLB;
1360 TLB.reserve(TL.getFullDataSize());
1361 QualType Result = Instantiator.TransformType(TLB, TL);
1362 if (Result.isNull())
1363 return 0;
1364
1365 return TLB.getTypeSourceInfo(Context, Result);
1366}
1367
John McCallcd7ba1c2009-10-21 00:58:09 +00001368/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001369QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001370 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001371 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001372 assert(!ActiveTemplateInstantiations.empty() &&
1373 "Cannot perform an instantiation without some context on the "
1374 "instantiation stack");
1375
Douglas Gregor836adf62010-05-24 17:22:01 +00001376 // If T is not a dependent type or a variably-modified type, there
1377 // is nothing to do.
1378 if (!T->isDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001379 return T;
1380
Douglas Gregor577f75a2009-08-04 16:50:30 +00001381 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1382 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001383}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001384
John McCall6cd3b9f2010-04-09 17:38:44 +00001385static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor836adf62010-05-24 17:22:01 +00001386 if (T->getType()->isDependentType() || T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001387 return true;
1388
Abramo Bagnara723df242010-12-14 22:11:44 +00001389 TypeLoc TL = T->getTypeLoc().IgnoreParens();
John McCall6cd3b9f2010-04-09 17:38:44 +00001390 if (!isa<FunctionProtoTypeLoc>(TL))
1391 return false;
1392
1393 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1394 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1395 ParmVarDecl *P = FP.getArg(I);
1396
Douglas Gregorc056c172011-05-09 20:45:16 +00001397 // The parameter's type as written might be dependent even if the
1398 // decayed type was not dependent.
1399 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1400 if (TSInfo->getType()->isDependentType())
1401 return true;
1402
John McCall6cd3b9f2010-04-09 17:38:44 +00001403 // TODO: currently we always rebuild expressions. When we
1404 // properly get lazier about this, we should use the same
1405 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001406 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001407 return true;
1408 }
1409
1410 return false;
1411}
1412
1413/// A form of SubstType intended specifically for instantiating the
1414/// type of a FunctionDecl. Its purpose is solely to force the
1415/// instantiation of default-argument expressions.
1416TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1417 const MultiLevelTemplateArgumentList &Args,
1418 SourceLocation Loc,
1419 DeclarationName Entity) {
1420 assert(!ActiveTemplateInstantiations.empty() &&
1421 "Cannot perform an instantiation without some context on the "
1422 "instantiation stack");
1423
1424 if (!NeedsInstantiationAsFunctionType(T))
1425 return T;
1426
1427 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1428
1429 TypeLocBuilder TLB;
1430
1431 TypeLoc TL = T->getTypeLoc();
1432 TLB.reserve(TL.getFullDataSize());
1433
John McCall43fed0d2010-11-12 08:19:04 +00001434 QualType Result = Instantiator.TransformType(TLB, TL);
John McCall6cd3b9f2010-04-09 17:38:44 +00001435 if (Result.isNull())
1436 return 0;
1437
1438 return TLB.getTypeSourceInfo(Context, Result);
1439}
1440
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001441ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001442 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001443 int indexAdjustment,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001444 llvm::Optional<unsigned> NumExpansions) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001445 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001446 TypeSourceInfo *NewDI = 0;
1447
Douglas Gregor603cfb42011-01-05 23:12:31 +00001448 TypeLoc OldTL = OldDI->getTypeLoc();
1449 if (isa<PackExpansionTypeLoc>(OldTL)) {
1450 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
Douglas Gregor603cfb42011-01-05 23:12:31 +00001451
1452 // We have a function parameter pack. Substitute into the pattern of the
1453 // expansion.
1454 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1455 OldParm->getLocation(), OldParm->getDeclName());
1456 if (!NewDI)
1457 return 0;
1458
1459 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1460 // We still have unexpanded parameter packs, which means that
1461 // our function parameter is still a function parameter pack.
1462 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001463 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001464 NumExpansions);
Douglas Gregor603cfb42011-01-05 23:12:31 +00001465 }
1466 } else {
1467 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1468 OldParm->getDeclName());
1469 }
1470
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001471 if (!NewDI)
1472 return 0;
1473
1474 if (NewDI->getType()->isVoidType()) {
1475 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1476 return 0;
1477 }
1478
1479 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001480 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001481 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001482 OldParm->getIdentifier(),
1483 NewDI->getType(), NewDI,
Douglas Gregor16573fa2010-04-19 22:54:31 +00001484 OldParm->getStorageClass(),
1485 OldParm->getStorageClassAsWritten());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001486 if (!NewParm)
1487 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001488
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001489 // Mark the (new) default argument as uninstantiated (if any).
1490 if (OldParm->hasUninstantiatedDefaultArg()) {
1491 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1492 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001493 } else if (OldParm->hasUnparsedDefaultArg()) {
1494 NewParm->setUnparsedDefaultArg();
1495 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001496 } else if (Expr *Arg = OldParm->getDefaultArg())
1497 NewParm->setUninstantiatedDefaultArg(Arg);
1498
1499 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1500
Douglas Gregor603cfb42011-01-05 23:12:31 +00001501 // FIXME: When OldParm is a parameter pack and NewParm is not a parameter
1502 // pack, we actually have a set of instantiated locations. Maintain this set!
Douglas Gregor12c9c002011-01-07 16:43:16 +00001503 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1504 // Add the new parameter to
1505 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1506 } else {
1507 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001508 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001509 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001510
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001511 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1512 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001513 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001514
1515 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1516 OldParm->getFunctionScopeIndex() + indexAdjustment);
Fariborz Jahaniane7ffbe22010-07-13 20:05:58 +00001517
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001518 return NewParm;
1519}
1520
Douglas Gregora009b592011-01-07 00:20:55 +00001521/// \brief Substitute the given template arguments into the given set of
1522/// parameters, producing the set of parameter types that would be generated
1523/// from such a substitution.
1524bool Sema::SubstParmTypes(SourceLocation Loc,
1525 ParmVarDecl **Params, unsigned NumParams,
1526 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001527 llvm::SmallVectorImpl<QualType> &ParamTypes,
1528 llvm::SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001529 assert(!ActiveTemplateInstantiations.empty() &&
1530 "Cannot perform an instantiation without some context on the "
1531 "instantiation stack");
1532
1533 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1534 DeclarationName());
1535 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001536 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001537}
1538
John McCallce3ff2b2009-08-25 22:02:44 +00001539/// \brief Perform substitution on the base class specifiers of the
1540/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001541///
1542/// Produces a diagnostic and returns true on error, returns false and
1543/// attaches the instantiated base classes to the class template
1544/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001545bool
John McCallce3ff2b2009-08-25 22:02:44 +00001546Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1547 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001548 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001549 bool Invalid = false;
Douglas Gregor0ca20ac2009-05-29 18:27:38 +00001550 llvm::SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001551 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001552 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001553 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001554 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001555 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001556 continue;
1557 }
1558
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001559 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001560 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001561 if (Base->isPackExpansion()) {
1562 // This is a pack expansion. See whether we should expand it now, or
1563 // wait until later.
1564 llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1565 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1566 Unexpanded);
1567 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001568 bool RetainExpansion = false;
Douglas Gregorcded4f62011-01-14 17:04:44 +00001569 llvm::Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001570 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1571 Base->getSourceRange(),
1572 Unexpanded.data(), Unexpanded.size(),
1573 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001574 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001575 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001576 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001577 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001578 }
1579
1580 // If we should expand this pack expansion now, do so.
1581 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001582 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001583 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1584
1585 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1586 TemplateArgs,
1587 Base->getSourceRange().getBegin(),
1588 DeclarationName());
1589 if (!BaseTypeLoc) {
1590 Invalid = true;
1591 continue;
1592 }
1593
1594 if (CXXBaseSpecifier *InstantiatedBase
1595 = CheckBaseSpecifier(Instantiation,
1596 Base->getSourceRange(),
1597 Base->isVirtual(),
1598 Base->getAccessSpecifierAsWritten(),
1599 BaseTypeLoc,
1600 SourceLocation()))
1601 InstantiatedBases.push_back(InstantiatedBase);
1602 else
1603 Invalid = true;
1604 }
1605
1606 continue;
1607 }
1608
1609 // The resulting base specifier will (still) be a pack expansion.
1610 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001611 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1612 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1613 TemplateArgs,
1614 Base->getSourceRange().getBegin(),
1615 DeclarationName());
1616 } else {
1617 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1618 TemplateArgs,
1619 Base->getSourceRange().getBegin(),
1620 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001621 }
1622
Nick Lewycky56062202010-07-26 16:56:01 +00001623 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001624 Invalid = true;
1625 continue;
1626 }
1627
1628 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001629 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001630 Base->getSourceRange(),
1631 Base->isVirtual(),
1632 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001633 BaseTypeLoc,
1634 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001635 InstantiatedBases.push_back(InstantiatedBase);
1636 else
1637 Invalid = true;
1638 }
1639
Douglas Gregor27b152f2009-03-10 18:52:44 +00001640 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001641 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001642 InstantiatedBases.size()))
1643 Invalid = true;
1644
1645 return Invalid;
1646}
1647
Douglas Gregord475b8d2009-03-25 21:17:03 +00001648/// \brief Instantiate the definition of a class from a given pattern.
1649///
1650/// \param PointOfInstantiation The point of instantiation within the
1651/// source code.
1652///
1653/// \param Instantiation is the declaration whose definition is being
1654/// instantiated. This will be either a class template specialization
1655/// or a member class of a class template specialization.
1656///
1657/// \param Pattern is the pattern from which the instantiation
1658/// occurs. This will be either the declaration of a class template or
1659/// the declaration of a member class of a class template.
1660///
1661/// \param TemplateArgs The template arguments to be substituted into
1662/// the pattern.
1663///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001664/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001665///
1666/// \param Complain whether to complain if the class cannot be instantiated due
1667/// to the lack of a definition.
1668///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001669/// \returns true if an error occurred, false otherwise.
1670bool
1671Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1672 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001673 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001674 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001675 bool Complain) {
Douglas Gregord475b8d2009-03-25 21:17:03 +00001676 bool Invalid = false;
John McCalle29ba202009-08-20 01:44:21 +00001677
Mike Stump1eb44332009-09-09 15:08:12 +00001678 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001679 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
John McCalld46a1122011-04-27 06:46:31 +00001680 if (!PatternDef || PatternDef->isBeingDefined()) {
1681 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001682 // Say nothing
John McCalld46a1122011-04-27 06:46:31 +00001683 } else if (PatternDef) {
1684 assert(PatternDef->isBeingDefined());
1685 Diag(PointOfInstantiation,
1686 diag::err_template_instantiate_within_definition)
1687 << (TSK != TSK_ImplicitInstantiation)
1688 << Context.getTypeDeclType(Instantiation);
1689 // Not much point in noting the template declaration here, since
1690 // we're lexically inside it.
1691 Instantiation->setInvalidDecl();
Douglas Gregor5842ba92009-08-24 15:23:48 +00001692 } else if (Pattern == Instantiation->getInstantiatedFromMemberClass()) {
Douglas Gregord475b8d2009-03-25 21:17:03 +00001693 Diag(PointOfInstantiation,
1694 diag::err_implicit_instantiate_member_undefined)
1695 << Context.getTypeDeclType(Instantiation);
1696 Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1697 } else {
Douglas Gregor93dfdb12009-05-13 00:25:59 +00001698 Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001699 << (TSK != TSK_ImplicitInstantiation)
Douglas Gregord475b8d2009-03-25 21:17:03 +00001700 << Context.getTypeDeclType(Instantiation);
1701 Diag(Pattern->getLocation(), diag::note_template_decl_here);
1702 }
1703 return true;
1704 }
1705 Pattern = PatternDef;
1706
Douglas Gregor454885e2009-10-15 15:54:05 +00001707 // \brief Record the point of instantiation.
1708 if (MemberSpecializationInfo *MSInfo
1709 = Instantiation->getMemberSpecializationInfo()) {
1710 MSInfo->setTemplateSpecializationKind(TSK);
1711 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001712 } else if (ClassTemplateSpecializationDecl *Spec
1713 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1714 Spec->setTemplateSpecializationKind(TSK);
1715 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001716 }
1717
Douglas Gregord048bb72009-03-25 21:23:52 +00001718 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001719 if (Inst)
1720 return true;
1721
1722 // Enter the scope of this instantiation. We don't use
1723 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001724 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001725 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001726 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001727
Douglas Gregor05030bb2010-03-24 01:33:17 +00001728 // If this is an instantiation of a local class, merge this local
1729 // instantiation scope with the enclosing scope. Otherwise, every
1730 // instantiation of a class has its own local instantiation scope.
1731 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001732 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001733
John McCall1d8d1cc2010-08-01 02:01:53 +00001734 // Pull attributes from the pattern onto the instantiation.
1735 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1736
Douglas Gregord475b8d2009-03-25 21:17:03 +00001737 // Start the definition of this instantiation.
1738 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001739
1740 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001741
John McCallce3ff2b2009-08-25 22:02:44 +00001742 // Do substitution on the base class specifiers.
1743 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001744 Invalid = true;
1745
Douglas Gregord65587f2010-11-10 19:44:59 +00001746 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
John McCalld226f652010-08-21 09:40:31 +00001747 llvm::SmallVector<Decl*, 4> Fields;
Richard Smith7a614d82011-06-11 17:19:42 +00001748 llvm::SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
1749 FieldsWithMemberInitializers;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001750 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001751 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001752 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001753 // Don't instantiate members not belonging in this semantic context.
1754 // e.g. for:
1755 // @code
1756 // template <int i> class A {
1757 // class B *g;
1758 // };
1759 // @endcode
1760 // 'class B' has the template as lexical context but semantically it is
1761 // introduced in namespace scope.
1762 if ((*Member)->getDeclContext() != Pattern)
1763 continue;
1764
Douglas Gregord65587f2010-11-10 19:44:59 +00001765 if ((*Member)->isInvalidDecl()) {
1766 Invalid = true;
1767 continue;
1768 }
1769
1770 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001771 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00001772 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00001773 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00001774 FieldDecl *OldField = cast<FieldDecl>(*Member);
1775 if (OldField->getInClassInitializer())
1776 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1777 Field));
1778 } else if (NewMember->isInvalidDecl())
Eli Friedman721e77d2009-12-07 00:22:08 +00001779 Invalid = true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001780 } else {
1781 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump390b4cc2009-05-16 07:39:55 +00001782 // instantiations was a semantic disaster, and we'll want to set Invalid =
1783 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00001784 }
1785 }
1786
1787 // Finish checking fields.
John McCalld226f652010-08-21 09:40:31 +00001788 ActOnFields(0, Instantiation->getLocation(), Instantiation,
Jay Foadbeaaccd2009-05-21 09:52:38 +00001789 Fields.data(), Fields.size(), SourceLocation(), SourceLocation(),
Douglas Gregord475b8d2009-03-25 21:17:03 +00001790 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00001791 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00001792
1793 // Attach any in-class member initializers now the class is complete.
1794 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
1795 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
1796 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
1797 Expr *OldInit = OldField->getInClassInitializer();
1798 ExprResult NewInit = SubstExpr(OldInit, TemplateArgs);
1799
1800 // If the initialization is no longer dependent, check it now.
1801 if ((OldField->getType()->isDependentType() || OldInit->isTypeDependent())
1802 && !NewField->getType()->isDependentType()
1803 && !NewInit.get()->isTypeDependent()) {
1804 // FIXME: handle list-initialization
1805 SourceLocation EqualLoc = NewField->getLocation();
1806 NewInit = PerformCopyInitialization(
1807 InitializedEntity::InitializeMember(NewField), EqualLoc,
1808 NewInit.release());
1809
1810 if (!NewInit.isInvalid()) {
1811 CheckImplicitConversions(NewInit.get(), EqualLoc);
1812
1813 // C++0x [class.base.init]p7:
1814 // The initialization of each base and member constitutes a
1815 // full-expression.
1816 NewInit = MaybeCreateExprWithCleanups(NewInit);
1817 }
1818 }
1819
1820 if (NewInit.isInvalid())
1821 NewField->setInvalidDecl();
1822 else
1823 NewField->setInClassInitializer(NewInit.release());
1824 }
1825
1826 if (!FieldsWithMemberInitializers.empty())
1827 ActOnFinishDelayedMemberInitializers(Instantiation);
1828
Douglas Gregor663b5a02009-10-14 20:14:33 +00001829 if (Instantiation->isInvalidDecl())
1830 Invalid = true;
Douglas Gregord65587f2010-11-10 19:44:59 +00001831 else {
1832 // Instantiate any out-of-line class template partial
1833 // specializations now.
1834 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1835 P = Instantiator.delayed_partial_spec_begin(),
1836 PEnd = Instantiator.delayed_partial_spec_end();
1837 P != PEnd; ++P) {
1838 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1839 P->first,
1840 P->second)) {
1841 Invalid = true;
1842 break;
1843 }
1844 }
1845 }
1846
Douglas Gregord475b8d2009-03-25 21:17:03 +00001847 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00001848 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001849
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001850 if (!Invalid) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00001851 Consumer.HandleTagDeclDefinition(Instantiation);
1852
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001853 // Always emit the vtable for an explicit instantiation definition
1854 // of a polymorphic class template specialization.
1855 if (TSK == TSK_ExplicitInstantiationDefinition)
1856 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1857 }
1858
Douglas Gregord475b8d2009-03-25 21:17:03 +00001859 return Invalid;
1860}
1861
Douglas Gregor9b623632010-10-12 23:32:35 +00001862namespace {
1863 /// \brief A partial specialization whose template arguments have matched
1864 /// a given template-id.
1865 struct PartialSpecMatchResult {
1866 ClassTemplatePartialSpecializationDecl *Partial;
1867 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00001868 };
1869}
1870
Mike Stump1eb44332009-09-09 15:08:12 +00001871bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00001872Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001873 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001874 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001875 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001876 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001877 // Perform the actual instantiation on the canonical declaration.
1878 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00001879 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00001880
Douglas Gregor52604ab2009-09-11 21:19:12 +00001881 // Check whether we have already instantiated or specialized this class
1882 // template specialization.
1883 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
1884 if (ClassTemplateSpec->getSpecializationKind() ==
1885 TSK_ExplicitInstantiationDeclaration &&
1886 TSK == TSK_ExplicitInstantiationDefinition) {
1887 // An explicit instantiation definition follows an explicit instantiation
1888 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
1889 // explicit instantiation.
1890 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001891
1892 // If this is an explicit instantiation definition, mark the
1893 // vtable as used.
1894 if (TSK == TSK_ExplicitInstantiationDefinition)
1895 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
1896
Douglas Gregor52604ab2009-09-11 21:19:12 +00001897 return false;
1898 }
1899
1900 // We can only instantiate something that hasn't already been
1901 // instantiated or specialized. Fail without any diagnostics: our
1902 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001903 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00001904 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00001905
Douglas Gregor9eea08b2009-09-15 16:51:42 +00001906 if (ClassTemplateSpec->isInvalidDecl())
1907 return true;
1908
Douglas Gregor2943aed2009-03-03 04:44:36 +00001909 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001910 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00001911
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00001912 // C++ [temp.class.spec.match]p1:
1913 // When a class template is used in a context that requires an
1914 // instantiation of the class, it is necessary to determine
1915 // whether the instantiation is to be generated using the primary
1916 // template or one of the partial specializations. This is done by
1917 // matching the template arguments of the class template
1918 // specialization with the template argument lists of the partial
1919 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00001920 typedef PartialSpecMatchResult MatchResult;
Douglas Gregor199d9912009-06-05 00:53:49 +00001921 llvm::SmallVector<MatchResult, 4> Matched;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001922 llvm::SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1923 Template->getPartialSpecializations(PartialSpecs);
1924 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
1925 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
John McCall5769d612010-02-08 23:07:23 +00001926 TemplateDeductionInfo Info(Context, PointOfInstantiation);
Douglas Gregorf67875d2009-06-12 18:26:56 +00001927 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00001928 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00001929 ClassTemplateSpec->getTemplateArgs(),
1930 Info)) {
1931 // FIXME: Store the failed-deduction information for use in
1932 // diagnostics, later.
1933 (void)Result;
1934 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00001935 Matched.push_back(PartialSpecMatchResult());
1936 Matched.back().Partial = Partial;
1937 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00001938 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00001939 }
1940
Douglas Gregor6952f1e2011-01-19 20:10:05 +00001941 // If we're dealing with a member template where the template parameters
1942 // have been instantiated, this provides the original template parameters
1943 // from which the member template's parameters were instantiated.
1944 llvm::SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
1945
Douglas Gregored9c0f92009-10-29 00:04:11 +00001946 if (Matched.size() >= 1) {
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001947 llvm::SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001948 if (Matched.size() == 1) {
1949 // -- If exactly one matching specialization is found, the
1950 // instantiation is generated from that specialization.
1951 // We don't need to do anything for this.
1952 } else {
1953 // -- If more than one matching specialization is found, the
1954 // partial order rules (14.5.4.2) are used to determine
1955 // whether one of the specializations is more specialized
1956 // than the others. If none of the specializations is more
1957 // specialized than all of the other matching
1958 // specializations, then the use of the class template is
1959 // ambiguous and the program is ill-formed.
1960 for (llvm::SmallVector<MatchResult, 4>::iterator P = Best + 1,
1961 PEnd = Matched.end();
1962 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00001963 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00001964 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00001965 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00001966 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001967 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001968
Douglas Gregored9c0f92009-10-29 00:04:11 +00001969 // Determine if the best partial specialization is more specialized than
1970 // the others.
1971 bool Ambiguous = false;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00001972 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1973 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00001974 P != PEnd; ++P) {
1975 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00001976 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00001977 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00001978 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00001979 Ambiguous = true;
1980 break;
1981 }
1982 }
1983
1984 if (Ambiguous) {
1985 // Partial ordering did not produce a clear winner. Complain.
1986 ClassTemplateSpec->setInvalidDecl();
1987 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
1988 << ClassTemplateSpec;
1989
1990 // Print the matching partial specializations.
1991 for (llvm::SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
1992 PEnd = Matched.end();
1993 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00001994 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
1995 << getTemplateArgumentBindingsText(
1996 P->Partial->getTemplateParameters(),
1997 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00001998
Douglas Gregored9c0f92009-10-29 00:04:11 +00001999 return true;
2000 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002001 }
2002
2003 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002004 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002005 while (OrigPartialSpec->getInstantiatedFromMember()) {
2006 // If we've found an explicit specialization of this class template,
2007 // stop here and use that as the pattern.
2008 if (OrigPartialSpec->isMemberSpecialization())
2009 break;
2010
2011 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2012 }
2013
2014 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002015 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002016 } else {
2017 // -- If no matches are found, the instantiation is generated
2018 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002019 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002020 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2021 // If we've found an explicit specialization of this class template,
2022 // stop here and use that as the pattern.
2023 if (OrigTemplate->isMemberSpecialization())
2024 break;
2025
Douglas Gregord6350ae2009-08-28 20:31:08 +00002026 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002027 }
2028
Douglas Gregord6350ae2009-08-28 20:31:08 +00002029 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002030 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002031
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002032 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2033 Pattern,
2034 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002035 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002036 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002037
Douglas Gregor199d9912009-06-05 00:53:49 +00002038 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002039}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002040
John McCallce3ff2b2009-08-25 22:02:44 +00002041/// \brief Instantiates the definitions of all of the member
2042/// of the given class, which is an instantiation of a class template
2043/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002044void
2045Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002046 CXXRecordDecl *Instantiation,
2047 const MultiLevelTemplateArgumentList &TemplateArgs,
2048 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002049 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2050 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002051 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002052 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002053 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002054 if (FunctionDecl *Pattern
2055 = Function->getInstantiatedFromMemberFunction()) {
2056 MemberSpecializationInfo *MSInfo
2057 = Function->getMemberSpecializationInfo();
2058 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002059 if (MSInfo->getTemplateSpecializationKind()
2060 == TSK_ExplicitSpecialization)
2061 continue;
2062
Douglas Gregor0d035142009-10-27 18:42:08 +00002063 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2064 Function,
2065 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002066 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002067 SuppressNew) ||
2068 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002069 continue;
2070
Sean Hunt10620eb2011-05-06 20:44:56 +00002071 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002072 continue;
2073
2074 if (TSK == TSK_ExplicitInstantiationDefinition) {
2075 // C++0x [temp.explicit]p8:
2076 // An explicit instantiation definition that names a class template
2077 // specialization explicitly instantiates the class template
2078 // specialization and is only an explicit instantiation definition
2079 // of members whose definition is visible at the point of
2080 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002081 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002082 continue;
2083
2084 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2085
2086 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2087 } else {
2088 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2089 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002090 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002091 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002092 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002093 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2094 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002095 if (MSInfo->getTemplateSpecializationKind()
2096 == TSK_ExplicitSpecialization)
2097 continue;
2098
Douglas Gregor0d035142009-10-27 18:42:08 +00002099 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2100 Var,
2101 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002102 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002103 SuppressNew) ||
2104 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002105 continue;
2106
Douglas Gregor0d035142009-10-27 18:42:08 +00002107 if (TSK == TSK_ExplicitInstantiationDefinition) {
2108 // C++0x [temp.explicit]p8:
2109 // An explicit instantiation definition that names a class template
2110 // specialization explicitly instantiates the class template
2111 // specialization and is only an explicit instantiation definition
2112 // of members whose definition is visible at the point of
2113 // instantiation.
2114 if (!Var->getInstantiatedFromStaticDataMember()
2115 ->getOutOfLineDefinition())
2116 continue;
2117
2118 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002119 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002120 } else {
2121 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2122 }
2123 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002124 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002125 // Always skip the injected-class-name, along with any
2126 // redeclarations of nested classes, since both would cause us
2127 // to try to instantiate the members of a class twice.
2128 if (Record->isInjectedClassName() || Record->getPreviousDeclaration())
Douglas Gregor2db32322009-10-07 23:56:10 +00002129 continue;
2130
Douglas Gregor0d035142009-10-27 18:42:08 +00002131 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2132 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002133
2134 if (MSInfo->getTemplateSpecializationKind()
2135 == TSK_ExplicitSpecialization)
2136 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002137
Douglas Gregor0d035142009-10-27 18:42:08 +00002138 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2139 Record,
2140 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002141 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002142 SuppressNew) ||
2143 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002144 continue;
2145
Douglas Gregor0d035142009-10-27 18:42:08 +00002146 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2147 assert(Pattern && "Missing instantiated-from-template information");
2148
Douglas Gregor952b0172010-02-11 01:04:33 +00002149 if (!Record->getDefinition()) {
2150 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002151 // C++0x [temp.explicit]p8:
2152 // An explicit instantiation definition that names a class template
2153 // specialization explicitly instantiates the class template
2154 // specialization and is only an explicit instantiation definition
2155 // of members whose definition is visible at the point of
2156 // instantiation.
2157 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2158 MSInfo->setTemplateSpecializationKind(TSK);
2159 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2160 }
2161
2162 continue;
2163 }
2164
2165 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002166 TemplateArgs,
2167 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002168 } else {
2169 if (TSK == TSK_ExplicitInstantiationDefinition &&
2170 Record->getTemplateSpecializationKind() ==
2171 TSK_ExplicitInstantiationDeclaration) {
2172 Record->setTemplateSpecializationKind(TSK);
2173 MarkVTableUsed(PointOfInstantiation, Record, true);
2174 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002175 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002176
Douglas Gregor952b0172010-02-11 01:04:33 +00002177 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002178 if (Pattern)
2179 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2180 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002181 }
2182 }
2183}
2184
2185/// \brief Instantiate the definitions of all of the members of the
2186/// given class template specialization, which was named as part of an
2187/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002188void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002189Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002190 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002191 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2192 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002193 // C++0x [temp.explicit]p7:
2194 // An explicit instantiation that names a class template
2195 // specialization is an explicit instantion of the same kind
2196 // (declaration or definition) of each of its members (not
2197 // including members inherited from base classes) that has not
2198 // been previously explicitly specialized in the translation unit
2199 // containing the explicit instantiation, except as described
2200 // below.
2201 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002202 getTemplateInstantiationArgs(ClassTemplateSpec),
2203 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002204}
2205
John McCall60d7b3a2010-08-24 06:29:42 +00002206StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002207Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002208 if (!S)
2209 return Owned(S);
2210
2211 TemplateInstantiator Instantiator(*this, TemplateArgs,
2212 SourceLocation(),
2213 DeclarationName());
2214 return Instantiator.TransformStmt(S);
2215}
2216
John McCall60d7b3a2010-08-24 06:29:42 +00002217ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002218Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002219 if (!E)
2220 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Douglas Gregorb98b1992009-08-11 05:31:07 +00002222 TemplateInstantiator Instantiator(*this, TemplateArgs,
2223 SourceLocation(),
2224 DeclarationName());
2225 return Instantiator.TransformExpr(E);
2226}
2227
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002228bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2229 const MultiLevelTemplateArgumentList &TemplateArgs,
2230 llvm::SmallVectorImpl<Expr *> &Outputs) {
2231 if (NumExprs == 0)
2232 return false;
2233
2234 TemplateInstantiator Instantiator(*this, TemplateArgs,
2235 SourceLocation(),
2236 DeclarationName());
2237 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2238}
2239
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002240NestedNameSpecifierLoc
2241Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2242 const MultiLevelTemplateArgumentList &TemplateArgs) {
2243 if (!NNS)
2244 return NestedNameSpecifierLoc();
2245
2246 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2247 DeclarationName());
2248 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2249}
2250
Abramo Bagnara25777432010-08-11 22:01:17 +00002251/// \brief Do template substitution on declaration name info.
2252DeclarationNameInfo
2253Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2254 const MultiLevelTemplateArgumentList &TemplateArgs) {
2255 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2256 NameInfo.getName());
2257 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2258}
2259
Douglas Gregorde650ae2009-03-31 18:38:02 +00002260TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002261Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2262 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002263 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002264 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2265 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002266 CXXScopeSpec SS;
2267 SS.Adopt(QualifierLoc);
2268 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002269}
Douglas Gregor91333002009-06-11 00:06:24 +00002270
Douglas Gregore02e2622010-12-22 21:19:48 +00002271bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2272 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002273 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002274 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2275 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002276
2277 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002278}
Douglas Gregor895162d2010-04-30 18:55:50 +00002279
Douglas Gregor12c9c002011-01-07 16:43:16 +00002280llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2281LocalInstantiationScope::findInstantiationOf(const Decl *D) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002282 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002283 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002284
Douglas Gregor895162d2010-04-30 18:55:50 +00002285 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002286 const Decl *CheckD = D;
2287 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002288 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002289 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002290 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002291
2292 // If this is a tag declaration, it's possible that we need to look for
2293 // a previous declaration.
2294 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2295 CheckD = Tag->getPreviousDeclaration();
2296 else
2297 CheckD = 0;
2298 } while (CheckD);
2299
Douglas Gregor895162d2010-04-30 18:55:50 +00002300 // If we aren't combined with our outer scope, we're done.
2301 if (!Current->CombineWithOuterScope)
2302 break;
2303 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002304
2305 // If we didn't find the decl, then we either have a sema bug, or we have a
2306 // forward reference to a label declaration. Return null to indicate that
2307 // we have an uninstantiated label.
2308 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002309 return 0;
2310}
2311
John McCall2a7fb272010-08-25 05:32:35 +00002312void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002313 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002314 if (Stored.isNull())
2315 Stored = Inst;
2316 else if (Stored.is<Decl *>()) {
2317 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2318 Stored = Inst;
2319 } else
2320 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
Douglas Gregor895162d2010-04-30 18:55:50 +00002321}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002322
2323void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2324 Decl *Inst) {
2325 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2326 Pack->push_back(Inst);
2327}
2328
2329void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2330 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2331 assert(Stored.isNull() && "Already instantiated this local");
2332 DeclArgumentPack *Pack = new DeclArgumentPack;
2333 Stored = Pack;
2334 ArgumentPacks.push_back(Pack);
2335}
2336
Douglas Gregord3731192011-01-10 07:32:04 +00002337void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2338 const TemplateArgument *ExplicitArgs,
2339 unsigned NumExplicitArgs) {
2340 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2341 "Already have a partially-substituted pack");
2342 assert((!PartiallySubstitutedPack
2343 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2344 "Wrong number of arguments in partially-substituted pack");
2345 PartiallySubstitutedPack = Pack;
2346 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2347 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2348}
2349
2350NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2351 const TemplateArgument **ExplicitArgs,
2352 unsigned *NumExplicitArgs) const {
2353 if (ExplicitArgs)
2354 *ExplicitArgs = 0;
2355 if (NumExplicitArgs)
2356 *NumExplicitArgs = 0;
2357
2358 for (const LocalInstantiationScope *Current = this; Current;
2359 Current = Current->Outer) {
2360 if (Current->PartiallySubstitutedPack) {
2361 if (ExplicitArgs)
2362 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2363 if (NumExplicitArgs)
2364 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2365
2366 return Current->PartiallySubstitutedPack;
2367 }
2368
2369 if (!Current->CombineWithOuterScope)
2370 break;
2371 }
2372
2373 return 0;
2374}