blob: 14c64050168a6093e215a5c39161b6e799739adb [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"
Faisal Valia3d311e2013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/Basic/LangOptions.h"
John McCall19510852010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000022#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000023#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000024#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000025#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000026
27using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000028using namespace sema;
Douglas Gregor99ebf652009-02-27 19:31:52 +000029
Douglas Gregoree1828a2009-03-10 18:03:33 +000030//===----------------------------------------------------------------------===/
31// Template Instantiation Support
32//===----------------------------------------------------------------------===/
33
Douglas Gregord6350ae2009-08-28 20:31:08 +000034/// \brief Retrieve the template argument list(s) that should be used to
35/// instantiate the definition of the given declaration.
Douglas Gregor0f8716b2009-11-09 19:17:50 +000036///
37/// \param D the declaration for which we are computing template instantiation
38/// arguments.
39///
40/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor525f96c2010-02-05 07:33:43 +000041///
42/// \param RelativeToPrimary true if we should get the template
43/// arguments relative to the primary template, even when we're
44/// dealing with a specialization. This is only relevant for function
45/// template specializations.
Douglas Gregore7089b02010-05-03 23:29:10 +000046///
47/// \param Pattern If non-NULL, indicates the pattern from which we will be
48/// instantiating the definition of the given declaration, \p D. This is
49/// used to determine the proper set of template instantiation arguments for
50/// friend function template specializations.
Douglas Gregord1102432009-08-28 17:37:35 +000051MultiLevelTemplateArgumentList
Douglas Gregor0f8716b2009-11-09 19:17:50 +000052Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor525f96c2010-02-05 07:33:43 +000053 const TemplateArgumentList *Innermost,
Douglas Gregore7089b02010-05-03 23:29:10 +000054 bool RelativeToPrimary,
55 const FunctionDecl *Pattern) {
Douglas Gregord1102432009-08-28 17:37:35 +000056 // Accumulate the set of template argument lists in this structure.
57 MultiLevelTemplateArgumentList Result;
Mike Stump1eb44332009-09-09 15:08:12 +000058
Douglas Gregor0f8716b2009-11-09 19:17:50 +000059 if (Innermost)
60 Result.addOuterTemplateArguments(Innermost);
61
Douglas Gregord1102432009-08-28 17:37:35 +000062 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregor93104c12011-05-22 00:21:10 +000063 if (!Ctx) {
Douglas Gregord1102432009-08-28 17:37:35 +000064 Ctx = D->getDeclContext();
Larisse Voufoef4579c2013-08-06 01:03:05 +000065
66 // Add template arguments from a variable template instantiation.
67 if (VarTemplateSpecializationDecl *Spec =
68 dyn_cast<VarTemplateSpecializationDecl>(D)) {
69 // We're done when we hit an explicit specialization.
70 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
71 !isa<VarTemplatePartialSpecializationDecl>(Spec))
72 return Result;
73
74 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
75
76 // If this variable template specialization was instantiated from a
77 // specialized member that is a variable template, we're done.
78 assert(Spec->getSpecializedTemplate() && "No variable template?");
Stephen Hines651f13c2014-04-23 16:59:28 -070079 llvm::PointerUnion<VarTemplateDecl*,
80 VarTemplatePartialSpecializationDecl*> Specialized
81 = Spec->getSpecializedTemplateOrPartial();
82 if (VarTemplatePartialSpecializationDecl *Partial =
83 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
84 if (Partial->isMemberSpecialization())
85 return Result;
86 } else {
87 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
88 if (Tmpl->isMemberSpecialization())
89 return Result;
90 }
Larisse Voufoef4579c2013-08-06 01:03:05 +000091 }
92
Douglas Gregor383041d2011-06-15 14:20:42 +000093 // If we have a template template parameter with translation unit context,
94 // then we're performing substitution into a default template argument of
95 // this template template parameter before we've constructed the template
96 // that will own this template template parameter. In this case, we
97 // use empty template parameter lists for all of the outer templates
98 // to avoid performing any substitutions.
99 if (Ctx->isTranslationUnit()) {
100 if (TemplateTemplateParmDecl *TTP
101 = dyn_cast<TemplateTemplateParmDecl>(D)) {
102 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith7a9f7c72013-05-17 03:04:50 +0000103 Result.addOuterTemplateArguments(None);
Douglas Gregor383041d2011-06-15 14:20:42 +0000104 return Result;
105 }
106 }
Douglas Gregor93104c12011-05-22 00:21:10 +0000107 }
108
John McCallf181d8a2009-08-29 03:16:09 +0000109 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +0000110 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +0000111 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +0000112 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
113 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +0000114 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
115 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +0000116 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000117
Douglas Gregord1102432009-08-28 17:37:35 +0000118 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000119
120 // If this class template specialization was instantiated from a
121 // specialized member that is a class template, we're done.
122 assert(Spec->getSpecializedTemplate() && "No class template?");
123 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
124 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000125 }
Douglas Gregord1102432009-08-28 17:37:35 +0000126 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +0000127 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000128 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000129 (Function->getTemplateSpecializationKind() ==
130 TSK_ExplicitSpecialization &&
131 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000132 break;
133
Douglas Gregord1102432009-08-28 17:37:35 +0000134 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000135 = Function->getTemplateSpecializationArgs()) {
136 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000137 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000138
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000139 // If this function was instantiated from a specialized member that is
140 // a function template, we're done.
141 assert(Function->getPrimaryTemplate() && "No function template?");
142 if (Function->getPrimaryTemplate()->isMemberSpecialization())
143 break;
Faisal Valia3d311e2013-10-23 06:44:28 +0000144
145 // If this function is a generic lambda specialization, we are done.
146 if (isGenericLambdaCallOperatorSpecialization(Function))
147 break;
148
Douglas Gregorc494f772011-03-05 17:54:25 +0000149 } else if (FunctionTemplateDecl *FunTmpl
150 = Function->getDescribedFunctionTemplate()) {
151 // Add the "injected" template arguments.
Richard Smith7a9f7c72013-05-17 03:04:50 +0000152 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000153 }
154
John McCallf181d8a2009-08-29 03:16:09 +0000155 // If this is a friend declaration and it declares an entity at
156 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000157 // instead of its semantic parent, unless of course the pattern we're
158 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000159 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000160 Function->getDeclContext()->isFileContext() &&
161 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000162 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000163 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000164 continue;
165 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000166 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
167 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
168 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith7a9f7c72013-05-17 03:04:50 +0000169 const TemplateSpecializationType *TST =
170 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
171 Result.addOuterTemplateArguments(
172 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor24bae922010-07-08 18:37:38 +0000173 if (ClassTemplate->isMemberSpecialization())
174 break;
175 }
Douglas Gregord1102432009-08-28 17:37:35 +0000176 }
John McCallf181d8a2009-08-29 03:16:09 +0000177
178 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000179 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000180 }
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Douglas Gregord1102432009-08-28 17:37:35 +0000182 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000183}
184
Douglas Gregorf35f8282009-11-11 21:54:23 +0000185bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
186 switch (Kind) {
187 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000188 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000189 case DefaultTemplateArgumentInstantiation:
190 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000191 case ExplicitTemplateArgumentSubstitution:
192 case DeducedTemplateArgumentSubstitution:
193 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000194 return true;
195
Douglas Gregorf35f8282009-11-11 21:54:23 +0000196 case DefaultTemplateArgumentChecking:
197 return false;
198 }
David Blaikie7530c032012-01-17 06:56:22 +0000199
200 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000201}
202
Stephen Hines651f13c2014-04-23 16:59:28 -0700203void Sema::InstantiatingTemplate::Initialize(
204 ActiveTemplateInstantiation::InstantiationKind Kind,
205 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
206 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
207 sema::TemplateDeductionInfo *DeductionInfo) {
208 SavedInNonInstantiationSFINAEContext =
209 SemaRef.InNonInstantiationSFINAEContext;
210 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
211 if (!Invalid) {
212 ActiveTemplateInstantiation Inst;
213 Inst.Kind = Kind;
214 Inst.PointOfInstantiation = PointOfInstantiation;
215 Inst.Entity = Entity;
216 Inst.Template = Template;
217 Inst.TemplateArgs = TemplateArgs.data();
218 Inst.NumTemplateArgs = TemplateArgs.size();
219 Inst.DeductionInfo = DeductionInfo;
220 Inst.InstantiationRange = InstantiationRange;
221 SemaRef.InNonInstantiationSFINAEContext = false;
222 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
223 if (!Inst.isInstantiationRecord())
224 ++SemaRef.NonInstantiationEntries;
225 }
226}
227
Douglas Gregor26dce442009-03-10 00:06:19 +0000228Sema::InstantiatingTemplate::
229InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000230 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000231 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700232 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000233{
Stephen Hines651f13c2014-04-23 16:59:28 -0700234 Initialize(ActiveTemplateInstantiation::TemplateInstantiation,
235 PointOfInstantiation, InstantiationRange, Entity);
Douglas Gregordf667e72009-03-10 20:44:00 +0000236}
237
Richard Smithe6975e92012-04-17 00:58:00 +0000238Sema::InstantiatingTemplate::
239InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
240 FunctionDecl *Entity, ExceptionSpecification,
241 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700242 : SemaRef(SemaRef)
Richard Smithe6975e92012-04-17 00:58:00 +0000243{
Stephen Hines651f13c2014-04-23 16:59:28 -0700244 Initialize(ActiveTemplateInstantiation::ExceptionSpecInstantiation,
245 PointOfInstantiation, InstantiationRange, Entity);
Richard Smithe6975e92012-04-17 00:58:00 +0000246}
247
Richard Smith7e54fb52012-07-16 01:09:10 +0000248Sema::InstantiatingTemplate::
249InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
250 TemplateDecl *Template,
251 ArrayRef<TemplateArgument> TemplateArgs,
252 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700253 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000254{
Stephen Hines651f13c2014-04-23 16:59:28 -0700255 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
256 PointOfInstantiation, InstantiationRange,
257 Template, nullptr, TemplateArgs);
Douglas Gregor26dce442009-03-10 00:06:19 +0000258}
259
Richard Smith7e54fb52012-07-16 01:09:10 +0000260Sema::InstantiatingTemplate::
261InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
262 FunctionTemplateDecl *FunctionTemplate,
263 ArrayRef<TemplateArgument> TemplateArgs,
264 ActiveTemplateInstantiation::InstantiationKind Kind,
265 sema::TemplateDeductionInfo &DeductionInfo,
266 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700267 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000268{
Stephen Hines651f13c2014-04-23 16:59:28 -0700269 Initialize(Kind, PointOfInstantiation, InstantiationRange,
270 FunctionTemplate, nullptr, TemplateArgs, &DeductionInfo);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000271}
272
Richard Smith7e54fb52012-07-16 01:09:10 +0000273Sema::InstantiatingTemplate::
274InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
275 ClassTemplatePartialSpecializationDecl *PartialSpec,
276 ArrayRef<TemplateArgument> TemplateArgs,
277 sema::TemplateDeductionInfo &DeductionInfo,
278 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700279 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000280{
Stephen Hines651f13c2014-04-23 16:59:28 -0700281 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
282 PointOfInstantiation, InstantiationRange,
283 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
Douglas Gregor637a4092009-06-10 23:47:09 +0000284}
285
Larisse Voufoef4579c2013-08-06 01:03:05 +0000286Sema::InstantiatingTemplate::InstantiatingTemplate(
287 Sema &SemaRef, SourceLocation PointOfInstantiation,
288 VarTemplatePartialSpecializationDecl *PartialSpec,
289 ArrayRef<TemplateArgument> TemplateArgs,
290 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700291 : SemaRef(SemaRef)
292{
293 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
294 PointOfInstantiation, InstantiationRange,
295 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000296}
297
Richard Smith7e54fb52012-07-16 01:09:10 +0000298Sema::InstantiatingTemplate::
299InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
300 ParmVarDecl *Param,
301 ArrayRef<TemplateArgument> TemplateArgs,
302 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700303 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000304{
Stephen Hines651f13c2014-04-23 16:59:28 -0700305 Initialize(ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
306 PointOfInstantiation, InstantiationRange,
307 Param, nullptr, TemplateArgs);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000308}
309
Stephen Hines651f13c2014-04-23 16:59:28 -0700310
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000311Sema::InstantiatingTemplate::
312InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000313 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
314 ArrayRef<TemplateArgument> TemplateArgs,
315 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700316 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000317{
Stephen Hines651f13c2014-04-23 16:59:28 -0700318 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
319 PointOfInstantiation, InstantiationRange,
320 Param, Template, TemplateArgs);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000321}
322
323Sema::InstantiatingTemplate::
324InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000325 NamedDecl *Template, TemplateTemplateParmDecl *Param,
326 ArrayRef<TemplateArgument> TemplateArgs,
327 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700328 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000329{
Stephen Hines651f13c2014-04-23 16:59:28 -0700330 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
331 PointOfInstantiation, InstantiationRange,
332 Param, Template, TemplateArgs);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000333}
334
335Sema::InstantiatingTemplate::
336InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000337 TemplateDecl *Template, NamedDecl *Param,
338 ArrayRef<TemplateArgument> TemplateArgs,
339 SourceRange InstantiationRange)
Stephen Hines651f13c2014-04-23 16:59:28 -0700340 : SemaRef(SemaRef)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000341{
Stephen Hines651f13c2014-04-23 16:59:28 -0700342 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
343 PointOfInstantiation, InstantiationRange,
344 Param, Template, TemplateArgs);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000345}
346
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000347void Sema::InstantiatingTemplate::Clear() {
348 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000349 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
350 assert(SemaRef.NonInstantiationEntries > 0);
351 --SemaRef.NonInstantiationEntries;
352 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000353 SemaRef.InNonInstantiationSFINAEContext
354 = SavedInNonInstantiationSFINAEContext;
Richard Smithb7751002013-07-25 23:08:39 +0000355
356 // Name lookup no longer looks in this template's defining module.
357 assert(SemaRef.ActiveTemplateInstantiations.size() >=
358 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
359 "forgot to remove a lookup module for a template instantiation");
360 if (SemaRef.ActiveTemplateInstantiations.size() ==
361 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
362 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
363 SemaRef.LookupModulesCache.erase(M);
364 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
365 }
366
Douglas Gregor26dce442009-03-10 00:06:19 +0000367 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000368 Invalid = true;
369 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000370}
371
Douglas Gregordf667e72009-03-10 20:44:00 +0000372bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
373 SourceLocation PointOfInstantiation,
374 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000375 assert(SemaRef.NonInstantiationEntries <=
376 SemaRef.ActiveTemplateInstantiations.size());
377 if ((SemaRef.ActiveTemplateInstantiations.size() -
378 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000379 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000380 return false;
381
Mike Stump1eb44332009-09-09 15:08:12 +0000382 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000383 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000384 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000385 << InstantiationRange;
386 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000387 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000388 return true;
389}
390
Douglas Gregoree1828a2009-03-10 18:03:33 +0000391/// \brief Prints the current instantiation stack through a series of
392/// notes.
393void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000394 // Determine which template instantiations to skip, if any.
395 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
396 unsigned Limit = Diags.getTemplateBacktraceLimit();
397 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
398 SkipStart = Limit / 2 + Limit % 2;
399 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
400 }
401
Douglas Gregorcca9e962009-07-01 22:01:06 +0000402 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000403 unsigned InstantiationIdx = 0;
Craig Topper09d19ef2013-07-04 03:08:24 +0000404 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000405 Active = ActiveTemplateInstantiations.rbegin(),
406 ActiveEnd = ActiveTemplateInstantiations.rend();
407 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000408 ++Active, ++InstantiationIdx) {
409 // Skip this instantiation?
410 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
411 if (InstantiationIdx == SkipStart) {
412 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000413 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000414 diag::note_instantiation_contexts_suppressed)
415 << unsigned(ActiveTemplateInstantiations.size() - Limit);
416 }
417 continue;
418 }
419
Douglas Gregordf667e72009-03-10 20:44:00 +0000420 switch (Active->Kind) {
421 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000422 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000423 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
424 unsigned DiagID = diag::note_template_member_class_here;
425 if (isa<ClassTemplateSpecializationDecl>(Record))
426 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000427 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000428 << Context.getTypeDeclType(Record)
429 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000430 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000431 unsigned DiagID;
432 if (Function->getPrimaryTemplate())
433 DiagID = diag::note_function_template_spec_here;
434 else
435 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000436 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000437 << Function
438 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000439 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000440 Diags.Report(Active->PointOfInstantiation,
Larisse Voufo933c66b2013-08-14 20:15:02 +0000441 VD->isStaticDataMember()?
442 diag::note_template_static_data_member_def_here
443 : diag::note_template_variable_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000444 << VD
445 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000446 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
447 Diags.Report(Active->PointOfInstantiation,
448 diag::note_template_enum_def_here)
449 << ED
450 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000451 } else {
452 Diags.Report(Active->PointOfInstantiation,
453 diag::note_template_type_alias_instantiation_here)
454 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000455 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000456 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000457 break;
458 }
459
460 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000461 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000462 SmallVector<char, 128> TemplateArgsStr;
463 llvm::raw_svector_ostream OS(TemplateArgsStr);
464 Template->printName(OS);
465 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000466 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000467 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000468 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000469 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000470 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000471 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000472 << Active->InstantiationRange;
473 break;
474 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000475
Douglas Gregorcca9e962009-07-01 22:01:06 +0000476 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000477 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000478 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000479 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000480 << FnTmpl
481 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
482 Active->TemplateArgs,
483 Active->NumTemplateArgs)
484 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000485 break;
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Douglas Gregorcca9e962009-07-01 22:01:06 +0000488 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000489 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
490 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000491 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000492 diag::note_partial_spec_deduct_instantiation_here)
493 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000494 << getTemplateArgumentBindingsText(
495 PartialSpec->getTemplateParameters(),
496 Active->TemplateArgs,
497 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000498 << Active->InstantiationRange;
499 } else {
500 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000501 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000502 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000503 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000504 << FnTmpl
505 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
506 Active->TemplateArgs,
507 Active->NumTemplateArgs)
508 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000509 }
510 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000511
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000512 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000513 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000514 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000515
Benjamin Kramer5eada842013-02-22 15:46:01 +0000516 SmallVector<char, 128> TemplateArgsStr;
517 llvm::raw_svector_ostream OS(TemplateArgsStr);
518 FD->printName(OS);
519 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000520 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000521 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000522 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000523 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000524 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000525 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000526 << Active->InstantiationRange;
527 break;
528 }
Mike Stump1eb44332009-09-09 15:08:12 +0000529
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000530 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000531 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000532 std::string Name;
533 if (!Parm->getName().empty())
534 Name = std::string(" '") + Parm->getName().str() + "'";
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700535
536 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000537 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
538 TemplateParams = Template->getTemplateParameters();
539 else
540 TemplateParams =
541 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
542 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000543 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000544 diag::note_prior_template_arg_substitution)
545 << isa<TemplateTemplateParmDecl>(Parm)
546 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000547 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000548 Active->TemplateArgs,
549 Active->NumTemplateArgs)
550 << Active->InstantiationRange;
551 break;
552 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000553
554 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700555 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000556 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
557 TemplateParams = Template->getTemplateParameters();
558 else
559 TemplateParams =
560 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
561 ->getTemplateParameters();
562
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000563 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000564 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000565 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000566 Active->TemplateArgs,
567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
569 break;
570 }
Richard Smithe6975e92012-04-17 00:58:00 +0000571
572 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
573 Diags.Report(Active->PointOfInstantiation,
574 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000575 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000576 << Active->InstantiationRange;
577 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000578 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000579 }
580}
581
David Blaikiedc84cd52013-02-20 22:23:23 +0000582Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000583 if (InNonInstantiationSFINAEContext)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700584 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000585
Craig Topper09d19ef2013-07-04 03:08:24 +0000586 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000587 Active = ActiveTemplateInstantiations.rbegin(),
588 ActiveEnd = ActiveTemplateInstantiations.rend();
589 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000590 ++Active)
591 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000592 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000593 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000594 // An instantiation of an alias template may or may not be a SFINAE
595 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000596 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000597 break;
598 // Fall through.
599 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000600 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000601 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000602 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000603
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000604 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000605 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000606 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000607 // A default template argument instantiation and substitution into
608 // template parameters with arguments for prior parameters may or may
609 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000610 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000611
Douglas Gregorcca9e962009-07-01 22:01:06 +0000612 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
613 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
614 // We're either substitution explicitly-specified template arguments
615 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000616 assert(Active->DeductionInfo && "Missing deduction info pointer");
617 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000618 }
619 }
620
David Blaikie66874fb2013-02-21 01:47:18 +0000621 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000622}
623
Douglas Gregord3731192011-01-10 07:32:04 +0000624/// \brief Retrieve the depth and index of a parameter pack.
625static std::pair<unsigned, unsigned>
626getDepthAndIndex(NamedDecl *ND) {
627 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
628 return std::make_pair(TTP->getDepth(), TTP->getIndex());
629
630 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
631 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
632
633 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
634 return std::make_pair(TTP->getDepth(), TTP->getIndex());
635}
636
Douglas Gregor99ebf652009-02-27 19:31:52 +0000637//===----------------------------------------------------------------------===/
638// Template Instantiation for Types
639//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000640namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000641 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000642 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000643 SourceLocation Loc;
644 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000645
Douglas Gregorcd281c32009-02-28 00:25:32 +0000646 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000647 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000648
649 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000650 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000651 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000652 DeclarationName Entity)
653 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000654 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000655
Mike Stump1eb44332009-09-09 15:08:12 +0000656 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000657 /// transformed.
658 ///
659 /// For the purposes of template instantiation, a type has already been
660 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000661 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000662
Douglas Gregor577f75a2009-08-04 16:50:30 +0000663 /// \brief Returns the location of the entity being instantiated, if known.
664 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000665
Douglas Gregor577f75a2009-08-04 16:50:30 +0000666 /// \brief Returns the name of the entity being instantiated, if any.
667 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000669 /// \brief Sets the "base" location and entity when that
670 /// information is known based on another transformation.
671 void setBase(SourceLocation Loc, DeclarationName Entity) {
672 this->Loc = Loc;
673 this->Entity = Entity;
674 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000675
676 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
677 SourceRange PatternRange,
Robert Wilhelm834c0582013-08-09 18:02:13 +0000678 ArrayRef<UnexpandedParameterPack> Unexpanded,
679 bool &ShouldExpand, bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000680 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000681 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
682 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000683 TemplateArgs,
684 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000685 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000686 NumExpansions);
687 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000688
Douglas Gregor12c9c002011-01-07 16:43:16 +0000689 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
690 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
691 }
692
Douglas Gregord3731192011-01-10 07:32:04 +0000693 TemplateArgument ForgetPartiallySubstitutedPack() {
694 TemplateArgument Result;
695 if (NamedDecl *PartialPack
696 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
697 MultiLevelTemplateArgumentList &TemplateArgs
698 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
699 unsigned Depth, Index;
Stephen Hines651f13c2014-04-23 16:59:28 -0700700 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregord3731192011-01-10 07:32:04 +0000701 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
702 Result = TemplateArgs(Depth, Index);
703 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
704 }
705 }
706
707 return Result;
708 }
709
710 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
711 if (Arg.isNull())
712 return;
713
714 if (NamedDecl *PartialPack
715 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
716 MultiLevelTemplateArgumentList &TemplateArgs
717 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
718 unsigned Depth, Index;
Stephen Hines651f13c2014-04-23 16:59:28 -0700719 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregord3731192011-01-10 07:32:04 +0000720 TemplateArgs.setArgument(Depth, Index, Arg);
721 }
722 }
723
Douglas Gregor577f75a2009-08-04 16:50:30 +0000724 /// \brief Transform the given declaration by instantiating a reference to
725 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000726 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000727
Douglas Gregordfca6f52012-02-13 22:00:16 +0000728 void transformAttrs(Decl *Old, Decl *New) {
729 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
730 }
731
732 void transformedLocalDecl(Decl *Old, Decl *New) {
733 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
734 }
735
Mike Stump1eb44332009-09-09 15:08:12 +0000736 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000737 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000738 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000740 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000741 /// declaration.
742 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
743
Douglas Gregor43959a92009-08-20 07:17:43 +0000744 /// \brief Rebuild the exception declaration and register the declaration
745 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000746 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000747 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000748 SourceLocation StartLoc,
749 SourceLocation NameLoc,
750 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Douglas Gregorbe270a02010-04-26 17:57:08 +0000752 /// \brief Rebuild the Objective-C exception declaration and register the
753 /// declaration as an instantiated local.
754 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
755 TypeSourceInfo *TSInfo, QualType T);
756
John McCallc4e70192009-09-11 04:59:25 +0000757 /// \brief Check for tag mismatches when instantiating an
758 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000759 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
760 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000761 NestedNameSpecifierLoc QualifierLoc,
762 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000763
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700764 TemplateName
765 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
766 SourceLocation NameLoc,
767 QualType ObjectType = QualType(),
768 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000769
John McCall60d7b3a2010-08-24 06:29:42 +0000770 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
771 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
772 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000773
John McCall60d7b3a2010-08-24 06:29:42 +0000774 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000775 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000776 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
777 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000778
779 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
780 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
781
782 /// \brief Transform a reference to a function parameter pack.
783 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
784 ParmVarDecl *PD);
785
786 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
787 /// expand a function parameter pack reference which refers to an expanded
788 /// pack.
789 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
790
Douglas Gregor895162d2010-04-30 18:55:50 +0000791 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000792 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000793 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
794 FunctionProtoTypeLoc TL,
795 CXXRecordDecl *ThisContext,
796 unsigned ThisTypeQuals);
797
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000798 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000799 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000800 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000801 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000802
Mike Stump1eb44332009-09-09 15:08:12 +0000803 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000804 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000805 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000806 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000807
Douglas Gregorc3069d62011-01-14 02:55:32 +0000808 /// \brief Transforms an already-substituted template type parameter pack
809 /// into either itself (if we aren't substituting into its pack expansion)
810 /// or the appropriate substituted argument.
811 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
812 SubstTemplateTypeParmPackTypeLoc TL);
813
John McCall60d7b3a2010-08-24 06:29:42 +0000814 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000815 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000816 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000817 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
818 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000819 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000820 }
John McCall91a57552011-07-15 05:09:51 +0000821
Richard Smith612409e2012-07-25 03:56:55 +0000822 ExprResult TransformLambdaExpr(LambdaExpr *E) {
823 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
824 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
825 }
826
827 ExprResult TransformLambdaScope(LambdaExpr *E,
Bill Wendling2434dcf2013-12-05 05:25:04 +0000828 CXXMethodDecl *NewCallOperator,
829 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
Faisal Valia3d311e2013-10-23 06:44:28 +0000830 CXXMethodDecl *const OldCallOperator = E->getCallOperator();
831 // In the generic lambda case, we set the NewTemplate to be considered
832 // an "instantiation" of the OldTemplate.
833 if (FunctionTemplateDecl *const NewCallOperatorTemplate =
834 NewCallOperator->getDescribedFunctionTemplate()) {
835
836 FunctionTemplateDecl *const OldCallOperatorTemplate =
837 OldCallOperator->getDescribedFunctionTemplate();
838 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
839 OldCallOperatorTemplate);
Faisal Valia3d311e2013-10-23 06:44:28 +0000840 } else
841 // For a non-generic lambda we set the NewCallOperator to
842 // be an instantiation of the OldCallOperator.
843 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
844 TSK_ImplicitInstantiation);
845
Bill Wendling2434dcf2013-12-05 05:25:04 +0000846 return inherited::TransformLambdaScope(E, NewCallOperator,
847 InitCaptureExprsAndTypes);
Rafael Espindolaf003acd2013-10-04 14:28:51 +0000848 }
Stephen Hines651f13c2014-04-23 16:59:28 -0700849 TemplateParameterList *TransformTemplateParameterList(
Faisal Valia3d311e2013-10-23 06:44:28 +0000850 TemplateParameterList *OrigTPL) {
851 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
852
853 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
854 TemplateDeclInstantiator DeclInstantiator(getSema(),
855 /* DeclContext *Owner */ Owner, TemplateArgs);
856 return DeclInstantiator.SubstTemplateParams(OrigTPL);
857 }
John McCall91a57552011-07-15 05:09:51 +0000858 private:
859 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
860 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000861 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000862 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000863}
864
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000865bool TemplateInstantiator::AlreadyTransformed(QualType T) {
866 if (T.isNull())
867 return true;
868
Douglas Gregor561f8122011-07-01 01:22:09 +0000869 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000870 return false;
871
872 getSema().MarkDeclarationsReferencedInType(Loc, T);
873 return true;
874}
875
Eli Friedman10ec0e42013-07-19 19:40:38 +0000876static TemplateArgument
877getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
878 assert(S.ArgumentPackSubstitutionIndex >= 0);
879 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
880 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
881 if (Arg.isPackExpansion())
882 Arg = Arg.getPackExpansionPattern();
883 return Arg;
884}
885
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000886Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000887 if (!D)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700888 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000889
Douglas Gregorc68afe22009-09-03 21:38:09 +0000890 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000891 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000892 // If the corresponding template argument is NULL or non-existent, it's
893 // because we are performing instantiation from explicitly-specified
894 // template arguments in a function template, but there were some
895 // arguments left unspecified.
896 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
897 TTP->getPosition()))
898 return D;
899
Douglas Gregor61c4d282011-01-05 15:48:55 +0000900 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
901
902 if (TTP->isParameterPack()) {
903 assert(Arg.getKind() == TemplateArgument::Pack &&
904 "Missing argument pack");
Eli Friedman10ec0e42013-07-19 19:40:38 +0000905 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000906 }
907
908 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000909 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000910 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000911 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000912 }
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Douglas Gregor788cd062009-11-11 01:00:40 +0000914 // Fall through to find the instantiated declaration for this template
915 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000916 }
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000918 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000919}
920
Douglas Gregoraac571c2010-03-01 17:25:41 +0000921Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000922 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000923 if (!Inst)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700924 return nullptr;
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Douglas Gregor43959a92009-08-20 07:17:43 +0000926 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
927 return Inst;
928}
929
Douglas Gregor6cd21982009-10-20 05:58:46 +0000930NamedDecl *
931TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
932 SourceLocation Loc) {
933 // If the first part of the nested-name-specifier was a template type
934 // parameter, instantiate that type parameter down to a tag type.
935 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
936 const TemplateTypeParmType *TTP
937 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000938
Douglas Gregor6cd21982009-10-20 05:58:46 +0000939 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000940 // FIXME: This needs testing w/ member access expressions.
941 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
942
943 if (TTP->isParameterPack()) {
944 assert(Arg.getKind() == TemplateArgument::Pack &&
945 "Missing argument pack");
946
Douglas Gregor2be29f42011-01-14 23:41:42 +0000947 if (getSema().ArgumentPackSubstitutionIndex == -1)
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700948 return nullptr;
949
Eli Friedman10ec0e42013-07-19 19:40:38 +0000950 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor984a58b2010-12-20 22:48:17 +0000951 }
952
953 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000954 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000955 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000956
957 if (const TagType *Tag = T->getAs<TagType>())
958 return Tag->getDecl();
959
960 // The resulting type is not a tag; complain.
961 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700962 return nullptr;
Douglas Gregor6cd21982009-10-20 05:58:46 +0000963 }
964 }
965
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000966 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000967}
968
Douglas Gregor43959a92009-08-20 07:17:43 +0000969VarDecl *
970TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000971 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000972 SourceLocation StartLoc,
973 SourceLocation NameLoc,
974 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000975 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000976 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000977 if (Var)
978 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
979 return Var;
980}
981
982VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
983 TypeSourceInfo *TSInfo,
984 QualType T) {
985 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
986 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000987 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
988 return Var;
989}
990
John McCallc4e70192009-09-11 04:59:25 +0000991QualType
John McCall21e413f2010-11-04 19:04:38 +0000992TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
993 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000994 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +0000995 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +0000996 if (const TagType *TT = T->getAs<TagType>()) {
997 TagDecl* TD = TT->getDecl();
998
John McCall21e413f2010-11-04 19:04:38 +0000999 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001000
John McCallc4e70192009-09-11 04:59:25 +00001001 IdentifierInfo *Id = TD->getIdentifier();
1002
1003 // TODO: should we even warn on struct/class mismatches for this? Seems
1004 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001005 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001006 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001007 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1008 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001009 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1010 << Id
1011 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1012 TD->getKindName());
1013 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1014 }
John McCallc4e70192009-09-11 04:59:25 +00001015 }
1016 }
1017
John McCall21e413f2010-11-04 19:04:38 +00001018 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1019 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001020 QualifierLoc,
1021 T);
John McCallc4e70192009-09-11 04:59:25 +00001022}
1023
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001024TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1025 TemplateName Name,
1026 SourceLocation NameLoc,
1027 QualType ObjectType,
1028 NamedDecl *FirstQualifierInScope) {
1029 if (TemplateTemplateParmDecl *TTP
1030 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1031 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1032 // If the corresponding template argument is NULL or non-existent, it's
1033 // because we are performing instantiation from explicitly-specified
1034 // template arguments in a function template, but there were some
1035 // arguments left unspecified.
1036 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1037 TTP->getPosition()))
1038 return Name;
1039
1040 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1041
1042 if (TTP->isParameterPack()) {
1043 assert(Arg.getKind() == TemplateArgument::Pack &&
1044 "Missing argument pack");
1045
1046 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1047 // We have the template argument pack to substitute, but we're not
1048 // actually expanding the enclosing pack expansion yet. So, just
1049 // keep the entire argument pack.
1050 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1051 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001052
1053 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001054 }
1055
1056 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001057 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001058
Douglas Gregor58750382011-03-05 20:06:51 +00001059 // We don't ever want to substitute for a qualified template name, since
1060 // the qualifier is handled separately. So, look through the qualified
1061 // template name to its underlying declaration.
1062 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1063 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001064
1065 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001066 return Template;
1067 }
1068 }
1069
1070 if (SubstTemplateTemplateParmPackStorage *SubstPack
1071 = Name.getAsSubstTemplateTemplateParmPack()) {
1072 if (getSema().ArgumentPackSubstitutionIndex == -1)
1073 return Name;
1074
Eli Friedman10ec0e42013-07-19 19:40:38 +00001075 TemplateArgument Arg = SubstPack->getArgumentPack();
1076 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1077 return Arg.getAsTemplate();
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001078 }
1079
1080 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1081 FirstQualifierInScope);
1082}
1083
John McCall60d7b3a2010-08-24 06:29:42 +00001084ExprResult
John McCall454feb92009-12-08 09:21:05 +00001085TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001086 if (!E->isTypeDependent())
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001087 return E;
Anders Carlsson773f3972009-09-11 01:22:35 +00001088
Wei Pan33129332013-09-16 13:57:27 +00001089 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson773f3972009-09-11 01:22:35 +00001090}
1091
John McCall60d7b3a2010-08-24 06:29:42 +00001092ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001093TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001094 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001095 // If the corresponding template argument is NULL or non-existent, it's
1096 // because we are performing instantiation from explicitly-specified
1097 // template arguments in a function template, but there were some
1098 // arguments left unspecified.
1099 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1100 NTTP->getPosition()))
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001101 return E;
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Douglas Gregor56bc9832010-12-24 00:15:10 +00001103 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1104 if (NTTP->isParameterPack()) {
1105 assert(Arg.getKind() == TemplateArgument::Pack &&
1106 "Missing argument pack");
1107
1108 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001109 // We have an argument pack, but we can't select a particular argument
1110 // out of it yet. Therefore, we'll build an expression to hold on to that
1111 // argument pack.
1112 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1113 E->getLocation(),
1114 NTTP->getDeclName());
1115 if (TargetType.isNull())
1116 return ExprError();
1117
1118 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1119 NTTP,
1120 E->getLocation(),
1121 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001122 }
1123
Eli Friedman10ec0e42013-07-19 19:40:38 +00001124 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001125 }
Mike Stump1eb44332009-09-09 15:08:12 +00001126
John McCall91a57552011-07-15 05:09:51 +00001127 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1128}
1129
1130ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1131 NonTypeTemplateParmDecl *parm,
1132 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001133 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001134 ExprResult result;
1135 QualType type;
1136
John McCallb8fc0532010-02-06 08:42:39 +00001137 // The template argument itself might be an expression, in which
1138 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001139 if (arg.getKind() == TemplateArgument::Expression) {
1140 Expr *argExpr = arg.getAsExpr();
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001141 result = argExpr;
John McCall91a57552011-07-15 05:09:51 +00001142 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Eli Friedmand7a6b162012-09-26 02:36:12 +00001144 } else if (arg.getKind() == TemplateArgument::Declaration ||
1145 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001146 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001147 if (arg.getKind() == TemplateArgument::Declaration) {
1148 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Douglas Gregord2008e22012-04-06 22:40:38 +00001150 // Find the instantiation of the template argument. This is
1151 // required for nested templates.
1152 VD = cast_or_null<ValueDecl>(
1153 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1154 if (!VD)
1155 return ExprError();
1156 } else {
1157 // Propagate NULL template argument.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001158 VD = nullptr;
Douglas Gregord2008e22012-04-06 22:40:38 +00001159 }
1160
John McCall645cf442010-02-06 10:23:53 +00001161 // Derive the type we want the substituted decl to have. This had
1162 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001163 if (parm->isExpandedParameterPack()) {
1164 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1165 } else if (parm->isParameterPack() &&
1166 isa<PackExpansionType>(parm->getType())) {
1167 type = SemaRef.SubstType(
1168 cast<PackExpansionType>(parm->getType())->getPattern(),
1169 TemplateArgs, loc, parm->getDeclName());
1170 } else {
1171 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1172 loc, parm->getDeclName());
1173 }
1174 assert(!type.isNull() && "type substitution failed for param type");
1175 assert(!type->isDependentType() && "param type still dependent");
1176 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001177
John McCall91a57552011-07-15 05:09:51 +00001178 if (!result.isInvalid()) type = result.get()->getType();
1179 } else {
1180 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1181
1182 // Note that this type can be different from the type of 'result',
1183 // e.g. if it's an enum type.
1184 type = arg.getIntegralType();
1185 }
1186 if (result.isInvalid()) return ExprError();
1187
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001188 Expr *resultExpr = result.get();
1189 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1190 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCallb8fc0532010-02-06 08:42:39 +00001191}
1192
Douglas Gregorc7793c72011-01-15 01:15:58 +00001193ExprResult
1194TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1195 SubstNonTypeTemplateParmPackExpr *E) {
1196 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1197 // We aren't expanding the parameter pack, so just return ourselves.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001198 return E;
Douglas Gregorc7793c72011-01-15 01:15:58 +00001199 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001200
1201 TemplateArgument Arg = E->getArgumentPack();
1202 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall91a57552011-07-15 05:09:51 +00001203 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1204 E->getParameterPackLocation(),
1205 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001206}
John McCallb8fc0532010-02-06 08:42:39 +00001207
John McCall60d7b3a2010-08-24 06:29:42 +00001208ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001209TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1210 SourceLocation Loc) {
1211 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1212 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1213}
1214
1215ExprResult
1216TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1217 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1218 // We can expand this parameter pack now.
1219 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1220 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1221 if (!VD)
1222 return ExprError();
1223 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1224 }
1225
1226 QualType T = TransformType(E->getType());
1227 if (T.isNull())
1228 return ExprError();
1229
1230 // Transform each of the parameter expansions into the corresponding
1231 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001232 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001233 Parms.reserve(E->getNumExpansions());
1234 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1235 I != End; ++I) {
1236 ParmVarDecl *D =
1237 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1238 if (!D)
1239 return ExprError();
1240 Parms.push_back(D);
1241 }
1242
1243 return FunctionParmPackExpr::Create(getSema().Context, T,
1244 E->getParameterPack(),
1245 E->getParameterPackLocation(), Parms);
1246}
1247
1248ExprResult
1249TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1250 ParmVarDecl *PD) {
1251 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1252 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1253 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1254 assert(Found && "no instantiation for parameter pack");
1255
1256 Decl *TransformedDecl;
1257 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1258 // If this is a reference to a function parameter pack which we can substitute
1259 // but can't yet expand, build a FunctionParmPackExpr for it.
1260 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1261 QualType T = TransformType(E->getType());
1262 if (T.isNull())
1263 return ExprError();
1264 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1265 E->getExprLoc(), *Pack);
1266 }
1267
1268 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1269 } else {
1270 TransformedDecl = Found->get<Decl*>();
1271 }
1272
1273 // We have either an unexpanded pack or a specific expansion.
1274 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1275 E->getExprLoc());
1276}
1277
1278ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001279TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1280 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001281
1282 // Handle references to non-type template parameters and non-type template
1283 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001284 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1285 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1286 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001287
1288 // We have a non-type template parameter that isn't fully substituted;
1289 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001290 }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Richard Smith9a4db032012-09-12 00:56:43 +00001292 // Handle references to function parameter packs.
1293 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1294 if (PD->isParameterPack())
1295 return TransformFunctionParmPackRefExpr(E, PD);
1296
John McCall454feb92009-12-08 09:21:05 +00001297 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001298}
1299
John McCall60d7b3a2010-08-24 06:29:42 +00001300ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001301 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001302 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1303 getDescribedFunctionTemplate() &&
1304 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001305 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1306 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1307 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001308}
1309
Douglas Gregor895162d2010-04-30 18:55:50 +00001310QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001311 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001312 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001313 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001314 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001315}
1316
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001317QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1318 FunctionProtoTypeLoc TL,
1319 CXXRecordDecl *ThisContext,
1320 unsigned ThisTypeQuals) {
1321 // We need a local instantiation scope for this function prototype.
1322 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1323 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1324 ThisTypeQuals);
1325}
1326
John McCall21ef0fa2010-03-11 09:03:00 +00001327ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001328TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001329 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001330 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001331 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001332 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001333 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001334}
1335
Mike Stump1eb44332009-09-09 15:08:12 +00001336QualType
John McCalla2becad2009-10-21 00:40:46 +00001337TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001338 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001339 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001340 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001341 // Replace the template type parameter with its corresponding
1342 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001343
1344 // If the corresponding template argument is NULL or doesn't exist, it's
1345 // because we are performing instantiation from explicitly-specified
1346 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001347 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001348 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1349 TemplateTypeParmTypeLoc NewTL
1350 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1351 NewTL.setNameLoc(TL.getNameLoc());
1352 return TL.getType();
1353 }
Mike Stump1eb44332009-09-09 15:08:12 +00001354
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001355 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1356
1357 if (T->isParameterPack()) {
1358 assert(Arg.getKind() == TemplateArgument::Pack &&
1359 "Missing argument pack");
1360
1361 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001362 // We have the template argument pack, but we're not expanding the
1363 // enclosing pack expansion yet. Just save the template argument
1364 // pack for later substitution.
1365 QualType Result
1366 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1367 SubstTemplateTypeParmPackTypeLoc NewTL
1368 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1369 NewTL.setNameLoc(TL.getNameLoc());
1370 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001371 }
1372
Eli Friedman10ec0e42013-07-19 19:40:38 +00001373 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001374 }
1375
1376 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001377 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001378
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001379 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001380
1381 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001382 QualType Result
1383 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1384 SubstTemplateTypeParmTypeLoc NewTL
1385 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1386 NewTL.setNameLoc(TL.getNameLoc());
1387 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001388 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001389
1390 // The template type parameter comes from an inner template (e.g.,
1391 // the template parameter list of a member template inside the
1392 // template we are instantiating). Create a new template type
1393 // parameter with the template "level" reduced by one.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001394 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001395 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1396 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1397 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1398
John McCalla2becad2009-10-21 00:40:46 +00001399 QualType Result
1400 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1401 - TemplateArgs.getNumLevels(),
1402 T->getIndex(),
1403 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001404 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001405 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1406 NewTL.setNameLoc(TL.getNameLoc());
1407 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001408}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001409
Douglas Gregorc3069d62011-01-14 02:55:32 +00001410QualType
1411TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1412 TypeLocBuilder &TLB,
1413 SubstTemplateTypeParmPackTypeLoc TL) {
1414 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1415 // We aren't expanding the parameter pack, so just return ourselves.
1416 SubstTemplateTypeParmPackTypeLoc NewTL
1417 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1418 NewTL.setNameLoc(TL.getNameLoc());
1419 return TL.getType();
1420 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001421
1422 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1423 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1424 QualType Result = Arg.getAsType();
1425
Douglas Gregorc3069d62011-01-14 02:55:32 +00001426 Result = getSema().Context.getSubstTemplateTypeParmType(
1427 TL.getTypePtr()->getReplacedParameter(),
1428 Result);
1429 SubstTemplateTypeParmTypeLoc NewTL
1430 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1431 NewTL.setNameLoc(TL.getNameLoc());
1432 return Result;
1433}
1434
John McCallce3ff2b2009-08-25 22:02:44 +00001435/// \brief Perform substitution on the type T with a given set of template
1436/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001437///
1438/// This routine substitutes the given template arguments into the
1439/// type T and produces the instantiated type.
1440///
1441/// \param T the type into which the template arguments will be
1442/// substituted. If this type is not dependent, it will be returned
1443/// immediately.
1444///
James Dennett1dfbd922012-06-14 21:40:34 +00001445/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001446/// substituted for the top-level template parameters within T.
1447///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001448/// \param Loc the location in the source code where this substitution
1449/// is being performed. It will typically be the location of the
1450/// declarator (if we're instantiating the type of some declaration)
1451/// or the location of the type in the source code (if, e.g., we're
1452/// instantiating the type of a cast expression).
1453///
1454/// \param Entity the name of the entity associated with a declaration
1455/// being instantiated (if any). May be empty to indicate that there
1456/// is no such entity (if, e.g., this is a type that occurs as part of
1457/// a cast expression) or that the entity has no name (e.g., an
1458/// unnamed function parameter).
1459///
1460/// \returns If the instantiation succeeds, the instantiated
1461/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001462TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001463 const MultiLevelTemplateArgumentList &Args,
1464 SourceLocation Loc,
1465 DeclarationName Entity) {
1466 assert(!ActiveTemplateInstantiations.empty() &&
1467 "Cannot perform an instantiation without some context on the "
1468 "instantiation stack");
1469
Douglas Gregor561f8122011-07-01 01:22:09 +00001470 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001471 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001472 return T;
1473
1474 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1475 return Instantiator.TransformType(T);
1476}
1477
Douglas Gregor603cfb42011-01-05 23:12:31 +00001478TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1479 const MultiLevelTemplateArgumentList &Args,
1480 SourceLocation Loc,
1481 DeclarationName Entity) {
1482 assert(!ActiveTemplateInstantiations.empty() &&
1483 "Cannot perform an instantiation without some context on the "
1484 "instantiation stack");
1485
1486 if (TL.getType().isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001487 return nullptr;
Douglas Gregor603cfb42011-01-05 23:12:31 +00001488
Douglas Gregor561f8122011-07-01 01:22:09 +00001489 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001490 !TL.getType()->isVariablyModifiedType()) {
1491 // FIXME: Make a copy of the TypeLoc data here, so that we can
1492 // return a new TypeSourceInfo. Inefficient!
1493 TypeLocBuilder TLB;
1494 TLB.pushFullCopy(TL);
1495 return TLB.getTypeSourceInfo(Context, TL.getType());
1496 }
1497
1498 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1499 TypeLocBuilder TLB;
1500 TLB.reserve(TL.getFullDataSize());
1501 QualType Result = Instantiator.TransformType(TLB, TL);
1502 if (Result.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001503 return nullptr;
Douglas Gregor603cfb42011-01-05 23:12:31 +00001504
1505 return TLB.getTypeSourceInfo(Context, Result);
1506}
1507
John McCallcd7ba1c2009-10-21 00:58:09 +00001508/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001509QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001510 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001511 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001512 assert(!ActiveTemplateInstantiations.empty() &&
1513 "Cannot perform an instantiation without some context on the "
1514 "instantiation stack");
1515
Douglas Gregor836adf62010-05-24 17:22:01 +00001516 // If T is not a dependent type or a variably-modified type, there
1517 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001518 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001519 return T;
1520
Douglas Gregor577f75a2009-08-04 16:50:30 +00001521 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1522 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001523}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001524
John McCall6cd3b9f2010-04-09 17:38:44 +00001525static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001526 if (T->getType()->isInstantiationDependentType() ||
1527 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001528 return true;
1529
Abramo Bagnara723df242010-12-14 22:11:44 +00001530 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001531 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001532 return false;
1533
David Blaikie39e6ab42013-02-18 22:06:02 +00001534 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Stephen Hines651f13c2014-04-23 16:59:28 -07001535 for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) {
1536 ParmVarDecl *P = FP.getParam(I);
John McCall6cd3b9f2010-04-09 17:38:44 +00001537
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001538 // This must be synthesized from a typedef.
1539 if (!P) continue;
1540
Douglas Gregorc056c172011-05-09 20:45:16 +00001541 // The parameter's type as written might be dependent even if the
1542 // decayed type was not dependent.
1543 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001544 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001545 return true;
1546
John McCall6cd3b9f2010-04-09 17:38:44 +00001547 // TODO: currently we always rebuild expressions. When we
1548 // properly get lazier about this, we should use the same
1549 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001550 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001551 return true;
1552 }
1553
1554 return false;
1555}
1556
1557/// A form of SubstType intended specifically for instantiating the
1558/// type of a FunctionDecl. Its purpose is solely to force the
1559/// instantiation of default-argument expressions.
1560TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1561 const MultiLevelTemplateArgumentList &Args,
1562 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001563 DeclarationName Entity,
1564 CXXRecordDecl *ThisContext,
1565 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001566 assert(!ActiveTemplateInstantiations.empty() &&
1567 "Cannot perform an instantiation without some context on the "
1568 "instantiation stack");
1569
1570 if (!NeedsInstantiationAsFunctionType(T))
1571 return T;
1572
1573 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1574
1575 TypeLocBuilder TLB;
1576
1577 TypeLoc TL = T->getTypeLoc();
1578 TLB.reserve(TL.getFullDataSize());
1579
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001580 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001581
1582 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1583 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001584 ThisTypeQuals);
1585 } else {
1586 Result = Instantiator.TransformType(TLB, TL);
1587 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001588 if (Result.isNull())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001589 return nullptr;
John McCall6cd3b9f2010-04-09 17:38:44 +00001590
1591 return TLB.getTypeSourceInfo(Context, Result);
1592}
1593
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001594ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001595 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001596 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001597 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001598 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001599 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001600 TypeSourceInfo *NewDI = nullptr;
1601
Douglas Gregor603cfb42011-01-05 23:12:31 +00001602 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001603 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1604
Douglas Gregor603cfb42011-01-05 23:12:31 +00001605 // We have a function parameter pack. Substitute into the pattern of the
1606 // expansion.
1607 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1608 OldParm->getLocation(), OldParm->getDeclName());
1609 if (!NewDI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001610 return nullptr;
1611
Douglas Gregor603cfb42011-01-05 23:12:31 +00001612 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1613 // We still have unexpanded parameter packs, which means that
1614 // our function parameter is still a function parameter pack.
1615 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001616 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001617 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001618 } else if (ExpectParameterPack) {
1619 // We expected to get a parameter pack but didn't (because the type
1620 // itself is not a pack expansion type), so complain. This can occur when
1621 // the substitution goes through an alias template that "loses" the
1622 // pack expansion.
1623 Diag(OldParm->getLocation(),
1624 diag::err_function_parameter_pack_without_parameter_packs)
1625 << NewDI->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001626 return nullptr;
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001627 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001628 } else {
1629 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1630 OldParm->getDeclName());
1631 }
1632
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001633 if (!NewDI)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001634 return nullptr;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001635
1636 if (NewDI->getType()->isVoidType()) {
1637 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001638 return nullptr;
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001639 }
1640
1641 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001642 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001643 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001644 OldParm->getIdentifier(),
1645 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001646 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001647 if (!NewParm)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001648 return nullptr;
1649
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001650 // Mark the (new) default argument as uninstantiated (if any).
1651 if (OldParm->hasUninstantiatedDefaultArg()) {
1652 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1653 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001654 } else if (OldParm->hasUnparsedDefaultArg()) {
1655 NewParm->setUnparsedDefaultArg();
1656 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001657 } else if (Expr *Arg = OldParm->getDefaultArg())
1658 // FIXME: if we non-lazily instantiated non-dependent default args for
1659 // non-dependent parameter types we could remove a bunch of duplicate
1660 // conversion warnings for such arguments.
1661 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001662
1663 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001664
Douglas Gregor12c9c002011-01-07 16:43:16 +00001665 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001666 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001667 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1668 } else {
1669 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001670 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001671 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001672
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001673 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1674 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001675 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001676
1677 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1678 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001679
1680 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1681
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001682 return NewParm;
1683}
1684
Douglas Gregora009b592011-01-07 00:20:55 +00001685/// \brief Substitute the given template arguments into the given set of
1686/// parameters, producing the set of parameter types that would be generated
1687/// from such a substitution.
1688bool Sema::SubstParmTypes(SourceLocation Loc,
1689 ParmVarDecl **Params, unsigned NumParams,
1690 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001691 SmallVectorImpl<QualType> &ParamTypes,
1692 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001693 assert(!ActiveTemplateInstantiations.empty() &&
1694 "Cannot perform an instantiation without some context on the "
1695 "instantiation stack");
1696
1697 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1698 DeclarationName());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001699 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
1700 nullptr, ParamTypes,
1701 OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001702}
1703
John McCallce3ff2b2009-08-25 22:02:44 +00001704/// \brief Perform substitution on the base class specifiers of the
1705/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001706///
1707/// Produces a diagnostic and returns true on error, returns false and
1708/// attaches the instantiated base classes to the class template
1709/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001710bool
John McCallce3ff2b2009-08-25 22:02:44 +00001711Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1712 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001713 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001714 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001715 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Stephen Hines651f13c2014-04-23 16:59:28 -07001716 for (const auto Base : Pattern->bases()) {
1717 if (!Base.getType()->isDependentType()) {
1718 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay538fccb2013-06-21 18:58:32 +00001719 if (RD->isInvalidDecl())
1720 Instantiation->setInvalidDecl();
1721 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001722 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001723 continue;
1724 }
1725
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001726 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001727 TypeSourceInfo *BaseTypeLoc;
Stephen Hines651f13c2014-04-23 16:59:28 -07001728 if (Base.isPackExpansion()) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001729 // This is a pack expansion. See whether we should expand it now, or
1730 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001731 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Stephen Hines651f13c2014-04-23 16:59:28 -07001732 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001733 Unexpanded);
1734 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001735 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001736 Optional<unsigned> NumExpansions;
Stephen Hines651f13c2014-04-23 16:59:28 -07001737 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1738 Base.getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001739 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001740 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001741 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001742 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001743 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001744 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001745 }
1746
1747 // If we should expand this pack expansion now, do so.
1748 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001749 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001750 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1751
Stephen Hines651f13c2014-04-23 16:59:28 -07001752 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001753 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001754 Base.getSourceRange().getBegin(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001755 DeclarationName());
1756 if (!BaseTypeLoc) {
1757 Invalid = true;
1758 continue;
1759 }
1760
1761 if (CXXBaseSpecifier *InstantiatedBase
1762 = CheckBaseSpecifier(Instantiation,
Stephen Hines651f13c2014-04-23 16:59:28 -07001763 Base.getSourceRange(),
1764 Base.isVirtual(),
1765 Base.getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001766 BaseTypeLoc,
1767 SourceLocation()))
1768 InstantiatedBases.push_back(InstantiatedBase);
1769 else
1770 Invalid = true;
1771 }
1772
1773 continue;
1774 }
1775
1776 // The resulting base specifier will (still) be a pack expansion.
Stephen Hines651f13c2014-04-23 16:59:28 -07001777 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001778 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Stephen Hines651f13c2014-04-23 16:59:28 -07001779 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001780 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001781 Base.getSourceRange().getBegin(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001782 DeclarationName());
1783 } else {
Stephen Hines651f13c2014-04-23 16:59:28 -07001784 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001785 TemplateArgs,
Stephen Hines651f13c2014-04-23 16:59:28 -07001786 Base.getSourceRange().getBegin(),
Douglas Gregor406f98f2011-03-02 02:04:06 +00001787 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001788 }
1789
Nick Lewycky56062202010-07-26 16:56:01 +00001790 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001791 Invalid = true;
1792 continue;
1793 }
1794
1795 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001796 = CheckBaseSpecifier(Instantiation,
Stephen Hines651f13c2014-04-23 16:59:28 -07001797 Base.getSourceRange(),
1798 Base.isVirtual(),
1799 Base.getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001800 BaseTypeLoc,
1801 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001802 InstantiatedBases.push_back(InstantiatedBase);
1803 else
1804 Invalid = true;
1805 }
1806
Douglas Gregor27b152f2009-03-10 18:52:44 +00001807 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001808 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001809 InstantiatedBases.size()))
1810 Invalid = true;
1811
1812 return Invalid;
1813}
1814
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001815// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001816namespace clang {
1817 namespace sema {
1818 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1819 const MultiLevelTemplateArgumentList &TemplateArgs);
1820 }
1821}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001822
Richard Smithf1c66b42012-03-14 23:13:10 +00001823/// Determine whether we would be unable to instantiate this template (because
1824/// it either has no definition, or is in the process of being instantiated).
1825static bool DiagnoseUninstantiableTemplate(Sema &S,
1826 SourceLocation PointOfInstantiation,
1827 TagDecl *Instantiation,
1828 bool InstantiatedFromMember,
1829 TagDecl *Pattern,
1830 TagDecl *PatternDef,
1831 TemplateSpecializationKind TSK,
1832 bool Complain = true) {
1833 if (PatternDef && !PatternDef->isBeingDefined())
1834 return false;
1835
1836 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1837 // Say nothing
1838 } else if (PatternDef) {
1839 assert(PatternDef->isBeingDefined());
1840 S.Diag(PointOfInstantiation,
1841 diag::err_template_instantiate_within_definition)
1842 << (TSK != TSK_ImplicitInstantiation)
1843 << S.Context.getTypeDeclType(Instantiation);
1844 // Not much point in noting the template declaration here, since
1845 // we're lexically inside it.
1846 Instantiation->setInvalidDecl();
1847 } else if (InstantiatedFromMember) {
1848 S.Diag(PointOfInstantiation,
1849 diag::err_implicit_instantiate_member_undefined)
1850 << S.Context.getTypeDeclType(Instantiation);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001851 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
Richard Smithf1c66b42012-03-14 23:13:10 +00001852 } else {
1853 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1854 << (TSK != TSK_ImplicitInstantiation)
1855 << S.Context.getTypeDeclType(Instantiation);
1856 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1857 }
1858
1859 // In general, Instantiation isn't marked invalid to get more than one
1860 // error for multiple undefined instantiations. But the code that does
1861 // explicit declaration -> explicit definition conversion can't handle
1862 // invalid declarations, so mark as invalid in that case.
1863 if (TSK == TSK_ExplicitInstantiationDeclaration)
1864 Instantiation->setInvalidDecl();
1865 return true;
1866}
1867
Douglas Gregord475b8d2009-03-25 21:17:03 +00001868/// \brief Instantiate the definition of a class from a given pattern.
1869///
1870/// \param PointOfInstantiation The point of instantiation within the
1871/// source code.
1872///
1873/// \param Instantiation is the declaration whose definition is being
1874/// instantiated. This will be either a class template specialization
1875/// or a member class of a class template specialization.
1876///
1877/// \param Pattern is the pattern from which the instantiation
1878/// occurs. This will be either the declaration of a class template or
1879/// the declaration of a member class of a class template.
1880///
1881/// \param TemplateArgs The template arguments to be substituted into
1882/// the pattern.
1883///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001884/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001885///
1886/// \param Complain whether to complain if the class cannot be instantiated due
1887/// to the lack of a definition.
1888///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001889/// \returns true if an error occurred, false otherwise.
1890bool
1891Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1892 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001893 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001894 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001895 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001896 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001897 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001898 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1899 Instantiation->getInstantiatedFromMemberClass(),
1900 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001901 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001902 Pattern = PatternDef;
1903
Douglas Gregor454885e2009-10-15 15:54:05 +00001904 // \brief Record the point of instantiation.
1905 if (MemberSpecializationInfo *MSInfo
1906 = Instantiation->getMemberSpecializationInfo()) {
1907 MSInfo->setTemplateSpecializationKind(TSK);
1908 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001909 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001910 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001911 Spec->setTemplateSpecializationKind(TSK);
1912 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001913 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001914
Douglas Gregord048bb72009-03-25 21:23:52 +00001915 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd69f37b2013-10-08 08:09:04 +00001916 if (Inst.isInvalid())
Douglas Gregord475b8d2009-03-25 21:17:03 +00001917 return true;
1918
1919 // Enter the scope of this instantiation. We don't use
1920 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001921 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001922 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001923 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001924
Douglas Gregor05030bb2010-03-24 01:33:17 +00001925 // If this is an instantiation of a local class, merge this local
1926 // instantiation scope with the enclosing scope. Otherwise, every
1927 // instantiation of a class has its own local instantiation scope.
1928 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001929 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001930
John McCall1d8d1cc2010-08-01 02:01:53 +00001931 // Pull attributes from the pattern onto the instantiation.
1932 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1933
Douglas Gregord475b8d2009-03-25 21:17:03 +00001934 // Start the definition of this instantiation.
1935 Instantiation->startDefinition();
Stephen Hines651f13c2014-04-23 16:59:28 -07001936
1937 // The instantiation is visible here, even if it was first declared in an
1938 // unimported module.
1939 Instantiation->setHidden(false);
1940
1941 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregor13c85772010-05-06 00:28:52 +00001942 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001943
John McCallce3ff2b2009-08-25 22:02:44 +00001944 // Do substitution on the base class specifiers.
1945 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001946 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001947
Douglas Gregord65587f2010-11-10 19:44:59 +00001948 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001949 SmallVector<Decl*, 4> Fields;
1950 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001951 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001952 // Delay instantiation of late parsed attributes.
1953 LateInstantiatedAttrVec LateAttrs;
1954 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1955
Stephen Hines651f13c2014-04-23 16:59:28 -07001956 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001957 // Don't instantiate members not belonging in this semantic context.
1958 // e.g. for:
1959 // @code
1960 // template <int i> class A {
1961 // class B *g;
1962 // };
1963 // @endcode
1964 // 'class B' has the template as lexical context but semantically it is
1965 // introduced in namespace scope.
Stephen Hines651f13c2014-04-23 16:59:28 -07001966 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001967 continue;
1968
Stephen Hines651f13c2014-04-23 16:59:28 -07001969 if (Member->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00001970 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00001971 continue;
1972 }
1973
Stephen Hines651f13c2014-04-23 16:59:28 -07001974 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001975 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00001976 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00001977 Fields.push_back(Field);
Stephen Hines651f13c2014-04-23 16:59:28 -07001978 FieldDecl *OldField = cast<FieldDecl>(Member);
Richard Smith7a614d82011-06-11 17:19:42 +00001979 if (OldField->getInClassInitializer())
1980 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1981 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00001982 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
1983 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1984 // specialization causes the implicit instantiation of the definitions
1985 // of unscoped member enumerations.
1986 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00001987 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
1988 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00001989 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
1990 assert(MSInfo && "no spec info for member enum specialization");
1991 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
1992 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1993 }
Richard Smithe3f470a2012-07-11 22:37:56 +00001994 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
1995 if (SA->isFailed()) {
1996 // A static_assert failed. Bail out; instantiating this
1997 // class is probably not meaningful.
1998 Instantiation->setInvalidDecl();
1999 break;
2000 }
Richard Smith1af83c42012-03-23 03:33:32 +00002001 }
2002
2003 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002004 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002005 } else {
2006 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002007 // instantiations was a semantic disaster, and we'll want to mark the
2008 // declaration invalid.
2009 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002010 }
2011 }
2012
2013 // Finish checking fields.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002014 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2015 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002016 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002017
2018 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002019 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002020 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002021 // C++11 [expr.prim.general]p4:
2022 // Otherwise, if a member-declarator declares a non-static data member
2023 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2024 // to X" within the optional brace-or-equal-initializer. It shall not
2025 // appear elsewhere in the member-declarator.
2026 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2027
2028 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2029 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2030 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2031 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002032
Stephen Hines651f13c2014-04-23 16:59:28 -07002033 ActOnStartCXXInClassMemberInitializer();
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002034 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2035 /*CXXDirectInit=*/false);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002036 Expr *Init = NewInit.get();
Stephen Hines651f13c2014-04-23 16:59:28 -07002037 assert((!Init || !isa<ParenListExpr>(Init)) &&
2038 "call-style init in class");
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002039 ActOnFinishCXXInClassMemberInitializer(NewField,
2040 Init ? Init->getLocStart() : SourceLocation(), Init);
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002041 }
Richard Smith7a614d82011-06-11 17:19:42 +00002042 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002043 // Instantiate late parsed attributes, and attach them to their decls.
2044 // See Sema::InstantiateAttrs
2045 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2046 E = LateAttrs.end(); I != E; ++I) {
2047 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2048 CurrentInstantiationScope = I->Scope;
Richard Smithcafeb942013-06-07 02:33:37 +00002049
2050 // Allow 'this' within late-parsed attributes.
2051 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2052 CXXRecordDecl *ThisContext =
2053 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2054 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2055 ND && ND->isCXXInstanceMember());
2056
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002057 Attr *NewAttr =
2058 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2059 I->NewDecl->addAttr(NewAttr);
2060 LocalInstantiationScope::deleteScopes(I->Scope,
2061 Instantiator.getStartingScope());
2062 }
2063 Instantiator.disableLateAttributeInstantiation();
2064 LateAttrs.clear();
2065
Richard Smithb9d0b762012-07-27 04:22:15 +00002066 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002067
Stephen Hines651f13c2014-04-23 16:59:28 -07002068 // FIXME: We should do something similar for explicit instantiations so they
2069 // end up in the right module.
Abramo Bagnarae9946242011-11-18 08:08:52 +00002070 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002071 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002072 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002073 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002074 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002075
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002076 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002077 // Perform any dependent diagnostics from the pattern.
2078 PerformDependentDiagnostics(Pattern, TemplateArgs);
2079
Douglas Gregord65587f2010-11-10 19:44:59 +00002080 // Instantiate any out-of-line class template partial
2081 // specializations now.
Richard Smithe688ddf2013-09-26 03:49:48 +00002082 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregord65587f2010-11-10 19:44:59 +00002083 P = Instantiator.delayed_partial_spec_begin(),
2084 PEnd = Instantiator.delayed_partial_spec_end();
2085 P != PEnd; ++P) {
2086 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smithe688ddf2013-09-26 03:49:48 +00002087 P->first, P->second)) {
2088 Instantiation->setInvalidDecl();
2089 break;
2090 }
2091 }
2092
2093 // Instantiate any out-of-line variable template partial
2094 // specializations now.
2095 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2096 P = Instantiator.delayed_var_partial_spec_begin(),
2097 PEnd = Instantiator.delayed_var_partial_spec_end();
2098 P != PEnd; ++P) {
2099 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2100 P->first, P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002101 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002102 break;
2103 }
2104 }
2105 }
2106
Douglas Gregord475b8d2009-03-25 21:17:03 +00002107 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002108 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002109
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002110 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002111 Consumer.HandleTagDeclDefinition(Instantiation);
2112
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002113 // Always emit the vtable for an explicit instantiation definition
2114 // of a polymorphic class template specialization.
2115 if (TSK == TSK_ExplicitInstantiationDefinition)
2116 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2117 }
2118
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002119 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002120}
2121
Richard Smithf1c66b42012-03-14 23:13:10 +00002122/// \brief Instantiate the definition of an enum from a given pattern.
2123///
2124/// \param PointOfInstantiation The point of instantiation within the
2125/// source code.
2126/// \param Instantiation is the declaration whose definition is being
2127/// instantiated. This will be a member enumeration of a class
2128/// temploid specialization, or a local enumeration within a
2129/// function temploid specialization.
2130/// \param Pattern The templated declaration from which the instantiation
2131/// occurs.
2132/// \param TemplateArgs The template arguments to be substituted into
2133/// the pattern.
2134/// \param TSK The kind of implicit or explicit instantiation to perform.
2135///
2136/// \return \c true if an error occurred, \c false otherwise.
2137bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2138 EnumDecl *Instantiation, EnumDecl *Pattern,
2139 const MultiLevelTemplateArgumentList &TemplateArgs,
2140 TemplateSpecializationKind TSK) {
2141 EnumDecl *PatternDef = Pattern->getDefinition();
2142 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2143 Instantiation->getInstantiatedFromMemberEnum(),
2144 Pattern, PatternDef, TSK,/*Complain*/true))
2145 return true;
2146 Pattern = PatternDef;
2147
2148 // Record the point of instantiation.
2149 if (MemberSpecializationInfo *MSInfo
2150 = Instantiation->getMemberSpecializationInfo()) {
2151 MSInfo->setTemplateSpecializationKind(TSK);
2152 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2153 }
2154
2155 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd69f37b2013-10-08 08:09:04 +00002156 if (Inst.isInvalid())
Richard Smithf1c66b42012-03-14 23:13:10 +00002157 return true;
2158
Stephen Hines651f13c2014-04-23 16:59:28 -07002159 // The instantiation is visible here, even if it was first declared in an
2160 // unimported module.
2161 Instantiation->setHidden(false);
2162
Richard Smithf1c66b42012-03-14 23:13:10 +00002163 // Enter the scope of this instantiation. We don't use
2164 // PushDeclContext because we don't have a scope.
2165 ContextRAII SavedContext(*this, Instantiation);
2166 EnterExpressionEvaluationContext EvalContext(*this,
2167 Sema::PotentiallyEvaluated);
2168
2169 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2170
2171 // Pull attributes from the pattern onto the instantiation.
2172 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2173
2174 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2175 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2176
2177 // Exit the scope of this instantiation.
2178 SavedContext.pop();
2179
2180 return Instantiation->isInvalidDecl();
2181}
2182
Douglas Gregor9b623632010-10-12 23:32:35 +00002183namespace {
2184 /// \brief A partial specialization whose template arguments have matched
2185 /// a given template-id.
2186 struct PartialSpecMatchResult {
2187 ClassTemplatePartialSpecializationDecl *Partial;
2188 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002189 };
2190}
2191
Larisse Voufo567f9172013-08-22 00:59:14 +00002192bool Sema::InstantiateClassTemplateSpecialization(
2193 SourceLocation PointOfInstantiation,
2194 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2195 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002196 // Perform the actual instantiation on the canonical declaration.
2197 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002198 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002199
Douglas Gregor52604ab2009-09-11 21:19:12 +00002200 // Check whether we have already instantiated or specialized this class
2201 // template specialization.
2202 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2203 if (ClassTemplateSpec->getSpecializationKind() ==
2204 TSK_ExplicitInstantiationDeclaration &&
2205 TSK == TSK_ExplicitInstantiationDefinition) {
2206 // An explicit instantiation definition follows an explicit instantiation
2207 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2208 // explicit instantiation.
2209 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002210
2211 // If this is an explicit instantiation definition, mark the
2212 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002213 if (TSK == TSK_ExplicitInstantiationDefinition &&
2214 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002215 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2216
Douglas Gregor52604ab2009-09-11 21:19:12 +00002217 return false;
2218 }
2219
2220 // We can only instantiate something that hasn't already been
2221 // instantiated or specialized. Fail without any diagnostics: our
2222 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002223 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002224 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002225
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002226 if (ClassTemplateSpec->isInvalidDecl())
2227 return true;
2228
Douglas Gregor2943aed2009-03-03 04:44:36 +00002229 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002230 CXXRecordDecl *Pattern = nullptr;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002231
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002232 // C++ [temp.class.spec.match]p1:
2233 // When a class template is used in a context that requires an
2234 // instantiation of the class, it is necessary to determine
2235 // whether the instantiation is to be generated using the primary
2236 // template or one of the partial specializations. This is done by
2237 // matching the template arguments of the class template
2238 // specialization with the template argument lists of the partial
2239 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002240 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002241 SmallVector<MatchResult, 4> Matched;
2242 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002243 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo43847122013-07-19 23:00:19 +00002244 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002245 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2246 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo43847122013-07-19 23:00:19 +00002247 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002248 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002249 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002250 ClassTemplateSpec->getTemplateArgs(),
2251 Info)) {
Larisse Voufo43847122013-07-19 23:00:19 +00002252 // Store the failed-deduction information for use in diagnostics, later.
2253 // TODO: Actually use the failed-deduction info?
2254 FailedCandidates.addCandidate()
2255 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorf67875d2009-06-12 18:26:56 +00002256 (void)Result;
2257 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002258 Matched.push_back(PartialSpecMatchResult());
2259 Matched.back().Partial = Partial;
2260 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002261 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002262 }
2263
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002264 // If we're dealing with a member template where the template parameters
2265 // have been instantiated, this provides the original template parameters
2266 // from which the member template's parameters were instantiated.
Stephen Hines651f13c2014-04-23 16:59:28 -07002267
Douglas Gregored9c0f92009-10-29 00:04:11 +00002268 if (Matched.size() >= 1) {
Craig Topper09d19ef2013-07-04 03:08:24 +00002269 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002270 if (Matched.size() == 1) {
2271 // -- If exactly one matching specialization is found, the
2272 // instantiation is generated from that specialization.
2273 // We don't need to do anything for this.
2274 } else {
2275 // -- If more than one matching specialization is found, the
2276 // partial order rules (14.5.4.2) are used to determine
2277 // whether one of the specializations is more specialized
2278 // than the others. If none of the specializations is more
2279 // specialized than all of the other matching
2280 // specializations, then the use of the class template is
2281 // ambiguous and the program is ill-formed.
Craig Topper09d19ef2013-07-04 03:08:24 +00002282 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2283 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002284 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002285 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002286 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002287 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002288 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002289 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002290
Douglas Gregored9c0f92009-10-29 00:04:11 +00002291 // Determine if the best partial specialization is more specialized than
2292 // the others.
2293 bool Ambiguous = false;
Craig Topper09d19ef2013-07-04 03:08:24 +00002294 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2295 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002296 P != PEnd; ++P) {
2297 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002298 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002299 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002300 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002301 Ambiguous = true;
2302 break;
2303 }
2304 }
2305
2306 if (Ambiguous) {
2307 // Partial ordering did not produce a clear winner. Complain.
2308 ClassTemplateSpec->setInvalidDecl();
2309 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2310 << ClassTemplateSpec;
2311
2312 // Print the matching partial specializations.
Craig Topper09d19ef2013-07-04 03:08:24 +00002313 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2314 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002315 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002316 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2317 << getTemplateArgumentBindingsText(
2318 P->Partial->getTemplateParameters(),
2319 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002320
Douglas Gregored9c0f92009-10-29 00:04:11 +00002321 return true;
2322 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002323 }
2324
2325 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002326 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002327 while (OrigPartialSpec->getInstantiatedFromMember()) {
2328 // If we've found an explicit specialization of this class template,
2329 // stop here and use that as the pattern.
2330 if (OrigPartialSpec->isMemberSpecialization())
2331 break;
2332
2333 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2334 }
2335
2336 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002337 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002338 } else {
2339 // -- If no matches are found, the instantiation is generated
2340 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002341 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002342 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2343 // If we've found an explicit specialization of this class template,
2344 // stop here and use that as the pattern.
2345 if (OrigTemplate->isMemberSpecialization())
2346 break;
2347
Douglas Gregord6350ae2009-08-28 20:31:08 +00002348 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002349 }
2350
Douglas Gregord6350ae2009-08-28 20:31:08 +00002351 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002352 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002353
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002354 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2355 Pattern,
2356 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002357 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002358 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002359
Douglas Gregor199d9912009-06-05 00:53:49 +00002360 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002361}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002362
John McCallce3ff2b2009-08-25 22:02:44 +00002363/// \brief Instantiates the definitions of all of the member
2364/// of the given class, which is an instantiation of a class template
2365/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002366void
2367Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002368 CXXRecordDecl *Instantiation,
2369 const MultiLevelTemplateArgumentList &TemplateArgs,
2370 TemplateSpecializationKind TSK) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002371 // FIXME: We need to notify the ASTMutationListener that we did all of these
2372 // things, in case we have an explicit instantiation definition in a PCM, a
2373 // module, or preamble, and the declaration is in an imported AST.
Bill Wendling57907e52013-11-28 00:34:08 +00002374 assert(
2375 (TSK == TSK_ExplicitInstantiationDefinition ||
2376 TSK == TSK_ExplicitInstantiationDeclaration ||
2377 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2378 "Unexpected template specialization kind!");
Stephen Hines651f13c2014-04-23 16:59:28 -07002379 for (auto *D : Instantiation->decls()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002380 bool SuppressNew = false;
Stephen Hines651f13c2014-04-23 16:59:28 -07002381 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002382 if (FunctionDecl *Pattern
2383 = Function->getInstantiatedFromMemberFunction()) {
2384 MemberSpecializationInfo *MSInfo
2385 = Function->getMemberSpecializationInfo();
2386 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002387 if (MSInfo->getTemplateSpecializationKind()
2388 == TSK_ExplicitSpecialization)
2389 continue;
2390
Douglas Gregor0d035142009-10-27 18:42:08 +00002391 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2392 Function,
2393 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002394 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002395 SuppressNew) ||
2396 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002397 continue;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002398
2399 // C++11 [temp.explicit]p8:
2400 // An explicit instantiation definition that names a class template
2401 // specialization explicitly instantiates the class template
2402 // specialization and is only an explicit instantiation definition
2403 // of members whose definition is visible at the point of
2404 // instantiation.
2405 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002406 continue;
2407
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002408 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2409
2410 if (Function->isDefined()) {
2411 // Let the ASTConsumer know that this function has been explicitly
2412 // instantiated now, and its linkage might have changed.
2413 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2414 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002415 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002416 } else if (TSK == TSK_ImplicitInstantiation) {
2417 PendingLocalImplicitInstantiations.push_back(
2418 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor0d035142009-10-27 18:42:08 +00002419 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002420 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002421 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smithd0629eb2013-09-27 20:14:12 +00002422 if (isa<VarTemplateSpecializationDecl>(Var))
2423 continue;
2424
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002425 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002426 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2427 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002428 if (MSInfo->getTemplateSpecializationKind()
2429 == TSK_ExplicitSpecialization)
2430 continue;
2431
Douglas Gregor0d035142009-10-27 18:42:08 +00002432 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2433 Var,
2434 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002435 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002436 SuppressNew) ||
2437 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002438 continue;
2439
Douglas Gregor0d035142009-10-27 18:42:08 +00002440 if (TSK == TSK_ExplicitInstantiationDefinition) {
2441 // C++0x [temp.explicit]p8:
2442 // An explicit instantiation definition that names a class template
2443 // specialization explicitly instantiates the class template
2444 // specialization and is only an explicit instantiation definition
2445 // of members whose definition is visible at the point of
2446 // instantiation.
2447 if (!Var->getInstantiatedFromStaticDataMember()
2448 ->getOutOfLineDefinition())
2449 continue;
2450
2451 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002452 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002453 } else {
2454 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2455 }
2456 }
Stephen Hines651f13c2014-04-23 16:59:28 -07002457 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002458 // Always skip the injected-class-name, along with any
2459 // redeclarations of nested classes, since both would cause us
2460 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002461 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002462 continue;
2463
Douglas Gregor0d035142009-10-27 18:42:08 +00002464 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2465 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002466
2467 if (MSInfo->getTemplateSpecializationKind()
2468 == TSK_ExplicitSpecialization)
2469 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002470
Douglas Gregor0d035142009-10-27 18:42:08 +00002471 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2472 Record,
2473 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002474 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002475 SuppressNew) ||
2476 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002477 continue;
2478
Douglas Gregor0d035142009-10-27 18:42:08 +00002479 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2480 assert(Pattern && "Missing instantiated-from-template information");
2481
Douglas Gregor952b0172010-02-11 01:04:33 +00002482 if (!Record->getDefinition()) {
2483 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002484 // C++0x [temp.explicit]p8:
2485 // An explicit instantiation definition that names a class template
2486 // specialization explicitly instantiates the class template
2487 // specialization and is only an explicit instantiation definition
2488 // of members whose definition is visible at the point of
2489 // instantiation.
2490 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2491 MSInfo->setTemplateSpecializationKind(TSK);
2492 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2493 }
2494
2495 continue;
2496 }
2497
2498 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002499 TemplateArgs,
2500 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002501 } else {
2502 if (TSK == TSK_ExplicitInstantiationDefinition &&
2503 Record->getTemplateSpecializationKind() ==
2504 TSK_ExplicitInstantiationDeclaration) {
2505 Record->setTemplateSpecializationKind(TSK);
2506 MarkVTableUsed(PointOfInstantiation, Record, true);
2507 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002508 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002509
Douglas Gregor952b0172010-02-11 01:04:33 +00002510 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002511 if (Pattern)
2512 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2513 TSK);
Stephen Hines651f13c2014-04-23 16:59:28 -07002514 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smithf1c66b42012-03-14 23:13:10 +00002515 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2516 assert(MSInfo && "No member specialization information?");
2517
2518 if (MSInfo->getTemplateSpecializationKind()
2519 == TSK_ExplicitSpecialization)
2520 continue;
2521
2522 if (CheckSpecializationInstantiationRedecl(
2523 PointOfInstantiation, TSK, Enum,
2524 MSInfo->getTemplateSpecializationKind(),
2525 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2526 SuppressNew)
2527 continue;
2528
2529 if (Enum->getDefinition())
2530 continue;
2531
2532 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2533 assert(Pattern && "Missing instantiated-from-template information");
2534
2535 if (TSK == TSK_ExplicitInstantiationDefinition) {
2536 if (!Pattern->getDefinition())
2537 continue;
2538
2539 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2540 } else {
2541 MSInfo->setTemplateSpecializationKind(TSK);
2542 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2543 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002544 }
2545 }
2546}
2547
2548/// \brief Instantiate the definitions of all of the members of the
2549/// given class template specialization, which was named as part of an
2550/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002551void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002552Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002553 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002554 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2555 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002556 // C++0x [temp.explicit]p7:
2557 // An explicit instantiation that names a class template
2558 // specialization is an explicit instantion of the same kind
2559 // (declaration or definition) of each of its members (not
2560 // including members inherited from base classes) that has not
2561 // been previously explicitly specialized in the translation unit
2562 // containing the explicit instantiation, except as described
2563 // below.
2564 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002565 getTemplateInstantiationArgs(ClassTemplateSpec),
2566 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002567}
2568
John McCall60d7b3a2010-08-24 06:29:42 +00002569StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002570Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002571 if (!S)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002572 return S;
Douglas Gregor43959a92009-08-20 07:17:43 +00002573
2574 TemplateInstantiator Instantiator(*this, TemplateArgs,
2575 SourceLocation(),
2576 DeclarationName());
2577 return Instantiator.TransformStmt(S);
2578}
2579
John McCall60d7b3a2010-08-24 06:29:42 +00002580ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002581Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002582 if (!E)
Stephen Hinesc568f1e2014-07-21 00:47:37 -07002583 return E;
Mike Stump1eb44332009-09-09 15:08:12 +00002584
Douglas Gregorb98b1992009-08-11 05:31:07 +00002585 TemplateInstantiator Instantiator(*this, TemplateArgs,
2586 SourceLocation(),
2587 DeclarationName());
2588 return Instantiator.TransformExpr(E);
2589}
2590
Richard Smithc83c2302012-12-19 01:39:02 +00002591ExprResult Sema::SubstInitializer(Expr *Init,
2592 const MultiLevelTemplateArgumentList &TemplateArgs,
2593 bool CXXDirectInit) {
2594 TemplateInstantiator Instantiator(*this, TemplateArgs,
2595 SourceLocation(),
2596 DeclarationName());
2597 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2598}
2599
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002600bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2601 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002602 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002603 if (NumExprs == 0)
2604 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002605
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002606 TemplateInstantiator Instantiator(*this, TemplateArgs,
2607 SourceLocation(),
2608 DeclarationName());
2609 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2610}
2611
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002612NestedNameSpecifierLoc
2613Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2614 const MultiLevelTemplateArgumentList &TemplateArgs) {
2615 if (!NNS)
2616 return NestedNameSpecifierLoc();
2617
2618 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2619 DeclarationName());
2620 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2621}
2622
Abramo Bagnara25777432010-08-11 22:01:17 +00002623/// \brief Do template substitution on declaration name info.
2624DeclarationNameInfo
2625Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2626 const MultiLevelTemplateArgumentList &TemplateArgs) {
2627 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2628 NameInfo.getName());
2629 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2630}
2631
Douglas Gregorde650ae2009-03-31 18:38:02 +00002632TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002633Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2634 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002635 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002636 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2637 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002638 CXXScopeSpec SS;
2639 SS.Adopt(QualifierLoc);
2640 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002641}
Douglas Gregor91333002009-06-11 00:06:24 +00002642
Douglas Gregore02e2622010-12-22 21:19:48 +00002643bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2644 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002645 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002646 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2647 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002648
2649 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002650}
Douglas Gregor895162d2010-04-30 18:55:50 +00002651
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002652
2653static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2654 // When storing ParmVarDecls in the local instantiation scope, we always
2655 // want to use the ParmVarDecl from the canonical function declaration,
2656 // since the map is then valid for any redeclaration or definition of that
2657 // function.
2658 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2659 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2660 unsigned i = PV->getFunctionScopeIndex();
2661 return FD->getCanonicalDecl()->getParamDecl(i);
2662 }
2663 }
2664 return D;
2665}
2666
2667
Douglas Gregor12c9c002011-01-07 16:43:16 +00002668llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2669LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002670 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002671 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002672 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002673
Douglas Gregor895162d2010-04-30 18:55:50 +00002674 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002675 const Decl *CheckD = D;
2676 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002677 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002678 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002679 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002680
2681 // If this is a tag declaration, it's possible that we need to look for
2682 // a previous declaration.
2683 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002684 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002685 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002686 CheckD = nullptr;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002687 } while (CheckD);
2688
Douglas Gregor895162d2010-04-30 18:55:50 +00002689 // If we aren't combined with our outer scope, we're done.
2690 if (!Current->CombineWithOuterScope)
2691 break;
2692 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002693
Serge Pavlovdc49d522013-07-15 06:14:07 +00002694 // If we're performing a partial substitution during template argument
2695 // deduction, we may not have values for template parameters yet.
2696 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2697 isa<TemplateTemplateParmDecl>(D))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002698 return nullptr;
Serge Pavlovdc49d522013-07-15 06:14:07 +00002699
Chris Lattner57ad3782011-02-17 20:34:02 +00002700 // If we didn't find the decl, then we either have a sema bug, or we have a
2701 // forward reference to a label declaration. Return null to indicate that
2702 // we have an uninstantiated label.
2703 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002704 return nullptr;
Douglas Gregor895162d2010-04-30 18:55:50 +00002705}
2706
John McCall2a7fb272010-08-25 05:32:35 +00002707void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002708 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002709 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002710 if (Stored.isNull())
2711 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002712 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2713 Pack->push_back(Inst);
2714 else
Douglas Gregord3731192011-01-10 07:32:04 +00002715 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002716}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002717
2718void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2719 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002720 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002721 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2722 Pack->push_back(Inst);
2723}
2724
2725void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002726 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002727 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2728 assert(Stored.isNull() && "Already instantiated this local");
2729 DeclArgumentPack *Pack = new DeclArgumentPack;
2730 Stored = Pack;
2731 ArgumentPacks.push_back(Pack);
2732}
2733
Douglas Gregord3731192011-01-10 07:32:04 +00002734void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2735 const TemplateArgument *ExplicitArgs,
2736 unsigned NumExplicitArgs) {
2737 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2738 "Already have a partially-substituted pack");
2739 assert((!PartiallySubstitutedPack
2740 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2741 "Wrong number of arguments in partially-substituted pack");
2742 PartiallySubstitutedPack = Pack;
2743 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2744 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2745}
2746
2747NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2748 const TemplateArgument **ExplicitArgs,
2749 unsigned *NumExplicitArgs) const {
2750 if (ExplicitArgs)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002751 *ExplicitArgs = nullptr;
Douglas Gregord3731192011-01-10 07:32:04 +00002752 if (NumExplicitArgs)
2753 *NumExplicitArgs = 0;
2754
2755 for (const LocalInstantiationScope *Current = this; Current;
2756 Current = Current->Outer) {
2757 if (Current->PartiallySubstitutedPack) {
2758 if (ExplicitArgs)
2759 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2760 if (NumExplicitArgs)
2761 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2762
2763 return Current->PartiallySubstitutedPack;
2764 }
2765
2766 if (!Current->CombineWithOuterScope)
2767 break;
2768 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002769
2770 return nullptr;
Douglas Gregord3731192011-01-10 07:32:04 +00002771}