blob: 8904f3794955622681ab62ad26c6431ec5a560cf [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?");
79 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
80 return Result;
81 }
82
Douglas Gregor383041d2011-06-15 14:20:42 +000083 // If we have a template template parameter with translation unit context,
84 // then we're performing substitution into a default template argument of
85 // this template template parameter before we've constructed the template
86 // that will own this template template parameter. In this case, we
87 // use empty template parameter lists for all of the outer templates
88 // to avoid performing any substitutions.
89 if (Ctx->isTranslationUnit()) {
90 if (TemplateTemplateParmDecl *TTP
91 = dyn_cast<TemplateTemplateParmDecl>(D)) {
92 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith7a9f7c72013-05-17 03:04:50 +000093 Result.addOuterTemplateArguments(None);
Douglas Gregor383041d2011-06-15 14:20:42 +000094 return Result;
95 }
96 }
Douglas Gregor93104c12011-05-22 00:21:10 +000097 }
98
John McCallf181d8a2009-08-29 03:16:09 +000099 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +0000100 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +0000101 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +0000102 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
103 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +0000104 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
105 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +0000106 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Douglas Gregord1102432009-08-28 17:37:35 +0000108 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000109
110 // If this class template specialization was instantiated from a
111 // specialized member that is a class template, we're done.
112 assert(Spec->getSpecializedTemplate() && "No class template?");
113 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
114 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000115 }
Douglas Gregord1102432009-08-28 17:37:35 +0000116 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +0000117 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000118 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000119 (Function->getTemplateSpecializationKind() ==
120 TSK_ExplicitSpecialization &&
121 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000122 break;
123
Douglas Gregord1102432009-08-28 17:37:35 +0000124 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000125 = Function->getTemplateSpecializationArgs()) {
126 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000127 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000128
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000129 // If this function was instantiated from a specialized member that is
130 // a function template, we're done.
131 assert(Function->getPrimaryTemplate() && "No function template?");
132 if (Function->getPrimaryTemplate()->isMemberSpecialization())
133 break;
Faisal Valia3d311e2013-10-23 06:44:28 +0000134
135 // If this function is a generic lambda specialization, we are done.
136 if (isGenericLambdaCallOperatorSpecialization(Function))
137 break;
138
Douglas Gregorc494f772011-03-05 17:54:25 +0000139 } else if (FunctionTemplateDecl *FunTmpl
140 = Function->getDescribedFunctionTemplate()) {
141 // Add the "injected" template arguments.
Richard Smith7a9f7c72013-05-17 03:04:50 +0000142 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000143 }
144
John McCallf181d8a2009-08-29 03:16:09 +0000145 // If this is a friend declaration and it declares an entity at
146 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000147 // instead of its semantic parent, unless of course the pattern we're
148 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000149 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000150 Function->getDeclContext()->isFileContext() &&
151 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000152 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000153 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000154 continue;
155 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000156 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
157 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
158 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith7a9f7c72013-05-17 03:04:50 +0000159 const TemplateSpecializationType *TST =
160 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
161 Result.addOuterTemplateArguments(
162 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor24bae922010-07-08 18:37:38 +0000163 if (ClassTemplate->isMemberSpecialization())
164 break;
165 }
Douglas Gregord1102432009-08-28 17:37:35 +0000166 }
John McCallf181d8a2009-08-29 03:16:09 +0000167
168 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000169 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000170 }
Mike Stump1eb44332009-09-09 15:08:12 +0000171
Douglas Gregord1102432009-08-28 17:37:35 +0000172 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000173}
174
Douglas Gregorf35f8282009-11-11 21:54:23 +0000175bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
176 switch (Kind) {
177 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000178 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000179 case DefaultTemplateArgumentInstantiation:
180 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000181 case ExplicitTemplateArgumentSubstitution:
182 case DeducedTemplateArgumentSubstitution:
183 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000184 return true;
185
Douglas Gregorf35f8282009-11-11 21:54:23 +0000186 case DefaultTemplateArgumentChecking:
187 return false;
188 }
David Blaikie7530c032012-01-17 06:56:22 +0000189
190 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000191}
192
Douglas Gregor26dce442009-03-10 00:06:19 +0000193Sema::InstantiatingTemplate::
194InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000195 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000196 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000197 : SemaRef(SemaRef),
198 SavedInNonInstantiationSFINAEContext(
199 SemaRef.InNonInstantiationSFINAEContext)
200{
Douglas Gregordf667e72009-03-10 20:44:00 +0000201 Invalid = CheckInstantiationDepth(PointOfInstantiation,
202 InstantiationRange);
203 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000204 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000205 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000206 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000207 Inst.Entity = Entity;
Douglas Gregor313a81d2009-03-12 18:36:18 +0000208 Inst.TemplateArgs = 0;
209 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000210 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000211 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000212 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000213 }
214}
215
Richard Smithe6975e92012-04-17 00:58:00 +0000216Sema::InstantiatingTemplate::
217InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
218 FunctionDecl *Entity, ExceptionSpecification,
219 SourceRange InstantiationRange)
220 : SemaRef(SemaRef),
221 SavedInNonInstantiationSFINAEContext(
222 SemaRef.InNonInstantiationSFINAEContext)
223{
224 Invalid = CheckInstantiationDepth(PointOfInstantiation,
225 InstantiationRange);
226 if (!Invalid) {
227 ActiveTemplateInstantiation Inst;
228 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
229 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000230 Inst.Entity = Entity;
Richard Smithe6975e92012-04-17 00:58:00 +0000231 Inst.TemplateArgs = 0;
232 Inst.NumTemplateArgs = 0;
233 Inst.InstantiationRange = InstantiationRange;
234 SemaRef.InNonInstantiationSFINAEContext = false;
235 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
236 }
237}
238
Richard Smith7e54fb52012-07-16 01:09:10 +0000239Sema::InstantiatingTemplate::
240InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
241 TemplateDecl *Template,
242 ArrayRef<TemplateArgument> TemplateArgs,
243 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000244 : SemaRef(SemaRef),
245 SavedInNonInstantiationSFINAEContext(
246 SemaRef.InNonInstantiationSFINAEContext)
247{
Douglas Gregordf667e72009-03-10 20:44:00 +0000248 Invalid = CheckInstantiationDepth(PointOfInstantiation,
249 InstantiationRange);
250 if (!Invalid) {
251 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000252 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000253 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
254 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000255 Inst.Entity = Template;
Richard Smith7e54fb52012-07-16 01:09:10 +0000256 Inst.TemplateArgs = TemplateArgs.data();
257 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor26dce442009-03-10 00:06:19 +0000258 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000259 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000260 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000261 }
262}
263
Richard Smith7e54fb52012-07-16 01:09:10 +0000264Sema::InstantiatingTemplate::
265InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
266 FunctionTemplateDecl *FunctionTemplate,
267 ArrayRef<TemplateArgument> TemplateArgs,
268 ActiveTemplateInstantiation::InstantiationKind Kind,
269 sema::TemplateDeductionInfo &DeductionInfo,
270 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000271 : SemaRef(SemaRef),
272 SavedInNonInstantiationSFINAEContext(
273 SemaRef.InNonInstantiationSFINAEContext)
274{
Richard Smithab91ef12012-07-08 02:38:24 +0000275 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000276 if (!Invalid) {
277 ActiveTemplateInstantiation Inst;
278 Inst.Kind = Kind;
279 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000280 Inst.Entity = FunctionTemplate;
Richard Smith7e54fb52012-07-16 01:09:10 +0000281 Inst.TemplateArgs = TemplateArgs.data();
282 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor9b623632010-10-12 23:32:35 +0000283 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000284 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000285 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000286 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000287
288 if (!Inst.isInstantiationRecord())
289 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000290 }
291}
292
Richard Smith7e54fb52012-07-16 01:09:10 +0000293Sema::InstantiatingTemplate::
294InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
295 ClassTemplatePartialSpecializationDecl *PartialSpec,
296 ArrayRef<TemplateArgument> TemplateArgs,
297 sema::TemplateDeductionInfo &DeductionInfo,
298 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000299 : SemaRef(SemaRef),
300 SavedInNonInstantiationSFINAEContext(
301 SemaRef.InNonInstantiationSFINAEContext)
302{
Richard Smithab91ef12012-07-08 02:38:24 +0000303 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
304 if (!Invalid) {
305 ActiveTemplateInstantiation Inst;
306 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
307 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000308 Inst.Entity = PartialSpec;
Richard Smith7e54fb52012-07-16 01:09:10 +0000309 Inst.TemplateArgs = TemplateArgs.data();
310 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000311 Inst.DeductionInfo = &DeductionInfo;
312 Inst.InstantiationRange = InstantiationRange;
313 SemaRef.InNonInstantiationSFINAEContext = false;
314 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
315 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000316}
317
Larisse Voufoef4579c2013-08-06 01:03:05 +0000318Sema::InstantiatingTemplate::InstantiatingTemplate(
319 Sema &SemaRef, SourceLocation PointOfInstantiation,
320 VarTemplatePartialSpecializationDecl *PartialSpec,
321 ArrayRef<TemplateArgument> TemplateArgs,
322 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
323 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
324 SemaRef.InNonInstantiationSFINAEContext) {
325 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
326 if (!Invalid) {
327 ActiveTemplateInstantiation Inst;
328 Inst.Kind =
329 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
330 Inst.PointOfInstantiation = PointOfInstantiation;
331 Inst.Entity = PartialSpec;
332 Inst.TemplateArgs = TemplateArgs.data();
333 Inst.NumTemplateArgs = TemplateArgs.size();
334 Inst.DeductionInfo = &DeductionInfo;
335 Inst.InstantiationRange = InstantiationRange;
336 SemaRef.InNonInstantiationSFINAEContext = false;
337 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
338 }
339}
340
Richard Smith7e54fb52012-07-16 01:09:10 +0000341Sema::InstantiatingTemplate::
342InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
343 ParmVarDecl *Param,
344 ArrayRef<TemplateArgument> TemplateArgs,
345 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000346 : SemaRef(SemaRef),
347 SavedInNonInstantiationSFINAEContext(
348 SemaRef.InNonInstantiationSFINAEContext)
349{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000350 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000351 if (!Invalid) {
352 ActiveTemplateInstantiation Inst;
353 Inst.Kind
354 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000355 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000356 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000357 Inst.TemplateArgs = TemplateArgs.data();
358 Inst.NumTemplateArgs = TemplateArgs.size();
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000359 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000360 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000361 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000362 }
363}
364
365Sema::InstantiatingTemplate::
366InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000367 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
368 ArrayRef<TemplateArgument> TemplateArgs,
369 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000370 : SemaRef(SemaRef),
371 SavedInNonInstantiationSFINAEContext(
372 SemaRef.InNonInstantiationSFINAEContext)
373{
Richard Smithab91ef12012-07-08 02:38:24 +0000374 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
375 if (!Invalid) {
376 ActiveTemplateInstantiation Inst;
377 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
378 Inst.PointOfInstantiation = PointOfInstantiation;
379 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000380 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000381 Inst.TemplateArgs = TemplateArgs.data();
382 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000383 Inst.InstantiationRange = InstantiationRange;
384 SemaRef.InNonInstantiationSFINAEContext = false;
385 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
386 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000387}
388
389Sema::InstantiatingTemplate::
390InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000391 NamedDecl *Template, TemplateTemplateParmDecl *Param,
392 ArrayRef<TemplateArgument> TemplateArgs,
393 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000394 : SemaRef(SemaRef),
395 SavedInNonInstantiationSFINAEContext(
396 SemaRef.InNonInstantiationSFINAEContext)
397{
Richard Smithab91ef12012-07-08 02:38:24 +0000398 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
399 if (!Invalid) {
400 ActiveTemplateInstantiation Inst;
401 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
402 Inst.PointOfInstantiation = PointOfInstantiation;
403 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000404 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000405 Inst.TemplateArgs = TemplateArgs.data();
406 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000407 Inst.InstantiationRange = InstantiationRange;
408 SemaRef.InNonInstantiationSFINAEContext = false;
409 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
410 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000411}
412
413Sema::InstantiatingTemplate::
414InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000415 TemplateDecl *Template, NamedDecl *Param,
416 ArrayRef<TemplateArgument> TemplateArgs,
417 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000418 : SemaRef(SemaRef),
419 SavedInNonInstantiationSFINAEContext(
420 SemaRef.InNonInstantiationSFINAEContext)
421{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000422 Invalid = false;
423
424 ActiveTemplateInstantiation Inst;
425 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
426 Inst.PointOfInstantiation = PointOfInstantiation;
427 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000428 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000429 Inst.TemplateArgs = TemplateArgs.data();
430 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregorf35f8282009-11-11 21:54:23 +0000431 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000432 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000433 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
434
435 assert(!Inst.isInstantiationRecord());
436 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000437}
438
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000439void Sema::InstantiatingTemplate::Clear() {
440 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000441 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
442 assert(SemaRef.NonInstantiationEntries > 0);
443 --SemaRef.NonInstantiationEntries;
444 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000445 SemaRef.InNonInstantiationSFINAEContext
446 = SavedInNonInstantiationSFINAEContext;
Richard Smithb7751002013-07-25 23:08:39 +0000447
448 // Name lookup no longer looks in this template's defining module.
449 assert(SemaRef.ActiveTemplateInstantiations.size() >=
450 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
451 "forgot to remove a lookup module for a template instantiation");
452 if (SemaRef.ActiveTemplateInstantiations.size() ==
453 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
454 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
455 SemaRef.LookupModulesCache.erase(M);
456 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
457 }
458
Douglas Gregor26dce442009-03-10 00:06:19 +0000459 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000460 Invalid = true;
461 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000462}
463
Douglas Gregordf667e72009-03-10 20:44:00 +0000464bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
465 SourceLocation PointOfInstantiation,
466 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000467 assert(SemaRef.NonInstantiationEntries <=
468 SemaRef.ActiveTemplateInstantiations.size());
469 if ((SemaRef.ActiveTemplateInstantiations.size() -
470 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000471 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000472 return false;
473
Mike Stump1eb44332009-09-09 15:08:12 +0000474 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000475 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000476 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000477 << InstantiationRange;
478 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000479 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000480 return true;
481}
482
Douglas Gregoree1828a2009-03-10 18:03:33 +0000483/// \brief Prints the current instantiation stack through a series of
484/// notes.
485void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000486 // Determine which template instantiations to skip, if any.
487 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
488 unsigned Limit = Diags.getTemplateBacktraceLimit();
489 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
490 SkipStart = Limit / 2 + Limit % 2;
491 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
492 }
493
Douglas Gregorcca9e962009-07-01 22:01:06 +0000494 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000495 unsigned InstantiationIdx = 0;
Craig Topper09d19ef2013-07-04 03:08:24 +0000496 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000497 Active = ActiveTemplateInstantiations.rbegin(),
498 ActiveEnd = ActiveTemplateInstantiations.rend();
499 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000500 ++Active, ++InstantiationIdx) {
501 // Skip this instantiation?
502 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
503 if (InstantiationIdx == SkipStart) {
504 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000505 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000506 diag::note_instantiation_contexts_suppressed)
507 << unsigned(ActiveTemplateInstantiations.size() - Limit);
508 }
509 continue;
510 }
511
Douglas Gregordf667e72009-03-10 20:44:00 +0000512 switch (Active->Kind) {
513 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000514 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000515 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
516 unsigned DiagID = diag::note_template_member_class_here;
517 if (isa<ClassTemplateSpecializationDecl>(Record))
518 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000519 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000520 << Context.getTypeDeclType(Record)
521 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000522 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000523 unsigned DiagID;
524 if (Function->getPrimaryTemplate())
525 DiagID = diag::note_function_template_spec_here;
526 else
527 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000528 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000529 << Function
530 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000531 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000532 Diags.Report(Active->PointOfInstantiation,
Larisse Voufo933c66b2013-08-14 20:15:02 +0000533 VD->isStaticDataMember()?
534 diag::note_template_static_data_member_def_here
535 : diag::note_template_variable_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000536 << VD
537 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000538 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
539 Diags.Report(Active->PointOfInstantiation,
540 diag::note_template_enum_def_here)
541 << ED
542 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000543 } else {
544 Diags.Report(Active->PointOfInstantiation,
545 diag::note_template_type_alias_instantiation_here)
546 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000547 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000548 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000549 break;
550 }
551
552 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000553 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000554 SmallVector<char, 128> TemplateArgsStr;
555 llvm::raw_svector_ostream OS(TemplateArgsStr);
556 Template->printName(OS);
557 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000558 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000559 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000560 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000561 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000562 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000563 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000564 << Active->InstantiationRange;
565 break;
566 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000567
Douglas Gregorcca9e962009-07-01 22:01:06 +0000568 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000569 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000570 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000571 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000572 << FnTmpl
573 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
574 Active->TemplateArgs,
575 Active->NumTemplateArgs)
576 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000577 break;
578 }
Mike Stump1eb44332009-09-09 15:08:12 +0000579
Douglas Gregorcca9e962009-07-01 22:01:06 +0000580 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000581 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
582 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000583 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000584 diag::note_partial_spec_deduct_instantiation_here)
585 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000586 << getTemplateArgumentBindingsText(
587 PartialSpec->getTemplateParameters(),
588 Active->TemplateArgs,
589 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000590 << Active->InstantiationRange;
591 } else {
592 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000593 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000594 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000595 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000596 << FnTmpl
597 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
598 Active->TemplateArgs,
599 Active->NumTemplateArgs)
600 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000601 }
602 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000603
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000604 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000605 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000606 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Benjamin Kramer5eada842013-02-22 15:46:01 +0000608 SmallVector<char, 128> TemplateArgsStr;
609 llvm::raw_svector_ostream OS(TemplateArgsStr);
610 FD->printName(OS);
611 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000612 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000613 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000614 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000615 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000616 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000617 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000618 << Active->InstantiationRange;
619 break;
620 }
Mike Stump1eb44332009-09-09 15:08:12 +0000621
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000622 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000623 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000624 std::string Name;
625 if (!Parm->getName().empty())
626 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000627
628 TemplateParameterList *TemplateParams = 0;
629 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
630 TemplateParams = Template->getTemplateParameters();
631 else
632 TemplateParams =
633 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
634 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000635 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000636 diag::note_prior_template_arg_substitution)
637 << isa<TemplateTemplateParmDecl>(Parm)
638 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000639 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000640 Active->TemplateArgs,
641 Active->NumTemplateArgs)
642 << Active->InstantiationRange;
643 break;
644 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000645
646 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000647 TemplateParameterList *TemplateParams = 0;
648 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
649 TemplateParams = Template->getTemplateParameters();
650 else
651 TemplateParams =
652 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
653 ->getTemplateParameters();
654
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000655 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000656 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000657 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000658 Active->TemplateArgs,
659 Active->NumTemplateArgs)
660 << Active->InstantiationRange;
661 break;
662 }
Richard Smithe6975e92012-04-17 00:58:00 +0000663
664 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
665 Diags.Report(Active->PointOfInstantiation,
666 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000667 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000668 << Active->InstantiationRange;
669 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000670 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000671 }
672}
673
David Blaikiedc84cd52013-02-20 22:23:23 +0000674Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000675 if (InNonInstantiationSFINAEContext)
David Blaikiedc84cd52013-02-20 22:23:23 +0000676 return Optional<TemplateDeductionInfo *>(0);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000677
Craig Topper09d19ef2013-07-04 03:08:24 +0000678 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000679 Active = ActiveTemplateInstantiations.rbegin(),
680 ActiveEnd = ActiveTemplateInstantiations.rend();
681 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000682 ++Active)
683 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000684 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000685 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000686 // An instantiation of an alias template may or may not be a SFINAE
687 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000688 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000689 break;
690 // Fall through.
691 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000692 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000693 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000694 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000695
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000696 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000697 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000698 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000699 // A default template argument instantiation and substitution into
700 // template parameters with arguments for prior parameters may or may
701 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000702 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Douglas Gregorcca9e962009-07-01 22:01:06 +0000704 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
705 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
706 // We're either substitution explicitly-specified template arguments
707 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000708 assert(Active->DeductionInfo && "Missing deduction info pointer");
709 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000710 }
711 }
712
David Blaikie66874fb2013-02-21 01:47:18 +0000713 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000714}
715
Douglas Gregord3731192011-01-10 07:32:04 +0000716/// \brief Retrieve the depth and index of a parameter pack.
717static std::pair<unsigned, unsigned>
718getDepthAndIndex(NamedDecl *ND) {
719 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
720 return std::make_pair(TTP->getDepth(), TTP->getIndex());
721
722 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
723 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
724
725 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
726 return std::make_pair(TTP->getDepth(), TTP->getIndex());
727}
728
Douglas Gregor99ebf652009-02-27 19:31:52 +0000729//===----------------------------------------------------------------------===/
730// Template Instantiation for Types
731//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000732namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000733 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000734 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000735 SourceLocation Loc;
736 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000737
Douglas Gregorcd281c32009-02-28 00:25:32 +0000738 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000739 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000740
741 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000742 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000743 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000744 DeclarationName Entity)
745 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000746 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000747
Mike Stump1eb44332009-09-09 15:08:12 +0000748 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000749 /// transformed.
750 ///
751 /// For the purposes of template instantiation, a type has already been
752 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000753 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Douglas Gregor577f75a2009-08-04 16:50:30 +0000755 /// \brief Returns the location of the entity being instantiated, if known.
756 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Douglas Gregor577f75a2009-08-04 16:50:30 +0000758 /// \brief Returns the name of the entity being instantiated, if any.
759 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000761 /// \brief Sets the "base" location and entity when that
762 /// information is known based on another transformation.
763 void setBase(SourceLocation Loc, DeclarationName Entity) {
764 this->Loc = Loc;
765 this->Entity = Entity;
766 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000767
768 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
769 SourceRange PatternRange,
Robert Wilhelm834c0582013-08-09 18:02:13 +0000770 ArrayRef<UnexpandedParameterPack> Unexpanded,
771 bool &ShouldExpand, bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000772 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000773 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
774 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000775 TemplateArgs,
776 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000777 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000778 NumExpansions);
779 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000780
Douglas Gregor12c9c002011-01-07 16:43:16 +0000781 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
782 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
783 }
784
Douglas Gregord3731192011-01-10 07:32:04 +0000785 TemplateArgument ForgetPartiallySubstitutedPack() {
786 TemplateArgument Result;
787 if (NamedDecl *PartialPack
788 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
789 MultiLevelTemplateArgumentList &TemplateArgs
790 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
791 unsigned Depth, Index;
792 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
793 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
794 Result = TemplateArgs(Depth, Index);
795 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
796 }
797 }
798
799 return Result;
800 }
801
802 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
803 if (Arg.isNull())
804 return;
805
806 if (NamedDecl *PartialPack
807 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
808 MultiLevelTemplateArgumentList &TemplateArgs
809 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
810 unsigned Depth, Index;
811 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
812 TemplateArgs.setArgument(Depth, Index, Arg);
813 }
814 }
815
Douglas Gregor577f75a2009-08-04 16:50:30 +0000816 /// \brief Transform the given declaration by instantiating a reference to
817 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000818 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000819
Douglas Gregordfca6f52012-02-13 22:00:16 +0000820 void transformAttrs(Decl *Old, Decl *New) {
821 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
822 }
823
824 void transformedLocalDecl(Decl *Old, Decl *New) {
825 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
826 }
827
Mike Stump1eb44332009-09-09 15:08:12 +0000828 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000829 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000830 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000832 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000833 /// declaration.
834 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
835
Douglas Gregor43959a92009-08-20 07:17:43 +0000836 /// \brief Rebuild the exception declaration and register the declaration
837 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000838 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000839 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000840 SourceLocation StartLoc,
841 SourceLocation NameLoc,
842 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000843
Douglas Gregorbe270a02010-04-26 17:57:08 +0000844 /// \brief Rebuild the Objective-C exception declaration and register the
845 /// declaration as an instantiated local.
846 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
847 TypeSourceInfo *TSInfo, QualType T);
848
John McCallc4e70192009-09-11 04:59:25 +0000849 /// \brief Check for tag mismatches when instantiating an
850 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000851 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
852 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000853 NestedNameSpecifierLoc QualifierLoc,
854 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000855
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000856 TemplateName TransformTemplateName(CXXScopeSpec &SS,
857 TemplateName Name,
858 SourceLocation NameLoc,
859 QualType ObjectType = QualType(),
860 NamedDecl *FirstQualifierInScope = 0);
861
John McCall60d7b3a2010-08-24 06:29:42 +0000862 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
863 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
864 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000865
John McCall60d7b3a2010-08-24 06:29:42 +0000866 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000867 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000868 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
869 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000870
871 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
872 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
873
874 /// \brief Transform a reference to a function parameter pack.
875 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
876 ParmVarDecl *PD);
877
878 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
879 /// expand a function parameter pack reference which refers to an expanded
880 /// pack.
881 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
882
Douglas Gregor895162d2010-04-30 18:55:50 +0000883 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000884 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000885 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
886 FunctionProtoTypeLoc TL,
887 CXXRecordDecl *ThisContext,
888 unsigned ThisTypeQuals);
889
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000890 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000891 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000892 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000893 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000894
Mike Stump1eb44332009-09-09 15:08:12 +0000895 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000896 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000897 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000898 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000899
Douglas Gregorc3069d62011-01-14 02:55:32 +0000900 /// \brief Transforms an already-substituted template type parameter pack
901 /// into either itself (if we aren't substituting into its pack expansion)
902 /// or the appropriate substituted argument.
903 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
904 SubstTemplateTypeParmPackTypeLoc TL);
905
John McCall60d7b3a2010-08-24 06:29:42 +0000906 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000907 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000908 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000909 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
910 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000911 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000912 }
John McCall91a57552011-07-15 05:09:51 +0000913
Richard Smith612409e2012-07-25 03:56:55 +0000914 ExprResult TransformLambdaExpr(LambdaExpr *E) {
915 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
916 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
917 }
918
919 ExprResult TransformLambdaScope(LambdaExpr *E,
Bill Wendling2434dcf2013-12-05 05:25:04 +0000920 CXXMethodDecl *NewCallOperator,
921 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
Faisal Valia3d311e2013-10-23 06:44:28 +0000922 CXXMethodDecl *const OldCallOperator = E->getCallOperator();
923 // In the generic lambda case, we set the NewTemplate to be considered
924 // an "instantiation" of the OldTemplate.
925 if (FunctionTemplateDecl *const NewCallOperatorTemplate =
926 NewCallOperator->getDescribedFunctionTemplate()) {
927
928 FunctionTemplateDecl *const OldCallOperatorTemplate =
929 OldCallOperator->getDescribedFunctionTemplate();
930 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
931 OldCallOperatorTemplate);
932 // Mark the NewCallOperatorTemplate a specialization.
933 NewCallOperatorTemplate->setMemberSpecialization();
934 } else
935 // For a non-generic lambda we set the NewCallOperator to
936 // be an instantiation of the OldCallOperator.
937 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
938 TSK_ImplicitInstantiation);
939
Bill Wendling2434dcf2013-12-05 05:25:04 +0000940 return inherited::TransformLambdaScope(E, NewCallOperator,
941 InitCaptureExprsAndTypes);
Rafael Espindolaf003acd2013-10-04 14:28:51 +0000942 }
Faisal Valia3d311e2013-10-23 06:44:28 +0000943 TemplateParameterList *TransformTemplateParameterList(
944 TemplateParameterList *OrigTPL) {
945 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
946
947 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
948 TemplateDeclInstantiator DeclInstantiator(getSema(),
949 /* DeclContext *Owner */ Owner, TemplateArgs);
950 return DeclInstantiator.SubstTemplateParams(OrigTPL);
951 }
John McCall91a57552011-07-15 05:09:51 +0000952 private:
953 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
954 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000955 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000956 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000957}
958
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000959bool TemplateInstantiator::AlreadyTransformed(QualType T) {
960 if (T.isNull())
961 return true;
962
Douglas Gregor561f8122011-07-01 01:22:09 +0000963 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000964 return false;
965
966 getSema().MarkDeclarationsReferencedInType(Loc, T);
967 return true;
968}
969
Eli Friedman10ec0e42013-07-19 19:40:38 +0000970static TemplateArgument
971getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
972 assert(S.ArgumentPackSubstitutionIndex >= 0);
973 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
974 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
975 if (Arg.isPackExpansion())
976 Arg = Arg.getPackExpansionPattern();
977 return Arg;
978}
979
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000980Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000981 if (!D)
982 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Douglas Gregorc68afe22009-09-03 21:38:09 +0000984 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000985 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000986 // If the corresponding template argument is NULL or non-existent, it's
987 // because we are performing instantiation from explicitly-specified
988 // template arguments in a function template, but there were some
989 // arguments left unspecified.
990 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
991 TTP->getPosition()))
992 return D;
993
Douglas Gregor61c4d282011-01-05 15:48:55 +0000994 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
995
996 if (TTP->isParameterPack()) {
997 assert(Arg.getKind() == TemplateArgument::Pack &&
998 "Missing argument pack");
Eli Friedman10ec0e42013-07-19 19:40:38 +0000999 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor61c4d282011-01-05 15:48:55 +00001000 }
1001
1002 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +00001003 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +00001004 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +00001005 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001006 }
Mike Stump1eb44332009-09-09 15:08:12 +00001007
Douglas Gregor788cd062009-11-11 01:00:40 +00001008 // Fall through to find the instantiated declaration for this template
1009 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +00001010 }
Mike Stump1eb44332009-09-09 15:08:12 +00001011
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001012 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +00001013}
1014
Douglas Gregoraac571c2010-03-01 17:25:41 +00001015Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +00001016 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +00001017 if (!Inst)
1018 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Douglas Gregor43959a92009-08-20 07:17:43 +00001020 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1021 return Inst;
1022}
1023
Douglas Gregor6cd21982009-10-20 05:58:46 +00001024NamedDecl *
1025TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1026 SourceLocation Loc) {
1027 // If the first part of the nested-name-specifier was a template type
1028 // parameter, instantiate that type parameter down to a tag type.
1029 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1030 const TemplateTypeParmType *TTP
1031 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +00001032
Douglas Gregor6cd21982009-10-20 05:58:46 +00001033 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +00001034 // FIXME: This needs testing w/ member access expressions.
1035 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1036
1037 if (TTP->isParameterPack()) {
1038 assert(Arg.getKind() == TemplateArgument::Pack &&
1039 "Missing argument pack");
1040
Douglas Gregor2be29f42011-01-14 23:41:42 +00001041 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +00001042 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +00001043
Eli Friedman10ec0e42013-07-19 19:40:38 +00001044 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor984a58b2010-12-20 22:48:17 +00001045 }
1046
1047 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +00001048 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001049 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +00001050
1051 if (const TagType *Tag = T->getAs<TagType>())
1052 return Tag->getDecl();
1053
1054 // The resulting type is not a tag; complain.
1055 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1056 return 0;
1057 }
1058 }
1059
Douglas Gregor7c1e98f2010-03-01 15:56:25 +00001060 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +00001061}
1062
Douglas Gregor43959a92009-08-20 07:17:43 +00001063VarDecl *
1064TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +00001065 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001066 SourceLocation StartLoc,
1067 SourceLocation NameLoc,
1068 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +00001069 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001070 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +00001071 if (Var)
1072 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1073 return Var;
1074}
1075
1076VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1077 TypeSourceInfo *TSInfo,
1078 QualType T) {
1079 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1080 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +00001081 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1082 return Var;
1083}
1084
John McCallc4e70192009-09-11 04:59:25 +00001085QualType
John McCall21e413f2010-11-04 19:04:38 +00001086TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1087 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001088 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001089 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +00001090 if (const TagType *TT = T->getAs<TagType>()) {
1091 TagDecl* TD = TT->getDecl();
1092
John McCall21e413f2010-11-04 19:04:38 +00001093 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001094
John McCallc4e70192009-09-11 04:59:25 +00001095 IdentifierInfo *Id = TD->getIdentifier();
1096
1097 // TODO: should we even warn on struct/class mismatches for this? Seems
1098 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001099 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001100 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001101 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1102 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001103 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1104 << Id
1105 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1106 TD->getKindName());
1107 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1108 }
John McCallc4e70192009-09-11 04:59:25 +00001109 }
1110 }
1111
John McCall21e413f2010-11-04 19:04:38 +00001112 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1113 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001114 QualifierLoc,
1115 T);
John McCallc4e70192009-09-11 04:59:25 +00001116}
1117
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001118TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1119 TemplateName Name,
1120 SourceLocation NameLoc,
1121 QualType ObjectType,
1122 NamedDecl *FirstQualifierInScope) {
1123 if (TemplateTemplateParmDecl *TTP
1124 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1125 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1126 // If the corresponding template argument is NULL or non-existent, it's
1127 // because we are performing instantiation from explicitly-specified
1128 // template arguments in a function template, but there were some
1129 // arguments left unspecified.
1130 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1131 TTP->getPosition()))
1132 return Name;
1133
1134 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1135
1136 if (TTP->isParameterPack()) {
1137 assert(Arg.getKind() == TemplateArgument::Pack &&
1138 "Missing argument pack");
1139
1140 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1141 // We have the template argument pack to substitute, but we're not
1142 // actually expanding the enclosing pack expansion yet. So, just
1143 // keep the entire argument pack.
1144 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1145 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001146
1147 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001148 }
1149
1150 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001151 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001152
Douglas Gregor58750382011-03-05 20:06:51 +00001153 // We don't ever want to substitute for a qualified template name, since
1154 // the qualifier is handled separately. So, look through the qualified
1155 // template name to its underlying declaration.
1156 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1157 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001158
1159 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001160 return Template;
1161 }
1162 }
1163
1164 if (SubstTemplateTemplateParmPackStorage *SubstPack
1165 = Name.getAsSubstTemplateTemplateParmPack()) {
1166 if (getSema().ArgumentPackSubstitutionIndex == -1)
1167 return Name;
1168
Eli Friedman10ec0e42013-07-19 19:40:38 +00001169 TemplateArgument Arg = SubstPack->getArgumentPack();
1170 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1171 return Arg.getAsTemplate();
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001172 }
1173
1174 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1175 FirstQualifierInScope);
1176}
1177
John McCall60d7b3a2010-08-24 06:29:42 +00001178ExprResult
John McCall454feb92009-12-08 09:21:05 +00001179TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001180 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001181 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001182
Wei Pan33129332013-09-16 13:57:27 +00001183 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson773f3972009-09-11 01:22:35 +00001184}
1185
John McCall60d7b3a2010-08-24 06:29:42 +00001186ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001187TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001188 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001189 // If the corresponding template argument is NULL or non-existent, it's
1190 // because we are performing instantiation from explicitly-specified
1191 // template arguments in a function template, but there were some
1192 // arguments left unspecified.
1193 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1194 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001195 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001196
Douglas Gregor56bc9832010-12-24 00:15:10 +00001197 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1198 if (NTTP->isParameterPack()) {
1199 assert(Arg.getKind() == TemplateArgument::Pack &&
1200 "Missing argument pack");
1201
1202 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001203 // We have an argument pack, but we can't select a particular argument
1204 // out of it yet. Therefore, we'll build an expression to hold on to that
1205 // argument pack.
1206 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1207 E->getLocation(),
1208 NTTP->getDeclName());
1209 if (TargetType.isNull())
1210 return ExprError();
1211
1212 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1213 NTTP,
1214 E->getLocation(),
1215 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001216 }
1217
Eli Friedman10ec0e42013-07-19 19:40:38 +00001218 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001219 }
Mike Stump1eb44332009-09-09 15:08:12 +00001220
John McCall91a57552011-07-15 05:09:51 +00001221 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1222}
1223
1224ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1225 NonTypeTemplateParmDecl *parm,
1226 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001227 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001228 ExprResult result;
1229 QualType type;
1230
John McCallb8fc0532010-02-06 08:42:39 +00001231 // The template argument itself might be an expression, in which
1232 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001233 if (arg.getKind() == TemplateArgument::Expression) {
1234 Expr *argExpr = arg.getAsExpr();
1235 result = SemaRef.Owned(argExpr);
1236 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Eli Friedmand7a6b162012-09-26 02:36:12 +00001238 } else if (arg.getKind() == TemplateArgument::Declaration ||
1239 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001240 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001241 if (arg.getKind() == TemplateArgument::Declaration) {
1242 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Douglas Gregord2008e22012-04-06 22:40:38 +00001244 // Find the instantiation of the template argument. This is
1245 // required for nested templates.
1246 VD = cast_or_null<ValueDecl>(
1247 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1248 if (!VD)
1249 return ExprError();
1250 } else {
1251 // Propagate NULL template argument.
1252 VD = 0;
1253 }
1254
John McCall645cf442010-02-06 10:23:53 +00001255 // Derive the type we want the substituted decl to have. This had
1256 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001257 if (parm->isExpandedParameterPack()) {
1258 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1259 } else if (parm->isParameterPack() &&
1260 isa<PackExpansionType>(parm->getType())) {
1261 type = SemaRef.SubstType(
1262 cast<PackExpansionType>(parm->getType())->getPattern(),
1263 TemplateArgs, loc, parm->getDeclName());
1264 } else {
1265 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1266 loc, parm->getDeclName());
1267 }
1268 assert(!type.isNull() && "type substitution failed for param type");
1269 assert(!type->isDependentType() && "param type still dependent");
1270 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001271
John McCall91a57552011-07-15 05:09:51 +00001272 if (!result.isInvalid()) type = result.get()->getType();
1273 } else {
1274 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1275
1276 // Note that this type can be different from the type of 'result',
1277 // e.g. if it's an enum type.
1278 type = arg.getIntegralType();
1279 }
1280 if (result.isInvalid()) return ExprError();
1281
1282 Expr *resultExpr = result.take();
1283 return SemaRef.Owned(new (SemaRef.Context)
1284 SubstNonTypeTemplateParmExpr(type,
1285 resultExpr->getValueKind(),
1286 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001287}
1288
Douglas Gregorc7793c72011-01-15 01:15:58 +00001289ExprResult
1290TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1291 SubstNonTypeTemplateParmPackExpr *E) {
1292 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1293 // We aren't expanding the parameter pack, so just return ourselves.
1294 return getSema().Owned(E);
1295 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001296
1297 TemplateArgument Arg = E->getArgumentPack();
1298 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall91a57552011-07-15 05:09:51 +00001299 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1300 E->getParameterPackLocation(),
1301 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001302}
John McCallb8fc0532010-02-06 08:42:39 +00001303
John McCall60d7b3a2010-08-24 06:29:42 +00001304ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001305TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1306 SourceLocation Loc) {
1307 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1308 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1309}
1310
1311ExprResult
1312TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1313 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1314 // We can expand this parameter pack now.
1315 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1316 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1317 if (!VD)
1318 return ExprError();
1319 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1320 }
1321
1322 QualType T = TransformType(E->getType());
1323 if (T.isNull())
1324 return ExprError();
1325
1326 // Transform each of the parameter expansions into the corresponding
1327 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001328 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001329 Parms.reserve(E->getNumExpansions());
1330 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1331 I != End; ++I) {
1332 ParmVarDecl *D =
1333 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1334 if (!D)
1335 return ExprError();
1336 Parms.push_back(D);
1337 }
1338
1339 return FunctionParmPackExpr::Create(getSema().Context, T,
1340 E->getParameterPack(),
1341 E->getParameterPackLocation(), Parms);
1342}
1343
1344ExprResult
1345TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1346 ParmVarDecl *PD) {
1347 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1348 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1349 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1350 assert(Found && "no instantiation for parameter pack");
1351
1352 Decl *TransformedDecl;
1353 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1354 // If this is a reference to a function parameter pack which we can substitute
1355 // but can't yet expand, build a FunctionParmPackExpr for it.
1356 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1357 QualType T = TransformType(E->getType());
1358 if (T.isNull())
1359 return ExprError();
1360 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1361 E->getExprLoc(), *Pack);
1362 }
1363
1364 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1365 } else {
1366 TransformedDecl = Found->get<Decl*>();
1367 }
1368
1369 // We have either an unexpanded pack or a specific expansion.
1370 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1371 E->getExprLoc());
1372}
1373
1374ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001375TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1376 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001377
1378 // Handle references to non-type template parameters and non-type template
1379 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001380 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1381 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1382 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001383
1384 // We have a non-type template parameter that isn't fully substituted;
1385 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001386 }
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Richard Smith9a4db032012-09-12 00:56:43 +00001388 // Handle references to function parameter packs.
1389 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1390 if (PD->isParameterPack())
1391 return TransformFunctionParmPackRefExpr(E, PD);
1392
John McCall454feb92009-12-08 09:21:05 +00001393 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001394}
1395
John McCall60d7b3a2010-08-24 06:29:42 +00001396ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001397 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001398 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1399 getDescribedFunctionTemplate() &&
1400 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001401 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1402 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1403 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001404}
1405
Douglas Gregor895162d2010-04-30 18:55:50 +00001406QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001407 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001408 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001409 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001410 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001411}
1412
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001413QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1414 FunctionProtoTypeLoc TL,
1415 CXXRecordDecl *ThisContext,
1416 unsigned ThisTypeQuals) {
1417 // We need a local instantiation scope for this function prototype.
1418 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1419 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1420 ThisTypeQuals);
1421}
1422
John McCall21ef0fa2010-03-11 09:03:00 +00001423ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001424TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001425 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001426 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001427 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001428 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001429 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001430}
1431
Mike Stump1eb44332009-09-09 15:08:12 +00001432QualType
John McCalla2becad2009-10-21 00:40:46 +00001433TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001434 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001435 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001436 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001437 // Replace the template type parameter with its corresponding
1438 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001439
1440 // If the corresponding template argument is NULL or doesn't exist, it's
1441 // because we are performing instantiation from explicitly-specified
1442 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001443 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001444 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1445 TemplateTypeParmTypeLoc NewTL
1446 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1447 NewTL.setNameLoc(TL.getNameLoc());
1448 return TL.getType();
1449 }
Mike Stump1eb44332009-09-09 15:08:12 +00001450
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001451 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1452
1453 if (T->isParameterPack()) {
1454 assert(Arg.getKind() == TemplateArgument::Pack &&
1455 "Missing argument pack");
1456
1457 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001458 // We have the template argument pack, but we're not expanding the
1459 // enclosing pack expansion yet. Just save the template argument
1460 // pack for later substitution.
1461 QualType Result
1462 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1463 SubstTemplateTypeParmPackTypeLoc NewTL
1464 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1465 NewTL.setNameLoc(TL.getNameLoc());
1466 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001467 }
1468
Eli Friedman10ec0e42013-07-19 19:40:38 +00001469 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001470 }
1471
1472 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001473 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001474
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001475 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001476
1477 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001478 QualType Result
1479 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1480 SubstTemplateTypeParmTypeLoc NewTL
1481 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1482 NewTL.setNameLoc(TL.getNameLoc());
1483 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001484 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001485
1486 // The template type parameter comes from an inner template (e.g.,
1487 // the template parameter list of a member template inside the
1488 // template we are instantiating). Create a new template type
1489 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001490 TemplateTypeParmDecl *NewTTPDecl = 0;
1491 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1492 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1493 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1494
John McCalla2becad2009-10-21 00:40:46 +00001495 QualType Result
1496 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1497 - TemplateArgs.getNumLevels(),
1498 T->getIndex(),
1499 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001500 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001501 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1502 NewTL.setNameLoc(TL.getNameLoc());
1503 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001504}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001505
Douglas Gregorc3069d62011-01-14 02:55:32 +00001506QualType
1507TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1508 TypeLocBuilder &TLB,
1509 SubstTemplateTypeParmPackTypeLoc TL) {
1510 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1511 // We aren't expanding the parameter pack, so just return ourselves.
1512 SubstTemplateTypeParmPackTypeLoc NewTL
1513 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1514 NewTL.setNameLoc(TL.getNameLoc());
1515 return TL.getType();
1516 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001517
1518 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1519 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1520 QualType Result = Arg.getAsType();
1521
Douglas Gregorc3069d62011-01-14 02:55:32 +00001522 Result = getSema().Context.getSubstTemplateTypeParmType(
1523 TL.getTypePtr()->getReplacedParameter(),
1524 Result);
1525 SubstTemplateTypeParmTypeLoc NewTL
1526 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1527 NewTL.setNameLoc(TL.getNameLoc());
1528 return Result;
1529}
1530
John McCallce3ff2b2009-08-25 22:02:44 +00001531/// \brief Perform substitution on the type T with a given set of template
1532/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001533///
1534/// This routine substitutes the given template arguments into the
1535/// type T and produces the instantiated type.
1536///
1537/// \param T the type into which the template arguments will be
1538/// substituted. If this type is not dependent, it will be returned
1539/// immediately.
1540///
James Dennett1dfbd922012-06-14 21:40:34 +00001541/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001542/// substituted for the top-level template parameters within T.
1543///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001544/// \param Loc the location in the source code where this substitution
1545/// is being performed. It will typically be the location of the
1546/// declarator (if we're instantiating the type of some declaration)
1547/// or the location of the type in the source code (if, e.g., we're
1548/// instantiating the type of a cast expression).
1549///
1550/// \param Entity the name of the entity associated with a declaration
1551/// being instantiated (if any). May be empty to indicate that there
1552/// is no such entity (if, e.g., this is a type that occurs as part of
1553/// a cast expression) or that the entity has no name (e.g., an
1554/// unnamed function parameter).
1555///
1556/// \returns If the instantiation succeeds, the instantiated
1557/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001558TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001559 const MultiLevelTemplateArgumentList &Args,
1560 SourceLocation Loc,
1561 DeclarationName Entity) {
1562 assert(!ActiveTemplateInstantiations.empty() &&
1563 "Cannot perform an instantiation without some context on the "
1564 "instantiation stack");
1565
Douglas Gregor561f8122011-07-01 01:22:09 +00001566 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001567 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001568 return T;
1569
1570 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1571 return Instantiator.TransformType(T);
1572}
1573
Douglas Gregor603cfb42011-01-05 23:12:31 +00001574TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1575 const MultiLevelTemplateArgumentList &Args,
1576 SourceLocation Loc,
1577 DeclarationName Entity) {
1578 assert(!ActiveTemplateInstantiations.empty() &&
1579 "Cannot perform an instantiation without some context on the "
1580 "instantiation stack");
1581
1582 if (TL.getType().isNull())
1583 return 0;
1584
Douglas Gregor561f8122011-07-01 01:22:09 +00001585 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001586 !TL.getType()->isVariablyModifiedType()) {
1587 // FIXME: Make a copy of the TypeLoc data here, so that we can
1588 // return a new TypeSourceInfo. Inefficient!
1589 TypeLocBuilder TLB;
1590 TLB.pushFullCopy(TL);
1591 return TLB.getTypeSourceInfo(Context, TL.getType());
1592 }
1593
1594 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1595 TypeLocBuilder TLB;
1596 TLB.reserve(TL.getFullDataSize());
1597 QualType Result = Instantiator.TransformType(TLB, TL);
1598 if (Result.isNull())
1599 return 0;
1600
1601 return TLB.getTypeSourceInfo(Context, Result);
1602}
1603
John McCallcd7ba1c2009-10-21 00:58:09 +00001604/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001605QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001606 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001607 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001608 assert(!ActiveTemplateInstantiations.empty() &&
1609 "Cannot perform an instantiation without some context on the "
1610 "instantiation stack");
1611
Douglas Gregor836adf62010-05-24 17:22:01 +00001612 // If T is not a dependent type or a variably-modified type, there
1613 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001614 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001615 return T;
1616
Douglas Gregor577f75a2009-08-04 16:50:30 +00001617 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1618 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001619}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001620
John McCall6cd3b9f2010-04-09 17:38:44 +00001621static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001622 if (T->getType()->isInstantiationDependentType() ||
1623 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001624 return true;
1625
Abramo Bagnara723df242010-12-14 22:11:44 +00001626 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001627 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001628 return false;
1629
David Blaikie39e6ab42013-02-18 22:06:02 +00001630 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
John McCall6cd3b9f2010-04-09 17:38:44 +00001631 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1632 ParmVarDecl *P = FP.getArg(I);
1633
Reid Klecknerc66e7e92013-07-31 21:00:18 +00001634 // This must be synthesized from a typedef.
1635 if (!P) continue;
1636
Douglas Gregorc056c172011-05-09 20:45:16 +00001637 // The parameter's type as written might be dependent even if the
1638 // decayed type was not dependent.
1639 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001640 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001641 return true;
1642
John McCall6cd3b9f2010-04-09 17:38:44 +00001643 // TODO: currently we always rebuild expressions. When we
1644 // properly get lazier about this, we should use the same
1645 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001646 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001647 return true;
1648 }
1649
1650 return false;
1651}
1652
1653/// A form of SubstType intended specifically for instantiating the
1654/// type of a FunctionDecl. Its purpose is solely to force the
1655/// instantiation of default-argument expressions.
1656TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1657 const MultiLevelTemplateArgumentList &Args,
1658 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001659 DeclarationName Entity,
1660 CXXRecordDecl *ThisContext,
1661 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001662 assert(!ActiveTemplateInstantiations.empty() &&
1663 "Cannot perform an instantiation without some context on the "
1664 "instantiation stack");
1665
1666 if (!NeedsInstantiationAsFunctionType(T))
1667 return T;
1668
1669 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1670
1671 TypeLocBuilder TLB;
1672
1673 TypeLoc TL = T->getTypeLoc();
1674 TLB.reserve(TL.getFullDataSize());
1675
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001676 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001677
1678 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1679 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001680 ThisTypeQuals);
1681 } else {
1682 Result = Instantiator.TransformType(TLB, TL);
1683 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001684 if (Result.isNull())
1685 return 0;
1686
1687 return TLB.getTypeSourceInfo(Context, Result);
1688}
1689
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001690ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001691 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001692 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001693 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001694 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001695 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001696 TypeSourceInfo *NewDI = 0;
1697
Douglas Gregor603cfb42011-01-05 23:12:31 +00001698 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001699 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1700
Douglas Gregor603cfb42011-01-05 23:12:31 +00001701 // We have a function parameter pack. Substitute into the pattern of the
1702 // expansion.
1703 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1704 OldParm->getLocation(), OldParm->getDeclName());
1705 if (!NewDI)
1706 return 0;
1707
1708 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1709 // We still have unexpanded parameter packs, which means that
1710 // our function parameter is still a function parameter pack.
1711 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001712 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001713 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001714 } else if (ExpectParameterPack) {
1715 // We expected to get a parameter pack but didn't (because the type
1716 // itself is not a pack expansion type), so complain. This can occur when
1717 // the substitution goes through an alias template that "loses" the
1718 // pack expansion.
1719 Diag(OldParm->getLocation(),
1720 diag::err_function_parameter_pack_without_parameter_packs)
1721 << NewDI->getType();
1722 return 0;
1723 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001724 } else {
1725 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1726 OldParm->getDeclName());
1727 }
1728
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001729 if (!NewDI)
1730 return 0;
1731
1732 if (NewDI->getType()->isVoidType()) {
1733 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1734 return 0;
1735 }
1736
1737 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001738 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001739 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001740 OldParm->getIdentifier(),
1741 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001742 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001743 if (!NewParm)
1744 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001745
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001746 // Mark the (new) default argument as uninstantiated (if any).
1747 if (OldParm->hasUninstantiatedDefaultArg()) {
1748 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1749 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001750 } else if (OldParm->hasUnparsedDefaultArg()) {
1751 NewParm->setUnparsedDefaultArg();
1752 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001753 } else if (Expr *Arg = OldParm->getDefaultArg())
1754 // FIXME: if we non-lazily instantiated non-dependent default args for
1755 // non-dependent parameter types we could remove a bunch of duplicate
1756 // conversion warnings for such arguments.
1757 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001758
1759 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001760
Douglas Gregor12c9c002011-01-07 16:43:16 +00001761 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001762 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001763 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1764 } else {
1765 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001766 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001767 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001768
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001769 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1770 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001771 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001772
1773 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1774 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001775
1776 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1777
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001778 return NewParm;
1779}
1780
Douglas Gregora009b592011-01-07 00:20:55 +00001781/// \brief Substitute the given template arguments into the given set of
1782/// parameters, producing the set of parameter types that would be generated
1783/// from such a substitution.
1784bool Sema::SubstParmTypes(SourceLocation Loc,
1785 ParmVarDecl **Params, unsigned NumParams,
1786 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001787 SmallVectorImpl<QualType> &ParamTypes,
1788 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001789 assert(!ActiveTemplateInstantiations.empty() &&
1790 "Cannot perform an instantiation without some context on the "
1791 "instantiation stack");
1792
1793 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1794 DeclarationName());
1795 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001796 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001797}
1798
John McCallce3ff2b2009-08-25 22:02:44 +00001799/// \brief Perform substitution on the base class specifiers of the
1800/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001801///
1802/// Produces a diagnostic and returns true on error, returns false and
1803/// attaches the instantiated base classes to the class template
1804/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001805bool
John McCallce3ff2b2009-08-25 22:02:44 +00001806Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1807 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001808 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001809 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001810 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001811 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001812 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001813 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001814 if (!Base->getType()->isDependentType()) {
Matt Beaumont-Gay538fccb2013-06-21 18:58:32 +00001815 if (const CXXRecordDecl *RD = Base->getType()->getAsCXXRecordDecl()) {
1816 if (RD->isInvalidDecl())
1817 Instantiation->setInvalidDecl();
1818 }
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001819 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001820 continue;
1821 }
1822
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001823 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001824 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001825 if (Base->isPackExpansion()) {
1826 // This is a pack expansion. See whether we should expand it now, or
1827 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001828 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001829 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1830 Unexpanded);
1831 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001832 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001833 Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001834 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1835 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001836 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001837 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001838 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001839 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001840 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001841 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001842 }
1843
1844 // If we should expand this pack expansion now, do so.
1845 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001846 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001847 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1848
1849 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1850 TemplateArgs,
1851 Base->getSourceRange().getBegin(),
1852 DeclarationName());
1853 if (!BaseTypeLoc) {
1854 Invalid = true;
1855 continue;
1856 }
1857
1858 if (CXXBaseSpecifier *InstantiatedBase
1859 = CheckBaseSpecifier(Instantiation,
1860 Base->getSourceRange(),
1861 Base->isVirtual(),
1862 Base->getAccessSpecifierAsWritten(),
1863 BaseTypeLoc,
1864 SourceLocation()))
1865 InstantiatedBases.push_back(InstantiatedBase);
1866 else
1867 Invalid = true;
1868 }
1869
1870 continue;
1871 }
1872
1873 // The resulting base specifier will (still) be a pack expansion.
1874 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001875 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1876 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1877 TemplateArgs,
1878 Base->getSourceRange().getBegin(),
1879 DeclarationName());
1880 } else {
1881 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1882 TemplateArgs,
1883 Base->getSourceRange().getBegin(),
1884 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001885 }
1886
Nick Lewycky56062202010-07-26 16:56:01 +00001887 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001888 Invalid = true;
1889 continue;
1890 }
1891
1892 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001893 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001894 Base->getSourceRange(),
1895 Base->isVirtual(),
1896 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001897 BaseTypeLoc,
1898 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001899 InstantiatedBases.push_back(InstantiatedBase);
1900 else
1901 Invalid = true;
1902 }
1903
Douglas Gregor27b152f2009-03-10 18:52:44 +00001904 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001905 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001906 InstantiatedBases.size()))
1907 Invalid = true;
1908
1909 return Invalid;
1910}
1911
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001912// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001913namespace clang {
1914 namespace sema {
1915 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1916 const MultiLevelTemplateArgumentList &TemplateArgs);
1917 }
1918}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001919
Richard Smithf1c66b42012-03-14 23:13:10 +00001920/// Determine whether we would be unable to instantiate this template (because
1921/// it either has no definition, or is in the process of being instantiated).
1922static bool DiagnoseUninstantiableTemplate(Sema &S,
1923 SourceLocation PointOfInstantiation,
1924 TagDecl *Instantiation,
1925 bool InstantiatedFromMember,
1926 TagDecl *Pattern,
1927 TagDecl *PatternDef,
1928 TemplateSpecializationKind TSK,
1929 bool Complain = true) {
1930 if (PatternDef && !PatternDef->isBeingDefined())
1931 return false;
1932
1933 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1934 // Say nothing
1935 } else if (PatternDef) {
1936 assert(PatternDef->isBeingDefined());
1937 S.Diag(PointOfInstantiation,
1938 diag::err_template_instantiate_within_definition)
1939 << (TSK != TSK_ImplicitInstantiation)
1940 << S.Context.getTypeDeclType(Instantiation);
1941 // Not much point in noting the template declaration here, since
1942 // we're lexically inside it.
1943 Instantiation->setInvalidDecl();
1944 } else if (InstantiatedFromMember) {
1945 S.Diag(PointOfInstantiation,
1946 diag::err_implicit_instantiate_member_undefined)
1947 << S.Context.getTypeDeclType(Instantiation);
1948 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1949 } else {
1950 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1951 << (TSK != TSK_ImplicitInstantiation)
1952 << S.Context.getTypeDeclType(Instantiation);
1953 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1954 }
1955
1956 // In general, Instantiation isn't marked invalid to get more than one
1957 // error for multiple undefined instantiations. But the code that does
1958 // explicit declaration -> explicit definition conversion can't handle
1959 // invalid declarations, so mark as invalid in that case.
1960 if (TSK == TSK_ExplicitInstantiationDeclaration)
1961 Instantiation->setInvalidDecl();
1962 return true;
1963}
1964
Douglas Gregord475b8d2009-03-25 21:17:03 +00001965/// \brief Instantiate the definition of a class from a given pattern.
1966///
1967/// \param PointOfInstantiation The point of instantiation within the
1968/// source code.
1969///
1970/// \param Instantiation is the declaration whose definition is being
1971/// instantiated. This will be either a class template specialization
1972/// or a member class of a class template specialization.
1973///
1974/// \param Pattern is the pattern from which the instantiation
1975/// occurs. This will be either the declaration of a class template or
1976/// the declaration of a member class of a class template.
1977///
1978/// \param TemplateArgs The template arguments to be substituted into
1979/// the pattern.
1980///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001981/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001982///
1983/// \param Complain whether to complain if the class cannot be instantiated due
1984/// to the lack of a definition.
1985///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001986/// \returns true if an error occurred, false otherwise.
1987bool
1988Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1989 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001990 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001991 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001992 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001993 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001994 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001995 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1996 Instantiation->getInstantiatedFromMemberClass(),
1997 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001998 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001999 Pattern = PatternDef;
2000
Douglas Gregor454885e2009-10-15 15:54:05 +00002001 // \brief Record the point of instantiation.
2002 if (MemberSpecializationInfo *MSInfo
2003 = Instantiation->getMemberSpecializationInfo()) {
2004 MSInfo->setTemplateSpecializationKind(TSK);
2005 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002006 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00002007 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002008 Spec->setTemplateSpecializationKind(TSK);
2009 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00002010 }
2011
Douglas Gregord048bb72009-03-25 21:23:52 +00002012 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd69f37b2013-10-08 08:09:04 +00002013 if (Inst.isInvalid())
Douglas Gregord475b8d2009-03-25 21:17:03 +00002014 return true;
2015
2016 // Enter the scope of this instantiation. We don't use
2017 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00002018 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00002019 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00002020 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002021
Douglas Gregor05030bb2010-03-24 01:33:17 +00002022 // If this is an instantiation of a local class, merge this local
2023 // instantiation scope with the enclosing scope. Otherwise, every
2024 // instantiation of a class has its own local instantiation scope.
2025 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00002026 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00002027
John McCall1d8d1cc2010-08-01 02:01:53 +00002028 // Pull attributes from the pattern onto the instantiation.
2029 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2030
Douglas Gregord475b8d2009-03-25 21:17:03 +00002031 // Start the definition of this instantiation.
2032 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00002033
2034 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00002035
John McCallce3ff2b2009-08-25 22:02:44 +00002036 // Do substitution on the base class specifiers.
2037 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002038 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002039
Douglas Gregord65587f2010-11-10 19:44:59 +00002040 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002041 SmallVector<Decl*, 4> Fields;
2042 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00002043 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002044 // Delay instantiation of late parsed attributes.
2045 LateInstantiatedAttrVec LateAttrs;
2046 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2047
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002048 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00002049 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00002050 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00002051 // Don't instantiate members not belonging in this semantic context.
2052 // e.g. for:
2053 // @code
2054 // template <int i> class A {
2055 // class B *g;
2056 // };
2057 // @endcode
2058 // 'class B' has the template as lexical context but semantically it is
2059 // introduced in namespace scope.
2060 if ((*Member)->getDeclContext() != Pattern)
2061 continue;
2062
Douglas Gregord65587f2010-11-10 19:44:59 +00002063 if ((*Member)->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00002064 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002065 continue;
2066 }
2067
2068 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002069 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002070 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002071 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00002072 FieldDecl *OldField = cast<FieldDecl>(*Member);
2073 if (OldField->getInClassInitializer())
2074 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2075 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00002076 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2077 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2078 // specialization causes the implicit instantiation of the definitions
2079 // of unscoped member enumerations.
2080 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002081 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2082 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002083 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2084 assert(MSInfo && "no spec info for member enum specialization");
2085 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2086 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2087 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002088 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2089 if (SA->isFailed()) {
2090 // A static_assert failed. Bail out; instantiating this
2091 // class is probably not meaningful.
2092 Instantiation->setInvalidDecl();
2093 break;
2094 }
Richard Smith1af83c42012-03-23 03:33:32 +00002095 }
2096
2097 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002098 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002099 } else {
2100 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002101 // instantiations was a semantic disaster, and we'll want to mark the
2102 // declaration invalid.
2103 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002104 }
2105 }
2106
2107 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00002108 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2109 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002110 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002111
2112 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002113 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002114 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002115 // C++11 [expr.prim.general]p4:
2116 // Otherwise, if a member-declarator declares a non-static data member
2117 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2118 // to X" within the optional brace-or-equal-initializer. It shall not
2119 // appear elsewhere in the member-declarator.
2120 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2121
2122 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2123 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2124 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2125 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002126
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002127 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2128 /*CXXDirectInit=*/false);
2129 if (NewInit.isInvalid())
2130 NewField->setInvalidDecl();
2131 else {
2132 Expr *Init = NewInit.take();
2133 assert(Init && "no-argument initializer in class");
2134 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
Richard Smithca523302012-06-10 03:12:00 +00002135 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002136 }
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002137 }
Richard Smith7a614d82011-06-11 17:19:42 +00002138 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002139 // Instantiate late parsed attributes, and attach them to their decls.
2140 // See Sema::InstantiateAttrs
2141 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2142 E = LateAttrs.end(); I != E; ++I) {
2143 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2144 CurrentInstantiationScope = I->Scope;
Richard Smithcafeb942013-06-07 02:33:37 +00002145
2146 // Allow 'this' within late-parsed attributes.
2147 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2148 CXXRecordDecl *ThisContext =
2149 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2150 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2151 ND && ND->isCXXInstanceMember());
2152
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002153 Attr *NewAttr =
2154 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2155 I->NewDecl->addAttr(NewAttr);
2156 LocalInstantiationScope::deleteScopes(I->Scope,
2157 Instantiator.getStartingScope());
2158 }
2159 Instantiator.disableLateAttributeInstantiation();
2160 LateAttrs.clear();
2161
Richard Smithb9d0b762012-07-27 04:22:15 +00002162 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002163
Abramo Bagnarae9946242011-11-18 08:08:52 +00002164 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002165 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002166 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002167 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002168 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002169
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002170 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002171 // Perform any dependent diagnostics from the pattern.
2172 PerformDependentDiagnostics(Pattern, TemplateArgs);
2173
Douglas Gregord65587f2010-11-10 19:44:59 +00002174 // Instantiate any out-of-line class template partial
2175 // specializations now.
Richard Smithe688ddf2013-09-26 03:49:48 +00002176 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregord65587f2010-11-10 19:44:59 +00002177 P = Instantiator.delayed_partial_spec_begin(),
2178 PEnd = Instantiator.delayed_partial_spec_end();
2179 P != PEnd; ++P) {
2180 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smithe688ddf2013-09-26 03:49:48 +00002181 P->first, P->second)) {
2182 Instantiation->setInvalidDecl();
2183 break;
2184 }
2185 }
2186
2187 // Instantiate any out-of-line variable template partial
2188 // specializations now.
2189 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2190 P = Instantiator.delayed_var_partial_spec_begin(),
2191 PEnd = Instantiator.delayed_var_partial_spec_end();
2192 P != PEnd; ++P) {
2193 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2194 P->first, P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002195 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002196 break;
2197 }
2198 }
2199 }
2200
Douglas Gregord475b8d2009-03-25 21:17:03 +00002201 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002202 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002203
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002204 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002205 Consumer.HandleTagDeclDefinition(Instantiation);
2206
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002207 // Always emit the vtable for an explicit instantiation definition
2208 // of a polymorphic class template specialization.
2209 if (TSK == TSK_ExplicitInstantiationDefinition)
2210 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2211 }
2212
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002213 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002214}
2215
Richard Smithf1c66b42012-03-14 23:13:10 +00002216/// \brief Instantiate the definition of an enum from a given pattern.
2217///
2218/// \param PointOfInstantiation The point of instantiation within the
2219/// source code.
2220/// \param Instantiation is the declaration whose definition is being
2221/// instantiated. This will be a member enumeration of a class
2222/// temploid specialization, or a local enumeration within a
2223/// function temploid specialization.
2224/// \param Pattern The templated declaration from which the instantiation
2225/// occurs.
2226/// \param TemplateArgs The template arguments to be substituted into
2227/// the pattern.
2228/// \param TSK The kind of implicit or explicit instantiation to perform.
2229///
2230/// \return \c true if an error occurred, \c false otherwise.
2231bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2232 EnumDecl *Instantiation, EnumDecl *Pattern,
2233 const MultiLevelTemplateArgumentList &TemplateArgs,
2234 TemplateSpecializationKind TSK) {
2235 EnumDecl *PatternDef = Pattern->getDefinition();
2236 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2237 Instantiation->getInstantiatedFromMemberEnum(),
2238 Pattern, PatternDef, TSK,/*Complain*/true))
2239 return true;
2240 Pattern = PatternDef;
2241
2242 // Record the point of instantiation.
2243 if (MemberSpecializationInfo *MSInfo
2244 = Instantiation->getMemberSpecializationInfo()) {
2245 MSInfo->setTemplateSpecializationKind(TSK);
2246 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2247 }
2248
2249 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd69f37b2013-10-08 08:09:04 +00002250 if (Inst.isInvalid())
Richard Smithf1c66b42012-03-14 23:13:10 +00002251 return true;
2252
2253 // Enter the scope of this instantiation. We don't use
2254 // PushDeclContext because we don't have a scope.
2255 ContextRAII SavedContext(*this, Instantiation);
2256 EnterExpressionEvaluationContext EvalContext(*this,
2257 Sema::PotentiallyEvaluated);
2258
2259 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2260
2261 // Pull attributes from the pattern onto the instantiation.
2262 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2263
2264 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2265 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2266
2267 // Exit the scope of this instantiation.
2268 SavedContext.pop();
2269
2270 return Instantiation->isInvalidDecl();
2271}
2272
Douglas Gregor9b623632010-10-12 23:32:35 +00002273namespace {
2274 /// \brief A partial specialization whose template arguments have matched
2275 /// a given template-id.
2276 struct PartialSpecMatchResult {
2277 ClassTemplatePartialSpecializationDecl *Partial;
2278 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002279 };
2280}
2281
Larisse Voufo567f9172013-08-22 00:59:14 +00002282bool Sema::InstantiateClassTemplateSpecialization(
2283 SourceLocation PointOfInstantiation,
2284 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2285 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002286 // Perform the actual instantiation on the canonical declaration.
2287 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002288 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002289
Douglas Gregor52604ab2009-09-11 21:19:12 +00002290 // Check whether we have already instantiated or specialized this class
2291 // template specialization.
2292 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2293 if (ClassTemplateSpec->getSpecializationKind() ==
2294 TSK_ExplicitInstantiationDeclaration &&
2295 TSK == TSK_ExplicitInstantiationDefinition) {
2296 // An explicit instantiation definition follows an explicit instantiation
2297 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2298 // explicit instantiation.
2299 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002300
2301 // If this is an explicit instantiation definition, mark the
2302 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002303 if (TSK == TSK_ExplicitInstantiationDefinition &&
2304 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002305 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2306
Douglas Gregor52604ab2009-09-11 21:19:12 +00002307 return false;
2308 }
2309
2310 // We can only instantiate something that hasn't already been
2311 // instantiated or specialized. Fail without any diagnostics: our
2312 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002313 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002314 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002315
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002316 if (ClassTemplateSpec->isInvalidDecl())
2317 return true;
2318
Douglas Gregor2943aed2009-03-03 04:44:36 +00002319 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002320 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002321
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002322 // C++ [temp.class.spec.match]p1:
2323 // When a class template is used in a context that requires an
2324 // instantiation of the class, it is necessary to determine
2325 // whether the instantiation is to be generated using the primary
2326 // template or one of the partial specializations. This is done by
2327 // matching the template arguments of the class template
2328 // specialization with the template argument lists of the partial
2329 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002330 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002331 SmallVector<MatchResult, 4> Matched;
2332 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002333 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo43847122013-07-19 23:00:19 +00002334 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002335 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2336 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo43847122013-07-19 23:00:19 +00002337 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorf67875d2009-06-12 18:26:56 +00002338 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002339 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002340 ClassTemplateSpec->getTemplateArgs(),
2341 Info)) {
Larisse Voufo43847122013-07-19 23:00:19 +00002342 // Store the failed-deduction information for use in diagnostics, later.
2343 // TODO: Actually use the failed-deduction info?
2344 FailedCandidates.addCandidate()
2345 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorf67875d2009-06-12 18:26:56 +00002346 (void)Result;
2347 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002348 Matched.push_back(PartialSpecMatchResult());
2349 Matched.back().Partial = Partial;
2350 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002351 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002352 }
2353
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002354 // If we're dealing with a member template where the template parameters
2355 // have been instantiated, this provides the original template parameters
2356 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002357 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002358
Douglas Gregored9c0f92009-10-29 00:04:11 +00002359 if (Matched.size() >= 1) {
Craig Topper09d19ef2013-07-04 03:08:24 +00002360 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002361 if (Matched.size() == 1) {
2362 // -- If exactly one matching specialization is found, the
2363 // instantiation is generated from that specialization.
2364 // We don't need to do anything for this.
2365 } else {
2366 // -- If more than one matching specialization is found, the
2367 // partial order rules (14.5.4.2) are used to determine
2368 // whether one of the specializations is more specialized
2369 // than the others. If none of the specializations is more
2370 // specialized than all of the other matching
2371 // specializations, then the use of the class template is
2372 // ambiguous and the program is ill-formed.
Craig Topper09d19ef2013-07-04 03:08:24 +00002373 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2374 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002375 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002376 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002377 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002378 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002379 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002380 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002381
Douglas Gregored9c0f92009-10-29 00:04:11 +00002382 // Determine if the best partial specialization is more specialized than
2383 // the others.
2384 bool Ambiguous = false;
Craig Topper09d19ef2013-07-04 03:08:24 +00002385 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2386 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002387 P != PEnd; ++P) {
2388 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002389 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002390 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002391 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002392 Ambiguous = true;
2393 break;
2394 }
2395 }
2396
2397 if (Ambiguous) {
2398 // Partial ordering did not produce a clear winner. Complain.
2399 ClassTemplateSpec->setInvalidDecl();
2400 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2401 << ClassTemplateSpec;
2402
2403 // Print the matching partial specializations.
Craig Topper09d19ef2013-07-04 03:08:24 +00002404 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2405 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002406 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002407 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2408 << getTemplateArgumentBindingsText(
2409 P->Partial->getTemplateParameters(),
2410 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002411
Douglas Gregored9c0f92009-10-29 00:04:11 +00002412 return true;
2413 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002414 }
2415
2416 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002417 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002418 while (OrigPartialSpec->getInstantiatedFromMember()) {
2419 // If we've found an explicit specialization of this class template,
2420 // stop here and use that as the pattern.
2421 if (OrigPartialSpec->isMemberSpecialization())
2422 break;
2423
2424 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2425 }
2426
2427 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002428 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002429 } else {
2430 // -- If no matches are found, the instantiation is generated
2431 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002432 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002433 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2434 // If we've found an explicit specialization of this class template,
2435 // stop here and use that as the pattern.
2436 if (OrigTemplate->isMemberSpecialization())
2437 break;
2438
Douglas Gregord6350ae2009-08-28 20:31:08 +00002439 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002440 }
2441
Douglas Gregord6350ae2009-08-28 20:31:08 +00002442 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002443 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002444
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002445 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2446 Pattern,
2447 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002448 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002449 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002450
Douglas Gregor199d9912009-06-05 00:53:49 +00002451 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002452}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002453
John McCallce3ff2b2009-08-25 22:02:44 +00002454/// \brief Instantiates the definitions of all of the member
2455/// of the given class, which is an instantiation of a class template
2456/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002457void
2458Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002459 CXXRecordDecl *Instantiation,
2460 const MultiLevelTemplateArgumentList &TemplateArgs,
2461 TemplateSpecializationKind TSK) {
Bill Wendling57907e52013-11-28 00:34:08 +00002462 assert(
2463 (TSK == TSK_ExplicitInstantiationDefinition ||
2464 TSK == TSK_ExplicitInstantiationDeclaration ||
2465 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2466 "Unexpected template specialization kind!");
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002467 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2468 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002469 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002470 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002471 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002472 if (FunctionDecl *Pattern
2473 = Function->getInstantiatedFromMemberFunction()) {
2474 MemberSpecializationInfo *MSInfo
2475 = Function->getMemberSpecializationInfo();
2476 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002477 if (MSInfo->getTemplateSpecializationKind()
2478 == TSK_ExplicitSpecialization)
2479 continue;
2480
Douglas Gregor0d035142009-10-27 18:42:08 +00002481 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2482 Function,
2483 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002484 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002485 SuppressNew) ||
2486 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002487 continue;
2488
Sean Hunt10620eb2011-05-06 20:44:56 +00002489 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002490 continue;
2491
2492 if (TSK == TSK_ExplicitInstantiationDefinition) {
2493 // C++0x [temp.explicit]p8:
2494 // An explicit instantiation definition that names a class template
2495 // specialization explicitly instantiates the class template
2496 // specialization and is only an explicit instantiation definition
2497 // of members whose definition is visible at the point of
2498 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002499 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002500 continue;
2501
2502 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2503
2504 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2505 } else {
2506 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Bill Wendling57907e52013-11-28 00:34:08 +00002507 if (TSK == TSK_ImplicitInstantiation)
2508 PendingLocalImplicitInstantiations.push_back(
2509 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor0d035142009-10-27 18:42:08 +00002510 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002511 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002512 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Richard Smithd0629eb2013-09-27 20:14:12 +00002513 if (isa<VarTemplateSpecializationDecl>(Var))
2514 continue;
2515
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002516 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002517 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2518 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002519 if (MSInfo->getTemplateSpecializationKind()
2520 == TSK_ExplicitSpecialization)
2521 continue;
2522
Douglas Gregor0d035142009-10-27 18:42:08 +00002523 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2524 Var,
2525 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002526 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002527 SuppressNew) ||
2528 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002529 continue;
2530
Douglas Gregor0d035142009-10-27 18:42:08 +00002531 if (TSK == TSK_ExplicitInstantiationDefinition) {
2532 // C++0x [temp.explicit]p8:
2533 // An explicit instantiation definition that names a class template
2534 // specialization explicitly instantiates the class template
2535 // specialization and is only an explicit instantiation definition
2536 // of members whose definition is visible at the point of
2537 // instantiation.
2538 if (!Var->getInstantiatedFromStaticDataMember()
2539 ->getOutOfLineDefinition())
2540 continue;
2541
2542 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002543 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002544 } else {
2545 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2546 }
2547 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002548 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002549 // Always skip the injected-class-name, along with any
2550 // redeclarations of nested classes, since both would cause us
2551 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002552 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002553 continue;
2554
Douglas Gregor0d035142009-10-27 18:42:08 +00002555 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2556 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002557
2558 if (MSInfo->getTemplateSpecializationKind()
2559 == TSK_ExplicitSpecialization)
2560 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002561
Douglas Gregor0d035142009-10-27 18:42:08 +00002562 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2563 Record,
2564 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002565 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002566 SuppressNew) ||
2567 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002568 continue;
2569
Douglas Gregor0d035142009-10-27 18:42:08 +00002570 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2571 assert(Pattern && "Missing instantiated-from-template information");
2572
Douglas Gregor952b0172010-02-11 01:04:33 +00002573 if (!Record->getDefinition()) {
2574 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002575 // C++0x [temp.explicit]p8:
2576 // An explicit instantiation definition that names a class template
2577 // specialization explicitly instantiates the class template
2578 // specialization and is only an explicit instantiation definition
2579 // of members whose definition is visible at the point of
2580 // instantiation.
2581 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2582 MSInfo->setTemplateSpecializationKind(TSK);
2583 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2584 }
2585
2586 continue;
2587 }
2588
2589 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002590 TemplateArgs,
2591 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002592 } else {
2593 if (TSK == TSK_ExplicitInstantiationDefinition &&
2594 Record->getTemplateSpecializationKind() ==
2595 TSK_ExplicitInstantiationDeclaration) {
2596 Record->setTemplateSpecializationKind(TSK);
2597 MarkVTableUsed(PointOfInstantiation, Record, true);
2598 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002599 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002600
Douglas Gregor952b0172010-02-11 01:04:33 +00002601 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002602 if (Pattern)
2603 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2604 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002605 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2606 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2607 assert(MSInfo && "No member specialization information?");
2608
2609 if (MSInfo->getTemplateSpecializationKind()
2610 == TSK_ExplicitSpecialization)
2611 continue;
2612
2613 if (CheckSpecializationInstantiationRedecl(
2614 PointOfInstantiation, TSK, Enum,
2615 MSInfo->getTemplateSpecializationKind(),
2616 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2617 SuppressNew)
2618 continue;
2619
2620 if (Enum->getDefinition())
2621 continue;
2622
2623 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2624 assert(Pattern && "Missing instantiated-from-template information");
2625
2626 if (TSK == TSK_ExplicitInstantiationDefinition) {
2627 if (!Pattern->getDefinition())
2628 continue;
2629
2630 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2631 } else {
2632 MSInfo->setTemplateSpecializationKind(TSK);
2633 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2634 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002635 }
2636 }
2637}
2638
2639/// \brief Instantiate the definitions of all of the members of the
2640/// given class template specialization, which was named as part of an
2641/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002642void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002643Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002644 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002645 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2646 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002647 // C++0x [temp.explicit]p7:
2648 // An explicit instantiation that names a class template
2649 // specialization is an explicit instantion of the same kind
2650 // (declaration or definition) of each of its members (not
2651 // including members inherited from base classes) that has not
2652 // been previously explicitly specialized in the translation unit
2653 // containing the explicit instantiation, except as described
2654 // below.
2655 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002656 getTemplateInstantiationArgs(ClassTemplateSpec),
2657 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002658}
2659
John McCall60d7b3a2010-08-24 06:29:42 +00002660StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002661Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002662 if (!S)
2663 return Owned(S);
2664
2665 TemplateInstantiator Instantiator(*this, TemplateArgs,
2666 SourceLocation(),
2667 DeclarationName());
2668 return Instantiator.TransformStmt(S);
2669}
2670
John McCall60d7b3a2010-08-24 06:29:42 +00002671ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002672Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002673 if (!E)
2674 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002675
Douglas Gregorb98b1992009-08-11 05:31:07 +00002676 TemplateInstantiator Instantiator(*this, TemplateArgs,
2677 SourceLocation(),
2678 DeclarationName());
2679 return Instantiator.TransformExpr(E);
2680}
2681
Richard Smithc83c2302012-12-19 01:39:02 +00002682ExprResult Sema::SubstInitializer(Expr *Init,
2683 const MultiLevelTemplateArgumentList &TemplateArgs,
2684 bool CXXDirectInit) {
2685 TemplateInstantiator Instantiator(*this, TemplateArgs,
2686 SourceLocation(),
2687 DeclarationName());
2688 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2689}
2690
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002691bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2692 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002693 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002694 if (NumExprs == 0)
2695 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002696
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002697 TemplateInstantiator Instantiator(*this, TemplateArgs,
2698 SourceLocation(),
2699 DeclarationName());
2700 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2701}
2702
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002703NestedNameSpecifierLoc
2704Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2705 const MultiLevelTemplateArgumentList &TemplateArgs) {
2706 if (!NNS)
2707 return NestedNameSpecifierLoc();
2708
2709 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2710 DeclarationName());
2711 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2712}
2713
Abramo Bagnara25777432010-08-11 22:01:17 +00002714/// \brief Do template substitution on declaration name info.
2715DeclarationNameInfo
2716Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2717 const MultiLevelTemplateArgumentList &TemplateArgs) {
2718 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2719 NameInfo.getName());
2720 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2721}
2722
Douglas Gregorde650ae2009-03-31 18:38:02 +00002723TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002724Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2725 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002726 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002727 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2728 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002729 CXXScopeSpec SS;
2730 SS.Adopt(QualifierLoc);
2731 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002732}
Douglas Gregor91333002009-06-11 00:06:24 +00002733
Douglas Gregore02e2622010-12-22 21:19:48 +00002734bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2735 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002736 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002737 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2738 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002739
2740 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002741}
Douglas Gregor895162d2010-04-30 18:55:50 +00002742
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002743
2744static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2745 // When storing ParmVarDecls in the local instantiation scope, we always
2746 // want to use the ParmVarDecl from the canonical function declaration,
2747 // since the map is then valid for any redeclaration or definition of that
2748 // function.
2749 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2750 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2751 unsigned i = PV->getFunctionScopeIndex();
2752 return FD->getCanonicalDecl()->getParamDecl(i);
2753 }
2754 }
2755 return D;
2756}
2757
2758
Douglas Gregor12c9c002011-01-07 16:43:16 +00002759llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2760LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002761 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002762 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002763 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002764
Douglas Gregor895162d2010-04-30 18:55:50 +00002765 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002766 const Decl *CheckD = D;
2767 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002768 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002769 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002770 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002771
2772 // If this is a tag declaration, it's possible that we need to look for
2773 // a previous declaration.
2774 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002775 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002776 else
2777 CheckD = 0;
2778 } while (CheckD);
2779
Douglas Gregor895162d2010-04-30 18:55:50 +00002780 // If we aren't combined with our outer scope, we're done.
2781 if (!Current->CombineWithOuterScope)
2782 break;
2783 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002784
Serge Pavlovdc49d522013-07-15 06:14:07 +00002785 // If we're performing a partial substitution during template argument
2786 // deduction, we may not have values for template parameters yet.
2787 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2788 isa<TemplateTemplateParmDecl>(D))
2789 return 0;
2790
Chris Lattner57ad3782011-02-17 20:34:02 +00002791 // If we didn't find the decl, then we either have a sema bug, or we have a
2792 // forward reference to a label declaration. Return null to indicate that
2793 // we have an uninstantiated label.
2794 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002795 return 0;
2796}
2797
John McCall2a7fb272010-08-25 05:32:35 +00002798void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002799 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002800 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002801 if (Stored.isNull())
2802 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002803 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2804 Pack->push_back(Inst);
2805 else
Douglas Gregord3731192011-01-10 07:32:04 +00002806 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002807}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002808
2809void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2810 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002811 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002812 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2813 Pack->push_back(Inst);
2814}
2815
2816void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002817 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002818 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2819 assert(Stored.isNull() && "Already instantiated this local");
2820 DeclArgumentPack *Pack = new DeclArgumentPack;
2821 Stored = Pack;
2822 ArgumentPacks.push_back(Pack);
2823}
2824
Douglas Gregord3731192011-01-10 07:32:04 +00002825void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2826 const TemplateArgument *ExplicitArgs,
2827 unsigned NumExplicitArgs) {
2828 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2829 "Already have a partially-substituted pack");
2830 assert((!PartiallySubstitutedPack
2831 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2832 "Wrong number of arguments in partially-substituted pack");
2833 PartiallySubstitutedPack = Pack;
2834 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2835 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2836}
2837
2838NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2839 const TemplateArgument **ExplicitArgs,
2840 unsigned *NumExplicitArgs) const {
2841 if (ExplicitArgs)
2842 *ExplicitArgs = 0;
2843 if (NumExplicitArgs)
2844 *NumExplicitArgs = 0;
2845
2846 for (const LocalInstantiationScope *Current = this; Current;
2847 Current = Current->Outer) {
2848 if (Current->PartiallySubstitutedPack) {
2849 if (ExplicitArgs)
2850 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2851 if (NumExplicitArgs)
2852 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2853
2854 return Current->PartiallySubstitutedPack;
2855 }
2856
2857 if (!Current->CombineWithOuterScope)
2858 break;
2859 }
2860
2861 return 0;
2862}