blob: 3904daa47f1360c0b7fca9bf8255803639c7b277 [file] [log] [blame]
Douglas Gregor99ebf652009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
John McCall2d887082010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregor577f75a2009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/Expr.h"
19#include "clang/Basic/LangOptions.h"
John McCall19510852010-08-20 18:27:03 +000020#include "clang/Sema/DeclSpec.h"
Richard Smith7a614d82011-06-11 17:19:42 +000021#include "clang/Sema/Initialization.h"
Douglas Gregore737f502010-08-12 20:07:10 +000022#include "clang/Sema/Lookup.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000024#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor99ebf652009-02-27 19:31:52 +000025
26using namespace clang;
John McCall2a7fb272010-08-25 05:32:35 +000027using namespace sema;
Douglas Gregor99ebf652009-02-27 19:31:52 +000028
Douglas Gregoree1828a2009-03-10 18:03:33 +000029//===----------------------------------------------------------------------===/
30// Template Instantiation Support
31//===----------------------------------------------------------------------===/
32
Douglas Gregord6350ae2009-08-28 20:31:08 +000033/// \brief Retrieve the template argument list(s) that should be used to
34/// instantiate the definition of the given declaration.
Douglas Gregor0f8716b2009-11-09 19:17:50 +000035///
36/// \param D the declaration for which we are computing template instantiation
37/// arguments.
38///
39/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor525f96c2010-02-05 07:33:43 +000040///
41/// \param RelativeToPrimary true if we should get the template
42/// arguments relative to the primary template, even when we're
43/// dealing with a specialization. This is only relevant for function
44/// template specializations.
Douglas Gregore7089b02010-05-03 23:29:10 +000045///
46/// \param Pattern If non-NULL, indicates the pattern from which we will be
47/// instantiating the definition of the given declaration, \p D. This is
48/// used to determine the proper set of template instantiation arguments for
49/// friend function template specializations.
Douglas Gregord1102432009-08-28 17:37:35 +000050MultiLevelTemplateArgumentList
Douglas Gregor0f8716b2009-11-09 19:17:50 +000051Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor525f96c2010-02-05 07:33:43 +000052 const TemplateArgumentList *Innermost,
Douglas Gregore7089b02010-05-03 23:29:10 +000053 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
Douglas Gregord1102432009-08-28 17:37:35 +000055 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
Mike Stump1eb44332009-09-09 15:08:12 +000057
Douglas Gregor0f8716b2009-11-09 19:17:50 +000058 if (Innermost)
59 Result.addOuterTemplateArguments(Innermost);
60
Douglas Gregord1102432009-08-28 17:37:35 +000061 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregor93104c12011-05-22 00:21:10 +000062 if (!Ctx) {
Douglas Gregord1102432009-08-28 17:37:35 +000063 Ctx = D->getDeclContext();
Douglas Gregor93104c12011-05-22 00:21:10 +000064
Douglas Gregor383041d2011-06-15 14:20:42 +000065 // If we have a template template parameter with translation unit context,
66 // then we're performing substitution into a default template argument of
67 // this template template parameter before we've constructed the template
68 // that will own this template template parameter. In this case, we
69 // use empty template parameter lists for all of the outer templates
70 // to avoid performing any substitutions.
71 if (Ctx->isTranslationUnit()) {
72 if (TemplateTemplateParmDecl *TTP
73 = dyn_cast<TemplateTemplateParmDecl>(D)) {
74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith7a9f7c72013-05-17 03:04:50 +000075 Result.addOuterTemplateArguments(None);
Douglas Gregor383041d2011-06-15 14:20:42 +000076 return Result;
77 }
78 }
Douglas Gregor93104c12011-05-22 00:21:10 +000079 }
80
John McCallf181d8a2009-08-29 03:16:09 +000081 while (!Ctx->isFileContext()) {
Douglas Gregord1102432009-08-28 17:37:35 +000082 // Add template arguments from a class template instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +000083 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregord1102432009-08-28 17:37:35 +000084 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
Douglas Gregor24bae922010-07-08 18:37:38 +000086 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregord1102432009-08-28 17:37:35 +000088 break;
Mike Stump1eb44332009-09-09 15:08:12 +000089
Douglas Gregord1102432009-08-28 17:37:35 +000090 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +000091
92 // If this class template specialization was instantiated from a
93 // specialized member that is a class template, we're done.
94 assert(Spec->getSpecializedTemplate() && "No class template?");
95 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
96 break;
Mike Stump1eb44332009-09-09 15:08:12 +000097 }
Douglas Gregord1102432009-08-28 17:37:35 +000098 // Add template arguments from a function template specialization.
John McCallf181d8a2009-08-29 03:16:09 +000099 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor525f96c2010-02-05 07:33:43 +0000100 if (!RelativeToPrimary &&
Francois Pichetaf0f4d02011-08-14 03:52:19 +0000101 (Function->getTemplateSpecializationKind() ==
102 TSK_ExplicitSpecialization &&
103 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000104 break;
105
Douglas Gregord1102432009-08-28 17:37:35 +0000106 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000107 = Function->getTemplateSpecializationArgs()) {
108 // Add the template arguments for this specialization.
Douglas Gregord1102432009-08-28 17:37:35 +0000109 Result.addOuterTemplateArguments(TemplateArgs);
John McCallf181d8a2009-08-29 03:16:09 +0000110
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000111 // If this function was instantiated from a specialized member that is
112 // a function template, we're done.
113 assert(Function->getPrimaryTemplate() && "No function template?");
114 if (Function->getPrimaryTemplate()->isMemberSpecialization())
115 break;
Douglas Gregorc494f772011-03-05 17:54:25 +0000116 } else if (FunctionTemplateDecl *FunTmpl
117 = Function->getDescribedFunctionTemplate()) {
118 // Add the "injected" template arguments.
Richard Smith7a9f7c72013-05-17 03:04:50 +0000119 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorfd056bc2009-10-13 16:30:37 +0000120 }
121
John McCallf181d8a2009-08-29 03:16:09 +0000122 // If this is a friend declaration and it declares an entity at
123 // namespace scope, take arguments from its lexical parent
Douglas Gregore7089b02010-05-03 23:29:10 +0000124 // instead of its semantic parent, unless of course the pattern we're
125 // instantiating actually comes from the file's context!
John McCallf181d8a2009-08-29 03:16:09 +0000126 if (Function->getFriendObjectKind() &&
Douglas Gregore7089b02010-05-03 23:29:10 +0000127 Function->getDeclContext()->isFileContext() &&
128 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCallf181d8a2009-08-29 03:16:09 +0000129 Ctx = Function->getLexicalDeclContext();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000130 RelativeToPrimary = false;
John McCallf181d8a2009-08-29 03:16:09 +0000131 continue;
132 }
Douglas Gregor24bae922010-07-08 18:37:38 +0000133 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
134 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
135 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith7a9f7c72013-05-17 03:04:50 +0000136 const TemplateSpecializationType *TST =
137 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
138 Result.addOuterTemplateArguments(
139 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor24bae922010-07-08 18:37:38 +0000140 if (ClassTemplate->isMemberSpecialization())
141 break;
142 }
Douglas Gregord1102432009-08-28 17:37:35 +0000143 }
John McCallf181d8a2009-08-29 03:16:09 +0000144
145 Ctx = Ctx->getParent();
Douglas Gregor525f96c2010-02-05 07:33:43 +0000146 RelativeToPrimary = false;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000147 }
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Douglas Gregord1102432009-08-28 17:37:35 +0000149 return Result;
Douglas Gregor54dabfc2009-05-14 23:26:13 +0000150}
151
Douglas Gregorf35f8282009-11-11 21:54:23 +0000152bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
153 switch (Kind) {
154 case TemplateInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000155 case ExceptionSpecInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000156 case DefaultTemplateArgumentInstantiation:
157 case DefaultFunctionArgumentInstantiation:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000158 case ExplicitTemplateArgumentSubstitution:
159 case DeducedTemplateArgumentSubstitution:
160 case PriorTemplateArgumentSubstitution:
Richard Smithab91ef12012-07-08 02:38:24 +0000161 return true;
162
Douglas Gregorf35f8282009-11-11 21:54:23 +0000163 case DefaultTemplateArgumentChecking:
164 return false;
165 }
David Blaikie7530c032012-01-17 06:56:22 +0000166
167 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregorf35f8282009-11-11 21:54:23 +0000168}
169
Douglas Gregor26dce442009-03-10 00:06:19 +0000170Sema::InstantiatingTemplate::
171InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000172 Decl *Entity,
Douglas Gregor26dce442009-03-10 00:06:19 +0000173 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000174 : SemaRef(SemaRef),
175 SavedInNonInstantiationSFINAEContext(
176 SemaRef.InNonInstantiationSFINAEContext)
177{
Douglas Gregordf667e72009-03-10 20:44:00 +0000178 Invalid = CheckInstantiationDepth(PointOfInstantiation,
179 InstantiationRange);
180 if (!Invalid) {
Douglas Gregor26dce442009-03-10 00:06:19 +0000181 ActiveTemplateInstantiation Inst;
Douglas Gregordf667e72009-03-10 20:44:00 +0000182 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregor26dce442009-03-10 00:06:19 +0000183 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000184 Inst.Entity = Entity;
Douglas Gregor313a81d2009-03-12 18:36:18 +0000185 Inst.TemplateArgs = 0;
186 Inst.NumTemplateArgs = 0;
Douglas Gregordf667e72009-03-10 20:44:00 +0000187 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000188 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregordf667e72009-03-10 20:44:00 +0000189 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregordf667e72009-03-10 20:44:00 +0000190 }
191}
192
Richard Smithe6975e92012-04-17 00:58:00 +0000193Sema::InstantiatingTemplate::
194InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
195 FunctionDecl *Entity, ExceptionSpecification,
196 SourceRange InstantiationRange)
197 : SemaRef(SemaRef),
198 SavedInNonInstantiationSFINAEContext(
199 SemaRef.InNonInstantiationSFINAEContext)
200{
201 Invalid = CheckInstantiationDepth(PointOfInstantiation,
202 InstantiationRange);
203 if (!Invalid) {
204 ActiveTemplateInstantiation Inst;
205 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
206 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000207 Inst.Entity = Entity;
Richard Smithe6975e92012-04-17 00:58:00 +0000208 Inst.TemplateArgs = 0;
209 Inst.NumTemplateArgs = 0;
210 Inst.InstantiationRange = InstantiationRange;
211 SemaRef.InNonInstantiationSFINAEContext = false;
212 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
213 }
214}
215
Richard Smith7e54fb52012-07-16 01:09:10 +0000216Sema::InstantiatingTemplate::
217InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
218 TemplateDecl *Template,
219 ArrayRef<TemplateArgument> TemplateArgs,
220 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000221 : SemaRef(SemaRef),
222 SavedInNonInstantiationSFINAEContext(
223 SemaRef.InNonInstantiationSFINAEContext)
224{
Douglas Gregordf667e72009-03-10 20:44:00 +0000225 Invalid = CheckInstantiationDepth(PointOfInstantiation,
226 InstantiationRange);
227 if (!Invalid) {
228 ActiveTemplateInstantiation Inst;
Mike Stump1eb44332009-09-09 15:08:12 +0000229 Inst.Kind
Douglas Gregordf667e72009-03-10 20:44:00 +0000230 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
231 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000232 Inst.Entity = Template;
Richard Smith7e54fb52012-07-16 01:09:10 +0000233 Inst.TemplateArgs = TemplateArgs.data();
234 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor26dce442009-03-10 00:06:19 +0000235 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000236 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor26dce442009-03-10 00:06:19 +0000237 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor26dce442009-03-10 00:06:19 +0000238 }
239}
240
Richard Smith7e54fb52012-07-16 01:09:10 +0000241Sema::InstantiatingTemplate::
242InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
243 FunctionTemplateDecl *FunctionTemplate,
244 ArrayRef<TemplateArgument> TemplateArgs,
245 ActiveTemplateInstantiation::InstantiationKind Kind,
246 sema::TemplateDeductionInfo &DeductionInfo,
247 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000248 : SemaRef(SemaRef),
249 SavedInNonInstantiationSFINAEContext(
250 SemaRef.InNonInstantiationSFINAEContext)
251{
Richard Smithab91ef12012-07-08 02:38:24 +0000252 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Douglas Gregorcca9e962009-07-01 22:01:06 +0000253 if (!Invalid) {
254 ActiveTemplateInstantiation Inst;
255 Inst.Kind = Kind;
256 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000257 Inst.Entity = FunctionTemplate;
Richard Smith7e54fb52012-07-16 01:09:10 +0000258 Inst.TemplateArgs = TemplateArgs.data();
259 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor9b623632010-10-12 23:32:35 +0000260 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000261 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000262 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000263 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorf35f8282009-11-11 21:54:23 +0000264
265 if (!Inst.isInstantiationRecord())
266 ++SemaRef.NonInstantiationEntries;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000267 }
268}
269
Richard Smith7e54fb52012-07-16 01:09:10 +0000270Sema::InstantiatingTemplate::
271InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
272 ClassTemplatePartialSpecializationDecl *PartialSpec,
273 ArrayRef<TemplateArgument> TemplateArgs,
274 sema::TemplateDeductionInfo &DeductionInfo,
275 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000276 : SemaRef(SemaRef),
277 SavedInNonInstantiationSFINAEContext(
278 SemaRef.InNonInstantiationSFINAEContext)
279{
Richard Smithab91ef12012-07-08 02:38:24 +0000280 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
281 if (!Invalid) {
282 ActiveTemplateInstantiation Inst;
283 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
284 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000285 Inst.Entity = PartialSpec;
Richard Smith7e54fb52012-07-16 01:09:10 +0000286 Inst.TemplateArgs = TemplateArgs.data();
287 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000288 Inst.DeductionInfo = &DeductionInfo;
289 Inst.InstantiationRange = InstantiationRange;
290 SemaRef.InNonInstantiationSFINAEContext = false;
291 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
292 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000293}
294
Richard Smith7e54fb52012-07-16 01:09:10 +0000295Sema::InstantiatingTemplate::
296InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
297 ParmVarDecl *Param,
298 ArrayRef<TemplateArgument> TemplateArgs,
299 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000300 : SemaRef(SemaRef),
301 SavedInNonInstantiationSFINAEContext(
302 SemaRef.InNonInstantiationSFINAEContext)
303{
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000304 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000305 if (!Invalid) {
306 ActiveTemplateInstantiation Inst;
307 Inst.Kind
308 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000309 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000310 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000311 Inst.TemplateArgs = TemplateArgs.data();
312 Inst.NumTemplateArgs = TemplateArgs.size();
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000313 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000314 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000315 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000316 }
317}
318
319Sema::InstantiatingTemplate::
320InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000321 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
322 ArrayRef<TemplateArgument> TemplateArgs,
323 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000324 : SemaRef(SemaRef),
325 SavedInNonInstantiationSFINAEContext(
326 SemaRef.InNonInstantiationSFINAEContext)
327{
Richard Smithab91ef12012-07-08 02:38:24 +0000328 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
329 if (!Invalid) {
330 ActiveTemplateInstantiation Inst;
331 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
332 Inst.PointOfInstantiation = PointOfInstantiation;
333 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000334 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000335 Inst.TemplateArgs = TemplateArgs.data();
336 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000337 Inst.InstantiationRange = InstantiationRange;
338 SemaRef.InNonInstantiationSFINAEContext = false;
339 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
340 }
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000341}
342
343Sema::InstantiatingTemplate::
344InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000345 NamedDecl *Template, TemplateTemplateParmDecl *Param,
346 ArrayRef<TemplateArgument> TemplateArgs,
347 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000348 : SemaRef(SemaRef),
349 SavedInNonInstantiationSFINAEContext(
350 SemaRef.InNonInstantiationSFINAEContext)
351{
Richard Smithab91ef12012-07-08 02:38:24 +0000352 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
353 if (!Invalid) {
354 ActiveTemplateInstantiation Inst;
355 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
356 Inst.PointOfInstantiation = PointOfInstantiation;
357 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000358 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000359 Inst.TemplateArgs = TemplateArgs.data();
360 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smithab91ef12012-07-08 02:38:24 +0000361 Inst.InstantiationRange = InstantiationRange;
362 SemaRef.InNonInstantiationSFINAEContext = false;
363 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
364 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000365}
366
367Sema::InstantiatingTemplate::
368InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith7e54fb52012-07-16 01:09:10 +0000369 TemplateDecl *Template, NamedDecl *Param,
370 ArrayRef<TemplateArgument> TemplateArgs,
371 SourceRange InstantiationRange)
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000372 : SemaRef(SemaRef),
373 SavedInNonInstantiationSFINAEContext(
374 SemaRef.InNonInstantiationSFINAEContext)
375{
Douglas Gregorf35f8282009-11-11 21:54:23 +0000376 Invalid = false;
377
378 ActiveTemplateInstantiation Inst;
379 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
380 Inst.PointOfInstantiation = PointOfInstantiation;
381 Inst.Template = Template;
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000382 Inst.Entity = Param;
Richard Smith7e54fb52012-07-16 01:09:10 +0000383 Inst.TemplateArgs = TemplateArgs.data();
384 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregorf35f8282009-11-11 21:54:23 +0000385 Inst.InstantiationRange = InstantiationRange;
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000386 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000387 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
388
389 assert(!Inst.isInstantiationRecord());
390 ++SemaRef.NonInstantiationEntries;
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000391}
392
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000393void Sema::InstantiatingTemplate::Clear() {
394 if (!Invalid) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000395 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
396 assert(SemaRef.NonInstantiationEntries > 0);
397 --SemaRef.NonInstantiationEntries;
398 }
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000399 SemaRef.InNonInstantiationSFINAEContext
400 = SavedInNonInstantiationSFINAEContext;
Douglas Gregor26dce442009-03-10 00:06:19 +0000401 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000402 Invalid = true;
403 }
Douglas Gregor26dce442009-03-10 00:06:19 +0000404}
405
Douglas Gregordf667e72009-03-10 20:44:00 +0000406bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
407 SourceLocation PointOfInstantiation,
408 SourceRange InstantiationRange) {
Douglas Gregorf35f8282009-11-11 21:54:23 +0000409 assert(SemaRef.NonInstantiationEntries <=
410 SemaRef.ActiveTemplateInstantiations.size());
411 if ((SemaRef.ActiveTemplateInstantiations.size() -
412 SemaRef.NonInstantiationEntries)
David Blaikie4e4d0842012-03-11 07:00:24 +0000413 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregordf667e72009-03-10 20:44:00 +0000414 return false;
415
Mike Stump1eb44332009-09-09 15:08:12 +0000416 SemaRef.Diag(PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000417 diag::err_template_recursion_depth_exceeded)
David Blaikie4e4d0842012-03-11 07:00:24 +0000418 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregordf667e72009-03-10 20:44:00 +0000419 << InstantiationRange;
420 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikie4e4d0842012-03-11 07:00:24 +0000421 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregordf667e72009-03-10 20:44:00 +0000422 return true;
423}
424
Douglas Gregoree1828a2009-03-10 18:03:33 +0000425/// \brief Prints the current instantiation stack through a series of
426/// notes.
427void Sema::PrintInstantiationStack() {
Douglas Gregor575cf372010-04-20 07:18:24 +0000428 // Determine which template instantiations to skip, if any.
429 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
430 unsigned Limit = Diags.getTemplateBacktraceLimit();
431 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
432 SkipStart = Limit / 2 + Limit % 2;
433 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
434 }
435
Douglas Gregorcca9e962009-07-01 22:01:06 +0000436 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregor575cf372010-04-20 07:18:24 +0000437 unsigned InstantiationIdx = 0;
Craig Topper09d19ef2013-07-04 03:08:24 +0000438 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregoree1828a2009-03-10 18:03:33 +0000439 Active = ActiveTemplateInstantiations.rbegin(),
440 ActiveEnd = ActiveTemplateInstantiations.rend();
441 Active != ActiveEnd;
Douglas Gregor575cf372010-04-20 07:18:24 +0000442 ++Active, ++InstantiationIdx) {
443 // Skip this instantiation?
444 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
445 if (InstantiationIdx == SkipStart) {
446 // Note that we're skipping instantiations.
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000447 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor575cf372010-04-20 07:18:24 +0000448 diag::note_instantiation_contexts_suppressed)
449 << unsigned(ActiveTemplateInstantiations.size() - Limit);
450 }
451 continue;
452 }
453
Douglas Gregordf667e72009-03-10 20:44:00 +0000454 switch (Active->Kind) {
455 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000456 Decl *D = Active->Entity;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000457 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
458 unsigned DiagID = diag::note_template_member_class_here;
459 if (isa<ClassTemplateSpecializationDecl>(Record))
460 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000461 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000462 << Context.getTypeDeclType(Record)
463 << Active->InstantiationRange;
Douglas Gregor7caa6822009-07-24 20:34:43 +0000464 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1637be72009-06-26 00:10:03 +0000465 unsigned DiagID;
466 if (Function->getPrimaryTemplate())
467 DiagID = diag::note_function_template_spec_here;
468 else
469 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000470 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000471 << Function
472 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000473 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000474 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor7caa6822009-07-24 20:34:43 +0000475 diag::note_template_static_data_member_def_here)
Richard Smith3e4c6c42011-05-05 21:57:07 +0000476 << VD
477 << Active->InstantiationRange;
Richard Smithf1c66b42012-03-14 23:13:10 +0000478 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
479 Diags.Report(Active->PointOfInstantiation,
480 diag::note_template_enum_def_here)
481 << ED
482 << Active->InstantiationRange;
Richard Smith3e4c6c42011-05-05 21:57:07 +0000483 } else {
484 Diags.Report(Active->PointOfInstantiation,
485 diag::note_template_type_alias_instantiation_here)
486 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregor7caa6822009-07-24 20:34:43 +0000487 << Active->InstantiationRange;
Douglas Gregorf3e7ce42009-05-18 17:01:57 +0000488 }
Douglas Gregordf667e72009-03-10 20:44:00 +0000489 break;
490 }
491
492 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000493 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer5eada842013-02-22 15:46:01 +0000494 SmallVector<char, 128> TemplateArgsStr;
495 llvm::raw_svector_ostream OS(TemplateArgsStr);
496 Template->printName(OS);
497 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000498 Active->TemplateArgs,
Douglas Gregord249e1d1f2009-05-29 20:38:28 +0000499 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000500 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000501 Diags.Report(Active->PointOfInstantiation,
Douglas Gregordf667e72009-03-10 20:44:00 +0000502 diag::note_default_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000503 << OS.str()
Douglas Gregordf667e72009-03-10 20:44:00 +0000504 << Active->InstantiationRange;
505 break;
506 }
Douglas Gregor637a4092009-06-10 23:47:09 +0000507
Douglas Gregorcca9e962009-07-01 22:01:06 +0000508 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000509 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000510 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000511 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000512 << FnTmpl
513 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
514 Active->TemplateArgs,
515 Active->NumTemplateArgs)
516 << Active->InstantiationRange;
Douglas Gregor637a4092009-06-10 23:47:09 +0000517 break;
518 }
Mike Stump1eb44332009-09-09 15:08:12 +0000519
Douglas Gregorcca9e962009-07-01 22:01:06 +0000520 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000521 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
522 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000523 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000524 diag::note_partial_spec_deduct_instantiation_here)
525 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor5e402912010-03-30 20:35:20 +0000526 << getTemplateArgumentBindingsText(
527 PartialSpec->getTemplateParameters(),
528 Active->TemplateArgs,
529 Active->NumTemplateArgs)
Douglas Gregorcca9e962009-07-01 22:01:06 +0000530 << Active->InstantiationRange;
531 } else {
532 FunctionTemplateDecl *FnTmpl
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000533 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000534 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorcca9e962009-07-01 22:01:06 +0000535 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor5e402912010-03-30 20:35:20 +0000536 << FnTmpl
537 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
538 Active->TemplateArgs,
539 Active->NumTemplateArgs)
540 << Active->InstantiationRange;
Douglas Gregorcca9e962009-07-01 22:01:06 +0000541 }
542 break;
Douglas Gregor637a4092009-06-10 23:47:09 +0000543
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000544 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000545 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000546 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Benjamin Kramer5eada842013-02-22 15:46:01 +0000548 SmallVector<char, 128> TemplateArgsStr;
549 llvm::raw_svector_ostream OS(TemplateArgsStr);
550 FD->printName(OS);
551 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000552 Active->TemplateArgs,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000553 Active->NumTemplateArgs,
Douglas Gregor8987b232011-09-27 23:30:47 +0000554 getPrintingPolicy());
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000555 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000556 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer5eada842013-02-22 15:46:01 +0000557 << OS.str()
Anders Carlsson25cae7f2009-09-05 05:14:19 +0000558 << Active->InstantiationRange;
559 break;
560 }
Mike Stump1eb44332009-09-09 15:08:12 +0000561
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000562 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000563 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000564 std::string Name;
565 if (!Parm->getName().empty())
566 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000567
568 TemplateParameterList *TemplateParams = 0;
569 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
570 TemplateParams = Template->getTemplateParameters();
571 else
572 TemplateParams =
573 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
574 ->getTemplateParameters();
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000575 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000576 diag::note_prior_template_arg_substitution)
577 << isa<TemplateTemplateParmDecl>(Parm)
578 << Name
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000579 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000580 Active->TemplateArgs,
581 Active->NumTemplateArgs)
582 << Active->InstantiationRange;
583 break;
584 }
Douglas Gregorf35f8282009-11-11 21:54:23 +0000585
586 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000587 TemplateParameterList *TemplateParams = 0;
588 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
589 TemplateParams = Template->getTemplateParameters();
590 else
591 TemplateParams =
592 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
593 ->getTemplateParameters();
594
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +0000595 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000596 diag::note_template_default_arg_checking)
Douglas Gregor54c53cc2011-01-04 23:35:54 +0000597 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregorf35f8282009-11-11 21:54:23 +0000598 Active->TemplateArgs,
599 Active->NumTemplateArgs)
600 << Active->InstantiationRange;
601 break;
602 }
Richard Smithe6975e92012-04-17 00:58:00 +0000603
604 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
605 Diags.Report(Active->PointOfInstantiation,
606 diag::note_template_exception_spec_instantiation_here)
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000607 << cast<FunctionDecl>(Active->Entity)
Richard Smithe6975e92012-04-17 00:58:00 +0000608 << Active->InstantiationRange;
609 break;
Douglas Gregordf667e72009-03-10 20:44:00 +0000610 }
Douglas Gregoree1828a2009-03-10 18:03:33 +0000611 }
612}
613
David Blaikiedc84cd52013-02-20 22:23:23 +0000614Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000615 if (InNonInstantiationSFINAEContext)
David Blaikiedc84cd52013-02-20 22:23:23 +0000616 return Optional<TemplateDeductionInfo *>(0);
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000617
Craig Topper09d19ef2013-07-04 03:08:24 +0000618 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000619 Active = ActiveTemplateInstantiations.rbegin(),
620 ActiveEnd = ActiveTemplateInstantiations.rend();
621 Active != ActiveEnd;
Douglas Gregorf35f8282009-11-11 21:54:23 +0000622 ++Active)
623 {
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000624 switch(Active->Kind) {
Douglas Gregor1eee5dc2011-01-27 22:31:44 +0000625 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smitha43ea642012-04-26 07:24:08 +0000626 // An instantiation of an alias template may or may not be a SFINAE
627 // context, depending on what else is on the stack.
Nick Lewycky4a9e60f2012-11-16 08:40:59 +0000628 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smitha43ea642012-04-26 07:24:08 +0000629 break;
630 // Fall through.
631 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithe6975e92012-04-17 00:58:00 +0000632 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorcca9e962009-07-01 22:01:06 +0000633 // This is a template instantiation, so there is no SFINAE.
David Blaikie66874fb2013-02-21 01:47:18 +0000634 return None;
Mike Stump1eb44332009-09-09 15:08:12 +0000635
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000636 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000637 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregorf35f8282009-11-11 21:54:23 +0000638 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregor9148c3f2009-11-11 19:13:48 +0000639 // A default template argument instantiation and substitution into
640 // template parameters with arguments for prior parameters may or may
641 // not be a SFINAE context; look further up the stack.
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000642 break;
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Douglas Gregorcca9e962009-07-01 22:01:06 +0000644 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
645 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
646 // We're either substitution explicitly-specified template arguments
647 // or deduced template arguments, so SFINAE applies.
Douglas Gregor9b623632010-10-12 23:32:35 +0000648 assert(Active->DeductionInfo && "Missing deduction info pointer");
649 return Active->DeductionInfo;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000650 }
651 }
652
David Blaikie66874fb2013-02-21 01:47:18 +0000653 return None;
Douglas Gregor5e9f35c2009-06-14 07:33:30 +0000654}
655
Douglas Gregord3731192011-01-10 07:32:04 +0000656/// \brief Retrieve the depth and index of a parameter pack.
657static std::pair<unsigned, unsigned>
658getDepthAndIndex(NamedDecl *ND) {
659 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
660 return std::make_pair(TTP->getDepth(), TTP->getIndex());
661
662 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
663 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
664
665 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
666 return std::make_pair(TTP->getDepth(), TTP->getIndex());
667}
668
Douglas Gregor99ebf652009-02-27 19:31:52 +0000669//===----------------------------------------------------------------------===/
670// Template Instantiation for Types
671//===----------------------------------------------------------------------===/
Douglas Gregorcd281c32009-02-28 00:25:32 +0000672namespace {
Douglas Gregor895162d2010-04-30 18:55:50 +0000673 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000674 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregorcd281c32009-02-28 00:25:32 +0000675 SourceLocation Loc;
676 DeclarationName Entity;
Douglas Gregor99ebf652009-02-27 19:31:52 +0000677
Douglas Gregorcd281c32009-02-28 00:25:32 +0000678 public:
Douglas Gregor43959a92009-08-20 07:17:43 +0000679 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump1eb44332009-09-09 15:08:12 +0000680
681 TemplateInstantiator(Sema &SemaRef,
Douglas Gregord6350ae2009-08-28 20:31:08 +0000682 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor577f75a2009-08-04 16:50:30 +0000683 SourceLocation Loc,
Mike Stump1eb44332009-09-09 15:08:12 +0000684 DeclarationName Entity)
685 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregor43959a92009-08-20 07:17:43 +0000686 Entity(Entity) { }
Douglas Gregorcd281c32009-02-28 00:25:32 +0000687
Mike Stump1eb44332009-09-09 15:08:12 +0000688 /// \brief Determine whether the given type \p T has already been
Douglas Gregor577f75a2009-08-04 16:50:30 +0000689 /// transformed.
690 ///
691 /// For the purposes of template instantiation, a type has already been
692 /// transformed if it is NULL or if it is not dependent.
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000693 bool AlreadyTransformed(QualType T);
Mike Stump1eb44332009-09-09 15:08:12 +0000694
Douglas Gregor577f75a2009-08-04 16:50:30 +0000695 /// \brief Returns the location of the entity being instantiated, if known.
696 SourceLocation getBaseLocation() { return Loc; }
Mike Stump1eb44332009-09-09 15:08:12 +0000697
Douglas Gregor577f75a2009-08-04 16:50:30 +0000698 /// \brief Returns the name of the entity being instantiated, if any.
699 DeclarationName getBaseEntity() { return Entity; }
Mike Stump1eb44332009-09-09 15:08:12 +0000700
Douglas Gregor972e6ce2009-10-27 06:26:26 +0000701 /// \brief Sets the "base" location and entity when that
702 /// information is known based on another transformation.
703 void setBase(SourceLocation Loc, DeclarationName Entity) {
704 this->Loc = Loc;
705 this->Entity = Entity;
706 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000707
708 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
709 SourceRange PatternRange,
David Blaikiea71f9d02011-09-22 02:34:54 +0000710 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000711 bool &ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000712 bool &RetainExpansion,
David Blaikiedc84cd52013-02-20 22:23:23 +0000713 Optional<unsigned> &NumExpansions) {
Douglas Gregorb99268b2010-12-21 00:52:54 +0000714 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
715 PatternRange, Unexpanded,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000716 TemplateArgs,
717 ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +0000718 RetainExpansion,
Douglas Gregorb99268b2010-12-21 00:52:54 +0000719 NumExpansions);
720 }
Douglas Gregor8491ffe2010-12-20 22:05:00 +0000721
Douglas Gregor12c9c002011-01-07 16:43:16 +0000722 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
723 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
724 }
725
Douglas Gregord3731192011-01-10 07:32:04 +0000726 TemplateArgument ForgetPartiallySubstitutedPack() {
727 TemplateArgument Result;
728 if (NamedDecl *PartialPack
729 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
730 MultiLevelTemplateArgumentList &TemplateArgs
731 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
732 unsigned Depth, Index;
733 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
734 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
735 Result = TemplateArgs(Depth, Index);
736 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
737 }
738 }
739
740 return Result;
741 }
742
743 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
744 if (Arg.isNull())
745 return;
746
747 if (NamedDecl *PartialPack
748 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
749 MultiLevelTemplateArgumentList &TemplateArgs
750 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
751 unsigned Depth, Index;
752 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
753 TemplateArgs.setArgument(Depth, Index, Arg);
754 }
755 }
756
Douglas Gregor577f75a2009-08-04 16:50:30 +0000757 /// \brief Transform the given declaration by instantiating a reference to
758 /// this declaration.
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000759 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregorb98b1992009-08-11 05:31:07 +0000760
Douglas Gregordfca6f52012-02-13 22:00:16 +0000761 void transformAttrs(Decl *Old, Decl *New) {
762 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
763 }
764
765 void transformedLocalDecl(Decl *Old, Decl *New) {
766 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
767 }
768
Mike Stump1eb44332009-09-09 15:08:12 +0000769 /// \brief Transform the definition of the given declaration by
Douglas Gregor43959a92009-08-20 07:17:43 +0000770 /// instantiating it.
Douglas Gregoraac571c2010-03-01 17:25:41 +0000771 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000773 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregor6cd21982009-10-20 05:58:46 +0000774 /// declaration.
775 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
776
Douglas Gregor43959a92009-08-20 07:17:43 +0000777 /// \brief Rebuild the exception declaration and register the declaration
778 /// as an instantiated local.
Douglas Gregor83cb9422010-09-09 17:09:21 +0000779 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000780 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000781 SourceLocation StartLoc,
782 SourceLocation NameLoc,
783 IdentifierInfo *Name);
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Douglas Gregorbe270a02010-04-26 17:57:08 +0000785 /// \brief Rebuild the Objective-C exception declaration and register the
786 /// declaration as an instantiated local.
787 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
788 TypeSourceInfo *TSInfo, QualType T);
789
John McCallc4e70192009-09-11 04:59:25 +0000790 /// \brief Check for tag mismatches when instantiating an
791 /// elaborated type.
John McCall21e413f2010-11-04 19:04:38 +0000792 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
793 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +0000794 NestedNameSpecifierLoc QualifierLoc,
795 QualType T);
John McCallc4e70192009-09-11 04:59:25 +0000796
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +0000797 TemplateName TransformTemplateName(CXXScopeSpec &SS,
798 TemplateName Name,
799 SourceLocation NameLoc,
800 QualType ObjectType = QualType(),
801 NamedDecl *FirstQualifierInScope = 0);
802
John McCall60d7b3a2010-08-24 06:29:42 +0000803 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
804 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
805 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000806
John McCall60d7b3a2010-08-24 06:29:42 +0000807 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor56bc9832010-12-24 00:15:10 +0000808 NonTypeTemplateParmDecl *D);
Douglas Gregorc7793c72011-01-15 01:15:58 +0000809 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
810 SubstNonTypeTemplateParmPackExpr *E);
Richard Smith9a4db032012-09-12 00:56:43 +0000811
812 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
813 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
814
815 /// \brief Transform a reference to a function parameter pack.
816 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
817 ParmVarDecl *PD);
818
819 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
820 /// expand a function parameter pack reference which refers to an expanded
821 /// pack.
822 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
823
Douglas Gregor895162d2010-04-30 18:55:50 +0000824 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000825 FunctionProtoTypeLoc TL);
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000826 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
827 FunctionProtoTypeLoc TL,
828 CXXRecordDecl *ThisContext,
829 unsigned ThisTypeQuals);
830
Douglas Gregor6a24bfd2011-01-14 22:40:04 +0000831 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +0000832 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +0000833 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +0000834 bool ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +0000835
Mike Stump1eb44332009-09-09 15:08:12 +0000836 /// \brief Transforms a template type parameter type by performing
Douglas Gregor577f75a2009-08-04 16:50:30 +0000837 /// substitution of the corresponding template type argument.
John McCalla2becad2009-10-21 00:40:46 +0000838 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +0000839 TemplateTypeParmTypeLoc TL);
Nick Lewycky03d98c52010-07-06 19:51:49 +0000840
Douglas Gregorc3069d62011-01-14 02:55:32 +0000841 /// \brief Transforms an already-substituted template type parameter pack
842 /// into either itself (if we aren't substituting into its pack expansion)
843 /// or the appropriate substituted argument.
844 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
845 SubstTemplateTypeParmPackTypeLoc TL);
846
John McCall60d7b3a2010-08-24 06:29:42 +0000847 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewycky03d98c52010-07-06 19:51:49 +0000848 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCall60d7b3a2010-08-24 06:29:42 +0000849 ExprResult Result =
Nick Lewycky03d98c52010-07-06 19:51:49 +0000850 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
851 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000852 return Result;
Nick Lewycky03d98c52010-07-06 19:51:49 +0000853 }
John McCall91a57552011-07-15 05:09:51 +0000854
Richard Smith612409e2012-07-25 03:56:55 +0000855 ExprResult TransformLambdaExpr(LambdaExpr *E) {
856 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
857 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
858 }
859
860 ExprResult TransformLambdaScope(LambdaExpr *E,
861 CXXMethodDecl *CallOperator) {
862 CallOperator->setInstantiationOfMemberFunction(E->getCallOperator(),
863 TSK_ImplicitInstantiation);
864 return TreeTransform<TemplateInstantiator>::
865 TransformLambdaScope(E, CallOperator);
866 }
867
John McCall91a57552011-07-15 05:09:51 +0000868 private:
869 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
870 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +0000871 TemplateArgument arg);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000872 };
Douglas Gregor7e7eb3d2009-07-06 15:59:29 +0000873}
874
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000875bool TemplateInstantiator::AlreadyTransformed(QualType T) {
876 if (T.isNull())
877 return true;
878
Douglas Gregor561f8122011-07-01 01:22:09 +0000879 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregorb4eeaff2010-05-07 23:12:07 +0000880 return false;
881
882 getSema().MarkDeclarationsReferencedInType(Loc, T);
883 return true;
884}
885
Eli Friedman10ec0e42013-07-19 19:40:38 +0000886static TemplateArgument
887getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
888 assert(S.ArgumentPackSubstitutionIndex >= 0);
889 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
890 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
891 if (Arg.isPackExpansion())
892 Arg = Arg.getPackExpansionPattern();
893 return Arg;
894}
895
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000896Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregorc68afe22009-09-03 21:38:09 +0000897 if (!D)
898 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000899
Douglas Gregorc68afe22009-09-03 21:38:09 +0000900 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregord6350ae2009-08-28 20:31:08 +0000901 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor6d3e6272010-02-05 19:54:12 +0000902 // If the corresponding template argument is NULL or non-existent, it's
903 // because we are performing instantiation from explicitly-specified
904 // template arguments in a function template, but there were some
905 // arguments left unspecified.
906 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
907 TTP->getPosition()))
908 return D;
909
Douglas Gregor61c4d282011-01-05 15:48:55 +0000910 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
911
912 if (TTP->isParameterPack()) {
913 assert(Arg.getKind() == TemplateArgument::Pack &&
914 "Missing argument pack");
Eli Friedman10ec0e42013-07-19 19:40:38 +0000915 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor61c4d282011-01-05 15:48:55 +0000916 }
917
918 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor788cd062009-11-11 01:00:40 +0000919 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregord6350ae2009-08-28 20:31:08 +0000920 "Wrong kind of template template argument");
Douglas Gregor788cd062009-11-11 01:00:40 +0000921 return Template.getAsTemplateDecl();
Douglas Gregord6350ae2009-08-28 20:31:08 +0000922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Douglas Gregor788cd062009-11-11 01:00:40 +0000924 // Fall through to find the instantiated declaration for this template
925 // template parameter.
Douglas Gregord1067e52009-08-06 06:41:21 +0000926 }
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000928 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregor577f75a2009-08-04 16:50:30 +0000929}
930
Douglas Gregoraac571c2010-03-01 17:25:41 +0000931Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCallce3ff2b2009-08-25 22:02:44 +0000932 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregor43959a92009-08-20 07:17:43 +0000933 if (!Inst)
934 return 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregor43959a92009-08-20 07:17:43 +0000936 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
937 return Inst;
938}
939
Douglas Gregor6cd21982009-10-20 05:58:46 +0000940NamedDecl *
941TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
942 SourceLocation Loc) {
943 // If the first part of the nested-name-specifier was a template type
944 // parameter, instantiate that type parameter down to a tag type.
945 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
946 const TemplateTypeParmType *TTP
947 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor984a58b2010-12-20 22:48:17 +0000948
Douglas Gregor6cd21982009-10-20 05:58:46 +0000949 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor984a58b2010-12-20 22:48:17 +0000950 // FIXME: This needs testing w/ member access expressions.
951 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
952
953 if (TTP->isParameterPack()) {
954 assert(Arg.getKind() == TemplateArgument::Pack &&
955 "Missing argument pack");
956
Douglas Gregor2be29f42011-01-14 23:41:42 +0000957 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor984a58b2010-12-20 22:48:17 +0000958 return 0;
Douglas Gregor984a58b2010-12-20 22:48:17 +0000959
Eli Friedman10ec0e42013-07-19 19:40:38 +0000960 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor984a58b2010-12-20 22:48:17 +0000961 }
962
963 QualType T = Arg.getAsType();
Douglas Gregor6cd21982009-10-20 05:58:46 +0000964 if (T.isNull())
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000965 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000966
967 if (const TagType *Tag = T->getAs<TagType>())
968 return Tag->getDecl();
969
970 // The resulting type is not a tag; complain.
971 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
972 return 0;
973 }
974 }
975
Douglas Gregor7c1e98f2010-03-01 15:56:25 +0000976 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregor6cd21982009-10-20 05:58:46 +0000977}
978
Douglas Gregor43959a92009-08-20 07:17:43 +0000979VarDecl *
980TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCalla93c9342009-12-07 02:54:59 +0000981 TypeSourceInfo *Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000982 SourceLocation StartLoc,
983 SourceLocation NameLoc,
984 IdentifierInfo *Name) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000985 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +0000986 StartLoc, NameLoc, Name);
Douglas Gregorbe270a02010-04-26 17:57:08 +0000987 if (Var)
988 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
989 return Var;
990}
991
992VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
993 TypeSourceInfo *TSInfo,
994 QualType T) {
995 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
996 if (Var)
Douglas Gregor43959a92009-08-20 07:17:43 +0000997 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
998 return Var;
999}
1000
John McCallc4e70192009-09-11 04:59:25 +00001001QualType
John McCall21e413f2010-11-04 19:04:38 +00001002TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1003 ElaboratedTypeKeyword Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001004 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001005 QualType T) {
John McCallc4e70192009-09-11 04:59:25 +00001006 if (const TagType *TT = T->getAs<TagType>()) {
1007 TagDecl* TD = TT->getDecl();
1008
John McCall21e413f2010-11-04 19:04:38 +00001009 SourceLocation TagLocation = KeywordLoc;
John McCallc4e70192009-09-11 04:59:25 +00001010
John McCallc4e70192009-09-11 04:59:25 +00001011 IdentifierInfo *Id = TD->getIdentifier();
1012
1013 // TODO: should we even warn on struct/class mismatches for this? Seems
1014 // like it's likely to produce a lot of spurious errors.
Richard Smithcbf97c52012-08-17 00:12:27 +00001015 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001016 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieubbf34c02011-06-10 03:11:26 +00001017 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1018 TagLocation, *Id)) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001019 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1020 << Id
1021 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1022 TD->getKindName());
1023 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1024 }
John McCallc4e70192009-09-11 04:59:25 +00001025 }
1026 }
1027
John McCall21e413f2010-11-04 19:04:38 +00001028 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1029 Keyword,
Douglas Gregor9e876872011-03-01 18:12:44 +00001030 QualifierLoc,
1031 T);
John McCallc4e70192009-09-11 04:59:25 +00001032}
1033
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001034TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1035 TemplateName Name,
1036 SourceLocation NameLoc,
1037 QualType ObjectType,
1038 NamedDecl *FirstQualifierInScope) {
1039 if (TemplateTemplateParmDecl *TTP
1040 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1041 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1042 // If the corresponding template argument is NULL or non-existent, it's
1043 // because we are performing instantiation from explicitly-specified
1044 // template arguments in a function template, but there were some
1045 // arguments left unspecified.
1046 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1047 TTP->getPosition()))
1048 return Name;
1049
1050 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1051
1052 if (TTP->isParameterPack()) {
1053 assert(Arg.getKind() == TemplateArgument::Pack &&
1054 "Missing argument pack");
1055
1056 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1057 // We have the template argument pack to substitute, but we're not
1058 // actually expanding the enclosing pack expansion yet. So, just
1059 // keep the entire argument pack.
1060 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1061 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001062
1063 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001064 }
1065
1066 TemplateName Template = Arg.getAsTemplate();
Richard Smith3e4c6c42011-05-05 21:57:07 +00001067 assert(!Template.isNull() && "Null template template argument");
John McCall14606042011-06-30 08:33:18 +00001068
Douglas Gregor58750382011-03-05 20:06:51 +00001069 // We don't ever want to substitute for a qualified template name, since
1070 // the qualifier is handled separately. So, look through the qualified
1071 // template name to its underlying declaration.
1072 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1073 Template = TemplateName(QTN->getTemplateDecl());
John McCall14606042011-06-30 08:33:18 +00001074
1075 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001076 return Template;
1077 }
1078 }
1079
1080 if (SubstTemplateTemplateParmPackStorage *SubstPack
1081 = Name.getAsSubstTemplateTemplateParmPack()) {
1082 if (getSema().ArgumentPackSubstitutionIndex == -1)
1083 return Name;
1084
Eli Friedman10ec0e42013-07-19 19:40:38 +00001085 TemplateArgument Arg = SubstPack->getArgumentPack();
1086 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1087 return Arg.getAsTemplate();
Douglas Gregorfd4ffeb2011-03-02 18:07:45 +00001088 }
1089
1090 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1091 FirstQualifierInScope);
1092}
1093
John McCall60d7b3a2010-08-24 06:29:42 +00001094ExprResult
John McCall454feb92009-12-08 09:21:05 +00001095TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson773f3972009-09-11 01:22:35 +00001096 if (!E->isTypeDependent())
John McCall3fa5cae2010-10-26 07:05:15 +00001097 return SemaRef.Owned(E);
Anders Carlsson773f3972009-09-11 01:22:35 +00001098
1099 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1100 assert(currentDecl && "Must have current function declaration when "
1101 "instantiating.");
1102
1103 PredefinedExpr::IdentType IT = E->getIdentType();
1104
Anders Carlsson848fa642010-02-11 18:20:28 +00001105 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson773f3972009-09-11 01:22:35 +00001106
1107 llvm::APInt LengthI(32, Length + 1);
Nico Weberb4e80082012-06-25 22:34:48 +00001108 QualType ResTy;
1109 if (IT == PredefinedExpr::LFunction)
Hans Wennborg15f92ba2013-05-10 10:08:40 +00001110 ResTy = getSema().Context.WideCharTy.withConst();
Nico Weberb4e80082012-06-25 22:34:48 +00001111 else
1112 ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson773f3972009-09-11 01:22:35 +00001113 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1114 ArrayType::Normal, 0);
1115 PredefinedExpr *PE =
1116 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1117 return getSema().Owned(PE);
1118}
1119
John McCall60d7b3a2010-08-24 06:29:42 +00001120ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001121TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregordcee9802010-02-08 23:41:45 +00001122 NonTypeTemplateParmDecl *NTTP) {
John McCallb8fc0532010-02-06 08:42:39 +00001123 // If the corresponding template argument is NULL or non-existent, it's
1124 // because we are performing instantiation from explicitly-specified
1125 // template arguments in a function template, but there were some
1126 // arguments left unspecified.
1127 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1128 NTTP->getPosition()))
John McCall3fa5cae2010-10-26 07:05:15 +00001129 return SemaRef.Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Douglas Gregor56bc9832010-12-24 00:15:10 +00001131 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1132 if (NTTP->isParameterPack()) {
1133 assert(Arg.getKind() == TemplateArgument::Pack &&
1134 "Missing argument pack");
1135
1136 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc7793c72011-01-15 01:15:58 +00001137 // We have an argument pack, but we can't select a particular argument
1138 // out of it yet. Therefore, we'll build an expression to hold on to that
1139 // argument pack.
1140 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1141 E->getLocation(),
1142 NTTP->getDeclName());
1143 if (TargetType.isNull())
1144 return ExprError();
1145
1146 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1147 NTTP,
1148 E->getLocation(),
1149 Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001150 }
1151
Eli Friedman10ec0e42013-07-19 19:40:38 +00001152 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor56bc9832010-12-24 00:15:10 +00001153 }
Mike Stump1eb44332009-09-09 15:08:12 +00001154
John McCall91a57552011-07-15 05:09:51 +00001155 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1156}
1157
1158ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1159 NonTypeTemplateParmDecl *parm,
1160 SourceLocation loc,
Richard Smith60983812012-07-09 03:07:20 +00001161 TemplateArgument arg) {
John McCall91a57552011-07-15 05:09:51 +00001162 ExprResult result;
1163 QualType type;
1164
John McCallb8fc0532010-02-06 08:42:39 +00001165 // The template argument itself might be an expression, in which
1166 // case we just return that expression.
John McCall91a57552011-07-15 05:09:51 +00001167 if (arg.getKind() == TemplateArgument::Expression) {
1168 Expr *argExpr = arg.getAsExpr();
1169 result = SemaRef.Owned(argExpr);
1170 type = argExpr->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Eli Friedmand7a6b162012-09-26 02:36:12 +00001172 } else if (arg.getKind() == TemplateArgument::Declaration ||
1173 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregord2008e22012-04-06 22:40:38 +00001174 ValueDecl *VD;
Eli Friedmand7a6b162012-09-26 02:36:12 +00001175 if (arg.getKind() == TemplateArgument::Declaration) {
1176 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Douglas Gregord2008e22012-04-06 22:40:38 +00001178 // Find the instantiation of the template argument. This is
1179 // required for nested templates.
1180 VD = cast_or_null<ValueDecl>(
1181 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1182 if (!VD)
1183 return ExprError();
1184 } else {
1185 // Propagate NULL template argument.
1186 VD = 0;
1187 }
1188
John McCall645cf442010-02-06 10:23:53 +00001189 // Derive the type we want the substituted decl to have. This had
1190 // better be non-dependent, or these checks will have serious problems.
John McCall91a57552011-07-15 05:09:51 +00001191 if (parm->isExpandedParameterPack()) {
1192 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1193 } else if (parm->isParameterPack() &&
1194 isa<PackExpansionType>(parm->getType())) {
1195 type = SemaRef.SubstType(
1196 cast<PackExpansionType>(parm->getType())->getPattern(),
1197 TemplateArgs, loc, parm->getDeclName());
1198 } else {
1199 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1200 loc, parm->getDeclName());
1201 }
1202 assert(!type.isNull() && "type substitution failed for param type");
1203 assert(!type->isDependentType() && "param type still dependent");
1204 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCallb8fc0532010-02-06 08:42:39 +00001205
John McCall91a57552011-07-15 05:09:51 +00001206 if (!result.isInvalid()) type = result.get()->getType();
1207 } else {
1208 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1209
1210 // Note that this type can be different from the type of 'result',
1211 // e.g. if it's an enum type.
1212 type = arg.getIntegralType();
1213 }
1214 if (result.isInvalid()) return ExprError();
1215
1216 Expr *resultExpr = result.take();
1217 return SemaRef.Owned(new (SemaRef.Context)
1218 SubstNonTypeTemplateParmExpr(type,
1219 resultExpr->getValueKind(),
1220 loc, parm, resultExpr));
John McCallb8fc0532010-02-06 08:42:39 +00001221}
1222
Douglas Gregorc7793c72011-01-15 01:15:58 +00001223ExprResult
1224TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1225 SubstNonTypeTemplateParmPackExpr *E) {
1226 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1227 // We aren't expanding the parameter pack, so just return ourselves.
1228 return getSema().Owned(E);
1229 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001230
1231 TemplateArgument Arg = E->getArgumentPack();
1232 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall91a57552011-07-15 05:09:51 +00001233 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1234 E->getParameterPackLocation(),
1235 Arg);
Douglas Gregorc7793c72011-01-15 01:15:58 +00001236}
John McCallb8fc0532010-02-06 08:42:39 +00001237
John McCall60d7b3a2010-08-24 06:29:42 +00001238ExprResult
Richard Smith9a4db032012-09-12 00:56:43 +00001239TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1240 SourceLocation Loc) {
1241 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1242 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1243}
1244
1245ExprResult
1246TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1247 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1248 // We can expand this parameter pack now.
1249 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1250 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1251 if (!VD)
1252 return ExprError();
1253 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1254 }
1255
1256 QualType T = TransformType(E->getType());
1257 if (T.isNull())
1258 return ExprError();
1259
1260 // Transform each of the parameter expansions into the corresponding
1261 // parameters in the instantiation of the function decl.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001262 SmallVector<Decl *, 8> Parms;
Richard Smith9a4db032012-09-12 00:56:43 +00001263 Parms.reserve(E->getNumExpansions());
1264 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1265 I != End; ++I) {
1266 ParmVarDecl *D =
1267 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1268 if (!D)
1269 return ExprError();
1270 Parms.push_back(D);
1271 }
1272
1273 return FunctionParmPackExpr::Create(getSema().Context, T,
1274 E->getParameterPack(),
1275 E->getParameterPackLocation(), Parms);
1276}
1277
1278ExprResult
1279TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1280 ParmVarDecl *PD) {
1281 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1282 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1283 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1284 assert(Found && "no instantiation for parameter pack");
1285
1286 Decl *TransformedDecl;
1287 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1288 // If this is a reference to a function parameter pack which we can substitute
1289 // but can't yet expand, build a FunctionParmPackExpr for it.
1290 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1291 QualType T = TransformType(E->getType());
1292 if (T.isNull())
1293 return ExprError();
1294 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1295 E->getExprLoc(), *Pack);
1296 }
1297
1298 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1299 } else {
1300 TransformedDecl = Found->get<Decl*>();
1301 }
1302
1303 // We have either an unexpanded pack or a specific expansion.
1304 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1305 E->getExprLoc());
1306}
1307
1308ExprResult
John McCallb8fc0532010-02-06 08:42:39 +00001309TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1310 NamedDecl *D = E->getDecl();
Richard Smith9a4db032012-09-12 00:56:43 +00001311
1312 // Handle references to non-type template parameters and non-type template
1313 // parameter packs.
John McCallb8fc0532010-02-06 08:42:39 +00001314 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1315 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1316 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor550d9b22009-10-31 17:21:17 +00001317
1318 // We have a non-type template parameter that isn't fully substituted;
1319 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregorb98b1992009-08-11 05:31:07 +00001320 }
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Richard Smith9a4db032012-09-12 00:56:43 +00001322 // Handle references to function parameter packs.
1323 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1324 if (PD->isParameterPack())
1325 return TransformFunctionParmPackRefExpr(E, PD);
1326
John McCall454feb92009-12-08 09:21:05 +00001327 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregorb98b1992009-08-11 05:31:07 +00001328}
1329
John McCall60d7b3a2010-08-24 06:29:42 +00001330ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall454feb92009-12-08 09:21:05 +00001331 CXXDefaultArgExpr *E) {
Sebastian Redla29e51b2009-11-08 13:56:19 +00001332 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1333 getDescribedFunctionTemplate() &&
1334 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor036aed12009-12-23 23:03:06 +00001335 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1336 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1337 E->getParam());
Sebastian Redla29e51b2009-11-08 13:56:19 +00001338}
1339
Douglas Gregor895162d2010-04-30 18:55:50 +00001340QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001341 FunctionProtoTypeLoc TL) {
Douglas Gregor895162d2010-04-30 18:55:50 +00001342 // We need a local instantiation scope for this function prototype.
John McCall2a7fb272010-08-25 05:32:35 +00001343 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall43fed0d2010-11-12 08:19:04 +00001344 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall21ef0fa2010-03-11 09:03:00 +00001345}
1346
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001347QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1348 FunctionProtoTypeLoc TL,
1349 CXXRecordDecl *ThisContext,
1350 unsigned ThisTypeQuals) {
1351 // We need a local instantiation scope for this function prototype.
1352 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1353 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1354 ThisTypeQuals);
1355}
1356
John McCall21ef0fa2010-03-11 09:03:00 +00001357ParmVarDecl *
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001358TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCallfb44de92011-05-01 22:35:37 +00001359 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001360 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001361 bool ExpectParameterPack) {
John McCallfb44de92011-05-01 22:35:37 +00001362 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001363 NumExpansions, ExpectParameterPack);
John McCall21ef0fa2010-03-11 09:03:00 +00001364}
1365
Mike Stump1eb44332009-09-09 15:08:12 +00001366QualType
John McCalla2becad2009-10-21 00:40:46 +00001367TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall43fed0d2010-11-12 08:19:04 +00001368 TemplateTypeParmTypeLoc TL) {
John McCallf4c73712011-01-19 06:33:43 +00001369 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregord6350ae2009-08-28 20:31:08 +00001370 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor99ebf652009-02-27 19:31:52 +00001371 // Replace the template type parameter with its corresponding
1372 // template argument.
Mike Stump1eb44332009-09-09 15:08:12 +00001373
1374 // If the corresponding template argument is NULL or doesn't exist, it's
1375 // because we are performing instantiation from explicitly-specified
1376 // template arguments in a function template class, but there were some
Douglas Gregor16134c62009-07-01 00:28:38 +00001377 // arguments left unspecified.
John McCalla2becad2009-10-21 00:40:46 +00001378 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1379 TemplateTypeParmTypeLoc NewTL
1380 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1381 NewTL.setNameLoc(TL.getNameLoc());
1382 return TL.getType();
1383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001385 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1386
1387 if (T->isParameterPack()) {
1388 assert(Arg.getKind() == TemplateArgument::Pack &&
1389 "Missing argument pack");
1390
1391 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorc3069d62011-01-14 02:55:32 +00001392 // We have the template argument pack, but we're not expanding the
1393 // enclosing pack expansion yet. Just save the template argument
1394 // pack for later substitution.
1395 QualType Result
1396 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1397 SubstTemplateTypeParmPackTypeLoc NewTL
1398 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1399 NewTL.setNameLoc(TL.getNameLoc());
1400 return Result;
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001401 }
1402
Eli Friedman10ec0e42013-07-19 19:40:38 +00001403 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001404 }
1405
1406 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregor99ebf652009-02-27 19:31:52 +00001407 "Template argument kind mismatch");
Douglas Gregord6350ae2009-08-28 20:31:08 +00001408
Douglas Gregor8491ffe2010-12-20 22:05:00 +00001409 QualType Replacement = Arg.getAsType();
John McCall49a832b2009-10-18 09:09:24 +00001410
1411 // TODO: only do this uniquing once, at the start of instantiation.
John McCalla2becad2009-10-21 00:40:46 +00001412 QualType Result
1413 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1414 SubstTemplateTypeParmTypeLoc NewTL
1415 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1416 NewTL.setNameLoc(TL.getNameLoc());
1417 return Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001418 }
Douglas Gregor99ebf652009-02-27 19:31:52 +00001419
1420 // The template type parameter comes from an inner template (e.g.,
1421 // the template parameter list of a member template inside the
1422 // template we are instantiating). Create a new template type
1423 // parameter with the template "level" reduced by one.
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001424 TemplateTypeParmDecl *NewTTPDecl = 0;
1425 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1426 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1427 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1428
John McCalla2becad2009-10-21 00:40:46 +00001429 QualType Result
1430 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1431 - TemplateArgs.getNumLevels(),
1432 T->getIndex(),
1433 T->isParameterPack(),
Chandler Carruth4fb86f82011-05-01 00:51:33 +00001434 NewTTPDecl);
John McCalla2becad2009-10-21 00:40:46 +00001435 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1436 NewTL.setNameLoc(TL.getNameLoc());
1437 return Result;
Douglas Gregorcd281c32009-02-28 00:25:32 +00001438}
Douglas Gregor99ebf652009-02-27 19:31:52 +00001439
Douglas Gregorc3069d62011-01-14 02:55:32 +00001440QualType
1441TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1442 TypeLocBuilder &TLB,
1443 SubstTemplateTypeParmPackTypeLoc TL) {
1444 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1445 // We aren't expanding the parameter pack, so just return ourselves.
1446 SubstTemplateTypeParmPackTypeLoc NewTL
1447 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1448 NewTL.setNameLoc(TL.getNameLoc());
1449 return TL.getType();
1450 }
Eli Friedman10ec0e42013-07-19 19:40:38 +00001451
1452 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1453 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1454 QualType Result = Arg.getAsType();
1455
Douglas Gregorc3069d62011-01-14 02:55:32 +00001456 Result = getSema().Context.getSubstTemplateTypeParmType(
1457 TL.getTypePtr()->getReplacedParameter(),
1458 Result);
1459 SubstTemplateTypeParmTypeLoc NewTL
1460 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1461 NewTL.setNameLoc(TL.getNameLoc());
1462 return Result;
1463}
1464
John McCallce3ff2b2009-08-25 22:02:44 +00001465/// \brief Perform substitution on the type T with a given set of template
1466/// arguments.
Douglas Gregor99ebf652009-02-27 19:31:52 +00001467///
1468/// This routine substitutes the given template arguments into the
1469/// type T and produces the instantiated type.
1470///
1471/// \param T the type into which the template arguments will be
1472/// substituted. If this type is not dependent, it will be returned
1473/// immediately.
1474///
James Dennett1dfbd922012-06-14 21:40:34 +00001475/// \param Args the template arguments that will be
Douglas Gregor99ebf652009-02-27 19:31:52 +00001476/// substituted for the top-level template parameters within T.
1477///
Douglas Gregor99ebf652009-02-27 19:31:52 +00001478/// \param Loc the location in the source code where this substitution
1479/// is being performed. It will typically be the location of the
1480/// declarator (if we're instantiating the type of some declaration)
1481/// or the location of the type in the source code (if, e.g., we're
1482/// instantiating the type of a cast expression).
1483///
1484/// \param Entity the name of the entity associated with a declaration
1485/// being instantiated (if any). May be empty to indicate that there
1486/// is no such entity (if, e.g., this is a type that occurs as part of
1487/// a cast expression) or that the entity has no name (e.g., an
1488/// unnamed function parameter).
1489///
1490/// \returns If the instantiation succeeds, the instantiated
1491/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCalla93c9342009-12-07 02:54:59 +00001492TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCallcd7ba1c2009-10-21 00:58:09 +00001493 const MultiLevelTemplateArgumentList &Args,
1494 SourceLocation Loc,
1495 DeclarationName Entity) {
1496 assert(!ActiveTemplateInstantiations.empty() &&
1497 "Cannot perform an instantiation without some context on the "
1498 "instantiation stack");
1499
Douglas Gregor561f8122011-07-01 01:22:09 +00001500 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor836adf62010-05-24 17:22:01 +00001501 !T->getType()->isVariablyModifiedType())
John McCallcd7ba1c2009-10-21 00:58:09 +00001502 return T;
1503
1504 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1505 return Instantiator.TransformType(T);
1506}
1507
Douglas Gregor603cfb42011-01-05 23:12:31 +00001508TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1509 const MultiLevelTemplateArgumentList &Args,
1510 SourceLocation Loc,
1511 DeclarationName Entity) {
1512 assert(!ActiveTemplateInstantiations.empty() &&
1513 "Cannot perform an instantiation without some context on the "
1514 "instantiation stack");
1515
1516 if (TL.getType().isNull())
1517 return 0;
1518
Douglas Gregor561f8122011-07-01 01:22:09 +00001519 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor603cfb42011-01-05 23:12:31 +00001520 !TL.getType()->isVariablyModifiedType()) {
1521 // FIXME: Make a copy of the TypeLoc data here, so that we can
1522 // return a new TypeSourceInfo. Inefficient!
1523 TypeLocBuilder TLB;
1524 TLB.pushFullCopy(TL);
1525 return TLB.getTypeSourceInfo(Context, TL.getType());
1526 }
1527
1528 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1529 TypeLocBuilder TLB;
1530 TLB.reserve(TL.getFullDataSize());
1531 QualType Result = Instantiator.TransformType(TLB, TL);
1532 if (Result.isNull())
1533 return 0;
1534
1535 return TLB.getTypeSourceInfo(Context, Result);
1536}
1537
John McCallcd7ba1c2009-10-21 00:58:09 +00001538/// Deprecated form of the above.
Mike Stump1eb44332009-09-09 15:08:12 +00001539QualType Sema::SubstType(QualType T,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001540 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallce3ff2b2009-08-25 22:02:44 +00001541 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregordf667e72009-03-10 20:44:00 +00001542 assert(!ActiveTemplateInstantiations.empty() &&
1543 "Cannot perform an instantiation without some context on the "
1544 "instantiation stack");
1545
Douglas Gregor836adf62010-05-24 17:22:01 +00001546 // If T is not a dependent type or a variably-modified type, there
1547 // is nothing to do.
Douglas Gregor561f8122011-07-01 01:22:09 +00001548 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregor99ebf652009-02-27 19:31:52 +00001549 return T;
1550
Douglas Gregor577f75a2009-08-04 16:50:30 +00001551 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1552 return Instantiator.TransformType(T);
Douglas Gregor99ebf652009-02-27 19:31:52 +00001553}
Douglas Gregor2943aed2009-03-03 04:44:36 +00001554
John McCall6cd3b9f2010-04-09 17:38:44 +00001555static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor561f8122011-07-01 01:22:09 +00001556 if (T->getType()->isInstantiationDependentType() ||
1557 T->getType()->isVariablyModifiedType())
John McCall6cd3b9f2010-04-09 17:38:44 +00001558 return true;
1559
Abramo Bagnara723df242010-12-14 22:11:44 +00001560 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie39e6ab42013-02-18 22:06:02 +00001561 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCall6cd3b9f2010-04-09 17:38:44 +00001562 return false;
1563
David Blaikie39e6ab42013-02-18 22:06:02 +00001564 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
John McCall6cd3b9f2010-04-09 17:38:44 +00001565 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1566 ParmVarDecl *P = FP.getArg(I);
1567
Douglas Gregorc056c172011-05-09 20:45:16 +00001568 // The parameter's type as written might be dependent even if the
1569 // decayed type was not dependent.
1570 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor561f8122011-07-01 01:22:09 +00001571 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregorc056c172011-05-09 20:45:16 +00001572 return true;
1573
John McCall6cd3b9f2010-04-09 17:38:44 +00001574 // TODO: currently we always rebuild expressions. When we
1575 // properly get lazier about this, we should use the same
1576 // logic to avoid rebuilding prototypes here.
Douglas Gregor7b1cf302011-01-05 21:14:17 +00001577 if (P->hasDefaultArg())
John McCall6cd3b9f2010-04-09 17:38:44 +00001578 return true;
1579 }
1580
1581 return false;
1582}
1583
1584/// A form of SubstType intended specifically for instantiating the
1585/// type of a FunctionDecl. Its purpose is solely to force the
1586/// instantiation of default-argument expressions.
1587TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1588 const MultiLevelTemplateArgumentList &Args,
1589 SourceLocation Loc,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001590 DeclarationName Entity,
1591 CXXRecordDecl *ThisContext,
1592 unsigned ThisTypeQuals) {
John McCall6cd3b9f2010-04-09 17:38:44 +00001593 assert(!ActiveTemplateInstantiations.empty() &&
1594 "Cannot perform an instantiation without some context on the "
1595 "instantiation stack");
1596
1597 if (!NeedsInstantiationAsFunctionType(T))
1598 return T;
1599
1600 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1601
1602 TypeLocBuilder TLB;
1603
1604 TypeLoc TL = T->getTypeLoc();
1605 TLB.reserve(TL.getFullDataSize());
1606
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001607 QualType Result;
David Blaikie39e6ab42013-02-18 22:06:02 +00001608
1609 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1610 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregorcefc3af2012-04-16 07:05:22 +00001611 ThisTypeQuals);
1612 } else {
1613 Result = Instantiator.TransformType(TLB, TL);
1614 }
John McCall6cd3b9f2010-04-09 17:38:44 +00001615 if (Result.isNull())
1616 return 0;
1617
1618 return TLB.getTypeSourceInfo(Context, Result);
1619}
1620
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001621ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001622 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCallfb44de92011-05-01 22:35:37 +00001623 int indexAdjustment,
David Blaikiedc84cd52013-02-20 22:23:23 +00001624 Optional<unsigned> NumExpansions,
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001625 bool ExpectParameterPack) {
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001626 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor603cfb42011-01-05 23:12:31 +00001627 TypeSourceInfo *NewDI = 0;
1628
Douglas Gregor603cfb42011-01-05 23:12:31 +00001629 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie39e6ab42013-02-18 22:06:02 +00001630 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1631
Douglas Gregor603cfb42011-01-05 23:12:31 +00001632 // We have a function parameter pack. Substitute into the pattern of the
1633 // expansion.
1634 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1635 OldParm->getLocation(), OldParm->getDeclName());
1636 if (!NewDI)
1637 return 0;
1638
1639 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1640 // We still have unexpanded parameter packs, which means that
1641 // our function parameter is still a function parameter pack.
1642 // Therefore, make its type a pack expansion type.
Douglas Gregorcded4f62011-01-14 17:04:44 +00001643 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor6a24bfd2011-01-14 22:40:04 +00001644 NumExpansions);
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001645 } else if (ExpectParameterPack) {
1646 // We expected to get a parameter pack but didn't (because the type
1647 // itself is not a pack expansion type), so complain. This can occur when
1648 // the substitution goes through an alias template that "loses" the
1649 // pack expansion.
1650 Diag(OldParm->getLocation(),
1651 diag::err_function_parameter_pack_without_parameter_packs)
1652 << NewDI->getType();
1653 return 0;
1654 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001655 } else {
1656 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1657 OldParm->getDeclName());
1658 }
1659
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001660 if (!NewDI)
1661 return 0;
1662
1663 if (NewDI->getType()->isVoidType()) {
1664 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1665 return 0;
1666 }
1667
1668 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001669 OldParm->getInnerLocStart(),
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001670 OldParm->getLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00001671 OldParm->getIdentifier(),
1672 NewDI->getType(), NewDI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001673 OldParm->getStorageClass());
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001674 if (!NewParm)
1675 return 0;
Douglas Gregor4469e8a2010-05-19 17:02:24 +00001676
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001677 // Mark the (new) default argument as uninstantiated (if any).
1678 if (OldParm->hasUninstantiatedDefaultArg()) {
1679 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1680 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor8cfb7a32010-10-12 18:23:32 +00001681 } else if (OldParm->hasUnparsedDefaultArg()) {
1682 NewParm->setUnparsedDefaultArg();
1683 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie57296722012-05-01 06:05:57 +00001684 } else if (Expr *Arg = OldParm->getDefaultArg())
1685 // FIXME: if we non-lazily instantiated non-dependent default args for
1686 // non-dependent parameter types we could remove a bunch of duplicate
1687 // conversion warnings for such arguments.
1688 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001689
1690 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregord1bb4ae2012-01-25 16:15:54 +00001691
Douglas Gregor12c9c002011-01-07 16:43:16 +00001692 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smithc0536c82012-01-25 02:14:59 +00001693 // Add the new parameter to the instantiated parameter pack.
Douglas Gregor12c9c002011-01-07 16:43:16 +00001694 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1695 } else {
1696 // Introduce an Old -> New mapping
Douglas Gregor603cfb42011-01-05 23:12:31 +00001697 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregor12c9c002011-01-07 16:43:16 +00001698 }
Douglas Gregor603cfb42011-01-05 23:12:31 +00001699
Argyrios Kyrtzidise3041be2010-07-19 10:14:41 +00001700 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1701 // can be anything, is this right ?
Fariborz Jahanian55a17c02010-07-13 21:05:02 +00001702 NewParm->setDeclContext(CurContext);
John McCallfb44de92011-05-01 22:35:37 +00001703
1704 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1705 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rose09189892013-03-08 22:25:36 +00001706
1707 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1708
Douglas Gregorcb27b0f2010-04-12 07:48:19 +00001709 return NewParm;
1710}
1711
Douglas Gregora009b592011-01-07 00:20:55 +00001712/// \brief Substitute the given template arguments into the given set of
1713/// parameters, producing the set of parameter types that would be generated
1714/// from such a substitution.
1715bool Sema::SubstParmTypes(SourceLocation Loc,
1716 ParmVarDecl **Params, unsigned NumParams,
1717 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001718 SmallVectorImpl<QualType> &ParamTypes,
1719 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregora009b592011-01-07 00:20:55 +00001720 assert(!ActiveTemplateInstantiations.empty() &&
1721 "Cannot perform an instantiation without some context on the "
1722 "instantiation stack");
1723
1724 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1725 DeclarationName());
1726 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregor12c9c002011-01-07 16:43:16 +00001727 ParamTypes, OutParams);
Douglas Gregora009b592011-01-07 00:20:55 +00001728}
1729
John McCallce3ff2b2009-08-25 22:02:44 +00001730/// \brief Perform substitution on the base class specifiers of the
1731/// given class template specialization.
Douglas Gregor2943aed2009-03-03 04:44:36 +00001732///
1733/// Produces a diagnostic and returns true on error, returns false and
1734/// attaches the instantiated base classes to the class template
1735/// specialization if successful.
Mike Stump1eb44332009-09-09 15:08:12 +00001736bool
John McCallce3ff2b2009-08-25 22:02:44 +00001737Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1738 CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001739 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001740 bool Invalid = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00001741 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump1eb44332009-09-09 15:08:12 +00001742 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregord475b8d2009-03-25 21:17:03 +00001743 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor27b152f2009-03-10 18:52:44 +00001744 Base != BaseEnd; ++Base) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001745 if (!Base->getType()->isDependentType()) {
Matt Beaumont-Gay538fccb2013-06-21 18:58:32 +00001746 if (const CXXRecordDecl *RD = Base->getType()->getAsCXXRecordDecl()) {
1747 if (RD->isInvalidDecl())
1748 Instantiation->setInvalidDecl();
1749 }
Fariborz Jahanian71c6e712009-07-22 17:41:53 +00001750 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor2943aed2009-03-03 04:44:36 +00001751 continue;
1752 }
1753
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001754 SourceLocation EllipsisLoc;
Douglas Gregor406f98f2011-03-02 02:04:06 +00001755 TypeSourceInfo *BaseTypeLoc;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001756 if (Base->isPackExpansion()) {
1757 // This is a pack expansion. See whether we should expand it now, or
1758 // wait until later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001759 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001760 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1761 Unexpanded);
1762 bool ShouldExpand = false;
Douglas Gregord3731192011-01-10 07:32:04 +00001763 bool RetainExpansion = false;
David Blaikiedc84cd52013-02-20 22:23:23 +00001764 Optional<unsigned> NumExpansions;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001765 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1766 Base->getSourceRange(),
David Blaikiea71f9d02011-09-22 02:34:54 +00001767 Unexpanded,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001768 TemplateArgs, ShouldExpand,
Douglas Gregord3731192011-01-10 07:32:04 +00001769 RetainExpansion,
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001770 NumExpansions)) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001771 Invalid = true;
Douglas Gregor3fb9e4b2011-01-04 00:32:56 +00001772 continue;
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001773 }
1774
1775 // If we should expand this pack expansion now, do so.
1776 if (ShouldExpand) {
Douglas Gregorcded4f62011-01-14 17:04:44 +00001777 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001778 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1779
1780 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1781 TemplateArgs,
1782 Base->getSourceRange().getBegin(),
1783 DeclarationName());
1784 if (!BaseTypeLoc) {
1785 Invalid = true;
1786 continue;
1787 }
1788
1789 if (CXXBaseSpecifier *InstantiatedBase
1790 = CheckBaseSpecifier(Instantiation,
1791 Base->getSourceRange(),
1792 Base->isVirtual(),
1793 Base->getAccessSpecifierAsWritten(),
1794 BaseTypeLoc,
1795 SourceLocation()))
1796 InstantiatedBases.push_back(InstantiatedBase);
1797 else
1798 Invalid = true;
1799 }
1800
1801 continue;
1802 }
1803
1804 // The resulting base specifier will (still) be a pack expansion.
1805 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregor406f98f2011-03-02 02:04:06 +00001806 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1807 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1808 TemplateArgs,
1809 Base->getSourceRange().getBegin(),
1810 DeclarationName());
1811 } else {
1812 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1813 TemplateArgs,
1814 Base->getSourceRange().getBegin(),
1815 DeclarationName());
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001816 }
1817
Nick Lewycky56062202010-07-26 16:56:01 +00001818 if (!BaseTypeLoc) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00001819 Invalid = true;
1820 continue;
1821 }
1822
1823 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregord475b8d2009-03-25 21:17:03 +00001824 = CheckBaseSpecifier(Instantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00001825 Base->getSourceRange(),
1826 Base->isVirtual(),
1827 Base->getAccessSpecifierAsWritten(),
Douglas Gregorf90b27a2011-01-03 22:36:02 +00001828 BaseTypeLoc,
1829 EllipsisLoc))
Douglas Gregor2943aed2009-03-03 04:44:36 +00001830 InstantiatedBases.push_back(InstantiatedBase);
1831 else
1832 Invalid = true;
1833 }
1834
Douglas Gregor27b152f2009-03-10 18:52:44 +00001835 if (!Invalid &&
Jay Foadbeaaccd2009-05-21 09:52:38 +00001836 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor2943aed2009-03-03 04:44:36 +00001837 InstantiatedBases.size()))
1838 Invalid = true;
1839
1840 return Invalid;
1841}
1842
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001843// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramer5bbc3852012-02-06 11:13:08 +00001844namespace clang {
1845 namespace sema {
1846 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1847 const MultiLevelTemplateArgumentList &TemplateArgs);
1848 }
1849}
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001850
Richard Smithf1c66b42012-03-14 23:13:10 +00001851/// Determine whether we would be unable to instantiate this template (because
1852/// it either has no definition, or is in the process of being instantiated).
1853static bool DiagnoseUninstantiableTemplate(Sema &S,
1854 SourceLocation PointOfInstantiation,
1855 TagDecl *Instantiation,
1856 bool InstantiatedFromMember,
1857 TagDecl *Pattern,
1858 TagDecl *PatternDef,
1859 TemplateSpecializationKind TSK,
1860 bool Complain = true) {
1861 if (PatternDef && !PatternDef->isBeingDefined())
1862 return false;
1863
1864 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1865 // Say nothing
1866 } else if (PatternDef) {
1867 assert(PatternDef->isBeingDefined());
1868 S.Diag(PointOfInstantiation,
1869 diag::err_template_instantiate_within_definition)
1870 << (TSK != TSK_ImplicitInstantiation)
1871 << S.Context.getTypeDeclType(Instantiation);
1872 // Not much point in noting the template declaration here, since
1873 // we're lexically inside it.
1874 Instantiation->setInvalidDecl();
1875 } else if (InstantiatedFromMember) {
1876 S.Diag(PointOfInstantiation,
1877 diag::err_implicit_instantiate_member_undefined)
1878 << S.Context.getTypeDeclType(Instantiation);
1879 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1880 } else {
1881 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1882 << (TSK != TSK_ImplicitInstantiation)
1883 << S.Context.getTypeDeclType(Instantiation);
1884 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1885 }
1886
1887 // In general, Instantiation isn't marked invalid to get more than one
1888 // error for multiple undefined instantiations. But the code that does
1889 // explicit declaration -> explicit definition conversion can't handle
1890 // invalid declarations, so mark as invalid in that case.
1891 if (TSK == TSK_ExplicitInstantiationDeclaration)
1892 Instantiation->setInvalidDecl();
1893 return true;
1894}
1895
Douglas Gregord475b8d2009-03-25 21:17:03 +00001896/// \brief Instantiate the definition of a class from a given pattern.
1897///
1898/// \param PointOfInstantiation The point of instantiation within the
1899/// source code.
1900///
1901/// \param Instantiation is the declaration whose definition is being
1902/// instantiated. This will be either a class template specialization
1903/// or a member class of a class template specialization.
1904///
1905/// \param Pattern is the pattern from which the instantiation
1906/// occurs. This will be either the declaration of a class template or
1907/// the declaration of a member class of a class template.
1908///
1909/// \param TemplateArgs The template arguments to be substituted into
1910/// the pattern.
1911///
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001912/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor5842ba92009-08-24 15:23:48 +00001913///
1914/// \param Complain whether to complain if the class cannot be instantiated due
1915/// to the lack of a definition.
1916///
Douglas Gregord475b8d2009-03-25 21:17:03 +00001917/// \returns true if an error occurred, false otherwise.
1918bool
1919Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1920 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregord6350ae2009-08-28 20:31:08 +00001921 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00001922 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00001923 bool Complain) {
Mike Stump1eb44332009-09-09 15:08:12 +00001924 CXXRecordDecl *PatternDef
Douglas Gregor952b0172010-02-11 01:04:33 +00001925 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smithf1c66b42012-03-14 23:13:10 +00001926 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1927 Instantiation->getInstantiatedFromMemberClass(),
1928 Pattern, PatternDef, TSK, Complain))
Douglas Gregord475b8d2009-03-25 21:17:03 +00001929 return true;
Douglas Gregord475b8d2009-03-25 21:17:03 +00001930 Pattern = PatternDef;
1931
Douglas Gregor454885e2009-10-15 15:54:05 +00001932 // \brief Record the point of instantiation.
1933 if (MemberSpecializationInfo *MSInfo
1934 = Instantiation->getMemberSpecializationInfo()) {
1935 MSInfo->setTemplateSpecializationKind(TSK);
1936 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001937 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weberc7feca02011-12-20 20:32:49 +00001938 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregor972e6ce2009-10-27 06:26:26 +00001939 Spec->setTemplateSpecializationKind(TSK);
1940 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregor454885e2009-10-15 15:54:05 +00001941 }
1942
Douglas Gregord048bb72009-03-25 21:23:52 +00001943 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001944 if (Inst)
1945 return true;
1946
1947 // Enter the scope of this instantiation. We don't use
1948 // PushDeclContext because we don't have a scope.
John McCallf5813822010-04-29 00:35:03 +00001949 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor9679caf2010-05-12 17:27:19 +00001950 EnterExpressionEvaluationContext EvalContext(*this,
John McCallf312b1e2010-08-26 23:41:50 +00001951 Sema::PotentiallyEvaluated);
Douglas Gregord475b8d2009-03-25 21:17:03 +00001952
Douglas Gregor05030bb2010-03-24 01:33:17 +00001953 // If this is an instantiation of a local class, merge this local
1954 // instantiation scope with the enclosing scope. Otherwise, every
1955 // instantiation of a class has its own local instantiation scope.
1956 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall2a7fb272010-08-25 05:32:35 +00001957 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor05030bb2010-03-24 01:33:17 +00001958
John McCall1d8d1cc2010-08-01 02:01:53 +00001959 // Pull attributes from the pattern onto the instantiation.
1960 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1961
Douglas Gregord475b8d2009-03-25 21:17:03 +00001962 // Start the definition of this instantiation.
1963 Instantiation->startDefinition();
Douglas Gregor13c85772010-05-06 00:28:52 +00001964
1965 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregord475b8d2009-03-25 21:17:03 +00001966
John McCallce3ff2b2009-08-25 22:02:44 +00001967 // Do substitution on the base class specifiers.
1968 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8a50fe02012-07-02 21:00:41 +00001969 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00001970
Douglas Gregord65587f2010-11-10 19:44:59 +00001971 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001972 SmallVector<Decl*, 4> Fields;
1973 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith7a614d82011-06-11 17:19:42 +00001974 FieldsWithMemberInitializers;
DeLesley Hutchins23323e02012-01-20 22:50:54 +00001975 // Delay instantiation of late parsed attributes.
1976 LateInstantiatedAttrVec LateAttrs;
1977 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1978
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001979 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001980 MemberEnd = Pattern->decls_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001981 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidisbb5e4312010-11-04 03:18:57 +00001982 // Don't instantiate members not belonging in this semantic context.
1983 // e.g. for:
1984 // @code
1985 // template <int i> class A {
1986 // class B *g;
1987 // };
1988 // @endcode
1989 // 'class B' has the template as lexical context but semantically it is
1990 // introduced in namespace scope.
1991 if ((*Member)->getDeclContext() != Pattern)
1992 continue;
1993
Douglas Gregord65587f2010-11-10 19:44:59 +00001994 if ((*Member)->isInvalidDecl()) {
Richard Smithe3f470a2012-07-11 22:37:56 +00001995 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00001996 continue;
1997 }
1998
1999 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregord475b8d2009-03-25 21:17:03 +00002000 if (NewMember) {
Richard Smith7a614d82011-06-11 17:19:42 +00002001 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCalld226f652010-08-21 09:40:31 +00002002 Fields.push_back(Field);
Richard Smith7a614d82011-06-11 17:19:42 +00002003 FieldDecl *OldField = cast<FieldDecl>(*Member);
2004 if (OldField->getInClassInitializer())
2005 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2006 Field));
Richard Smith1af83c42012-03-23 03:33:32 +00002007 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2008 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2009 // specialization causes the implicit instantiation of the definitions
2010 // of unscoped member enumerations.
2011 // Record a point of instantiation for this implicit instantiation.
Richard Smith3343fad2012-03-23 23:09:08 +00002012 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2013 Enum->isCompleteDefinition()) {
Richard Smith1af83c42012-03-23 03:33:32 +00002014 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2015 assert(MSInfo && "no spec info for member enum specialization");
2016 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2017 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2018 }
Richard Smithe3f470a2012-07-11 22:37:56 +00002019 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2020 if (SA->isFailed()) {
2021 // A static_assert failed. Bail out; instantiating this
2022 // class is probably not meaningful.
2023 Instantiation->setInvalidDecl();
2024 break;
2025 }
Richard Smith1af83c42012-03-23 03:33:32 +00002026 }
2027
2028 if (NewMember->isInvalidDecl())
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002029 Instantiation->setInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002030 } else {
2031 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002032 // instantiations was a semantic disaster, and we'll want to mark the
2033 // declaration invalid.
2034 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregord475b8d2009-03-25 21:17:03 +00002035 }
2036 }
2037
2038 // Finish checking fields.
David Blaikie77b6de02011-09-22 02:58:26 +00002039 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2040 SourceLocation(), SourceLocation(), 0);
Douglas Gregor23c94db2010-07-02 17:43:08 +00002041 CheckCompletedCXXClass(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002042
2043 // Attach any in-class member initializers now the class is complete.
Richard Smithd5be2b52012-12-08 02:13:02 +00002044 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer268efba2012-05-17 12:01:52 +00002045 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002046 // C++11 [expr.prim.general]p4:
2047 // Otherwise, if a member-declarator declares a non-static data member
2048 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2049 // to X" within the optional brace-or-equal-initializer. It shall not
2050 // appear elsewhere in the member-declarator.
2051 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2052
2053 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2054 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2055 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2056 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith7a614d82011-06-11 17:19:42 +00002057
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002058 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2059 /*CXXDirectInit=*/false);
2060 if (NewInit.isInvalid())
2061 NewField->setInvalidDecl();
2062 else {
2063 Expr *Init = NewInit.take();
2064 assert(Init && "no-argument initializer in class");
2065 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
Richard Smithca523302012-06-10 03:12:00 +00002066 ActOnCXXInClassMemberInitializer(NewField, Init->getLocStart(), Init);
Douglas Gregorcefc3af2012-04-16 07:05:22 +00002067 }
Richard Smith0ff6f8f2011-07-20 00:12:52 +00002068 }
Richard Smith7a614d82011-06-11 17:19:42 +00002069 }
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002070 // Instantiate late parsed attributes, and attach them to their decls.
2071 // See Sema::InstantiateAttrs
2072 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2073 E = LateAttrs.end(); I != E; ++I) {
2074 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2075 CurrentInstantiationScope = I->Scope;
Richard Smithcafeb942013-06-07 02:33:37 +00002076
2077 // Allow 'this' within late-parsed attributes.
2078 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2079 CXXRecordDecl *ThisContext =
2080 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2081 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2082 ND && ND->isCXXInstanceMember());
2083
DeLesley Hutchins23323e02012-01-20 22:50:54 +00002084 Attr *NewAttr =
2085 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2086 I->NewDecl->addAttr(NewAttr);
2087 LocalInstantiationScope::deleteScopes(I->Scope,
2088 Instantiator.getStartingScope());
2089 }
2090 Instantiator.disableLateAttributeInstantiation();
2091 LateAttrs.clear();
2092
Richard Smithb9d0b762012-07-27 04:22:15 +00002093 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith7a614d82011-06-11 17:19:42 +00002094
Abramo Bagnarae9946242011-11-18 08:08:52 +00002095 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidis734bd6e2012-02-11 01:59:57 +00002096 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002097 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnara09d82122011-10-03 20:34:03 +00002098 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnarae9946242011-11-18 08:08:52 +00002099 }
Abramo Bagnara09d82122011-10-03 20:34:03 +00002100
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002101 if (!Instantiation->isInvalidDecl()) {
John McCall1f2e1a92012-08-10 03:15:35 +00002102 // Perform any dependent diagnostics from the pattern.
2103 PerformDependentDiagnostics(Pattern, TemplateArgs);
2104
Douglas Gregord65587f2010-11-10 19:44:59 +00002105 // Instantiate any out-of-line class template partial
2106 // specializations now.
2107 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2108 P = Instantiator.delayed_partial_spec_begin(),
2109 PEnd = Instantiator.delayed_partial_spec_end();
2110 P != PEnd; ++P) {
2111 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2112 P->first,
2113 P->second)) {
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002114 Instantiation->setInvalidDecl();
Douglas Gregord65587f2010-11-10 19:44:59 +00002115 break;
2116 }
2117 }
2118 }
2119
Douglas Gregord475b8d2009-03-25 21:17:03 +00002120 // Exit the scope of this instantiation.
John McCallf5813822010-04-29 00:35:03 +00002121 SavedContext.pop();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002122
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002123 if (!Instantiation->isInvalidDecl()) {
Douglas Gregoraba43bb2009-05-26 20:50:29 +00002124 Consumer.HandleTagDeclDefinition(Instantiation);
2125
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002126 // Always emit the vtable for an explicit instantiation definition
2127 // of a polymorphic class template specialization.
2128 if (TSK == TSK_ExplicitInstantiationDefinition)
2129 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2130 }
2131
Douglas Gregor8a50fe02012-07-02 21:00:41 +00002132 return Instantiation->isInvalidDecl();
Douglas Gregord475b8d2009-03-25 21:17:03 +00002133}
2134
Richard Smithf1c66b42012-03-14 23:13:10 +00002135/// \brief Instantiate the definition of an enum from a given pattern.
2136///
2137/// \param PointOfInstantiation The point of instantiation within the
2138/// source code.
2139/// \param Instantiation is the declaration whose definition is being
2140/// instantiated. This will be a member enumeration of a class
2141/// temploid specialization, or a local enumeration within a
2142/// function temploid specialization.
2143/// \param Pattern The templated declaration from which the instantiation
2144/// occurs.
2145/// \param TemplateArgs The template arguments to be substituted into
2146/// the pattern.
2147/// \param TSK The kind of implicit or explicit instantiation to perform.
2148///
2149/// \return \c true if an error occurred, \c false otherwise.
2150bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2151 EnumDecl *Instantiation, EnumDecl *Pattern,
2152 const MultiLevelTemplateArgumentList &TemplateArgs,
2153 TemplateSpecializationKind TSK) {
2154 EnumDecl *PatternDef = Pattern->getDefinition();
2155 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2156 Instantiation->getInstantiatedFromMemberEnum(),
2157 Pattern, PatternDef, TSK,/*Complain*/true))
2158 return true;
2159 Pattern = PatternDef;
2160
2161 // Record the point of instantiation.
2162 if (MemberSpecializationInfo *MSInfo
2163 = Instantiation->getMemberSpecializationInfo()) {
2164 MSInfo->setTemplateSpecializationKind(TSK);
2165 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2166 }
2167
2168 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2169 if (Inst)
2170 return true;
2171
2172 // Enter the scope of this instantiation. We don't use
2173 // PushDeclContext because we don't have a scope.
2174 ContextRAII SavedContext(*this, Instantiation);
2175 EnterExpressionEvaluationContext EvalContext(*this,
2176 Sema::PotentiallyEvaluated);
2177
2178 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2179
2180 // Pull attributes from the pattern onto the instantiation.
2181 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2182
2183 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2184 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2185
2186 // Exit the scope of this instantiation.
2187 SavedContext.pop();
2188
2189 return Instantiation->isInvalidDecl();
2190}
2191
Douglas Gregor9b623632010-10-12 23:32:35 +00002192namespace {
2193 /// \brief A partial specialization whose template arguments have matched
2194 /// a given template-id.
2195 struct PartialSpecMatchResult {
2196 ClassTemplatePartialSpecializationDecl *Partial;
2197 TemplateArgumentList *Args;
Douglas Gregor9b623632010-10-12 23:32:35 +00002198 };
2199}
2200
Mike Stump1eb44332009-09-09 15:08:12 +00002201bool
Douglas Gregor2943aed2009-03-03 04:44:36 +00002202Sema::InstantiateClassTemplateSpecialization(
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002203 SourceLocation PointOfInstantiation,
Douglas Gregor2943aed2009-03-03 04:44:36 +00002204 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002205 TemplateSpecializationKind TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002206 bool Complain) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002207 // Perform the actual instantiation on the canonical declaration.
2208 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis97fbaa22009-07-18 00:34:25 +00002209 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor2943aed2009-03-03 04:44:36 +00002210
Douglas Gregor52604ab2009-09-11 21:19:12 +00002211 // Check whether we have already instantiated or specialized this class
2212 // template specialization.
2213 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2214 if (ClassTemplateSpec->getSpecializationKind() ==
2215 TSK_ExplicitInstantiationDeclaration &&
2216 TSK == TSK_ExplicitInstantiationDefinition) {
2217 // An explicit instantiation definition follows an explicit instantiation
2218 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2219 // explicit instantiation.
2220 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002221
2222 // If this is an explicit instantiation definition, mark the
2223 // vtable as used.
Nico Weberc7feca02011-12-20 20:32:49 +00002224 if (TSK == TSK_ExplicitInstantiationDefinition &&
2225 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor6fb745b2010-05-13 16:44:06 +00002226 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2227
Douglas Gregor52604ab2009-09-11 21:19:12 +00002228 return false;
2229 }
2230
2231 // We can only instantiate something that hasn't already been
2232 // instantiated or specialized. Fail without any diagnostics: our
2233 // caller will provide an error message.
Douglas Gregor2943aed2009-03-03 04:44:36 +00002234 return true;
Douglas Gregor52604ab2009-09-11 21:19:12 +00002235 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002236
Douglas Gregor9eea08b2009-09-15 16:51:42 +00002237 if (ClassTemplateSpec->isInvalidDecl())
2238 return true;
2239
Douglas Gregor2943aed2009-03-03 04:44:36 +00002240 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregord6350ae2009-08-28 20:31:08 +00002241 CXXRecordDecl *Pattern = 0;
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002242
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002243 // C++ [temp.class.spec.match]p1:
2244 // When a class template is used in a context that requires an
2245 // instantiation of the class, it is necessary to determine
2246 // whether the instantiation is to be generated using the primary
2247 // template or one of the partial specializations. This is done by
2248 // matching the template arguments of the class template
2249 // specialization with the template argument lists of the partial
2250 // specializations.
Douglas Gregor9b623632010-10-12 23:32:35 +00002251 typedef PartialSpecMatchResult MatchResult;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002252 SmallVector<MatchResult, 4> Matched;
2253 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002254 Template->getPartialSpecializations(PartialSpecs);
2255 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2256 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo8c5d4072013-07-19 22:53:23 +00002257 TemplateDeductionInfo Info(PointOfInstantiation);
Douglas Gregorf67875d2009-06-12 18:26:56 +00002258 if (TemplateDeductionResult Result
Douglas Gregordc60c1e2010-04-30 05:56:50 +00002259 = DeduceTemplateArguments(Partial,
Douglas Gregorf67875d2009-06-12 18:26:56 +00002260 ClassTemplateSpec->getTemplateArgs(),
2261 Info)) {
Larisse Voufo8c5d4072013-07-19 22:53:23 +00002262 // FIXME: Store the failed-deduction information for use in
2263 // diagnostics, later.
Douglas Gregorf67875d2009-06-12 18:26:56 +00002264 (void)Result;
2265 } else {
Douglas Gregor9b623632010-10-12 23:32:35 +00002266 Matched.push_back(PartialSpecMatchResult());
2267 Matched.back().Partial = Partial;
2268 Matched.back().Args = Info.take();
Douglas Gregorf67875d2009-06-12 18:26:56 +00002269 }
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002270 }
2271
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002272 // If we're dealing with a member template where the template parameters
2273 // have been instantiated, this provides the original template parameters
2274 // from which the member template's parameters were instantiated.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002275 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor6952f1e2011-01-19 20:10:05 +00002276
Douglas Gregored9c0f92009-10-29 00:04:11 +00002277 if (Matched.size() >= 1) {
Craig Topper09d19ef2013-07-04 03:08:24 +00002278 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002279 if (Matched.size() == 1) {
2280 // -- If exactly one matching specialization is found, the
2281 // instantiation is generated from that specialization.
2282 // We don't need to do anything for this.
2283 } else {
2284 // -- If more than one matching specialization is found, the
2285 // partial order rules (14.5.4.2) are used to determine
2286 // whether one of the specializations is more specialized
2287 // than the others. If none of the specializations is more
2288 // specialized than all of the other matching
2289 // specializations, then the use of the class template is
2290 // ambiguous and the program is ill-formed.
Craig Topper09d19ef2013-07-04 03:08:24 +00002291 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2292 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002293 P != PEnd; ++P) {
Douglas Gregor9b623632010-10-12 23:32:35 +00002294 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002295 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002296 == P->Partial)
Douglas Gregored9c0f92009-10-29 00:04:11 +00002297 Best = P;
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002298 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002299
Douglas Gregored9c0f92009-10-29 00:04:11 +00002300 // Determine if the best partial specialization is more specialized than
2301 // the others.
2302 bool Ambiguous = false;
Craig Topper09d19ef2013-07-04 03:08:24 +00002303 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2304 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002305 P != PEnd; ++P) {
2306 if (P != Best &&
Douglas Gregor9b623632010-10-12 23:32:35 +00002307 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCall5769d612010-02-08 23:07:23 +00002308 PointOfInstantiation)
Douglas Gregor9b623632010-10-12 23:32:35 +00002309 != Best->Partial) {
Douglas Gregored9c0f92009-10-29 00:04:11 +00002310 Ambiguous = true;
2311 break;
2312 }
2313 }
2314
2315 if (Ambiguous) {
2316 // Partial ordering did not produce a clear winner. Complain.
2317 ClassTemplateSpec->setInvalidDecl();
2318 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2319 << ClassTemplateSpec;
2320
2321 // Print the matching partial specializations.
Craig Topper09d19ef2013-07-04 03:08:24 +00002322 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2323 PEnd = Matched.end();
Douglas Gregored9c0f92009-10-29 00:04:11 +00002324 P != PEnd; ++P)
Douglas Gregor9b623632010-10-12 23:32:35 +00002325 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2326 << getTemplateArgumentBindingsText(
2327 P->Partial->getTemplateParameters(),
2328 *P->Args);
Douglas Gregord6350ae2009-08-28 20:31:08 +00002329
Douglas Gregored9c0f92009-10-29 00:04:11 +00002330 return true;
2331 }
Douglas Gregorbf4ea562009-09-15 16:23:51 +00002332 }
2333
2334 // Instantiate using the best class template partial specialization.
Douglas Gregor9b623632010-10-12 23:32:35 +00002335 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregored9c0f92009-10-29 00:04:11 +00002336 while (OrigPartialSpec->getInstantiatedFromMember()) {
2337 // If we've found an explicit specialization of this class template,
2338 // stop here and use that as the pattern.
2339 if (OrigPartialSpec->isMemberSpecialization())
2340 break;
2341
2342 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2343 }
2344
2345 Pattern = OrigPartialSpec;
Douglas Gregor9b623632010-10-12 23:32:35 +00002346 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregorc1efb3f2009-06-12 22:31:52 +00002347 } else {
2348 // -- If no matches are found, the instantiation is generated
2349 // from the primary template.
Douglas Gregord6350ae2009-08-28 20:31:08 +00002350 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002351 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2352 // If we've found an explicit specialization of this class template,
2353 // stop here and use that as the pattern.
2354 if (OrigTemplate->isMemberSpecialization())
2355 break;
2356
Douglas Gregord6350ae2009-08-28 20:31:08 +00002357 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorfd056bc2009-10-13 16:30:37 +00002358 }
2359
Douglas Gregord6350ae2009-08-28 20:31:08 +00002360 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregorc8ab2562009-05-31 09:31:02 +00002361 }
Douglas Gregor2943aed2009-03-03 04:44:36 +00002362
Douglas Gregor972e6ce2009-10-27 06:26:26 +00002363 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2364 Pattern,
2365 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002366 TSK,
Douglas Gregor5842ba92009-08-24 15:23:48 +00002367 Complain);
Mike Stump1eb44332009-09-09 15:08:12 +00002368
Douglas Gregor199d9912009-06-05 00:53:49 +00002369 return Result;
Douglas Gregor2943aed2009-03-03 04:44:36 +00002370}
Douglas Gregor5953d8b2009-03-19 17:26:29 +00002371
John McCallce3ff2b2009-08-25 22:02:44 +00002372/// \brief Instantiates the definitions of all of the member
2373/// of the given class, which is an instantiation of a class template
2374/// or a member class of a template.
Douglas Gregora58861f2009-05-13 20:28:22 +00002375void
2376Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002377 CXXRecordDecl *Instantiation,
2378 const MultiLevelTemplateArgumentList &TemplateArgs,
2379 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002380 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2381 DEnd = Instantiation->decls_end();
Douglas Gregora58861f2009-05-13 20:28:22 +00002382 D != DEnd; ++D) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002383 bool SuppressNew = false;
Douglas Gregora58861f2009-05-13 20:28:22 +00002384 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002385 if (FunctionDecl *Pattern
2386 = Function->getInstantiatedFromMemberFunction()) {
2387 MemberSpecializationInfo *MSInfo
2388 = Function->getMemberSpecializationInfo();
2389 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002390 if (MSInfo->getTemplateSpecializationKind()
2391 == TSK_ExplicitSpecialization)
2392 continue;
2393
Douglas Gregor0d035142009-10-27 18:42:08 +00002394 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2395 Function,
2396 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002397 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002398 SuppressNew) ||
2399 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002400 continue;
2401
Sean Hunt10620eb2011-05-06 20:44:56 +00002402 if (Function->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002403 continue;
2404
2405 if (TSK == TSK_ExplicitInstantiationDefinition) {
2406 // C++0x [temp.explicit]p8:
2407 // An explicit instantiation definition that names a class template
2408 // specialization explicitly instantiates the class template
2409 // specialization and is only an explicit instantiation definition
2410 // of members whose definition is visible at the point of
2411 // instantiation.
Sean Hunt10620eb2011-05-06 20:44:56 +00002412 if (!Pattern->isDefined())
Douglas Gregor0d035142009-10-27 18:42:08 +00002413 continue;
2414
2415 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2416
2417 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2418 } else {
2419 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2420 }
Douglas Gregorf6b11852009-10-08 15:14:33 +00002421 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002422 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002423 if (Var->isStaticDataMember()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002424 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2425 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002426 if (MSInfo->getTemplateSpecializationKind()
2427 == TSK_ExplicitSpecialization)
2428 continue;
2429
Douglas Gregor0d035142009-10-27 18:42:08 +00002430 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2431 Var,
2432 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002433 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002434 SuppressNew) ||
2435 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002436 continue;
2437
Douglas Gregor0d035142009-10-27 18:42:08 +00002438 if (TSK == TSK_ExplicitInstantiationDefinition) {
2439 // C++0x [temp.explicit]p8:
2440 // An explicit instantiation definition that names a class template
2441 // specialization explicitly instantiates the class template
2442 // specialization and is only an explicit instantiation definition
2443 // of members whose definition is visible at the point of
2444 // instantiation.
2445 if (!Var->getInstantiatedFromStaticDataMember()
2446 ->getOutOfLineDefinition())
2447 continue;
2448
2449 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor251b4ff2009-10-08 07:24:58 +00002450 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor0d035142009-10-27 18:42:08 +00002451 } else {
2452 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2453 }
2454 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002455 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregora77eaa92010-04-18 18:11:38 +00002456 // Always skip the injected-class-name, along with any
2457 // redeclarations of nested classes, since both would cause us
2458 // to try to instantiate the members of a class twice.
Douglas Gregoref96ee02012-01-14 16:38:05 +00002459 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregor2db32322009-10-07 23:56:10 +00002460 continue;
2461
Douglas Gregor0d035142009-10-27 18:42:08 +00002462 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2463 assert(MSInfo && "No member specialization information?");
Douglas Gregorc42b6522010-04-09 21:02:29 +00002464
2465 if (MSInfo->getTemplateSpecializationKind()
2466 == TSK_ExplicitSpecialization)
2467 continue;
Nico Weberc956b6e2010-09-27 21:02:09 +00002468
Douglas Gregor0d035142009-10-27 18:42:08 +00002469 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2470 Record,
2471 MSInfo->getTemplateSpecializationKind(),
Nico Weberc956b6e2010-09-27 21:02:09 +00002472 MSInfo->getPointOfInstantiation(),
Douglas Gregor0d035142009-10-27 18:42:08 +00002473 SuppressNew) ||
2474 SuppressNew)
Douglas Gregorf6b11852009-10-08 15:14:33 +00002475 continue;
2476
Douglas Gregor0d035142009-10-27 18:42:08 +00002477 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2478 assert(Pattern && "Missing instantiated-from-template information");
2479
Douglas Gregor952b0172010-02-11 01:04:33 +00002480 if (!Record->getDefinition()) {
2481 if (!Pattern->getDefinition()) {
Douglas Gregor0d035142009-10-27 18:42:08 +00002482 // C++0x [temp.explicit]p8:
2483 // An explicit instantiation definition that names a class template
2484 // specialization explicitly instantiates the class template
2485 // specialization and is only an explicit instantiation definition
2486 // of members whose definition is visible at the point of
2487 // instantiation.
2488 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2489 MSInfo->setTemplateSpecializationKind(TSK);
2490 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2491 }
2492
2493 continue;
2494 }
2495
2496 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002497 TemplateArgs,
2498 TSK);
Nico Weberc956b6e2010-09-27 21:02:09 +00002499 } else {
2500 if (TSK == TSK_ExplicitInstantiationDefinition &&
2501 Record->getTemplateSpecializationKind() ==
2502 TSK_ExplicitInstantiationDeclaration) {
2503 Record->setTemplateSpecializationKind(TSK);
2504 MarkVTableUsed(PointOfInstantiation, Record, true);
2505 }
Douglas Gregor0d035142009-10-27 18:42:08 +00002506 }
Douglas Gregore9374d52009-10-08 01:19:17 +00002507
Douglas Gregor952b0172010-02-11 01:04:33 +00002508 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor0d035142009-10-27 18:42:08 +00002509 if (Pattern)
2510 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2511 TSK);
Richard Smithf1c66b42012-03-14 23:13:10 +00002512 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2513 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2514 assert(MSInfo && "No member specialization information?");
2515
2516 if (MSInfo->getTemplateSpecializationKind()
2517 == TSK_ExplicitSpecialization)
2518 continue;
2519
2520 if (CheckSpecializationInstantiationRedecl(
2521 PointOfInstantiation, TSK, Enum,
2522 MSInfo->getTemplateSpecializationKind(),
2523 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2524 SuppressNew)
2525 continue;
2526
2527 if (Enum->getDefinition())
2528 continue;
2529
2530 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2531 assert(Pattern && "Missing instantiated-from-template information");
2532
2533 if (TSK == TSK_ExplicitInstantiationDefinition) {
2534 if (!Pattern->getDefinition())
2535 continue;
2536
2537 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2538 } else {
2539 MSInfo->setTemplateSpecializationKind(TSK);
2540 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2541 }
Douglas Gregora58861f2009-05-13 20:28:22 +00002542 }
2543 }
2544}
2545
2546/// \brief Instantiate the definitions of all of the members of the
2547/// given class template specialization, which was named as part of an
2548/// explicit instantiation.
Mike Stump1eb44332009-09-09 15:08:12 +00002549void
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002550Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregora58861f2009-05-13 20:28:22 +00002551 SourceLocation PointOfInstantiation,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002552 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2553 TemplateSpecializationKind TSK) {
Douglas Gregora58861f2009-05-13 20:28:22 +00002554 // C++0x [temp.explicit]p7:
2555 // An explicit instantiation that names a class template
2556 // specialization is an explicit instantion of the same kind
2557 // (declaration or definition) of each of its members (not
2558 // including members inherited from base classes) that has not
2559 // been previously explicitly specialized in the translation unit
2560 // containing the explicit instantiation, except as described
2561 // below.
2562 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregord0e3daf2009-09-04 22:48:11 +00002563 getTemplateInstantiationArgs(ClassTemplateSpec),
2564 TSK);
Douglas Gregora58861f2009-05-13 20:28:22 +00002565}
2566
John McCall60d7b3a2010-08-24 06:29:42 +00002567StmtResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002568Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor43959a92009-08-20 07:17:43 +00002569 if (!S)
2570 return Owned(S);
2571
2572 TemplateInstantiator Instantiator(*this, TemplateArgs,
2573 SourceLocation(),
2574 DeclarationName());
2575 return Instantiator.TransformStmt(S);
2576}
2577
John McCall60d7b3a2010-08-24 06:29:42 +00002578ExprResult
Douglas Gregord6350ae2009-08-28 20:31:08 +00002579Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorb98b1992009-08-11 05:31:07 +00002580 if (!E)
2581 return Owned(E);
Mike Stump1eb44332009-09-09 15:08:12 +00002582
Douglas Gregorb98b1992009-08-11 05:31:07 +00002583 TemplateInstantiator Instantiator(*this, TemplateArgs,
2584 SourceLocation(),
2585 DeclarationName());
2586 return Instantiator.TransformExpr(E);
2587}
2588
Richard Smithc83c2302012-12-19 01:39:02 +00002589ExprResult Sema::SubstInitializer(Expr *Init,
2590 const MultiLevelTemplateArgumentList &TemplateArgs,
2591 bool CXXDirectInit) {
2592 TemplateInstantiator Instantiator(*this, TemplateArgs,
2593 SourceLocation(),
2594 DeclarationName());
2595 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2596}
2597
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002598bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2599 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner5f9e2722011-07-23 10:55:15 +00002600 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002601 if (NumExprs == 0)
2602 return false;
Richard Smithc83c2302012-12-19 01:39:02 +00002603
Douglas Gregor91fc73e2011-01-07 19:35:17 +00002604 TemplateInstantiator Instantiator(*this, TemplateArgs,
2605 SourceLocation(),
2606 DeclarationName());
2607 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2608}
2609
Douglas Gregorc22b5ff2011-02-25 02:25:35 +00002610NestedNameSpecifierLoc
2611Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2612 const MultiLevelTemplateArgumentList &TemplateArgs) {
2613 if (!NNS)
2614 return NestedNameSpecifierLoc();
2615
2616 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2617 DeclarationName());
2618 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2619}
2620
Abramo Bagnara25777432010-08-11 22:01:17 +00002621/// \brief Do template substitution on declaration name info.
2622DeclarationNameInfo
2623Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2624 const MultiLevelTemplateArgumentList &TemplateArgs) {
2625 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2626 NameInfo.getName());
2627 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2628}
2629
Douglas Gregorde650ae2009-03-31 18:38:02 +00002630TemplateName
Douglas Gregor1d752d72011-03-02 18:46:51 +00002631Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2632 TemplateName Name, SourceLocation Loc,
Douglas Gregord6350ae2009-08-28 20:31:08 +00002633 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregord1067e52009-08-06 06:41:21 +00002634 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2635 DeclarationName());
Douglas Gregor1d752d72011-03-02 18:46:51 +00002636 CXXScopeSpec SS;
2637 SS.Adopt(QualifierLoc);
2638 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregorde650ae2009-03-31 18:38:02 +00002639}
Douglas Gregor91333002009-06-11 00:06:24 +00002640
Douglas Gregore02e2622010-12-22 21:19:48 +00002641bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2642 TemplateArgumentListInfo &Result,
John McCall833ca992009-10-29 08:12:44 +00002643 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor670444e2009-08-04 22:27:00 +00002644 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2645 DeclarationName());
Douglas Gregore02e2622010-12-22 21:19:48 +00002646
2647 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregor91333002009-06-11 00:06:24 +00002648}
Douglas Gregor895162d2010-04-30 18:55:50 +00002649
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002650
2651static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2652 // When storing ParmVarDecls in the local instantiation scope, we always
2653 // want to use the ParmVarDecl from the canonical function declaration,
2654 // since the map is then valid for any redeclaration or definition of that
2655 // function.
2656 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2657 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2658 unsigned i = PV->getFunctionScopeIndex();
2659 return FD->getCanonicalDecl()->getParamDecl(i);
2660 }
2661 }
2662 return D;
2663}
2664
2665
Douglas Gregor12c9c002011-01-07 16:43:16 +00002666llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2667LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002668 D = getCanonicalParmVarDecl(D);
Chris Lattner57ad3782011-02-17 20:34:02 +00002669 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor895162d2010-04-30 18:55:50 +00002670 Current = Current->Outer) {
Chris Lattner57ad3782011-02-17 20:34:02 +00002671
Douglas Gregor895162d2010-04-30 18:55:50 +00002672 // Check if we found something within this scope.
Douglas Gregorebb1c562010-12-21 21:22:51 +00002673 const Decl *CheckD = D;
2674 do {
Douglas Gregor12c9c002011-01-07 16:43:16 +00002675 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregorebb1c562010-12-21 21:22:51 +00002676 if (Found != Current->LocalDecls.end())
Douglas Gregor12c9c002011-01-07 16:43:16 +00002677 return &Found->second;
Douglas Gregorebb1c562010-12-21 21:22:51 +00002678
2679 // If this is a tag declaration, it's possible that we need to look for
2680 // a previous declaration.
2681 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregoref96ee02012-01-14 16:38:05 +00002682 CheckD = Tag->getPreviousDecl();
Douglas Gregorebb1c562010-12-21 21:22:51 +00002683 else
2684 CheckD = 0;
2685 } while (CheckD);
2686
Douglas Gregor895162d2010-04-30 18:55:50 +00002687 // If we aren't combined with our outer scope, we're done.
2688 if (!Current->CombineWithOuterScope)
2689 break;
2690 }
Chris Lattner57ad3782011-02-17 20:34:02 +00002691
Serge Pavlovdc49d522013-07-15 06:14:07 +00002692 // If we're performing a partial substitution during template argument
2693 // deduction, we may not have values for template parameters yet.
2694 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2695 isa<TemplateTemplateParmDecl>(D))
2696 return 0;
2697
Chris Lattner57ad3782011-02-17 20:34:02 +00002698 // If we didn't find the decl, then we either have a sema bug, or we have a
2699 // forward reference to a label declaration. Return null to indicate that
2700 // we have an uninstantiated label.
2701 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor895162d2010-04-30 18:55:50 +00002702 return 0;
2703}
2704
John McCall2a7fb272010-08-25 05:32:35 +00002705void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002706 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002707 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregord3731192011-01-10 07:32:04 +00002708 if (Stored.isNull())
2709 Stored = Inst;
Benjamin Kramer3bbffd52013-04-12 15:22:25 +00002710 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2711 Pack->push_back(Inst);
2712 else
Douglas Gregord3731192011-01-10 07:32:04 +00002713 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor895162d2010-04-30 18:55:50 +00002714}
Douglas Gregor12c9c002011-01-07 16:43:16 +00002715
2716void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2717 Decl *Inst) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002718 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002719 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2720 Pack->push_back(Inst);
2721}
2722
2723void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsd278dbe2012-09-26 17:57:31 +00002724 D = getCanonicalParmVarDecl(D);
Douglas Gregor12c9c002011-01-07 16:43:16 +00002725 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2726 assert(Stored.isNull() && "Already instantiated this local");
2727 DeclArgumentPack *Pack = new DeclArgumentPack;
2728 Stored = Pack;
2729 ArgumentPacks.push_back(Pack);
2730}
2731
Douglas Gregord3731192011-01-10 07:32:04 +00002732void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2733 const TemplateArgument *ExplicitArgs,
2734 unsigned NumExplicitArgs) {
2735 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2736 "Already have a partially-substituted pack");
2737 assert((!PartiallySubstitutedPack
2738 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2739 "Wrong number of arguments in partially-substituted pack");
2740 PartiallySubstitutedPack = Pack;
2741 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2742 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2743}
2744
2745NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2746 const TemplateArgument **ExplicitArgs,
2747 unsigned *NumExplicitArgs) const {
2748 if (ExplicitArgs)
2749 *ExplicitArgs = 0;
2750 if (NumExplicitArgs)
2751 *NumExplicitArgs = 0;
2752
2753 for (const LocalInstantiationScope *Current = this; Current;
2754 Current = Current->Outer) {
2755 if (Current->PartiallySubstitutedPack) {
2756 if (ExplicitArgs)
2757 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2758 if (NumExplicitArgs)
2759 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2760
2761 return Current->PartiallySubstitutedPack;
2762 }
2763
2764 if (!Current->CombineWithOuterScope)
2765 break;
2766 }
2767
2768 return 0;
2769}