blob: 7ef04e964dc664759acb3d69a96d848ed837d6f0 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/LangOptions.h"
John McCall19510852010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000021#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000022#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000024#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000025
26using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000027using namespace sema;
Douglas Gregor99ebf652009-02-27 19:31:52 +000028
Douglas Gregoree1828a2009-03-10 18:03:33 +000029//===----------------------------------------------------------------------===/
30// Template Instantiation Support
31//===----------------------------------------------------------------------===/
32
Douglas Gregord6350ae2009-08-28 20:31:08 +000033/// \brief Retrieve the template argument list(s) that should be used to
34/// instantiate the definition of the given declaration.
Douglas Gregor0f8716b2009-11-09 19:17:50 +000035///
36/// \param D the declaration for which we are computing template instantiation
37/// arguments.
38///
39/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor525f96c2010-02-05 07:33:43 +000040///
41/// \param RelativeToPrimary true if we should get the template
42/// arguments relative to the primary template, even when we're
43/// dealing with a specialization. This is only relevant for function
44/// template specializations.
Douglas Gregore7089b02010-05-03 23:29:10 +000045///
46/// \param Pattern If non-NULL, indicates the pattern from which we will be
47/// instantiating the definition of the given declaration, \p D. This is
48/// used to determine the proper set of template instantiation arguments for
49/// friend function template specializations.
Douglas Gregord1102432009-08-28 17:37:35 +000050MultiLevelTemplateArgumentList
Douglas Gregor0f8716b2009-11-09 19:17:50 +000051Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor525f96c2010-02-05 07:33:43 +000052 const TemplateArgumentList *Innermost,
Douglas Gregore7089b02010-05-03 23:29:10 +000053 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
Douglas Gregord1102432009-08-28 17:37:35 +000055 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor0f8716b2009-11-09 19:17:50 +000058 if (Innermost)
59 Result.addOuterTemplateArguments(Innermost);
60
Douglas Gregord1102432009-08-28 17:37:35 +000061 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregor93104c12011-05-22 00:21:10 +000062 if (!Ctx) {
Douglas Gregord1102432009-08-28 17:37:35 +000063 Ctx = D->getDeclContext();
Douglas Gregor93104c12011-05-22 00:21:10 +000064
Douglas Gregor383041d2011-06-15 14:20:42 +000065 // If we have a template template parameter with translation unit context,
66 // then we're performing substitution into a default template argument of
67 // this template template parameter before we've constructed the template
68 // that will own this template template parameter. In this case, we
69 // use empty template parameter lists for all of the outer templates
70 // to avoid performing any substitutions.
71 if (Ctx->isTranslationUnit()) {
72 if (TemplateTemplateParmDecl *TTP
73 = dyn_cast<TemplateTemplateParmDecl>(D)) {
74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
75 Result.addOuterTemplateArguments(0, 0);
76 return Result;
77 }
78 }
Douglas Gregor93104c12011-05-22 00:21:10 +000079 }
80
John McCallf181d8a2009-08-29 03:16:09 +000081 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +000082 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +000083 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +000084 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +000086 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +000088 break;
Mike Stump1eb44332009-09-09 15:08:12 +000089
Douglas Gregord1102432009-08-28 17:37:35 +000090 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +000091
92 // If this class template specialization was instantiated from a
93 // specialized member that is a class template, we're done.
94 assert(Spec->getSpecializedTemplate() && "No class template?");
95 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
96 break;
Mike Stump1eb44332009-09-09 15:08:12 +000097 }
Douglas Gregord1102432009-08-28 17:37:35 +000098 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +000099 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000100 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000101 (Function->getTemplateSpecializationKind() ==
102 TSK_ExplicitSpecialization &&
103 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000104 break;
105
Douglas Gregord1102432009-08-28 17:37:35 +0000106 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000107 = Function->getTemplateSpecializationArgs()) {
108 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000109 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000110
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000111 // If this function was instantiated from a specialized member that is
112 // a function template, we're done.
113 assert(Function->getPrimaryTemplate() && "No function template?");
114 if (Function->getPrimaryTemplate()->isMemberSpecialization())
115 break;
Douglas Gregorc494f772011-03-05 17:54:25 +0000116 } else if (FunctionTemplateDecl *FunTmpl
117 = Function->getDescribedFunctionTemplate()) {
118 // Add the "injected" template arguments.
119 std::pair<const TemplateArgument *, unsigned>
120 Injected = FunTmpl->getInjectedTemplateArgs();
121 Result.addOuterTemplateArguments(Injected.first, Injected.second);
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000122 }
123
John McCallf181d8a2009-08-29 03:16:09 +0000124 // If this is a friend declaration and it declares an entity at
125 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000126 // instead of its semantic parent, unless of course the pattern we're
127 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000128 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000129 Function->getDeclContext()->isFileContext() &&
130 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000131 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000132 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000133 continue;
134 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000135 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
136 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
137 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
138 const TemplateSpecializationType *TST
139 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
140 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
141 if (ClassTemplate->isMemberSpecialization())
142 break;
143 }
Douglas Gregord1102432009-08-28 17:37:35 +0000144 }
John McCallf181d8a2009-08-29 03:16:09 +0000145
146 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000147 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000148 }
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregord1102432009-08-28 17:37:35 +0000150 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000151}
152
Douglas Gregorf35f8282009-11-11 21:54:23 +0000153bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
154 switch (Kind) {
155 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000156 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000157 case DefaultTemplateArgumentInstantiation:
158 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000159 case ExplicitTemplateArgumentSubstitution:
160 case DeducedTemplateArgumentSubstitution:
161 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000162 return true;
163
Douglas Gregorf35f8282009-11-11 21:54:23 +0000164 case DefaultTemplateArgumentChecking:
165 return false;
166 }
David Blaikie7530c032012-01-17 06:56:22 +0000167
168 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000169}
170
Douglas Gregor26dce442009-03-10 00:06:19 +0000171Sema::InstantiatingTemplate::
172InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000173 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000174 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000175 : SemaRef(SemaRef),
176 SavedInNonInstantiationSFINAEContext(
177 SemaRef.InNonInstantiationSFINAEContext)
178{
Douglas Gregordf667e72009-03-10 20:44:00 +0000179 Invalid = CheckInstantiationDepth(PointOfInstantiation,
180 InstantiationRange);
181 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000182 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000183 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000184 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000185 Inst.Entity = Entity;
Douglas Gregor313a81d2009-03-12 18:36:18 +0000186 Inst.TemplateArgs = 0;
187 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000188 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000189 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000190 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000191 }
192}
193
Richard Smithe6975e92012-04-17 00:58:00 +0000194Sema::InstantiatingTemplate::
195InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
196 FunctionDecl *Entity, ExceptionSpecification,
197 SourceRange InstantiationRange)
198 : SemaRef(SemaRef),
199 SavedInNonInstantiationSFINAEContext(
200 SemaRef.InNonInstantiationSFINAEContext)
201{
202 Invalid = CheckInstantiationDepth(PointOfInstantiation,
203 InstantiationRange);
204 if (!Invalid) {
205 ActiveTemplateInstantiation Inst;
206 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
207 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000208 Inst.Entity = Entity;
Richard Smithe6975e92012-04-17 00:58:00 +0000209 Inst.TemplateArgs = 0;
210 Inst.NumTemplateArgs = 0;
211 Inst.InstantiationRange = InstantiationRange;
212 SemaRef.InNonInstantiationSFINAEContext = false;
213 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
214 }
215}
216
Richard Smith7e54fb52012-07-16 01:09:10 +0000217Sema::InstantiatingTemplate::
218InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
219 TemplateDecl *Template,
220 ArrayRef<TemplateArgument> TemplateArgs,
221 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000222 : SemaRef(SemaRef),
223 SavedInNonInstantiationSFINAEContext(
224 SemaRef.InNonInstantiationSFINAEContext)
225{
Douglas Gregordf667e72009-03-10 20:44:00 +0000226 Invalid = CheckInstantiationDepth(PointOfInstantiation,
227 InstantiationRange);
228 if (!Invalid) {
229 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000230 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000231 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
232 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000233 Inst.Entity = Template;
Richard Smith7e54fb52012-07-16 01:09:10 +0000234 Inst.TemplateArgs = TemplateArgs.data();
235 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor26dce442009-03-10 00:06:19 +0000236 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000237 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000238 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000239 }
240}
241
Richard Smith7e54fb52012-07-16 01:09:10 +0000242Sema::InstantiatingTemplate::
243InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
244 FunctionTemplateDecl *FunctionTemplate,
245 ArrayRef<TemplateArgument> TemplateArgs,
246 ActiveTemplateInstantiation::InstantiationKind Kind,
247 sema::TemplateDeductionInfo &DeductionInfo,
248 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000249 : SemaRef(SemaRef),
250 SavedInNonInstantiationSFINAEContext(
251 SemaRef.InNonInstantiationSFINAEContext)
252{
Richard Smithab91ef12012-07-08 02:38:24 +0000253 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000254 if (!Invalid) {
255 ActiveTemplateInstantiation Inst;
256 Inst.Kind = Kind;
257 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000258 Inst.Entity = FunctionTemplate;
Richard Smith7e54fb52012-07-16 01:09:10 +0000259 Inst.TemplateArgs = TemplateArgs.data();
260 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor9b623632010-10-12 23:32:35 +0000261 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000262 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000263 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000264 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000265
266 if (!Inst.isInstantiationRecord())
267 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000268 }
269}
270
Richard Smith7e54fb52012-07-16 01:09:10 +0000271Sema::InstantiatingTemplate::
272InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
273 ClassTemplatePartialSpecializationDecl *PartialSpec,
274 ArrayRef<TemplateArgument> TemplateArgs,
275 sema::TemplateDeductionInfo &DeductionInfo,
276 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000277 : SemaRef(SemaRef),
278 SavedInNonInstantiationSFINAEContext(
279 SemaRef.InNonInstantiationSFINAEContext)
280{
Richard Smithab91ef12012-07-08 02:38:24 +0000281 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
282 if (!Invalid) {
283 ActiveTemplateInstantiation Inst;
284 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
285 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000286 Inst.Entity = PartialSpec;
Richard Smith7e54fb52012-07-16 01:09:10 +0000287 Inst.TemplateArgs = TemplateArgs.data();
288 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000289 Inst.DeductionInfo = &DeductionInfo;
290 Inst.InstantiationRange = InstantiationRange;
291 SemaRef.InNonInstantiationSFINAEContext = false;
292 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
293 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000294}
295
Richard Smith7e54fb52012-07-16 01:09:10 +0000296Sema::InstantiatingTemplate::
297InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
298 ParmVarDecl *Param,
299 ArrayRef<TemplateArgument> TemplateArgs,
300 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000301 : SemaRef(SemaRef),
302 SavedInNonInstantiationSFINAEContext(
303 SemaRef.InNonInstantiationSFINAEContext)
304{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000305 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000306 if (!Invalid) {
307 ActiveTemplateInstantiation Inst;
308 Inst.Kind
309 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000310 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000311 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000312 Inst.TemplateArgs = TemplateArgs.data();
313 Inst.NumTemplateArgs = TemplateArgs.size();
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000314 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000315 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000316 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000317 }
318}
319
320Sema::InstantiatingTemplate::
321InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000322 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
323 ArrayRef<TemplateArgument> TemplateArgs,
324 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000325 : SemaRef(SemaRef),
326 SavedInNonInstantiationSFINAEContext(
327 SemaRef.InNonInstantiationSFINAEContext)
328{
Richard Smithab91ef12012-07-08 02:38:24 +0000329 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
330 if (!Invalid) {
331 ActiveTemplateInstantiation Inst;
332 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
333 Inst.PointOfInstantiation = PointOfInstantiation;
334 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000335 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000336 Inst.TemplateArgs = TemplateArgs.data();
337 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000338 Inst.InstantiationRange = InstantiationRange;
339 SemaRef.InNonInstantiationSFINAEContext = false;
340 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
341 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000342}
343
344Sema::InstantiatingTemplate::
345InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000346 NamedDecl *Template, TemplateTemplateParmDecl *Param,
347 ArrayRef<TemplateArgument> TemplateArgs,
348 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000349 : SemaRef(SemaRef),
350 SavedInNonInstantiationSFINAEContext(
351 SemaRef.InNonInstantiationSFINAEContext)
352{
Richard Smithab91ef12012-07-08 02:38:24 +0000353 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
354 if (!Invalid) {
355 ActiveTemplateInstantiation Inst;
356 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
357 Inst.PointOfInstantiation = PointOfInstantiation;
358 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000359 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000360 Inst.TemplateArgs = TemplateArgs.data();
361 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000362 Inst.InstantiationRange = InstantiationRange;
363 SemaRef.InNonInstantiationSFINAEContext = false;
364 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
365 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000366}
367
368Sema::InstantiatingTemplate::
369InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000370 TemplateDecl *Template, NamedDecl *Param,
371 ArrayRef<TemplateArgument> TemplateArgs,
372 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000373 : SemaRef(SemaRef),
374 SavedInNonInstantiationSFINAEContext(
375 SemaRef.InNonInstantiationSFINAEContext)
376{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000377 Invalid = false;
378
379 ActiveTemplateInstantiation Inst;
380 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
381 Inst.PointOfInstantiation = PointOfInstantiation;
382 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000383 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000384 Inst.TemplateArgs = TemplateArgs.data();
385 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregorf35f8282009-11-11 21:54:23 +0000386 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000387 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000388 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
389
390 assert(!Inst.isInstantiationRecord());
391 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000392}
393
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000394void Sema::InstantiatingTemplate::Clear() {
395 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000396 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
397 assert(SemaRef.NonInstantiationEntries > 0);
398 --SemaRef.NonInstantiationEntries;
399 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000400 SemaRef.InNonInstantiationSFINAEContext
401 = SavedInNonInstantiationSFINAEContext;
Douglas Gregor26dce442009-03-10 00:06:19 +0000402 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000403 Invalid = true;
404 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000405}
406
Douglas Gregordf667e72009-03-10 20:44:00 +0000407bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
408 SourceLocation PointOfInstantiation,
409 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000410 assert(SemaRef.NonInstantiationEntries <=
411 SemaRef.ActiveTemplateInstantiations.size());
412 if ((SemaRef.ActiveTemplateInstantiations.size() -
413 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000414 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000415 return false;
416
Mike Stump1eb44332009-09-09 15:08:12 +0000417 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000418 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000419 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000420 << InstantiationRange;
421 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000422 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000423 return true;
424}
425
Douglas Gregoree1828a2009-03-10 18:03:33 +0000426/// \brief Prints the current instantiation stack through a series of
427/// notes.
428void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000429 // Determine which template instantiations to skip, if any.
430 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
431 unsigned Limit = Diags.getTemplateBacktraceLimit();
432 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
433 SkipStart = Limit / 2 + Limit % 2;
434 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
435 }
436
Douglas Gregorcca9e962009-07-01 22:01:06 +0000437 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000438 unsigned InstantiationIdx = 0;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000439 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000440 Active = ActiveTemplateInstantiations.rbegin(),
441 ActiveEnd = ActiveTemplateInstantiations.rend();
442 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000443 ++Active, ++InstantiationIdx) {
444 // Skip this instantiation?
445 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
446 if (InstantiationIdx == SkipStart) {
447 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000448 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000449 diag::note_instantiation_contexts_suppressed)
450 << unsigned(ActiveTemplateInstantiations.size() - Limit);
451 }
452 continue;
453 }
454
Douglas Gregordf667e72009-03-10 20:44:00 +0000455 switch (Active->Kind) {
456 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000457 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000458 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
459 unsigned DiagID = diag::note_template_member_class_here;
460 if (isa<ClassTemplateSpecializationDecl>(Record))
461 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000462 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000463 << Context.getTypeDeclType(Record)
464 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000465 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000466 unsigned DiagID;
467 if (Function->getPrimaryTemplate())
468 DiagID = diag::note_function_template_spec_here;
469 else
470 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000471 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000472 << Function
473 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000474 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000475 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000476 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000477 << VD
478 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000479 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
480 Diags.Report(Active->PointOfInstantiation,
481 diag::note_template_enum_def_here)
482 << ED
483 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000484 } else {
485 Diags.Report(Active->PointOfInstantiation,
486 diag::note_template_type_alias_instantiation_here)
487 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000488 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000489 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000490 break;
491 }
492
493 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000494 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000495 SmallVector<char, 128> TemplateArgsStr;
496 llvm::raw_svector_ostream OS(TemplateArgsStr);
497 Template->printName(OS);
498 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000499 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000500 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000501 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000502 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000503 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000504 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000505 << Active->InstantiationRange;
506 break;
507 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000508
Douglas Gregorcca9e962009-07-01 22:01:06 +0000509 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000510 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000511 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000512 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000513 << FnTmpl
514 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
515 Active->TemplateArgs,
516 Active->NumTemplateArgs)
517 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000518 break;
519 }
Mike Stump1eb44332009-09-09 15:08:12 +0000520
Douglas Gregorcca9e962009-07-01 22:01:06 +0000521 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000522 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
523 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000524 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000525 diag::note_partial_spec_deduct_instantiation_here)
526 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000527 << getTemplateArgumentBindingsText(
528 PartialSpec->getTemplateParameters(),
529 Active->TemplateArgs,
530 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000531 << Active->InstantiationRange;
532 } else {
533 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000534 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000535 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000536 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000537 << FnTmpl
538 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
539 Active->TemplateArgs,
540 Active->NumTemplateArgs)
541 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000542 }
543 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000544
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000545 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000546 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000547 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Benjamin Kramer5eada842013-02-22 15:46:01 +0000549 SmallVector<char, 128> TemplateArgsStr;
550 llvm::raw_svector_ostream OS(TemplateArgsStr);
551 FD->printName(OS);
552 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000553 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000554 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000555 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000556 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000557 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000558 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000559 << Active->InstantiationRange;
560 break;
561 }
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000563 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000564 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000565 std::string Name;
566 if (!Parm->getName().empty())
567 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000568
569 TemplateParameterList *TemplateParams = 0;
570 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
571 TemplateParams = Template->getTemplateParameters();
572 else
573 TemplateParams =
574 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
575 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000576 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000577 diag::note_prior_template_arg_substitution)
578 << isa<TemplateTemplateParmDecl>(Parm)
579 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000580 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000581 Active->TemplateArgs,
582 Active->NumTemplateArgs)
583 << Active->InstantiationRange;
584 break;
585 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000586
587 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000588 TemplateParameterList *TemplateParams = 0;
589 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
590 TemplateParams = Template->getTemplateParameters();
591 else
592 TemplateParams =
593 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
594 ->getTemplateParameters();
595
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000596 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000597 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000598 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000599 Active->TemplateArgs,
600 Active->NumTemplateArgs)
601 << Active->InstantiationRange;
602 break;
603 }
Richard Smithe6975e92012-04-17 00:58:00 +0000604
605 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
606 Diags.Report(Active->PointOfInstantiation,
607 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000608 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000609 << Active->InstantiationRange;
610 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000611 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000612 }
613}
614
David Blaikiedc84cd52013-02-20 22:23:23 +0000615Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000616 if (InNonInstantiationSFINAEContext)
David Blaikiedc84cd52013-02-20 22:23:23 +0000617 return Optional<TemplateDeductionInfo *>(0);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000618
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000619 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
620 Active = ActiveTemplateInstantiations.rbegin(),
621 ActiveEnd = ActiveTemplateInstantiations.rend();
622 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000623 ++Active)
624 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000625 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000626 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000627 // An instantiation of an alias template may or may not be a SFINAE
628 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000629 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000630 break;
631 // Fall through.
632 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000633 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000634 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000635 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000636
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000637 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000638 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000639 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000640 // A default template argument instantiation and substitution into
641 // template parameters with arguments for prior parameters may or may
642 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000643 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000644
Douglas Gregorcca9e962009-07-01 22:01:06 +0000645 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
646 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
647 // We're either substitution explicitly-specified template arguments
648 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000649 assert(Active->DeductionInfo && "Missing deduction info pointer");
650 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000651 }
652 }
653
David Blaikie66874fb2013-02-21 01:47:18 +0000654 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000655}
656
Douglas Gregord3731192011-01-10 07:32:04 +0000657/// \brief Retrieve the depth and index of a parameter pack.
658static std::pair<unsigned, unsigned>
659getDepthAndIndex(NamedDecl *ND) {
660 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
661 return std::make_pair(TTP->getDepth(), TTP->getIndex());
662
663 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
664 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
665
666 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
667 return std::make_pair(TTP->getDepth(), TTP->getIndex());
668}
669
Douglas Gregor99ebf652009-02-27 19:31:52 +0000670//===----------------------------------------------------------------------===/
671// Template Instantiation for Types
672//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000673namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000674 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000675 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000676 SourceLocation Loc;
677 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000678
Douglas Gregorcd281c32009-02-28 00:25:32 +0000679 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000680 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000681
682 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000683 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000684 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000685 DeclarationName Entity)
686 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000687 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000688
Mike Stump1eb44332009-09-09 15:08:12 +0000689 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000690 /// transformed.
691 ///
692 /// For the purposes of template instantiation, a type has already been
693 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000694 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Douglas Gregor577f75a2009-08-04 16:50:30 +0000696 /// \brief Returns the location of the entity being instantiated, if known.
697 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000698
Douglas Gregor577f75a2009-08-04 16:50:30 +0000699 /// \brief Returns the name of the entity being instantiated, if any.
700 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000701
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000702 /// \brief Sets the "base" location and entity when that
703 /// information is known based on another transformation.
704 void setBase(SourceLocation Loc, DeclarationName Entity) {
705 this->Loc = Loc;
706 this->Entity = Entity;
707 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000708
709 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
710 SourceRange PatternRange,
David Blaikiea71f9d02011-09-22 02:34:54 +0000711 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000712 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000713 bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000714 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000715 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
716 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000717 TemplateArgs,
718 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000719 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000720 NumExpansions);
721 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000722
Douglas Gregor12c9c002011-01-07 16:43:16 +0000723 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
724 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
725 }
726
Douglas Gregord3731192011-01-10 07:32:04 +0000727 TemplateArgument ForgetPartiallySubstitutedPack() {
728 TemplateArgument Result;
729 if (NamedDecl *PartialPack
730 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
731 MultiLevelTemplateArgumentList &TemplateArgs
732 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
733 unsigned Depth, Index;
734 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
735 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
736 Result = TemplateArgs(Depth, Index);
737 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
738 }
739 }
740
741 return Result;
742 }
743
744 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
745 if (Arg.isNull())
746 return;
747
748 if (NamedDecl *PartialPack
749 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
750 MultiLevelTemplateArgumentList &TemplateArgs
751 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
752 unsigned Depth, Index;
753 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
754 TemplateArgs.setArgument(Depth, Index, Arg);
755 }
756 }
757
Douglas Gregor577f75a2009-08-04 16:50:30 +0000758 /// \brief Transform the given declaration by instantiating a reference to
759 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000760 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000761
Douglas Gregordfca6f52012-02-13 22:00:16 +0000762 void transformAttrs(Decl *Old, Decl *New) {
763 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
764 }
765
766 void transformedLocalDecl(Decl *Old, Decl *New) {
767 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
768 }
769
Mike Stump1eb44332009-09-09 15:08:12 +0000770 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000771 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000772 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000773
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000774 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000775 /// declaration.
776 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
777
Douglas Gregor43959a92009-08-20 07:17:43 +0000778 /// \brief Rebuild the exception declaration and register the declaration
779 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000780 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000781 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000782 SourceLocation StartLoc,
783 SourceLocation NameLoc,
784 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Douglas Gregorbe270a02010-04-26 17:57:08 +0000786 /// \brief Rebuild the Objective-C exception declaration and register the
787 /// declaration as an instantiated local.
788 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
789 TypeSourceInfo *TSInfo, QualType T);
790
John McCallc4e70192009-09-11 04:59:25 +0000791 /// \brief Check for tag mismatches when instantiating an
792 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000793 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
794 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000795 NestedNameSpecifierLoc QualifierLoc,
796 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000797
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000798 TemplateName TransformTemplateName(CXXScopeSpec &SS,
799 TemplateName Name,
800 SourceLocation NameLoc,
801 QualType ObjectType = QualType(),
802 NamedDecl *FirstQualifierInScope = 0);
803
John McCall60d7b3a2010-08-24 06:29:42 +0000804 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
805 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
806 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000807
John McCall60d7b3a2010-08-24 06:29:42 +0000808 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000809 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000810 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
811 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000812
813 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
814 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
815
816 /// \brief Transform a reference to a function parameter pack.
817 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
818 ParmVarDecl *PD);
819
820 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
821 /// expand a function parameter pack reference which refers to an expanded
822 /// pack.
823 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
824
Douglas Gregor895162d2010-04-30 18:55:50 +0000825 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000826 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000827 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
828 FunctionProtoTypeLoc TL,
829 CXXRecordDecl *ThisContext,
830 unsigned ThisTypeQuals);
831
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000832 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000833 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000834 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000835 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000836
Mike Stump1eb44332009-09-09 15:08:12 +0000837 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000838 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000839 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000840 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000841
Douglas Gregorc3069d62011-01-14 02:55:32 +0000842 /// \brief Transforms an already-substituted template type parameter pack
843 /// into either itself (if we aren't substituting into its pack expansion)
844 /// or the appropriate substituted argument.
845 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
846 SubstTemplateTypeParmPackTypeLoc TL);
847
John McCall60d7b3a2010-08-24 06:29:42 +0000848 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000849 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000850 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000851 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
852 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000853 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000854 }
John McCall91a57552011-07-15 05:09:51 +0000855
Richard Smith612409e2012-07-25 03:56:55 +0000856 ExprResult TransformLambdaExpr(LambdaExpr *E) {
857 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
858 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
859 }
860
861 ExprResult TransformLambdaScope(LambdaExpr *E,
862 CXXMethodDecl *CallOperator) {
863 CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
864 TSK_ImplicitInstantiation);
865 return TreeTransform<TemplateInstantiator>::
866 TransformLambdaScope(E, CallOperator);
867 }
868
John McCall91a57552011-07-15 05:09:51 +0000869 private:
870 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
871 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000872 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000873 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000874}
875
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000876bool TemplateInstantiator::AlreadyTransformed(QualType T) {
877 if (T.isNull())
878 return true;
879
Douglas Gregor561f8122011-07-01 01:22:09 +0000880 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000881 return false;
882
883 getSema().MarkDeclarationsReferencedInType(Loc, T);
884 return true;
885}
886
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000887Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000888 if (!D)
889 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000890
Douglas Gregorc68afe22009-09-03 21:38:09 +0000891 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000892 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000893 // If the corresponding template argument is NULL or non-existent, it's
894 // because we are performing instantiation from explicitly-specified
895 // template arguments in a function template, but there were some
896 // arguments left unspecified.
897 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
898 TTP->getPosition()))
899 return D;
900
Douglas Gregor61c4d282011-01-05 15:48:55 +0000901 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
902
903 if (TTP->isParameterPack()) {
904 assert(Arg.getKind() == TemplateArgument::Pack &&
905 "Missing argument pack");
906
Douglas Gregor1aee05d2011-01-15 06:45:20 +0000907 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregord3731192011-01-10 07:32:04 +0000908 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor61c4d282011-01-05 15:48:55 +0000909 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
910 }
911
912 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000913 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000914 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000915 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Douglas Gregor788cd062009-11-11 01:00:40 +0000918 // Fall through to find the instantiated declaration for this template
919 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000920 }
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000922 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000923}
924
Douglas Gregoraac571c2010-03-01 17:25:41 +0000925Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000926 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000927 if (!Inst)
928 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Douglas Gregor43959a92009-08-20 07:17:43 +0000930 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
931 return Inst;
932}
933
Douglas Gregor6cd21982009-10-20 05:58:46 +0000934NamedDecl *
935TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
936 SourceLocation Loc) {
937 // If the first part of the nested-name-specifier was a template type
938 // parameter, instantiate that type parameter down to a tag type.
939 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
940 const TemplateTypeParmType *TTP
941 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000942
Douglas Gregor6cd21982009-10-20 05:58:46 +0000943 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000944 // FIXME: This needs testing w/ member access expressions.
945 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
946
947 if (TTP->isParameterPack()) {
948 assert(Arg.getKind() == TemplateArgument::Pack &&
949 "Missing argument pack");
950
Douglas Gregor2be29f42011-01-14 23:41:42 +0000951 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000952 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000953
Douglas Gregord3731192011-01-10 07:32:04 +0000954 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor984a58b2010-12-20 22:48:17 +0000955 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
956 }
957
958 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000959 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000960 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000961
962 if (const TagType *Tag = T->getAs<TagType>())
963 return Tag->getDecl();
964
965 // The resulting type is not a tag; complain.
966 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
967 return 0;
968 }
969 }
970
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000971 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000972}
973
Douglas Gregor43959a92009-08-20 07:17:43 +0000974VarDecl *
975TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000976 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000977 SourceLocation StartLoc,
978 SourceLocation NameLoc,
979 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000980 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000981 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000982 if (Var)
983 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
984 return Var;
985}
986
987VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
988 TypeSourceInfo *TSInfo,
989 QualType T) {
990 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
991 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000992 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
993 return Var;
994}
995
John McCallc4e70192009-09-11 04:59:25 +0000996QualType
John McCall21e413f2010-11-04 19:04:38 +0000997TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
998 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000999 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001000 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +00001001 if (const TagType *TT = T->getAs<TagType>()) {
1002 TagDecl* TD = TT->getDecl();
1003
John McCall21e413f2010-11-04 19:04:38 +00001004 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001005
John McCallc4e70192009-09-11 04:59:25 +00001006 IdentifierInfo *Id = TD->getIdentifier();
1007
1008 // TODO: should we even warn on struct/class mismatches for this? Seems
1009 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001010 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001011 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001012 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1013 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001014 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1015 << Id
1016 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1017 TD->getKindName());
1018 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1019 }
John McCallc4e70192009-09-11 04:59:25 +00001020 }
1021 }
1022
John McCall21e413f2010-11-04 19:04:38 +00001023 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1024 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001025 QualifierLoc,
1026 T);
John McCallc4e70192009-09-11 04:59:25 +00001027}
1028
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001029TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1030 TemplateName Name,
1031 SourceLocation NameLoc,
1032 QualType ObjectType,
1033 NamedDecl *FirstQualifierInScope) {
1034 if (TemplateTemplateParmDecl *TTP
1035 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1036 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1037 // If the corresponding template argument is NULL or non-existent, it's
1038 // because we are performing instantiation from explicitly-specified
1039 // template arguments in a function template, but there were some
1040 // arguments left unspecified.
1041 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1042 TTP->getPosition()))
1043 return Name;
1044
1045 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1046
1047 if (TTP->isParameterPack()) {
1048 assert(Arg.getKind() == TemplateArgument::Pack &&
1049 "Missing argument pack");
1050
1051 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1052 // We have the template argument pack to substitute, but we're not
1053 // actually expanding the enclosing pack expansion yet. So, just
1054 // keep the entire argument pack.
1055 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1056 }
1057
1058 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1059 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1060 }
1061
1062 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001063 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001064
Douglas Gregor58750382011-03-05 20:06:51 +00001065 // We don't ever want to substitute for a qualified template name, since
1066 // the qualifier is handled separately. So, look through the qualified
1067 // template name to its underlying declaration.
1068 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1069 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001070
1071 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001072 return Template;
1073 }
1074 }
1075
1076 if (SubstTemplateTemplateParmPackStorage *SubstPack
1077 = Name.getAsSubstTemplateTemplateParmPack()) {
1078 if (getSema().ArgumentPackSubstitutionIndex == -1)
1079 return Name;
1080
1081 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1082 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1083 "Pack substitution index out-of-range");
1084 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1085 .getAsTemplate();
1086 }
1087
1088 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1089 FirstQualifierInScope);
1090}
1091
John McCall60d7b3a2010-08-24 06:29:42 +00001092ExprResult
John McCall454feb92009-12-08 09:21:05 +00001093TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001094 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001095 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001096
1097 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1098 assert(currentDecl && "Must have current function declaration when "
1099 "instantiating.");
1100
1101 PredefinedExpr::IdentType IT = E->getIdentType();
1102
Anders Carlsson848fa642010-02-11 18:20:28 +00001103 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001104
1105 llvm::APInt LengthI(32, Length + 1);
Nico Weberb4e80082012-06-25 22:34:48 +00001106 QualType ResTy;
1107 if (IT == PredefinedExpr::LFunction)
1108 ResTy = getSema().Context.WCharTy.withConst();
1109 else
1110 ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001111 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1112 ArrayType::Normal, 0);
1113 PredefinedExpr *PE =
1114 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1115 return getSema().Owned(PE);
1116}
1117
John McCall60d7b3a2010-08-24 06:29:42 +00001118ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001119TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001120 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001121 // If the corresponding template argument is NULL or non-existent, it's
1122 // because we are performing instantiation from explicitly-specified
1123 // template arguments in a function template, but there were some
1124 // arguments left unspecified.
1125 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1126 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001127 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Douglas Gregor56bc9832010-12-24 00:15:10 +00001129 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1130 if (NTTP->isParameterPack()) {
1131 assert(Arg.getKind() == TemplateArgument::Pack &&
1132 "Missing argument pack");
1133
1134 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001135 // We have an argument pack, but we can't select a particular argument
1136 // out of it yet. Therefore, we'll build an expression to hold on to that
1137 // argument pack.
1138 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1139 E->getLocation(),
1140 NTTP->getDeclName());
1141 if (TargetType.isNull())
1142 return ExprError();
1143
1144 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1145 NTTP,
1146 E->getLocation(),
1147 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001148 }
1149
Douglas Gregord3731192011-01-10 07:32:04 +00001150 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor56bc9832010-12-24 00:15:10 +00001151 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1152 }
Mike Stump1eb44332009-09-09 15:08:12 +00001153
John McCall91a57552011-07-15 05:09:51 +00001154 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1155}
1156
1157ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1158 NonTypeTemplateParmDecl *parm,
1159 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001160 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001161 ExprResult result;
1162 QualType type;
1163
Richard Smith60983812012-07-09 03:07:20 +00001164 // If the argument is a pack expansion, the parameter must actually be a
1165 // parameter pack, and we should substitute the pattern itself, producing
1166 // an expression which contains an unexpanded parameter pack.
1167 if (arg.isPackExpansion()) {
1168 assert(parm->isParameterPack() && "pack expansion for non-pack");
1169 arg = arg.getPackExpansionPattern();
1170 }
1171
John McCallb8fc0532010-02-06 08:42:39 +00001172 // The template argument itself might be an expression, in which
1173 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001174 if (arg.getKind() == TemplateArgument::Expression) {
1175 Expr *argExpr = arg.getAsExpr();
1176 result = SemaRef.Owned(argExpr);
1177 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001178
Eli Friedmand7a6b162012-09-26 02:36:12 +00001179 } else if (arg.getKind() == TemplateArgument::Declaration ||
1180 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001181 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001182 if (arg.getKind() == TemplateArgument::Declaration) {
1183 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Douglas Gregord2008e22012-04-06 22:40:38 +00001185 // Find the instantiation of the template argument. This is
1186 // required for nested templates.
1187 VD = cast_or_null<ValueDecl>(
1188 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1189 if (!VD)
1190 return ExprError();
1191 } else {
1192 // Propagate NULL template argument.
1193 VD = 0;
1194 }
1195
John McCall645cf442010-02-06 10:23:53 +00001196 // Derive the type we want the substituted decl to have. This had
1197 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001198 if (parm->isExpandedParameterPack()) {
1199 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1200 } else if (parm->isParameterPack() &&
1201 isa<PackExpansionType>(parm->getType())) {
1202 type = SemaRef.SubstType(
1203 cast<PackExpansionType>(parm->getType())->getPattern(),
1204 TemplateArgs, loc, parm->getDeclName());
1205 } else {
1206 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1207 loc, parm->getDeclName());
1208 }
1209 assert(!type.isNull() && "type substitution failed for param type");
1210 assert(!type->isDependentType() && "param type still dependent");
1211 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001212
John McCall91a57552011-07-15 05:09:51 +00001213 if (!result.isInvalid()) type = result.get()->getType();
1214 } else {
1215 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1216
1217 // Note that this type can be different from the type of 'result',
1218 // e.g. if it's an enum type.
1219 type = arg.getIntegralType();
1220 }
1221 if (result.isInvalid()) return ExprError();
1222
1223 Expr *resultExpr = result.take();
1224 return SemaRef.Owned(new (SemaRef.Context)
1225 SubstNonTypeTemplateParmExpr(type,
1226 resultExpr->getValueKind(),
1227 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001228}
1229
Douglas Gregorc7793c72011-01-15 01:15:58 +00001230ExprResult
1231TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1232 SubstNonTypeTemplateParmPackExpr *E) {
1233 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1234 // We aren't expanding the parameter pack, so just return ourselves.
1235 return getSema().Owned(E);
1236 }
1237
Douglas Gregorc7793c72011-01-15 01:15:58 +00001238 const TemplateArgument &ArgPack = E->getArgumentPack();
1239 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1240 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1241
1242 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
John McCall91a57552011-07-15 05:09:51 +00001243 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1244 E->getParameterPackLocation(),
1245 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001246}
John McCallb8fc0532010-02-06 08:42:39 +00001247
John McCall60d7b3a2010-08-24 06:29:42 +00001248ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001249TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1250 SourceLocation Loc) {
1251 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1252 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1253}
1254
1255ExprResult
1256TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1257 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1258 // We can expand this parameter pack now.
1259 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1260 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1261 if (!VD)
1262 return ExprError();
1263 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1264 }
1265
1266 QualType T = TransformType(E->getType());
1267 if (T.isNull())
1268 return ExprError();
1269
1270 // Transform each of the parameter expansions into the corresponding
1271 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001272 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001273 Parms.reserve(E->getNumExpansions());
1274 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1275 I != End; ++I) {
1276 ParmVarDecl *D =
1277 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1278 if (!D)
1279 return ExprError();
1280 Parms.push_back(D);
1281 }
1282
1283 return FunctionParmPackExpr::Create(getSema().Context, T,
1284 E->getParameterPack(),
1285 E->getParameterPackLocation(), Parms);
1286}
1287
1288ExprResult
1289TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1290 ParmVarDecl *PD) {
1291 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1292 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1293 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1294 assert(Found && "no instantiation for parameter pack");
1295
1296 Decl *TransformedDecl;
1297 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1298 // If this is a reference to a function parameter pack which we can substitute
1299 // but can't yet expand, build a FunctionParmPackExpr for it.
1300 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1301 QualType T = TransformType(E->getType());
1302 if (T.isNull())
1303 return ExprError();
1304 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1305 E->getExprLoc(), *Pack);
1306 }
1307
1308 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1309 } else {
1310 TransformedDecl = Found->get<Decl*>();
1311 }
1312
1313 // We have either an unexpanded pack or a specific expansion.
1314 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1315 E->getExprLoc());
1316}
1317
1318ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001319TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1320 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001321
1322 // Handle references to non-type template parameters and non-type template
1323 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001324 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1325 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1326 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001327
1328 // We have a non-type template parameter that isn't fully substituted;
1329 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001330 }
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Richard Smith9a4db032012-09-12 00:56:43 +00001332 // Handle references to function parameter packs.
1333 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1334 if (PD->isParameterPack())
1335 return TransformFunctionParmPackRefExpr(E, PD);
1336
John McCall454feb92009-12-08 09:21:05 +00001337 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001338}
1339
John McCall60d7b3a2010-08-24 06:29:42 +00001340ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001341 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001342 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1343 getDescribedFunctionTemplate() &&
1344 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001345 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1346 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1347 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001348}
1349
Douglas Gregor895162d2010-04-30 18:55:50 +00001350QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001351 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001352 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001353 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001354 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001355}
1356
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001357QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1358 FunctionProtoTypeLoc TL,
1359 CXXRecordDecl *ThisContext,
1360 unsigned ThisTypeQuals) {
1361 // We need a local instantiation scope for this function prototype.
1362 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1363 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1364 ThisTypeQuals);
1365}
1366
John McCall21ef0fa2010-03-11 09:03:00 +00001367ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001368TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001369 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001370 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001371 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001372 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001373 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001374}
1375
Mike Stump1eb44332009-09-09 15:08:12 +00001376QualType
John McCalla2becad2009-10-21 00:40:46 +00001377TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001378 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001379 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001380 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001381 // Replace the template type parameter with its corresponding
1382 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001383
1384 // If the corresponding template argument is NULL or doesn't exist, it's
1385 // because we are performing instantiation from explicitly-specified
1386 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001387 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001388 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1389 TemplateTypeParmTypeLoc NewTL
1390 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1391 NewTL.setNameLoc(TL.getNameLoc());
1392 return TL.getType();
1393 }
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001395 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1396
1397 if (T->isParameterPack()) {
1398 assert(Arg.getKind() == TemplateArgument::Pack &&
1399 "Missing argument pack");
1400
1401 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001402 // We have the template argument pack, but we're not expanding the
1403 // enclosing pack expansion yet. Just save the template argument
1404 // pack for later substitution.
1405 QualType Result
1406 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1407 SubstTemplateTypeParmPackTypeLoc NewTL
1408 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1409 NewTL.setNameLoc(TL.getNameLoc());
1410 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001411 }
1412
Douglas Gregord3731192011-01-10 07:32:04 +00001413 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001414 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1415 }
1416
1417 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001418 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001419
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001420 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001421
1422 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001423 QualType Result
1424 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1425 SubstTemplateTypeParmTypeLoc NewTL
1426 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1427 NewTL.setNameLoc(TL.getNameLoc());
1428 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001429 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001430
1431 // The template type parameter comes from an inner template (e.g.,
1432 // the template parameter list of a member template inside the
1433 // template we are instantiating). Create a new template type
1434 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001435 TemplateTypeParmDecl *NewTTPDecl = 0;
1436 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1437 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1438 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1439
John McCalla2becad2009-10-21 00:40:46 +00001440 QualType Result
1441 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1442 - TemplateArgs.getNumLevels(),
1443 T->getIndex(),
1444 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001445 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001446 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1447 NewTL.setNameLoc(TL.getNameLoc());
1448 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001449}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001450
Douglas Gregorc3069d62011-01-14 02:55:32 +00001451QualType
1452TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1453 TypeLocBuilder &TLB,
1454 SubstTemplateTypeParmPackTypeLoc TL) {
1455 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1456 // We aren't expanding the parameter pack, so just return ourselves.
1457 SubstTemplateTypeParmPackTypeLoc NewTL
1458 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1459 NewTL.setNameLoc(TL.getNameLoc());
1460 return TL.getType();
1461 }
1462
1463 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1464 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1465 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1466
1467 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1468 Result = getSema().Context.getSubstTemplateTypeParmType(
1469 TL.getTypePtr()->getReplacedParameter(),
1470 Result);
1471 SubstTemplateTypeParmTypeLoc NewTL
1472 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1473 NewTL.setNameLoc(TL.getNameLoc());
1474 return Result;
1475}
1476
John McCallce3ff2b2009-08-25 22:02:44 +00001477/// \brief Perform substitution on the type T with a given set of template
1478/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001479///
1480/// This routine substitutes the given template arguments into the
1481/// type T and produces the instantiated type.
1482///
1483/// \param T the type into which the template arguments will be
1484/// substituted. If this type is not dependent, it will be returned
1485/// immediately.
1486///
James Dennett1dfbd922012-06-14 21:40:34 +00001487/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001488/// substituted for the top-level template parameters within T.
1489///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001490/// \param Loc the location in the source code where this substitution
1491/// is being performed. It will typically be the location of the
1492/// declarator (if we're instantiating the type of some declaration)
1493/// or the location of the type in the source code (if, e.g., we're
1494/// instantiating the type of a cast expression).
1495///
1496/// \param Entity the name of the entity associated with a declaration
1497/// being instantiated (if any). May be empty to indicate that there
1498/// is no such entity (if, e.g., this is a type that occurs as part of
1499/// a cast expression) or that the entity has no name (e.g., an
1500/// unnamed function parameter).
1501///
1502/// \returns If the instantiation succeeds, the instantiated
1503/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001504TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001505 const MultiLevelTemplateArgumentList &Args,
1506 SourceLocation Loc,
1507 DeclarationName Entity) {
1508 assert(!ActiveTemplateInstantiations.empty() &&
1509 "Cannot perform an instantiation without some context on the "
1510 "instantiation stack");
1511
Douglas Gregor561f8122011-07-01 01:22:09 +00001512 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001513 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001514 return T;
1515
1516 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1517 return Instantiator.TransformType(T);
1518}
1519
Douglas Gregor603cfb42011-01-05 23:12:31 +00001520TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1521 const MultiLevelTemplateArgumentList &Args,
1522 SourceLocation Loc,
1523 DeclarationName Entity) {
1524 assert(!ActiveTemplateInstantiations.empty() &&
1525 "Cannot perform an instantiation without some context on the "
1526 "instantiation stack");
1527
1528 if (TL.getType().isNull())
1529 return 0;
1530
Douglas Gregor561f8122011-07-01 01:22:09 +00001531 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001532 !TL.getType()->isVariablyModifiedType()) {
1533 // FIXME: Make a copy of the TypeLoc data here, so that we can
1534 // return a new TypeSourceInfo. Inefficient!
1535 TypeLocBuilder TLB;
1536 TLB.pushFullCopy(TL);
1537 return TLB.getTypeSourceInfo(Context, TL.getType());
1538 }
1539
1540 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1541 TypeLocBuilder TLB;
1542 TLB.reserve(TL.getFullDataSize());
1543 QualType Result = Instantiator.TransformType(TLB, TL);
1544 if (Result.isNull())
1545 return 0;
1546
1547 return TLB.getTypeSourceInfo(Context, Result);
1548}
1549
John McCallcd7ba1c2009-10-21 00:58:09 +00001550/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001551QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001552 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001553 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001554 assert(!ActiveTemplateInstantiations.empty() &&
1555 "Cannot perform an instantiation without some context on the "
1556 "instantiation stack");
1557
Douglas Gregor836adf62010-05-24 17:22:01 +00001558 // If T is not a dependent type or a variably-modified type, there
1559 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001560 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001561 return T;
1562
Douglas Gregor577f75a2009-08-04 16:50:30 +00001563 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1564 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001565}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001566
John McCall6cd3b9f2010-04-09 17:38:44 +00001567static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001568 if (T->getType()->isInstantiationDependentType() ||
1569 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001570 return true;
1571
Abramo Bagnara723df242010-12-14 22:11:44 +00001572 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001573 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001574 return false;
1575
David Blaikie39e6ab42013-02-18 22:06:02 +00001576 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
John McCall6cd3b9f2010-04-09 17:38:44 +00001577 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1578 ParmVarDecl *P = FP.getArg(I);
1579
Douglas Gregorc056c172011-05-09 20:45:16 +00001580 // The parameter's type as written might be dependent even if the
1581 // decayed type was not dependent.
1582 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001583 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001584 return true;
1585
John McCall6cd3b9f2010-04-09 17:38:44 +00001586 // TODO: currently we always rebuild expressions. When we
1587 // properly get lazier about this, we should use the same
1588 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001589 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001590 return true;
1591 }
1592
1593 return false;
1594}
1595
1596/// A form of SubstType intended specifically for instantiating the
1597/// type of a FunctionDecl. Its purpose is solely to force the
1598/// instantiation of default-argument expressions.
1599TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1600 const MultiLevelTemplateArgumentList &Args,
1601 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001602 DeclarationName Entity,
1603 CXXRecordDecl *ThisContext,
1604 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001605 assert(!ActiveTemplateInstantiations.empty() &&
1606 "Cannot perform an instantiation without some context on the "
1607 "instantiation stack");
1608
1609 if (!NeedsInstantiationAsFunctionType(T))
1610 return T;
1611
1612 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1613
1614 TypeLocBuilder TLB;
1615
1616 TypeLoc TL = T->getTypeLoc();
1617 TLB.reserve(TL.getFullDataSize());
1618
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001619 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001620
1621 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1622 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001623 ThisTypeQuals);
1624 } else {
1625 Result = Instantiator.TransformType(TLB, TL);
1626 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001627 if (Result.isNull())
1628 return 0;
1629
1630 return TLB.getTypeSourceInfo(Context, Result);
1631}
1632
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001633ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001634 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001635 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001636 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001637 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001638 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001639 TypeSourceInfo *NewDI = 0;
1640
Douglas Gregor603cfb42011-01-05 23:12:31 +00001641 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001642 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1643
Douglas Gregor603cfb42011-01-05 23:12:31 +00001644 // We have a function parameter pack. Substitute into the pattern of the
1645 // expansion.
1646 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1647 OldParm->getLocation(), OldParm->getDeclName());
1648 if (!NewDI)
1649 return 0;
1650
1651 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1652 // We still have unexpanded parameter packs, which means that
1653 // our function parameter is still a function parameter pack.
1654 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001655 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001656 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001657 } else if (ExpectParameterPack) {
1658 // We expected to get a parameter pack but didn't (because the type
1659 // itself is not a pack expansion type), so complain. This can occur when
1660 // the substitution goes through an alias template that "loses" the
1661 // pack expansion.
1662 Diag(OldParm->getLocation(),
1663 diag::err_function_parameter_pack_without_parameter_packs)
1664 << NewDI->getType();
1665 return 0;
1666 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001667 } else {
1668 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1669 OldParm->getDeclName());
1670 }
1671
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001672 if (!NewDI)
1673 return 0;
1674
1675 if (NewDI->getType()->isVoidType()) {
1676 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1677 return 0;
1678 }
1679
1680 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001681 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001682 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001683 OldParm->getIdentifier(),
1684 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001685 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001686 if (!NewParm)
1687 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001688
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001689 // Mark the (new) default argument as uninstantiated (if any).
1690 if (OldParm->hasUninstantiatedDefaultArg()) {
1691 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1692 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001693 } else if (OldParm->hasUnparsedDefaultArg()) {
1694 NewParm->setUnparsedDefaultArg();
1695 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001696 } else if (Expr *Arg = OldParm->getDefaultArg())
1697 // FIXME: if we non-lazily instantiated non-dependent default args for
1698 // non-dependent parameter types we could remove a bunch of duplicate
1699 // conversion warnings for such arguments.
1700 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001701
1702 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001703
Douglas Gregor12c9c002011-01-07 16:43:16 +00001704 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001705 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001706 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1707 } else {
1708 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001709 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001710 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001711
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001712 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1713 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001714 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001715
1716 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1717 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001718
1719 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1720
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001721 return NewParm;
1722}
1723
Douglas Gregora009b592011-01-07 00:20:55 +00001724/// \brief Substitute the given template arguments into the given set of
1725/// parameters, producing the set of parameter types that would be generated
1726/// from such a substitution.
1727bool Sema::SubstParmTypes(SourceLocation Loc,
1728 ParmVarDecl **Params, unsigned NumParams,
1729 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001730 SmallVectorImpl<QualType> &ParamTypes,
1731 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001732 assert(!ActiveTemplateInstantiations.empty() &&
1733 "Cannot perform an instantiation without some context on the "
1734 "instantiation stack");
1735
1736 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1737 DeclarationName());
1738 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001739 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001740}
1741
John McCallce3ff2b2009-08-25 22:02:44 +00001742/// \brief Perform substitution on the base class specifiers of the
1743/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001744///
1745/// Produces a diagnostic and returns true on error, returns false and
1746/// attaches the instantiated base classes to the class template
1747/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001748bool
John McCallce3ff2b2009-08-25 22:02:44 +00001749Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1750 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001751 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001752 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001753 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001754 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001755 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001756 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001757 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001758 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001759 continue;
1760 }
1761
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001762 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001763 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001764 if (Base->isPackExpansion()) {
1765 // This is a pack expansion. See whether we should expand it now, or
1766 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001767 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001768 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1769 Unexpanded);
1770 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001771 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001772 Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001773 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1774 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001775 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001776 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001777 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001778 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001779 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001780 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001781 }
1782
1783 // If we should expand this pack expansion now, do so.
1784 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001785 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001786 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1787
1788 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1789 TemplateArgs,
1790 Base->getSourceRange().getBegin(),
1791 DeclarationName());
1792 if (!BaseTypeLoc) {
1793 Invalid = true;
1794 continue;
1795 }
1796
1797 if (CXXBaseSpecifier *InstantiatedBase
1798 = CheckBaseSpecifier(Instantiation,
1799 Base->getSourceRange(),
1800 Base->isVirtual(),
1801 Base->getAccessSpecifierAsWritten(),
1802 BaseTypeLoc,
1803 SourceLocation()))
1804 InstantiatedBases.push_back(InstantiatedBase);
1805 else
1806 Invalid = true;
1807 }
1808
1809 continue;
1810 }
1811
1812 // The resulting base specifier will (still) be a pack expansion.
1813 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001814 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1815 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1816 TemplateArgs,
1817 Base->getSourceRange().getBegin(),
1818 DeclarationName());
1819 } else {
1820 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1821 TemplateArgs,
1822 Base->getSourceRange().getBegin(),
1823 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001824 }
1825
Nick Lewycky56062202010-07-26 16:56:01 +00001826 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001827 Invalid = true;
1828 continue;
1829 }
1830
1831 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001832 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001833 Base->getSourceRange(),
1834 Base->isVirtual(),
1835 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001836 BaseTypeLoc,
1837 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001838 InstantiatedBases.push_back(InstantiatedBase);
1839 else
1840 Invalid = true;
1841 }
1842
Douglas Gregor27b152f2009-03-10 18:52:44 +00001843 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001844 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001845 InstantiatedBases.size()))
1846 Invalid = true;
1847
1848 return Invalid;
1849}
1850
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001851// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001852namespace clang {
1853 namespace sema {
1854 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1855 const MultiLevelTemplateArgumentList &TemplateArgs);
1856 }
1857}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001858
Richard Smithf1c66b42012-03-14 23:13:10 +00001859/// Determine whether we would be unable to instantiate this template (because
1860/// it either has no definition, or is in the process of being instantiated).
1861static bool DiagnoseUninstantiableTemplate(Sema &S,
1862 SourceLocation PointOfInstantiation,
1863 TagDecl *Instantiation,
1864 bool InstantiatedFromMember,
1865 TagDecl *Pattern,
1866 TagDecl *PatternDef,
1867 TemplateSpecializationKind TSK,
1868 bool Complain = true) {
1869 if (PatternDef && !PatternDef->isBeingDefined())
1870 return false;
1871
1872 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1873 // Say nothing
1874 } else if (PatternDef) {
1875 assert(PatternDef->isBeingDefined());
1876 S.Diag(PointOfInstantiation,
1877 diag::err_template_instantiate_within_definition)
1878 << (TSK != TSK_ImplicitInstantiation)
1879 << S.Context.getTypeDeclType(Instantiation);
1880 // Not much point in noting the template declaration here, since
1881 // we're lexically inside it.
1882 Instantiation->setInvalidDecl();
1883 } else if (InstantiatedFromMember) {
1884 S.Diag(PointOfInstantiation,
1885 diag::err_implicit_instantiate_member_undefined)
1886 << S.Context.getTypeDeclType(Instantiation);
1887 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1888 } else {
1889 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1890 << (TSK != TSK_ImplicitInstantiation)
1891 << S.Context.getTypeDeclType(Instantiation);
1892 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1893 }
1894
1895 // In general, Instantiation isn't marked invalid to get more than one
1896 // error for multiple undefined instantiations. But the code that does
1897 // explicit declaration -> explicit definition conversion can't handle
1898 // invalid declarations, so mark as invalid in that case.
1899 if (TSK == TSK_ExplicitInstantiationDeclaration)
1900 Instantiation->setInvalidDecl();
1901 return true;
1902}
1903
Douglas Gregord475b8d2009-03-25 21:17:03 +00001904/// \brief Instantiate the definition of a class from a given pattern.
1905///
1906/// \param PointOfInstantiation The point of instantiation within the
1907/// source code.
1908///
1909/// \param Instantiation is the declaration whose definition is being
1910/// instantiated. This will be either a class template specialization
1911/// or a member class of a class template specialization.
1912///
1913/// \param Pattern is the pattern from which the instantiation
1914/// occurs. This will be either the declaration of a class template or
1915/// the declaration of a member class of a class template.
1916///
1917/// \param TemplateArgs The template arguments to be substituted into
1918/// the pattern.
1919///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001920/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001921///
1922/// \param Complain whether to complain if the class cannot be instantiated due
1923/// to the lack of a definition.
1924///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001925/// \returns true if an error occurred, false otherwise.
1926bool
1927Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1928 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001929 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001930 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001931 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001932 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001933 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001934 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1935 Instantiation->getInstantiatedFromMemberClass(),
1936 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001937 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001938 Pattern = PatternDef;
1939
Douglas Gregor454885e2009-10-15 15:54:05 +00001940 // \brief Record the point of instantiation.
1941 if (MemberSpecializationInfo *MSInfo
1942 = Instantiation->getMemberSpecializationInfo()) {
1943 MSInfo->setTemplateSpecializationKind(TSK);
1944 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001945 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001946 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001947 Spec->setTemplateSpecializationKind(TSK);
1948 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001949 }
1950
Douglas Gregord048bb72009-03-25 21:23:52 +00001951 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001952 if (Inst)
1953 return true;
1954
1955 // Enter the scope of this instantiation. We don't use
1956 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001957 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001958 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001959 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001960
Douglas Gregor05030bb2010-03-24 01:33:17 +00001961 // If this is an instantiation of a local class, merge this local
1962 // instantiation scope with the enclosing scope. Otherwise, every
1963 // instantiation of a class has its own local instantiation scope.
1964 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001965 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001966
John McCall1d8d1cc2010-08-01 02:01:53 +00001967 // Pull attributes from the pattern onto the instantiation.
1968 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1969
Douglas Gregord475b8d2009-03-25 21:17:03 +00001970 // Start the definition of this instantiation.
1971 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001972
1973 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001974
John McCallce3ff2b2009-08-25 22:02:44 +00001975 // Do substitution on the base class specifiers.
1976 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001977 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001978
Douglas Gregord65587f2010-11-10 19:44:59 +00001979 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001980 SmallVector<Decl*, 4> Fields;
1981 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001982 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001983 // Delay instantiation of late parsed attributes.
1984 LateInstantiatedAttrVec LateAttrs;
1985 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1986
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001987 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001988 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001989 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001990 // Don't instantiate members not belonging in this semantic context.
1991 // e.g. for:
1992 // @code
1993 // template <int i> class A {
1994 // class B *g;
1995 // };
1996 // @endcode
1997 // 'class B' has the template as lexical context but semantically it is
1998 // introduced in namespace scope.
1999 if ((*Member)->getDeclContext() != Pattern)
2000 continue;
2001
Douglas Gregord65587f2010-11-10 19:44:59 +00002002 if ((*Member)->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00002003 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002004 continue;
2005 }
2006
2007 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002008 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002009 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002010 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00002011 FieldDecl *OldField = cast<FieldDecl>(*Member);
2012 if (OldField->getInClassInitializer())
2013 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2014 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00002015 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2016 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2017 // specialization causes the implicit instantiation of the definitions
2018 // of unscoped member enumerations.
2019 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002020 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2021 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002022 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2023 assert(MSInfo && "no spec info for member enum specialization");
2024 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2025 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2026 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002027 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2028 if (SA->isFailed()) {
2029 // A static_assert failed. Bail out; instantiating this
2030 // class is probably not meaningful.
2031 Instantiation->setInvalidDecl();
2032 break;
2033 }
Richard Smith1af83c42012-03-23 03:33:32 +00002034 }
2035
2036 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002037 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002038 } else {
2039 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002040 // instantiations was a semantic disaster, and we'll want to mark the
2041 // declaration invalid.
2042 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002043 }
2044 }
2045
2046 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00002047 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2048 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002049 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002050
2051 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002052 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002053 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002054 // C++11 [expr.prim.general]p4:
2055 // Otherwise, if a member-declarator declares a non-static data member
2056 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2057 // to X" within the optional brace-or-equal-initializer. It shall not
2058 // appear elsewhere in the member-declarator.
2059 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2060
2061 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2062 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2063 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2064 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002065
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002066 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2067 /*CXXDirectInit=*/false);
2068 if (NewInit.isInvalid())
2069 NewField->setInvalidDecl();
2070 else {
2071 Expr *Init = NewInit.take();
2072 assert(Init && "no-argument initializer in class");
2073 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
Richard Smithca523302012-06-10 03:12:00 +00002074 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002075 }
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002076 }
Richard Smith7a614d82011-06-11 17:19:42 +00002077 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002078 // Instantiate late parsed attributes, and attach them to their decls.
2079 // See Sema::InstantiateAttrs
2080 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2081 E = LateAttrs.end(); I != E; ++I) {
2082 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2083 CurrentInstantiationScope = I->Scope;
2084 Attr *NewAttr =
2085 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2086 I->NewDecl->addAttr(NewAttr);
2087 LocalInstantiationScope::deleteScopes(I->Scope,
2088 Instantiator.getStartingScope());
2089 }
2090 Instantiator.disableLateAttributeInstantiation();
2091 LateAttrs.clear();
2092
Richard Smithb9d0b762012-07-27 04:22:15 +00002093 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002094
Abramo Bagnarae9946242011-11-18 08:08:52 +00002095 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002096 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002097 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002098 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002099 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002100
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002101 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002102 // Perform any dependent diagnostics from the pattern.
2103 PerformDependentDiagnostics(Pattern, TemplateArgs);
2104
Douglas Gregord65587f2010-11-10 19:44:59 +00002105 // Instantiate any out-of-line class template partial
2106 // specializations now.
2107 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2108 P = Instantiator.delayed_partial_spec_begin(),
2109 PEnd = Instantiator.delayed_partial_spec_end();
2110 P != PEnd; ++P) {
2111 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2112 P->first,
2113 P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002114 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002115 break;
2116 }
2117 }
2118 }
2119
Douglas Gregord475b8d2009-03-25 21:17:03 +00002120 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002121 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002122
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002123 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002124 Consumer.HandleTagDeclDefinition(Instantiation);
2125
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002126 // Always emit the vtable for an explicit instantiation definition
2127 // of a polymorphic class template specialization.
2128 if (TSK == TSK_ExplicitInstantiationDefinition)
2129 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2130 }
2131
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002132 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002133}
2134
Richard Smithf1c66b42012-03-14 23:13:10 +00002135/// \brief Instantiate the definition of an enum from a given pattern.
2136///
2137/// \param PointOfInstantiation The point of instantiation within the
2138/// source code.
2139/// \param Instantiation is the declaration whose definition is being
2140/// instantiated. This will be a member enumeration of a class
2141/// temploid specialization, or a local enumeration within a
2142/// function temploid specialization.
2143/// \param Pattern The templated declaration from which the instantiation
2144/// occurs.
2145/// \param TemplateArgs The template arguments to be substituted into
2146/// the pattern.
2147/// \param TSK The kind of implicit or explicit instantiation to perform.
2148///
2149/// \return \c true if an error occurred, \c false otherwise.
2150bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2151 EnumDecl *Instantiation, EnumDecl *Pattern,
2152 const MultiLevelTemplateArgumentList &TemplateArgs,
2153 TemplateSpecializationKind TSK) {
2154 EnumDecl *PatternDef = Pattern->getDefinition();
2155 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2156 Instantiation->getInstantiatedFromMemberEnum(),
2157 Pattern, PatternDef, TSK,/*Complain*/true))
2158 return true;
2159 Pattern = PatternDef;
2160
2161 // Record the point of instantiation.
2162 if (MemberSpecializationInfo *MSInfo
2163 = Instantiation->getMemberSpecializationInfo()) {
2164 MSInfo->setTemplateSpecializationKind(TSK);
2165 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2166 }
2167
2168 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2169 if (Inst)
2170 return true;
2171
2172 // Enter the scope of this instantiation. We don't use
2173 // PushDeclContext because we don't have a scope.
2174 ContextRAII SavedContext(*this, Instantiation);
2175 EnterExpressionEvaluationContext EvalContext(*this,
2176 Sema::PotentiallyEvaluated);
2177
2178 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2179
2180 // Pull attributes from the pattern onto the instantiation.
2181 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2182
2183 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2184 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2185
2186 // Exit the scope of this instantiation.
2187 SavedContext.pop();
2188
2189 return Instantiation->isInvalidDecl();
2190}
2191
Douglas Gregor9b623632010-10-12 23:32:35 +00002192namespace {
2193 /// \brief A partial specialization whose template arguments have matched
2194 /// a given template-id.
2195 struct PartialSpecMatchResult {
2196 ClassTemplatePartialSpecializationDecl *Partial;
2197 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002198 };
2199}
2200
Mike Stump1eb44332009-09-09 15:08:12 +00002201bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00002202Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002203 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00002204 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002205 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002206 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002207 // Perform the actual instantiation on the canonical declaration.
2208 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002209 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002210
Douglas Gregor52604ab2009-09-11 21:19:12 +00002211 // Check whether we have already instantiated or specialized this class
2212 // template specialization.
2213 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2214 if (ClassTemplateSpec->getSpecializationKind() ==
2215 TSK_ExplicitInstantiationDeclaration &&
2216 TSK == TSK_ExplicitInstantiationDefinition) {
2217 // An explicit instantiation definition follows an explicit instantiation
2218 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2219 // explicit instantiation.
2220 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002221
2222 // If this is an explicit instantiation definition, mark the
2223 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002224 if (TSK == TSK_ExplicitInstantiationDefinition &&
2225 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002226 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2227
Douglas Gregor52604ab2009-09-11 21:19:12 +00002228 return false;
2229 }
2230
2231 // We can only instantiate something that hasn't already been
2232 // instantiated or specialized. Fail without any diagnostics: our
2233 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002234 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002235 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002236
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002237 if (ClassTemplateSpec->isInvalidDecl())
2238 return true;
2239
Douglas Gregor2943aed2009-03-03 04:44:36 +00002240 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002241 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002242
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002243 // C++ [temp.class.spec.match]p1:
2244 // When a class template is used in a context that requires an
2245 // instantiation of the class, it is necessary to determine
2246 // whether the instantiation is to be generated using the primary
2247 // template or one of the partial specializations. This is done by
2248 // matching the template arguments of the class template
2249 // specialization with the template argument lists of the partial
2250 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002251 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002252 SmallVector<MatchResult, 4> Matched;
2253 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002254 Template->getPartialSpecializations(PartialSpecs);
2255 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2256 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Craig Topper93e45992012-09-19 02:26:47 +00002257 TemplateDeductionInfo Info(PointOfInstantiation);
Douglas Gregorf67875d2009-06-12 18:26:56 +00002258 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002259 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002260 ClassTemplateSpec->getTemplateArgs(),
2261 Info)) {
2262 // FIXME: Store the failed-deduction information for use in
2263 // diagnostics, later.
2264 (void)Result;
2265 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002266 Matched.push_back(PartialSpecMatchResult());
2267 Matched.back().Partial = Partial;
2268 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002269 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002270 }
2271
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002272 // If we're dealing with a member template where the template parameters
2273 // have been instantiated, this provides the original template parameters
2274 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002275 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002276
Douglas Gregored9c0f92009-10-29 00:04:11 +00002277 if (Matched.size() >= 1) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002278 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002279 if (Matched.size() == 1) {
2280 // -- If exactly one matching specialization is found, the
2281 // instantiation is generated from that specialization.
2282 // We don't need to do anything for this.
2283 } else {
2284 // -- If more than one matching specialization is found, the
2285 // partial order rules (14.5.4.2) are used to determine
2286 // whether one of the specializations is more specialized
2287 // than the others. If none of the specializations is more
2288 // specialized than all of the other matching
2289 // specializations, then the use of the class template is
2290 // ambiguous and the program is ill-formed.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002291 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
Douglas Gregored9c0f92009-10-29 00:04:11 +00002292 PEnd = Matched.end();
2293 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002294 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002295 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002296 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002297 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002298 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002299
Douglas Gregored9c0f92009-10-29 00:04:11 +00002300 // Determine if the best partial specialization is more specialized than
2301 // the others.
2302 bool Ambiguous = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002303 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002304 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002305 P != PEnd; ++P) {
2306 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002307 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002308 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002309 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002310 Ambiguous = true;
2311 break;
2312 }
2313 }
2314
2315 if (Ambiguous) {
2316 // Partial ordering did not produce a clear winner. Complain.
2317 ClassTemplateSpec->setInvalidDecl();
2318 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2319 << ClassTemplateSpec;
2320
2321 // Print the matching partial specializations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002322 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregored9c0f92009-10-29 00:04:11 +00002323 PEnd = Matched.end();
2324 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002325 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2326 << getTemplateArgumentBindingsText(
2327 P->Partial->getTemplateParameters(),
2328 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002329
Douglas Gregored9c0f92009-10-29 00:04:11 +00002330 return true;
2331 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002332 }
2333
2334 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002335 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002336 while (OrigPartialSpec->getInstantiatedFromMember()) {
2337 // If we've found an explicit specialization of this class template,
2338 // stop here and use that as the pattern.
2339 if (OrigPartialSpec->isMemberSpecialization())
2340 break;
2341
2342 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2343 }
2344
2345 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002346 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002347 } else {
2348 // -- If no matches are found, the instantiation is generated
2349 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002350 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002351 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2352 // If we've found an explicit specialization of this class template,
2353 // stop here and use that as the pattern.
2354 if (OrigTemplate->isMemberSpecialization())
2355 break;
2356
Douglas Gregord6350ae2009-08-28 20:31:08 +00002357 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002358 }
2359
Douglas Gregord6350ae2009-08-28 20:31:08 +00002360 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002361 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002362
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002363 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2364 Pattern,
2365 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002366 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002367 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Douglas Gregor199d9912009-06-05 00:53:49 +00002369 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002370}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002371
John McCallce3ff2b2009-08-25 22:02:44 +00002372/// \brief Instantiates the definitions of all of the member
2373/// of the given class, which is an instantiation of a class template
2374/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002375void
2376Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002377 CXXRecordDecl *Instantiation,
2378 const MultiLevelTemplateArgumentList &TemplateArgs,
2379 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002380 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2381 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002382 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002383 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002384 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002385 if (FunctionDecl *Pattern
2386 = Function->getInstantiatedFromMemberFunction()) {
2387 MemberSpecializationInfo *MSInfo
2388 = Function->getMemberSpecializationInfo();
2389 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002390 if (MSInfo->getTemplateSpecializationKind()
2391 == TSK_ExplicitSpecialization)
2392 continue;
2393
Douglas Gregor0d035142009-10-27 18:42:08 +00002394 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2395 Function,
2396 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002397 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002398 SuppressNew) ||
2399 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002400 continue;
2401
Sean Hunt10620eb2011-05-06 20:44:56 +00002402 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002403 continue;
2404
2405 if (TSK == TSK_ExplicitInstantiationDefinition) {
2406 // C++0x [temp.explicit]p8:
2407 // An explicit instantiation definition that names a class template
2408 // specialization explicitly instantiates the class template
2409 // specialization and is only an explicit instantiation definition
2410 // of members whose definition is visible at the point of
2411 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002412 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002413 continue;
2414
2415 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2416
2417 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2418 } else {
2419 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2420 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002421 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002422 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002423 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002424 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2425 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002426 if (MSInfo->getTemplateSpecializationKind()
2427 == TSK_ExplicitSpecialization)
2428 continue;
2429
Douglas Gregor0d035142009-10-27 18:42:08 +00002430 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2431 Var,
2432 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002433 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002434 SuppressNew) ||
2435 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002436 continue;
2437
Douglas Gregor0d035142009-10-27 18:42:08 +00002438 if (TSK == TSK_ExplicitInstantiationDefinition) {
2439 // C++0x [temp.explicit]p8:
2440 // An explicit instantiation definition that names a class template
2441 // specialization explicitly instantiates the class template
2442 // specialization and is only an explicit instantiation definition
2443 // of members whose definition is visible at the point of
2444 // instantiation.
2445 if (!Var->getInstantiatedFromStaticDataMember()
2446 ->getOutOfLineDefinition())
2447 continue;
2448
2449 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002450 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002451 } else {
2452 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2453 }
2454 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002455 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002456 // Always skip the injected-class-name, along with any
2457 // redeclarations of nested classes, since both would cause us
2458 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002459 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002460 continue;
2461
Douglas Gregor0d035142009-10-27 18:42:08 +00002462 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2463 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002464
2465 if (MSInfo->getTemplateSpecializationKind()
2466 == TSK_ExplicitSpecialization)
2467 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002468
Douglas Gregor0d035142009-10-27 18:42:08 +00002469 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2470 Record,
2471 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002472 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002473 SuppressNew) ||
2474 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002475 continue;
2476
Douglas Gregor0d035142009-10-27 18:42:08 +00002477 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2478 assert(Pattern && "Missing instantiated-from-template information");
2479
Douglas Gregor952b0172010-02-11 01:04:33 +00002480 if (!Record->getDefinition()) {
2481 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002482 // C++0x [temp.explicit]p8:
2483 // An explicit instantiation definition that names a class template
2484 // specialization explicitly instantiates the class template
2485 // specialization and is only an explicit instantiation definition
2486 // of members whose definition is visible at the point of
2487 // instantiation.
2488 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2489 MSInfo->setTemplateSpecializationKind(TSK);
2490 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2491 }
2492
2493 continue;
2494 }
2495
2496 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002497 TemplateArgs,
2498 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002499 } else {
2500 if (TSK == TSK_ExplicitInstantiationDefinition &&
2501 Record->getTemplateSpecializationKind() ==
2502 TSK_ExplicitInstantiationDeclaration) {
2503 Record->setTemplateSpecializationKind(TSK);
2504 MarkVTableUsed(PointOfInstantiation, Record, true);
2505 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002506 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002507
Douglas Gregor952b0172010-02-11 01:04:33 +00002508 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002509 if (Pattern)
2510 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2511 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002512 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2513 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2514 assert(MSInfo && "No member specialization information?");
2515
2516 if (MSInfo->getTemplateSpecializationKind()
2517 == TSK_ExplicitSpecialization)
2518 continue;
2519
2520 if (CheckSpecializationInstantiationRedecl(
2521 PointOfInstantiation, TSK, Enum,
2522 MSInfo->getTemplateSpecializationKind(),
2523 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2524 SuppressNew)
2525 continue;
2526
2527 if (Enum->getDefinition())
2528 continue;
2529
2530 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2531 assert(Pattern && "Missing instantiated-from-template information");
2532
2533 if (TSK == TSK_ExplicitInstantiationDefinition) {
2534 if (!Pattern->getDefinition())
2535 continue;
2536
2537 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2538 } else {
2539 MSInfo->setTemplateSpecializationKind(TSK);
2540 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2541 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002542 }
2543 }
2544}
2545
2546/// \brief Instantiate the definitions of all of the members of the
2547/// given class template specialization, which was named as part of an
2548/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002549void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002550Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002551 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002552 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2553 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002554 // C++0x [temp.explicit]p7:
2555 // An explicit instantiation that names a class template
2556 // specialization is an explicit instantion of the same kind
2557 // (declaration or definition) of each of its members (not
2558 // including members inherited from base classes) that has not
2559 // been previously explicitly specialized in the translation unit
2560 // containing the explicit instantiation, except as described
2561 // below.
2562 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002563 getTemplateInstantiationArgs(ClassTemplateSpec),
2564 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002565}
2566
John McCall60d7b3a2010-08-24 06:29:42 +00002567StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002568Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002569 if (!S)
2570 return Owned(S);
2571
2572 TemplateInstantiator Instantiator(*this, TemplateArgs,
2573 SourceLocation(),
2574 DeclarationName());
2575 return Instantiator.TransformStmt(S);
2576}
2577
John McCall60d7b3a2010-08-24 06:29:42 +00002578ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002579Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002580 if (!E)
2581 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Douglas Gregorb98b1992009-08-11 05:31:07 +00002583 TemplateInstantiator Instantiator(*this, TemplateArgs,
2584 SourceLocation(),
2585 DeclarationName());
2586 return Instantiator.TransformExpr(E);
2587}
2588
Richard Smithc83c2302012-12-19 01:39:02 +00002589ExprResult Sema::SubstInitializer(Expr *Init,
2590 const MultiLevelTemplateArgumentList &TemplateArgs,
2591 bool CXXDirectInit) {
2592 TemplateInstantiator Instantiator(*this, TemplateArgs,
2593 SourceLocation(),
2594 DeclarationName());
2595 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2596}
2597
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002598bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2599 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002600 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002601 if (NumExprs == 0)
2602 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002603
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002604 TemplateInstantiator Instantiator(*this, TemplateArgs,
2605 SourceLocation(),
2606 DeclarationName());
2607 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2608}
2609
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002610NestedNameSpecifierLoc
2611Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2612 const MultiLevelTemplateArgumentList &TemplateArgs) {
2613 if (!NNS)
2614 return NestedNameSpecifierLoc();
2615
2616 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2617 DeclarationName());
2618 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2619}
2620
Abramo Bagnara25777432010-08-11 22:01:17 +00002621/// \brief Do template substitution on declaration name info.
2622DeclarationNameInfo
2623Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2624 const MultiLevelTemplateArgumentList &TemplateArgs) {
2625 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2626 NameInfo.getName());
2627 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2628}
2629
Douglas Gregorde650ae2009-03-31 18:38:02 +00002630TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002631Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2632 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002633 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002634 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2635 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002636 CXXScopeSpec SS;
2637 SS.Adopt(QualifierLoc);
2638 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002639}
Douglas Gregor91333002009-06-11 00:06:24 +00002640
Douglas Gregore02e2622010-12-22 21:19:48 +00002641bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2642 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002643 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002644 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2645 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002646
2647 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002648}
Douglas Gregor895162d2010-04-30 18:55:50 +00002649
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002650
2651static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2652 // When storing ParmVarDecls in the local instantiation scope, we always
2653 // want to use the ParmVarDecl from the canonical function declaration,
2654 // since the map is then valid for any redeclaration or definition of that
2655 // function.
2656 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2658 unsigned i = PV->getFunctionScopeIndex();
2659 return FD->getCanonicalDecl()->getParamDecl(i);
2660 }
2661 }
2662 return D;
2663}
2664
2665
Douglas Gregor12c9c002011-01-07 16:43:16 +00002666llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2667LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002668 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002669 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002670 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002671
Douglas Gregor895162d2010-04-30 18:55:50 +00002672 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002673 const Decl *CheckD = D;
2674 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002675 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002676 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002677 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002678
2679 // If this is a tag declaration, it's possible that we need to look for
2680 // a previous declaration.
2681 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002682 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002683 else
2684 CheckD = 0;
2685 } while (CheckD);
2686
Douglas Gregor895162d2010-04-30 18:55:50 +00002687 // If we aren't combined with our outer scope, we're done.
2688 if (!Current->CombineWithOuterScope)
2689 break;
2690 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002691
2692 // If we didn't find the decl, then we either have a sema bug, or we have a
2693 // forward reference to a label declaration. Return null to indicate that
2694 // we have an uninstantiated label.
2695 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002696 return 0;
2697}
2698
John McCall2a7fb272010-08-25 05:32:35 +00002699void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002700 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002701 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002702 if (Stored.isNull())
2703 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002704 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2705 Pack->push_back(Inst);
2706 else
Douglas Gregord3731192011-01-10 07:32:04 +00002707 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002708}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002709
2710void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2711 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002712 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002713 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2714 Pack->push_back(Inst);
2715}
2716
2717void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002718 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002719 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2720 assert(Stored.isNull() && "Already instantiated this local");
2721 DeclArgumentPack *Pack = new DeclArgumentPack;
2722 Stored = Pack;
2723 ArgumentPacks.push_back(Pack);
2724}
2725
Douglas Gregord3731192011-01-10 07:32:04 +00002726void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2727 const TemplateArgument *ExplicitArgs,
2728 unsigned NumExplicitArgs) {
2729 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2730 "Already have a partially-substituted pack");
2731 assert((!PartiallySubstitutedPack
2732 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2733 "Wrong number of arguments in partially-substituted pack");
2734 PartiallySubstitutedPack = Pack;
2735 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2736 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2737}
2738
2739NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2740 const TemplateArgument **ExplicitArgs,
2741 unsigned *NumExplicitArgs) const {
2742 if (ExplicitArgs)
2743 *ExplicitArgs = 0;
2744 if (NumExplicitArgs)
2745 *NumExplicitArgs = 0;
2746
2747 for (const LocalInstantiationScope *Current = this; Current;
2748 Current = Current->Outer) {
2749 if (Current->PartiallySubstitutedPack) {
2750 if (ExplicitArgs)
2751 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2752 if (NumExplicitArgs)
2753 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2754
2755 return Current->PartiallySubstitutedPack;
2756 }
2757
2758 if (!Current->CombineWithOuterScope)
2759 break;
2760 }
2761
2762 return 0;
2763}