blob: 4740145fd5ace624b698783ae39cf84c5d9092e3 [file] [log] [blame]
Douglas Gregorfe1e1102009-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 McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000014#include "TreeTransform.h"
John McCall8b0666c2010-08-20 18:27:03 +000015#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000016#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000017#include "clang/Sema/Lookup.h"
John McCallde6836a2010-08-24 07:21:54 +000018#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000019#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor28ad4b52009-05-26 20:50:29 +000020#include "clang/AST/ASTConsumer.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000021#include "clang/AST/ASTContext.h"
22#include "clang/AST/Expr.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000023#include "clang/AST/DeclTemplate.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000024#include "clang/Basic/LangOptions.h"
25
26using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000027using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000028
Douglas Gregor4ea568f2009-03-10 18:03:33 +000029//===----------------------------------------------------------------------===/
30// Template Instantiation Support
31//===----------------------------------------------------------------------===/
32
Douglas Gregor01afeef2009-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 Gregor36d7c5f2009-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 Gregor8c702532010-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 Gregor1bd7a942010-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 Gregora654dd82009-08-28 17:37:35 +000050MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000051Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000052 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000053 bool RelativeToPrimary,
54 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000055 // Accumulate the set of template argument lists in this structure.
56 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000057
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000058 if (Innermost)
59 Result.addOuterTemplateArguments(Innermost);
60
Douglas Gregora654dd82009-08-28 17:37:35 +000061 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000062 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000063 Ctx = D->getDeclContext();
Douglas Gregora51c9cc2011-05-22 00:21:10 +000064
Douglas Gregor55462622011-06-15 14:20:42 +000065 // If we have a template template parameter with translation unit context,
66 // then we're performing substitution into a default template argument of
67 // this template template parameter before we've constructed the template
68 // that will own this template template parameter. In this case, we
69 // use empty template parameter lists for all of the outer templates
70 // to avoid performing any substitutions.
71 if (Ctx->isTranslationUnit()) {
72 if (TemplateTemplateParmDecl *TTP
73 = dyn_cast<TemplateTemplateParmDecl>(D)) {
74 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
75 Result.addOuterTemplateArguments(0, 0);
76 return Result;
77 }
78 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +000079 }
80
John McCall970d5302009-08-29 03:16:09 +000081 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +000082 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +000083 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +000084 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
85 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +000086 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
87 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +000088 break;
Mike Stump11289f42009-09-09 15:08:12 +000089
Douglas Gregora654dd82009-08-28 17:37:35 +000090 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-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 Stump11289f42009-09-09 15:08:12 +000097 }
Douglas Gregora654dd82009-08-28 17:37:35 +000098 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +000099 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000100 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000101 (Function->getTemplateSpecializationKind() ==
102 TSK_ExplicitSpecialization &&
103 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000104 break;
105
Douglas Gregora654dd82009-08-28 17:37:35 +0000106 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000107 = Function->getTemplateSpecializationArgs()) {
108 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000109 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000110
Douglas Gregorcf915552009-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 Gregor43669f82011-03-05 17:54:25 +0000116 } else if (FunctionTemplateDecl *FunTmpl
117 = Function->getDescribedFunctionTemplate()) {
118 // Add the "injected" template arguments.
119 std::pair<const TemplateArgument *, unsigned>
120 Injected = FunTmpl->getInjectedTemplateArgs();
121 Result.addOuterTemplateArguments(Injected.first, Injected.second);
Douglas Gregorcf915552009-10-13 16:30:37 +0000122 }
123
John McCall970d5302009-08-29 03:16:09 +0000124 // If this is a friend declaration and it declares an entity at
125 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000126 // instead of its semantic parent, unless of course the pattern we're
127 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000128 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000129 Function->getDeclContext()->isFileContext() &&
130 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000131 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000132 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000133 continue;
134 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000135 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
136 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
137 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
138 const TemplateSpecializationType *TST
139 = cast<TemplateSpecializationType>(Context.getCanonicalType(T));
140 Result.addOuterTemplateArguments(TST->getArgs(), TST->getNumArgs());
141 if (ClassTemplate->isMemberSpecialization())
142 break;
143 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000144 }
John McCall970d5302009-08-29 03:16:09 +0000145
146 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000147 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000148 }
Mike Stump11289f42009-09-09 15:08:12 +0000149
Douglas Gregora654dd82009-08-28 17:37:35 +0000150 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000151}
152
Douglas Gregor84d49a22009-11-11 21:54:23 +0000153bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
154 switch (Kind) {
155 case TemplateInstantiation:
156 case DefaultTemplateArgumentInstantiation:
157 case DefaultFunctionArgumentInstantiation:
158 return true;
159
160 case ExplicitTemplateArgumentSubstitution:
161 case DeducedTemplateArgumentSubstitution:
162 case PriorTemplateArgumentSubstitution:
163 case DefaultTemplateArgumentChecking:
164 return false;
165 }
David Blaikie8a40f702012-01-17 06:56:22 +0000166
167 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000168}
169
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000170Sema::InstantiatingTemplate::
171InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor85673582009-05-18 17:01:57 +0000172 Decl *Entity,
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000173 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000174 : SemaRef(SemaRef),
175 SavedInNonInstantiationSFINAEContext(
176 SemaRef.InNonInstantiationSFINAEContext)
177{
Douglas Gregor79cf6032009-03-10 20:44:00 +0000178 Invalid = CheckInstantiationDepth(PointOfInstantiation,
179 InstantiationRange);
180 if (!Invalid) {
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000181 ActiveTemplateInstantiation Inst;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000182 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000183 Inst.PointOfInstantiation = PointOfInstantiation;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000184 Inst.Entity = reinterpret_cast<uintptr_t>(Entity);
Douglas Gregorc9220832009-03-12 18:36:18 +0000185 Inst.TemplateArgs = 0;
186 Inst.NumTemplateArgs = 0;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000187 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000188 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000189 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor79cf6032009-03-10 20:44:00 +0000190 }
191}
192
Mike Stump11289f42009-09-09 15:08:12 +0000193Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000194 SourceLocation PointOfInstantiation,
195 TemplateDecl *Template,
196 const TemplateArgument *TemplateArgs,
197 unsigned NumTemplateArgs,
198 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000199 : SemaRef(SemaRef),
200 SavedInNonInstantiationSFINAEContext(
201 SemaRef.InNonInstantiationSFINAEContext)
202{
Douglas Gregor79cf6032009-03-10 20:44:00 +0000203 Invalid = CheckInstantiationDepth(PointOfInstantiation,
204 InstantiationRange);
205 if (!Invalid) {
206 ActiveTemplateInstantiation Inst;
Mike Stump11289f42009-09-09 15:08:12 +0000207 Inst.Kind
Douglas Gregor79cf6032009-03-10 20:44:00 +0000208 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
209 Inst.PointOfInstantiation = PointOfInstantiation;
210 Inst.Entity = reinterpret_cast<uintptr_t>(Template);
211 Inst.TemplateArgs = TemplateArgs;
212 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000213 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000214 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000215 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000216 }
217}
218
Mike Stump11289f42009-09-09 15:08:12 +0000219Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregor637d9982009-06-10 23:47:09 +0000220 SourceLocation PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000221 FunctionTemplateDecl *FunctionTemplate,
222 const TemplateArgument *TemplateArgs,
223 unsigned NumTemplateArgs,
224 ActiveTemplateInstantiation::InstantiationKind Kind,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000225 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000226 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000227 : SemaRef(SemaRef),
228 SavedInNonInstantiationSFINAEContext(
229 SemaRef.InNonInstantiationSFINAEContext)
230{
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000231 Invalid = CheckInstantiationDepth(PointOfInstantiation,
232 InstantiationRange);
233 if (!Invalid) {
234 ActiveTemplateInstantiation Inst;
235 Inst.Kind = Kind;
236 Inst.PointOfInstantiation = PointOfInstantiation;
237 Inst.Entity = reinterpret_cast<uintptr_t>(FunctionTemplate);
238 Inst.TemplateArgs = TemplateArgs;
239 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000240 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000241 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000242 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000243 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor84d49a22009-11-11 21:54:23 +0000244
245 if (!Inst.isInstantiationRecord())
246 ++SemaRef.NonInstantiationEntries;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000247 }
248}
249
Mike Stump11289f42009-09-09 15:08:12 +0000250Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000251 SourceLocation PointOfInstantiation,
Douglas Gregor637d9982009-06-10 23:47:09 +0000252 ClassTemplatePartialSpecializationDecl *PartialSpec,
253 const TemplateArgument *TemplateArgs,
254 unsigned NumTemplateArgs,
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000255 sema::TemplateDeductionInfo &DeductionInfo,
Douglas Gregor637d9982009-06-10 23:47:09 +0000256 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000257 : SemaRef(SemaRef),
258 SavedInNonInstantiationSFINAEContext(
259 SemaRef.InNonInstantiationSFINAEContext)
260{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000261 Invalid = false;
262
263 ActiveTemplateInstantiation Inst;
264 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
265 Inst.PointOfInstantiation = PointOfInstantiation;
266 Inst.Entity = reinterpret_cast<uintptr_t>(PartialSpec);
267 Inst.TemplateArgs = TemplateArgs;
268 Inst.NumTemplateArgs = NumTemplateArgs;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000269 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000270 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000271 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000272 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
273
274 assert(!Inst.isInstantiationRecord());
275 ++SemaRef.NonInstantiationEntries;
Douglas Gregor637d9982009-06-10 23:47:09 +0000276}
277
Mike Stump11289f42009-09-09 15:08:12 +0000278Sema::InstantiatingTemplate::InstantiatingTemplate(Sema &SemaRef,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000279 SourceLocation PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000280 ParmVarDecl *Param,
281 const TemplateArgument *TemplateArgs,
282 unsigned NumTemplateArgs,
283 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000284 : SemaRef(SemaRef),
285 SavedInNonInstantiationSFINAEContext(
286 SemaRef.InNonInstantiationSFINAEContext)
287{
Douglas Gregore62e6a02009-11-11 19:13:48 +0000288 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson657bad42009-09-05 05:14:19 +0000289
290 if (!Invalid) {
291 ActiveTemplateInstantiation Inst;
292 Inst.Kind
293 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000294 Inst.PointOfInstantiation = PointOfInstantiation;
Anders Carlsson657bad42009-09-05 05:14:19 +0000295 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
296 Inst.TemplateArgs = TemplateArgs;
297 Inst.NumTemplateArgs = NumTemplateArgs;
298 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000299 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson657bad42009-09-05 05:14:19 +0000300 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000301 }
302}
303
304Sema::InstantiatingTemplate::
305InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorca4686d2011-01-04 23:35:54 +0000306 NamedDecl *Template,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000307 NonTypeTemplateParmDecl *Param,
308 const TemplateArgument *TemplateArgs,
309 unsigned NumTemplateArgs,
Douglas Gregoredb76852011-01-27 22:31:44 +0000310 SourceRange InstantiationRange)
311 : SemaRef(SemaRef),
312 SavedInNonInstantiationSFINAEContext(
313 SemaRef.InNonInstantiationSFINAEContext)
314{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000315 Invalid = false;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000316
Douglas Gregor84d49a22009-11-11 21:54:23 +0000317 ActiveTemplateInstantiation Inst;
318 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
319 Inst.PointOfInstantiation = PointOfInstantiation;
320 Inst.Template = Template;
321 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
322 Inst.TemplateArgs = TemplateArgs;
323 Inst.NumTemplateArgs = NumTemplateArgs;
324 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000325 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000326 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
327
328 assert(!Inst.isInstantiationRecord());
329 ++SemaRef.NonInstantiationEntries;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000330}
331
332Sema::InstantiatingTemplate::
333InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregorca4686d2011-01-04 23:35:54 +0000334 NamedDecl *Template,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000335 TemplateTemplateParmDecl *Param,
336 const TemplateArgument *TemplateArgs,
337 unsigned NumTemplateArgs,
Douglas Gregoredb76852011-01-27 22:31:44 +0000338 SourceRange InstantiationRange)
339 : SemaRef(SemaRef),
340 SavedInNonInstantiationSFINAEContext(
341 SemaRef.InNonInstantiationSFINAEContext)
342{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000343 Invalid = false;
344 ActiveTemplateInstantiation Inst;
345 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
346 Inst.PointOfInstantiation = PointOfInstantiation;
347 Inst.Template = Template;
348 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
349 Inst.TemplateArgs = TemplateArgs;
350 Inst.NumTemplateArgs = NumTemplateArgs;
351 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000352 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000353 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000354
Douglas Gregor84d49a22009-11-11 21:54:23 +0000355 assert(!Inst.isInstantiationRecord());
356 ++SemaRef.NonInstantiationEntries;
357}
358
359Sema::InstantiatingTemplate::
360InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
361 TemplateDecl *Template,
362 NamedDecl *Param,
363 const TemplateArgument *TemplateArgs,
364 unsigned NumTemplateArgs,
Douglas Gregoredb76852011-01-27 22:31:44 +0000365 SourceRange InstantiationRange)
366 : SemaRef(SemaRef),
367 SavedInNonInstantiationSFINAEContext(
368 SemaRef.InNonInstantiationSFINAEContext)
369{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000370 Invalid = false;
371
372 ActiveTemplateInstantiation Inst;
373 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
374 Inst.PointOfInstantiation = PointOfInstantiation;
375 Inst.Template = Template;
376 Inst.Entity = reinterpret_cast<uintptr_t>(Param);
377 Inst.TemplateArgs = TemplateArgs;
378 Inst.NumTemplateArgs = NumTemplateArgs;
379 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000380 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000381 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
382
383 assert(!Inst.isInstantiationRecord());
384 ++SemaRef.NonInstantiationEntries;
Anders Carlsson657bad42009-09-05 05:14:19 +0000385}
386
Douglas Gregor85673582009-05-18 17:01:57 +0000387void Sema::InstantiatingTemplate::Clear() {
388 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000389 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
390 assert(SemaRef.NonInstantiationEntries > 0);
391 --SemaRef.NonInstantiationEntries;
392 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000393 SemaRef.InNonInstantiationSFINAEContext
394 = SavedInNonInstantiationSFINAEContext;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000395 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000396 Invalid = true;
397 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000398}
399
Douglas Gregor79cf6032009-03-10 20:44:00 +0000400bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
401 SourceLocation PointOfInstantiation,
402 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000403 assert(SemaRef.NonInstantiationEntries <=
404 SemaRef.ActiveTemplateInstantiations.size());
405 if ((SemaRef.ActiveTemplateInstantiations.size() -
406 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000407 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000408 return false;
409
Mike Stump11289f42009-09-09 15:08:12 +0000410 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000411 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000412 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000413 << InstantiationRange;
414 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000415 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000416 return true;
417}
418
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000419/// \brief Prints the current instantiation stack through a series of
420/// notes.
421void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000422 // Determine which template instantiations to skip, if any.
423 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
424 unsigned Limit = Diags.getTemplateBacktraceLimit();
425 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
426 SkipStart = Limit / 2 + Limit % 2;
427 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
428 }
429
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000430 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000431 unsigned InstantiationIdx = 0;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000432 for (SmallVector<ActiveTemplateInstantiation, 16>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000433 Active = ActiveTemplateInstantiations.rbegin(),
434 ActiveEnd = ActiveTemplateInstantiations.rend();
435 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000436 ++Active, ++InstantiationIdx) {
437 // Skip this instantiation?
438 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
439 if (InstantiationIdx == SkipStart) {
440 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000441 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000442 diag::note_instantiation_contexts_suppressed)
443 << unsigned(ActiveTemplateInstantiations.size() - Limit);
444 }
445 continue;
446 }
447
Douglas Gregor79cf6032009-03-10 20:44:00 +0000448 switch (Active->Kind) {
449 case ActiveTemplateInstantiation::TemplateInstantiation: {
Douglas Gregor85673582009-05-18 17:01:57 +0000450 Decl *D = reinterpret_cast<Decl *>(Active->Entity);
451 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
452 unsigned DiagID = diag::note_template_member_class_here;
453 if (isa<ClassTemplateSpecializationDecl>(Record))
454 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000455 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000456 << Context.getTypeDeclType(Record)
457 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000458 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000459 unsigned DiagID;
460 if (Function->getPrimaryTemplate())
461 DiagID = diag::note_function_template_spec_here;
462 else
463 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000464 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000465 << Function
466 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000467 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000468 Diags.Report(Active->PointOfInstantiation,
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000469 diag::note_template_static_data_member_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000470 << VD
471 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000472 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
473 Diags.Report(Active->PointOfInstantiation,
474 diag::note_template_enum_def_here)
475 << ED
476 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000477 } else {
478 Diags.Report(Active->PointOfInstantiation,
479 diag::note_template_type_alias_instantiation_here)
480 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000481 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000482 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000483 break;
484 }
485
486 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
487 TemplateDecl *Template = cast<TemplateDecl>((Decl *)Active->Entity);
488 std::string TemplateArgsStr
Douglas Gregordc572a32009-03-30 22:58:21 +0000489 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump11289f42009-09-09 15:08:12 +0000490 Active->TemplateArgs,
Douglas Gregor7de59662009-05-29 20:38:28 +0000491 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000492 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000493 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000494 diag::note_default_arg_instantiation_here)
495 << (Template->getNameAsString() + TemplateArgsStr)
496 << Active->InstantiationRange;
497 break;
498 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000499
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000500 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Mike Stump11289f42009-09-09 15:08:12 +0000501 FunctionTemplateDecl *FnTmpl
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000502 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000503 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000504 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000505 << FnTmpl
506 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
507 Active->TemplateArgs,
508 Active->NumTemplateArgs)
509 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000510 break;
511 }
Mike Stump11289f42009-09-09 15:08:12 +0000512
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000513 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
514 if (ClassTemplatePartialSpecializationDecl *PartialSpec
515 = dyn_cast<ClassTemplatePartialSpecializationDecl>(
516 (Decl *)Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000517 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000518 diag::note_partial_spec_deduct_instantiation_here)
519 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000520 << getTemplateArgumentBindingsText(
521 PartialSpec->getTemplateParameters(),
522 Active->TemplateArgs,
523 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000524 << Active->InstantiationRange;
525 } else {
526 FunctionTemplateDecl *FnTmpl
527 = cast<FunctionTemplateDecl>((Decl *)Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000528 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000529 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000530 << FnTmpl
531 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
532 Active->TemplateArgs,
533 Active->NumTemplateArgs)
534 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000535 }
536 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000537
Anders Carlsson657bad42009-09-05 05:14:19 +0000538 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
539 ParmVarDecl *Param = cast<ParmVarDecl>((Decl *)Active->Entity);
540 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000541
Anders Carlsson657bad42009-09-05 05:14:19 +0000542 std::string TemplateArgsStr
543 = TemplateSpecializationType::PrintTemplateArgumentList(
Mike Stump11289f42009-09-09 15:08:12 +0000544 Active->TemplateArgs,
Anders Carlsson657bad42009-09-05 05:14:19 +0000545 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000546 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000547 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000548 diag::note_default_function_arg_instantiation_here)
Anders Carlssondc6d2c32009-09-05 05:38:54 +0000549 << (FD->getNameAsString() + TemplateArgsStr)
Anders Carlsson657bad42009-09-05 05:14:19 +0000550 << Active->InstantiationRange;
551 break;
552 }
Mike Stump11289f42009-09-09 15:08:12 +0000553
Douglas Gregore62e6a02009-11-11 19:13:48 +0000554 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
555 NamedDecl *Parm = cast<NamedDecl>((Decl *)Active->Entity);
556 std::string Name;
557 if (!Parm->getName().empty())
558 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregorca4686d2011-01-04 23:35:54 +0000559
560 TemplateParameterList *TemplateParams = 0;
561 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
562 TemplateParams = Template->getTemplateParameters();
563 else
564 TemplateParams =
565 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
566 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000567 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000568 diag::note_prior_template_arg_substitution)
569 << isa<TemplateTemplateParmDecl>(Parm)
570 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000571 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000572 Active->TemplateArgs,
573 Active->NumTemplateArgs)
574 << Active->InstantiationRange;
575 break;
576 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000577
578 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregorca4686d2011-01-04 23:35:54 +0000579 TemplateParameterList *TemplateParams = 0;
580 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
581 TemplateParams = Template->getTemplateParameters();
582 else
583 TemplateParams =
584 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
585 ->getTemplateParameters();
586
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000587 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000588 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000589 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000590 Active->TemplateArgs,
591 Active->NumTemplateArgs)
592 << Active->InstantiationRange;
593 break;
594 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000595 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000596 }
597}
598
Douglas Gregoredb76852011-01-27 22:31:44 +0000599llvm::Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000600 if (InNonInstantiationSFINAEContext)
601 return llvm::Optional<TemplateDeductionInfo *>(0);
602
Douglas Gregor33834512009-06-14 07:33:30 +0000603 for (SmallVector<ActiveTemplateInstantiation, 16>::const_reverse_iterator
604 Active = ActiveTemplateInstantiations.rbegin(),
605 ActiveEnd = ActiveTemplateInstantiations.rend();
606 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000607 ++Active)
608 {
Douglas Gregor33834512009-06-14 07:33:30 +0000609 switch(Active->Kind) {
Anders Carlsson657bad42009-09-05 05:14:19 +0000610 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Douglas Gregoredb76852011-01-27 22:31:44 +0000611 case ActiveTemplateInstantiation::TemplateInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000612 // This is a template instantiation, so there is no SFINAE.
Douglas Gregoredb76852011-01-27 22:31:44 +0000613 return llvm::Optional<TemplateDeductionInfo *>();
Mike Stump11289f42009-09-09 15:08:12 +0000614
Douglas Gregor33834512009-06-14 07:33:30 +0000615 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000616 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000617 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000618 // A default template argument instantiation and substitution into
619 // template parameters with arguments for prior parameters may or may
620 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000621 break;
Mike Stump11289f42009-09-09 15:08:12 +0000622
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000623 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
624 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
625 // We're either substitution explicitly-specified template arguments
626 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000627 assert(Active->DeductionInfo && "Missing deduction info pointer");
628 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000629 }
630 }
631
Douglas Gregoredb76852011-01-27 22:31:44 +0000632 return llvm::Optional<TemplateDeductionInfo *>();
Douglas Gregor33834512009-06-14 07:33:30 +0000633}
634
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000635/// \brief Retrieve the depth and index of a parameter pack.
636static std::pair<unsigned, unsigned>
637getDepthAndIndex(NamedDecl *ND) {
638 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
639 return std::make_pair(TTP->getDepth(), TTP->getIndex());
640
641 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
642 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
643
644 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
645 return std::make_pair(TTP->getDepth(), TTP->getIndex());
646}
647
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000648//===----------------------------------------------------------------------===/
649// Template Instantiation for Types
650//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000651namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000652 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000653 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000654 SourceLocation Loc;
655 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000656
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000657 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000658 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000659
660 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000661 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000662 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000663 DeclarationName Entity)
664 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000665 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000666
Mike Stump11289f42009-09-09 15:08:12 +0000667 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000668 /// transformed.
669 ///
670 /// For the purposes of template instantiation, a type has already been
671 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000672 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000673
Douglas Gregord6ff3322009-08-04 16:50:30 +0000674 /// \brief Returns the location of the entity being instantiated, if known.
675 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000676
Douglas Gregord6ff3322009-08-04 16:50:30 +0000677 /// \brief Returns the name of the entity being instantiated, if any.
678 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000679
Douglas Gregoref6ab412009-10-27 06:26:26 +0000680 /// \brief Sets the "base" location and entity when that
681 /// information is known based on another transformation.
682 void setBase(SourceLocation Loc, DeclarationName Entity) {
683 this->Loc = Loc;
684 this->Entity = Entity;
685 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000686
687 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
688 SourceRange PatternRange,
David Blaikieb9c168a2011-09-22 02:34:54 +0000689 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded,
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000690 bool &ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000691 bool &RetainExpansion,
Douglas Gregor0dca5fd2011-01-14 17:04:44 +0000692 llvm::Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000693 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
694 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000695 TemplateArgs,
696 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000697 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000698 NumExpansions);
699 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000700
Douglas Gregorf3010112011-01-07 16:43:16 +0000701 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
702 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
703 }
704
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000705 TemplateArgument ForgetPartiallySubstitutedPack() {
706 TemplateArgument Result;
707 if (NamedDecl *PartialPack
708 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
709 MultiLevelTemplateArgumentList &TemplateArgs
710 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
711 unsigned Depth, Index;
712 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
713 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
714 Result = TemplateArgs(Depth, Index);
715 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
716 }
717 }
718
719 return Result;
720 }
721
722 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
723 if (Arg.isNull())
724 return;
725
726 if (NamedDecl *PartialPack
727 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
728 MultiLevelTemplateArgumentList &TemplateArgs
729 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
730 unsigned Depth, Index;
731 llvm::tie(Depth, Index) = getDepthAndIndex(PartialPack);
732 TemplateArgs.setArgument(Depth, Index, Arg);
733 }
734 }
735
Douglas Gregord6ff3322009-08-04 16:50:30 +0000736 /// \brief Transform the given declaration by instantiating a reference to
737 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000738 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000739
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000740 void transformAttrs(Decl *Old, Decl *New) {
741 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
742 }
743
744 void transformedLocalDecl(Decl *Old, Decl *New) {
745 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
746 }
747
Mike Stump11289f42009-09-09 15:08:12 +0000748 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000749 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000750 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000751
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000752 /// \bried Transform the first qualifier within a scope by instantiating the
753 /// declaration.
754 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
755
Douglas Gregorebe10102009-08-20 07:17:43 +0000756 /// \brief Rebuild the exception declaration and register the declaration
757 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000758 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000759 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000760 SourceLocation StartLoc,
761 SourceLocation NameLoc,
762 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000763
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000764 /// \brief Rebuild the Objective-C exception declaration and register the
765 /// declaration as an instantiated local.
766 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
767 TypeSourceInfo *TSInfo, QualType T);
768
John McCall7f41d982009-09-11 04:59:25 +0000769 /// \brief Check for tag mismatches when instantiating an
770 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000771 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
772 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000773 NestedNameSpecifierLoc QualifierLoc,
774 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000775
Douglas Gregor9db53502011-03-02 18:07:45 +0000776 TemplateName TransformTemplateName(CXXScopeSpec &SS,
777 TemplateName Name,
778 SourceLocation NameLoc,
779 QualType ObjectType = QualType(),
780 NamedDecl *FirstQualifierInScope = 0);
781
John McCalldadc5752010-08-24 06:29:42 +0000782 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
783 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
784 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
785 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000786 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000787 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
788 SubstNonTypeTemplateParmPackExpr *E);
789
Douglas Gregor14cf7522010-04-30 18:55:50 +0000790 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000791 FunctionProtoTypeLoc TL);
Douglas Gregor715e4612011-01-14 22:40:04 +0000792 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000793 int indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000794 llvm::Optional<unsigned> NumExpansions,
795 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000796
Mike Stump11289f42009-09-09 15:08:12 +0000797 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000798 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000799 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000800 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000801
Douglas Gregorada4b792011-01-14 02:55:32 +0000802 /// \brief Transforms an already-substituted template type parameter pack
803 /// into either itself (if we aren't substituting into its pack expansion)
804 /// or the appropriate substituted argument.
805 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
806 SubstTemplateTypeParmPackTypeLoc TL);
807
John McCalldadc5752010-08-24 06:29:42 +0000808 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000809 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCalldadc5752010-08-24 06:29:42 +0000810 ExprResult Result =
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000811 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
812 getSema().CallsUndergoingInstantiation.pop_back();
813 return move(Result);
814 }
John McCall7c454bb2011-07-15 05:09:51 +0000815
816 private:
817 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
818 SourceLocation loc,
819 const TemplateArgument &arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000820 };
Douglas Gregor04318252009-07-06 15:59:29 +0000821}
822
Douglas Gregor5597ab42010-05-07 23:12:07 +0000823bool TemplateInstantiator::AlreadyTransformed(QualType T) {
824 if (T.isNull())
825 return true;
826
Douglas Gregor678d76c2011-07-01 01:22:09 +0000827 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000828 return false;
829
830 getSema().MarkDeclarationsReferencedInType(Loc, T);
831 return true;
832}
833
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000834Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000835 if (!D)
836 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000837
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000838 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000839 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000840 // If the corresponding template argument is NULL or non-existent, it's
841 // because we are performing instantiation from explicitly-specified
842 // template arguments in a function template, but there were some
843 // arguments left unspecified.
844 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
845 TTP->getPosition()))
846 return D;
847
Douglas Gregorf5500772011-01-05 15:48:55 +0000848 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
849
850 if (TTP->isParameterPack()) {
851 assert(Arg.getKind() == TemplateArgument::Pack &&
852 "Missing argument pack");
853
Douglas Gregor5590be02011-01-15 06:45:20 +0000854 assert(getSema().ArgumentPackSubstitutionIndex >= 0);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000855 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregorf5500772011-01-05 15:48:55 +0000856 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
857 }
858
859 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000860 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000861 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000862 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000863 }
Mike Stump11289f42009-09-09 15:08:12 +0000864
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000865 // Fall through to find the instantiated declaration for this template
866 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000867 }
Mike Stump11289f42009-09-09 15:08:12 +0000868
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000869 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000870}
871
Douglas Gregor25289362010-03-01 17:25:41 +0000872Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000873 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000874 if (!Inst)
875 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000876
Douglas Gregorebe10102009-08-20 07:17:43 +0000877 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
878 return Inst;
879}
880
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000881NamedDecl *
882TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
883 SourceLocation Loc) {
884 // If the first part of the nested-name-specifier was a template type
885 // parameter, instantiate that type parameter down to a tag type.
886 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
887 const TemplateTypeParmType *TTP
888 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000889
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000890 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000891 // FIXME: This needs testing w/ member access expressions.
892 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
893
894 if (TTP->isParameterPack()) {
895 assert(Arg.getKind() == TemplateArgument::Pack &&
896 "Missing argument pack");
897
Douglas Gregore1d60df2011-01-14 23:41:42 +0000898 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000899 return 0;
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000900
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000901 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000902 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
903 }
904
905 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000906 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000907 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000908
909 if (const TagType *Tag = T->getAs<TagType>())
910 return Tag->getDecl();
911
912 // The resulting type is not a tag; complain.
913 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
914 return 0;
915 }
916 }
917
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000918 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000919}
920
Douglas Gregorebe10102009-08-20 07:17:43 +0000921VarDecl *
922TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000923 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000924 SourceLocation StartLoc,
925 SourceLocation NameLoc,
926 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000927 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000928 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000929 if (Var)
930 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
931 return Var;
932}
933
934VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
935 TypeSourceInfo *TSInfo,
936 QualType T) {
937 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
938 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000939 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
940 return Var;
941}
942
John McCall7f41d982009-09-11 04:59:25 +0000943QualType
John McCall954b5de2010-11-04 19:04:38 +0000944TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
945 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000946 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000947 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000948 if (const TagType *TT = T->getAs<TagType>()) {
949 TagDecl* TD = TT->getDecl();
950
John McCall954b5de2010-11-04 19:04:38 +0000951 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000952
953 // FIXME: type might be anonymous.
954 IdentifierInfo *Id = TD->getIdentifier();
955
956 // TODO: should we even warn on struct/class mismatches for this? Seems
957 // like it's likely to produce a lot of spurious errors.
Abramo Bagnara6150c882010-05-11 21:36:43 +0000958 if (Keyword != ETK_None && Keyword != ETK_Typename) {
959 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +0000960 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
961 TagLocation, *Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000962 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
963 << Id
964 << FixItHint::CreateReplacement(SourceRange(TagLocation),
965 TD->getKindName());
966 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
967 }
John McCall7f41d982009-09-11 04:59:25 +0000968 }
969 }
970
John McCall954b5de2010-11-04 19:04:38 +0000971 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
972 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000973 QualifierLoc,
974 T);
John McCall7f41d982009-09-11 04:59:25 +0000975}
976
Douglas Gregor9db53502011-03-02 18:07:45 +0000977TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
978 TemplateName Name,
979 SourceLocation NameLoc,
980 QualType ObjectType,
981 NamedDecl *FirstQualifierInScope) {
982 if (TemplateTemplateParmDecl *TTP
983 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
984 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
985 // If the corresponding template argument is NULL or non-existent, it's
986 // because we are performing instantiation from explicitly-specified
987 // template arguments in a function template, but there were some
988 // arguments left unspecified.
989 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
990 TTP->getPosition()))
991 return Name;
992
993 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
994
995 if (TTP->isParameterPack()) {
996 assert(Arg.getKind() == TemplateArgument::Pack &&
997 "Missing argument pack");
998
999 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1000 // We have the template argument pack to substitute, but we're not
1001 // actually expanding the enclosing pack expansion yet. So, just
1002 // keep the entire argument pack.
1003 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1004 }
1005
1006 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1007 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1008 }
1009
1010 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001011 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001012
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001013 // We don't ever want to substitute for a qualified template name, since
1014 // the qualifier is handled separately. So, look through the qualified
1015 // template name to its underlying declaration.
1016 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1017 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001018
1019 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001020 return Template;
1021 }
1022 }
1023
1024 if (SubstTemplateTemplateParmPackStorage *SubstPack
1025 = Name.getAsSubstTemplateTemplateParmPack()) {
1026 if (getSema().ArgumentPackSubstitutionIndex == -1)
1027 return Name;
1028
1029 const TemplateArgument &ArgPack = SubstPack->getArgumentPack();
1030 assert(getSema().ArgumentPackSubstitutionIndex < (int)ArgPack.pack_size() &&
1031 "Pack substitution index out-of-range");
1032 return ArgPack.pack_begin()[getSema().ArgumentPackSubstitutionIndex]
1033 .getAsTemplate();
1034 }
1035
1036 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1037 FirstQualifierInScope);
1038}
1039
John McCalldadc5752010-08-24 06:29:42 +00001040ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001041TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001042 if (!E->isTypeDependent())
John McCallc3007a22010-10-26 07:05:15 +00001043 return SemaRef.Owned(E);
Anders Carlsson0b209a82009-09-11 01:22:35 +00001044
1045 FunctionDecl *currentDecl = getSema().getCurFunctionDecl();
1046 assert(currentDecl && "Must have current function declaration when "
1047 "instantiating.");
1048
1049 PredefinedExpr::IdentType IT = E->getIdentType();
1050
Anders Carlsson5bd8d192010-02-11 18:20:28 +00001051 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001052
1053 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00001054 QualType ResTy = getSema().Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00001055 ResTy = getSema().Context.getConstantArrayType(ResTy, LengthI,
1056 ArrayType::Normal, 0);
1057 PredefinedExpr *PE =
1058 new (getSema().Context) PredefinedExpr(E->getLocation(), ResTy, IT);
1059 return getSema().Owned(PE);
1060}
1061
John McCalldadc5752010-08-24 06:29:42 +00001062ExprResult
John McCall13481c52010-02-06 08:42:39 +00001063TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001064 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001065 // If the corresponding template argument is NULL or non-existent, it's
1066 // because we are performing instantiation from explicitly-specified
1067 // template arguments in a function template, but there were some
1068 // arguments left unspecified.
1069 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1070 NTTP->getPosition()))
John McCallc3007a22010-10-26 07:05:15 +00001071 return SemaRef.Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00001072
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001073 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1074 if (NTTP->isParameterPack()) {
1075 assert(Arg.getKind() == TemplateArgument::Pack &&
1076 "Missing argument pack");
1077
1078 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001079 // We have an argument pack, but we can't select a particular argument
1080 // out of it yet. Therefore, we'll build an expression to hold on to that
1081 // argument pack.
1082 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1083 E->getLocation(),
1084 NTTP->getDeclName());
1085 if (TargetType.isNull())
1086 return ExprError();
1087
1088 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1089 NTTP,
1090 E->getLocation(),
1091 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001092 }
1093
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001094 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001095 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1096 }
Mike Stump11289f42009-09-09 15:08:12 +00001097
John McCall7c454bb2011-07-15 05:09:51 +00001098 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1099}
1100
1101ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1102 NonTypeTemplateParmDecl *parm,
1103 SourceLocation loc,
1104 const TemplateArgument &arg) {
1105 ExprResult result;
1106 QualType type;
1107
John McCall13481c52010-02-06 08:42:39 +00001108 // The template argument itself might be an expression, in which
1109 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001110 if (arg.getKind() == TemplateArgument::Expression) {
1111 Expr *argExpr = arg.getAsExpr();
1112 result = SemaRef.Owned(argExpr);
1113 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001114
John McCall7c454bb2011-07-15 05:09:51 +00001115 } else if (arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001116 ValueDecl *VD;
1117 if (Decl *D = arg.getAsDecl()) {
1118 VD = cast<ValueDecl>(D);
Mike Stump11289f42009-09-09 15:08:12 +00001119
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001120 // Find the instantiation of the template argument. This is
1121 // required for nested templates.
1122 VD = cast_or_null<ValueDecl>(
1123 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1124 if (!VD)
1125 return ExprError();
1126 } else {
1127 // Propagate NULL template argument.
1128 VD = 0;
1129 }
1130
John McCall15dda372010-02-06 10:23:53 +00001131 // Derive the type we want the substituted decl to have. This had
1132 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001133 if (parm->isExpandedParameterPack()) {
1134 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1135 } else if (parm->isParameterPack() &&
1136 isa<PackExpansionType>(parm->getType())) {
1137 type = SemaRef.SubstType(
1138 cast<PackExpansionType>(parm->getType())->getPattern(),
1139 TemplateArgs, loc, parm->getDeclName());
1140 } else {
1141 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1142 loc, parm->getDeclName());
1143 }
1144 assert(!type.isNull() && "type substitution failed for param type");
1145 assert(!type->isDependentType() && "param type still dependent");
1146 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001147
John McCall7c454bb2011-07-15 05:09:51 +00001148 if (!result.isInvalid()) type = result.get()->getType();
1149 } else {
1150 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1151
1152 // Note that this type can be different from the type of 'result',
1153 // e.g. if it's an enum type.
1154 type = arg.getIntegralType();
1155 }
1156 if (result.isInvalid()) return ExprError();
1157
1158 Expr *resultExpr = result.take();
1159 return SemaRef.Owned(new (SemaRef.Context)
1160 SubstNonTypeTemplateParmExpr(type,
1161 resultExpr->getValueKind(),
1162 loc, parm, resultExpr));
John McCall13481c52010-02-06 08:42:39 +00001163}
1164
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001165ExprResult
1166TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1167 SubstNonTypeTemplateParmPackExpr *E) {
1168 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1169 // We aren't expanding the parameter pack, so just return ourselves.
1170 return getSema().Owned(E);
1171 }
1172
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001173 const TemplateArgument &ArgPack = E->getArgumentPack();
1174 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1175 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1176
1177 const TemplateArgument &Arg = ArgPack.pack_begin()[Index];
John McCall7c454bb2011-07-15 05:09:51 +00001178 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1179 E->getParameterPackLocation(),
1180 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001181}
John McCall13481c52010-02-06 08:42:39 +00001182
John McCalldadc5752010-08-24 06:29:42 +00001183ExprResult
John McCall13481c52010-02-06 08:42:39 +00001184TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1185 NamedDecl *D = E->getDecl();
1186 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1187 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1188 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001189
1190 // We have a non-type template parameter that isn't fully substituted;
1191 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001192 }
Mike Stump11289f42009-09-09 15:08:12 +00001193
John McCall47f29ea2009-12-08 09:21:05 +00001194 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001195}
1196
John McCalldadc5752010-08-24 06:29:42 +00001197ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001198 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001199 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1200 getDescribedFunctionTemplate() &&
1201 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001202 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1203 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1204 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001205}
1206
Douglas Gregor14cf7522010-04-30 18:55:50 +00001207QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001208 FunctionProtoTypeLoc TL) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00001209 // We need a local instantiation scope for this function prototype.
John McCall19c1bfd2010-08-25 05:32:35 +00001210 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall31f82722010-11-12 08:19:04 +00001211 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall58f10c32010-03-11 09:03:00 +00001212}
1213
1214ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001215TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001216 int indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001217 llvm::Optional<unsigned> NumExpansions,
1218 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001219 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001220 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001221}
1222
Mike Stump11289f42009-09-09 15:08:12 +00001223QualType
John McCall550e0c22009-10-21 00:40:46 +00001224TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001225 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001226 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001227 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001228 // Replace the template type parameter with its corresponding
1229 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001230
1231 // If the corresponding template argument is NULL or doesn't exist, it's
1232 // because we are performing instantiation from explicitly-specified
1233 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001234 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001235 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1236 TemplateTypeParmTypeLoc NewTL
1237 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1238 NewTL.setNameLoc(TL.getNameLoc());
1239 return TL.getType();
1240 }
Mike Stump11289f42009-09-09 15:08:12 +00001241
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001242 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1243
1244 if (T->isParameterPack()) {
1245 assert(Arg.getKind() == TemplateArgument::Pack &&
1246 "Missing argument pack");
1247
1248 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001249 // We have the template argument pack, but we're not expanding the
1250 // enclosing pack expansion yet. Just save the template argument
1251 // pack for later substitution.
1252 QualType Result
1253 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1254 SubstTemplateTypeParmPackTypeLoc NewTL
1255 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1256 NewTL.setNameLoc(TL.getNameLoc());
1257 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001258 }
1259
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001260 assert(getSema().ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001261 Arg = Arg.pack_begin()[getSema().ArgumentPackSubstitutionIndex];
1262 }
1263
1264 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001265 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001266
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001267 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001268
1269 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001270 QualType Result
1271 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1272 SubstTemplateTypeParmTypeLoc NewTL
1273 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1274 NewTL.setNameLoc(TL.getNameLoc());
1275 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001276 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001277
1278 // The template type parameter comes from an inner template (e.g.,
1279 // the template parameter list of a member template inside the
1280 // template we are instantiating). Create a new template type
1281 // parameter with the template "level" reduced by one.
Chandler Carruth08836322011-05-01 00:51:33 +00001282 TemplateTypeParmDecl *NewTTPDecl = 0;
1283 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1284 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1285 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1286
John McCall550e0c22009-10-21 00:40:46 +00001287 QualType Result
1288 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1289 - TemplateArgs.getNumLevels(),
1290 T->getIndex(),
1291 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001292 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001293 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1294 NewTL.setNameLoc(TL.getNameLoc());
1295 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001296}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001297
Douglas Gregorada4b792011-01-14 02:55:32 +00001298QualType
1299TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1300 TypeLocBuilder &TLB,
1301 SubstTemplateTypeParmPackTypeLoc TL) {
1302 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1303 // We aren't expanding the parameter pack, so just return ourselves.
1304 SubstTemplateTypeParmPackTypeLoc NewTL
1305 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1306 NewTL.setNameLoc(TL.getNameLoc());
1307 return TL.getType();
1308 }
1309
1310 const TemplateArgument &ArgPack = TL.getTypePtr()->getArgumentPack();
1311 unsigned Index = (unsigned)getSema().ArgumentPackSubstitutionIndex;
1312 assert(Index < ArgPack.pack_size() && "Substitution index out-of-range");
1313
1314 QualType Result = ArgPack.pack_begin()[Index].getAsType();
1315 Result = getSema().Context.getSubstTemplateTypeParmType(
1316 TL.getTypePtr()->getReplacedParameter(),
1317 Result);
1318 SubstTemplateTypeParmTypeLoc NewTL
1319 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1320 NewTL.setNameLoc(TL.getNameLoc());
1321 return Result;
1322}
1323
John McCall76d824f2009-08-25 22:02:44 +00001324/// \brief Perform substitution on the type T with a given set of template
1325/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001326///
1327/// This routine substitutes the given template arguments into the
1328/// type T and produces the instantiated type.
1329///
1330/// \param T the type into which the template arguments will be
1331/// substituted. If this type is not dependent, it will be returned
1332/// immediately.
1333///
1334/// \param TemplateArgs the template arguments that will be
1335/// substituted for the top-level template parameters within T.
1336///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001337/// \param Loc the location in the source code where this substitution
1338/// is being performed. It will typically be the location of the
1339/// declarator (if we're instantiating the type of some declaration)
1340/// or the location of the type in the source code (if, e.g., we're
1341/// instantiating the type of a cast expression).
1342///
1343/// \param Entity the name of the entity associated with a declaration
1344/// being instantiated (if any). May be empty to indicate that there
1345/// is no such entity (if, e.g., this is a type that occurs as part of
1346/// a cast expression) or that the entity has no name (e.g., an
1347/// unnamed function parameter).
1348///
1349/// \returns If the instantiation succeeds, the instantiated
1350/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001351TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001352 const MultiLevelTemplateArgumentList &Args,
1353 SourceLocation Loc,
1354 DeclarationName Entity) {
1355 assert(!ActiveTemplateInstantiations.empty() &&
1356 "Cannot perform an instantiation without some context on the "
1357 "instantiation stack");
1358
Douglas Gregor678d76c2011-07-01 01:22:09 +00001359 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001360 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001361 return T;
1362
1363 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1364 return Instantiator.TransformType(T);
1365}
1366
Douglas Gregor5499af42011-01-05 23:12:31 +00001367TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1368 const MultiLevelTemplateArgumentList &Args,
1369 SourceLocation Loc,
1370 DeclarationName Entity) {
1371 assert(!ActiveTemplateInstantiations.empty() &&
1372 "Cannot perform an instantiation without some context on the "
1373 "instantiation stack");
1374
1375 if (TL.getType().isNull())
1376 return 0;
1377
Douglas Gregor678d76c2011-07-01 01:22:09 +00001378 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001379 !TL.getType()->isVariablyModifiedType()) {
1380 // FIXME: Make a copy of the TypeLoc data here, so that we can
1381 // return a new TypeSourceInfo. Inefficient!
1382 TypeLocBuilder TLB;
1383 TLB.pushFullCopy(TL);
1384 return TLB.getTypeSourceInfo(Context, TL.getType());
1385 }
1386
1387 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1388 TypeLocBuilder TLB;
1389 TLB.reserve(TL.getFullDataSize());
1390 QualType Result = Instantiator.TransformType(TLB, TL);
1391 if (Result.isNull())
1392 return 0;
1393
1394 return TLB.getTypeSourceInfo(Context, Result);
1395}
1396
John McCall609459e2009-10-21 00:58:09 +00001397/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001398QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001399 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001400 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001401 assert(!ActiveTemplateInstantiations.empty() &&
1402 "Cannot perform an instantiation without some context on the "
1403 "instantiation stack");
1404
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001405 // If T is not a dependent type or a variably-modified type, there
1406 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001407 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001408 return T;
1409
Douglas Gregord6ff3322009-08-04 16:50:30 +00001410 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1411 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001412}
Douglas Gregor463421d2009-03-03 04:44:36 +00001413
John McCallb29f78f2010-04-09 17:38:44 +00001414static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001415 if (T->getType()->isInstantiationDependentType() ||
1416 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001417 return true;
1418
Abramo Bagnara6d810632010-12-14 22:11:44 +00001419 TypeLoc TL = T->getTypeLoc().IgnoreParens();
John McCallb29f78f2010-04-09 17:38:44 +00001420 if (!isa<FunctionProtoTypeLoc>(TL))
1421 return false;
1422
1423 FunctionProtoTypeLoc FP = cast<FunctionProtoTypeLoc>(TL);
1424 for (unsigned I = 0, E = FP.getNumArgs(); I != E; ++I) {
1425 ParmVarDecl *P = FP.getArg(I);
1426
Douglas Gregora7203e52011-05-09 20:45:16 +00001427 // The parameter's type as written might be dependent even if the
1428 // decayed type was not dependent.
1429 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001430 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregora7203e52011-05-09 20:45:16 +00001431 return true;
1432
John McCallb29f78f2010-04-09 17:38:44 +00001433 // TODO: currently we always rebuild expressions. When we
1434 // properly get lazier about this, we should use the same
1435 // logic to avoid rebuilding prototypes here.
Douglas Gregor9cc278222011-01-05 21:14:17 +00001436 if (P->hasDefaultArg())
John McCallb29f78f2010-04-09 17:38:44 +00001437 return true;
1438 }
1439
1440 return false;
1441}
1442
1443/// A form of SubstType intended specifically for instantiating the
1444/// type of a FunctionDecl. Its purpose is solely to force the
1445/// instantiation of default-argument expressions.
1446TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1447 const MultiLevelTemplateArgumentList &Args,
1448 SourceLocation Loc,
1449 DeclarationName Entity) {
1450 assert(!ActiveTemplateInstantiations.empty() &&
1451 "Cannot perform an instantiation without some context on the "
1452 "instantiation stack");
1453
1454 if (!NeedsInstantiationAsFunctionType(T))
1455 return T;
1456
1457 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1458
1459 TypeLocBuilder TLB;
1460
1461 TypeLoc TL = T->getTypeLoc();
1462 TLB.reserve(TL.getFullDataSize());
1463
John McCall31f82722010-11-12 08:19:04 +00001464 QualType Result = Instantiator.TransformType(TLB, TL);
John McCallb29f78f2010-04-09 17:38:44 +00001465 if (Result.isNull())
1466 return 0;
1467
1468 return TLB.getTypeSourceInfo(Context, Result);
1469}
1470
Douglas Gregor940bca72010-04-12 07:48:19 +00001471ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001472 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001473 int indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001474 llvm::Optional<unsigned> NumExpansions,
1475 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001476 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor5499af42011-01-05 23:12:31 +00001477 TypeSourceInfo *NewDI = 0;
1478
Douglas Gregor5499af42011-01-05 23:12:31 +00001479 TypeLoc OldTL = OldDI->getTypeLoc();
1480 if (isa<PackExpansionTypeLoc>(OldTL)) {
1481 PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
Douglas Gregor5499af42011-01-05 23:12:31 +00001482
1483 // We have a function parameter pack. Substitute into the pattern of the
1484 // expansion.
1485 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1486 OldParm->getLocation(), OldParm->getDeclName());
1487 if (!NewDI)
1488 return 0;
1489
1490 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1491 // We still have unexpanded parameter packs, which means that
1492 // our function parameter is still a function parameter pack.
1493 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001494 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001495 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001496 } else if (ExpectParameterPack) {
1497 // We expected to get a parameter pack but didn't (because the type
1498 // itself is not a pack expansion type), so complain. This can occur when
1499 // the substitution goes through an alias template that "loses" the
1500 // pack expansion.
1501 Diag(OldParm->getLocation(),
1502 diag::err_function_parameter_pack_without_parameter_packs)
1503 << NewDI->getType();
1504 return 0;
1505 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001506 } else {
1507 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1508 OldParm->getDeclName());
1509 }
1510
Douglas Gregor940bca72010-04-12 07:48:19 +00001511 if (!NewDI)
1512 return 0;
1513
1514 if (NewDI->getType()->isVoidType()) {
1515 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1516 return 0;
1517 }
1518
1519 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001520 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001521 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001522 OldParm->getIdentifier(),
1523 NewDI->getType(), NewDI,
Douglas Gregorc4df4072010-04-19 22:54:31 +00001524 OldParm->getStorageClass(),
1525 OldParm->getStorageClassAsWritten());
Douglas Gregor940bca72010-04-12 07:48:19 +00001526 if (!NewParm)
1527 return 0;
Douglas Gregor6044d692010-05-19 17:02:24 +00001528
Douglas Gregor940bca72010-04-12 07:48:19 +00001529 // Mark the (new) default argument as uninstantiated (if any).
1530 if (OldParm->hasUninstantiatedDefaultArg()) {
1531 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1532 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001533 } else if (OldParm->hasUnparsedDefaultArg()) {
1534 NewParm->setUnparsedDefaultArg();
1535 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Douglas Gregor940bca72010-04-12 07:48:19 +00001536 } else if (Expr *Arg = OldParm->getDefaultArg())
1537 NewParm->setUninstantiatedDefaultArg(Arg);
1538
1539 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001540
Douglas Gregorf3010112011-01-07 16:43:16 +00001541 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001542 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001543 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1544 } else {
1545 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001546 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001547 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001548
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001549 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1550 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001551 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001552
1553 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1554 OldParm->getFunctionScopeIndex() + indexAdjustment);
Fariborz Jahaniana6c7efe2010-07-13 20:05:58 +00001555
Douglas Gregor940bca72010-04-12 07:48:19 +00001556 return NewParm;
1557}
1558
Douglas Gregordd472162011-01-07 00:20:55 +00001559/// \brief Substitute the given template arguments into the given set of
1560/// parameters, producing the set of parameter types that would be generated
1561/// from such a substitution.
1562bool Sema::SubstParmTypes(SourceLocation Loc,
1563 ParmVarDecl **Params, unsigned NumParams,
1564 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001565 SmallVectorImpl<QualType> &ParamTypes,
1566 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregordd472162011-01-07 00:20:55 +00001567 assert(!ActiveTemplateInstantiations.empty() &&
1568 "Cannot perform an instantiation without some context on the "
1569 "instantiation stack");
1570
1571 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1572 DeclarationName());
1573 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregorf3010112011-01-07 16:43:16 +00001574 ParamTypes, OutParams);
Douglas Gregordd472162011-01-07 00:20:55 +00001575}
1576
John McCall76d824f2009-08-25 22:02:44 +00001577/// \brief Perform substitution on the base class specifiers of the
1578/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001579///
1580/// Produces a diagnostic and returns true on error, returns false and
1581/// attaches the instantiated base classes to the class template
1582/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001583bool
John McCall76d824f2009-08-25 22:02:44 +00001584Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1585 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001586 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001587 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001588 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Mike Stump11289f42009-09-09 15:08:12 +00001589 for (ClassTemplateSpecializationDecl::base_class_iterator
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001590 Base = Pattern->bases_begin(), BaseEnd = Pattern->bases_end();
Douglas Gregor2a72edd2009-03-10 18:52:44 +00001591 Base != BaseEnd; ++Base) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001592 if (!Base->getType()->isDependentType()) {
Fariborz Jahanian5c14ec32009-07-22 17:41:53 +00001593 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(*Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001594 continue;
1595 }
1596
Douglas Gregor752a5952011-01-03 22:36:02 +00001597 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001598 TypeSourceInfo *BaseTypeLoc;
Douglas Gregor752a5952011-01-03 22:36:02 +00001599 if (Base->isPackExpansion()) {
1600 // This is a pack expansion. See whether we should expand it now, or
1601 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001602 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Douglas Gregor752a5952011-01-03 22:36:02 +00001603 collectUnexpandedParameterPacks(Base->getTypeSourceInfo()->getTypeLoc(),
1604 Unexpanded);
1605 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001606 bool RetainExpansion = false;
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001607 llvm::Optional<unsigned> NumExpansions;
Douglas Gregor752a5952011-01-03 22:36:02 +00001608 if (CheckParameterPacksForExpansion(Base->getEllipsisLoc(),
1609 Base->getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001610 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001611 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001612 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001613 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001614 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001615 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001616 }
1617
1618 // If we should expand this pack expansion now, do so.
1619 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001620 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001621 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1622
1623 TypeSourceInfo *BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1624 TemplateArgs,
1625 Base->getSourceRange().getBegin(),
1626 DeclarationName());
1627 if (!BaseTypeLoc) {
1628 Invalid = true;
1629 continue;
1630 }
1631
1632 if (CXXBaseSpecifier *InstantiatedBase
1633 = CheckBaseSpecifier(Instantiation,
1634 Base->getSourceRange(),
1635 Base->isVirtual(),
1636 Base->getAccessSpecifierAsWritten(),
1637 BaseTypeLoc,
1638 SourceLocation()))
1639 InstantiatedBases.push_back(InstantiatedBase);
1640 else
1641 Invalid = true;
1642 }
1643
1644 continue;
1645 }
1646
1647 // The resulting base specifier will (still) be a pack expansion.
1648 EllipsisLoc = Base->getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001649 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1650 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1651 TemplateArgs,
1652 Base->getSourceRange().getBegin(),
1653 DeclarationName());
1654 } else {
1655 BaseTypeLoc = SubstType(Base->getTypeSourceInfo(),
1656 TemplateArgs,
1657 Base->getSourceRange().getBegin(),
1658 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001659 }
1660
Nick Lewycky19b9f952010-07-26 16:56:01 +00001661 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001662 Invalid = true;
1663 continue;
1664 }
1665
1666 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001667 = CheckBaseSpecifier(Instantiation,
Douglas Gregor463421d2009-03-03 04:44:36 +00001668 Base->getSourceRange(),
1669 Base->isVirtual(),
1670 Base->getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001671 BaseTypeLoc,
1672 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001673 InstantiatedBases.push_back(InstantiatedBase);
1674 else
1675 Invalid = true;
1676 }
1677
Douglas Gregor2a72edd2009-03-10 18:52:44 +00001678 if (!Invalid &&
Jay Foad7d0479f2009-05-21 09:52:38 +00001679 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor463421d2009-03-03 04:44:36 +00001680 InstantiatedBases.size()))
1681 Invalid = true;
1682
1683 return Invalid;
1684}
1685
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001686// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001687namespace clang {
1688 namespace sema {
1689 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1690 const MultiLevelTemplateArgumentList &TemplateArgs);
1691 }
1692}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001693
Richard Smith4b38ded2012-03-14 23:13:10 +00001694/// Determine whether we would be unable to instantiate this template (because
1695/// it either has no definition, or is in the process of being instantiated).
1696static bool DiagnoseUninstantiableTemplate(Sema &S,
1697 SourceLocation PointOfInstantiation,
1698 TagDecl *Instantiation,
1699 bool InstantiatedFromMember,
1700 TagDecl *Pattern,
1701 TagDecl *PatternDef,
1702 TemplateSpecializationKind TSK,
1703 bool Complain = true) {
1704 if (PatternDef && !PatternDef->isBeingDefined())
1705 return false;
1706
1707 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1708 // Say nothing
1709 } else if (PatternDef) {
1710 assert(PatternDef->isBeingDefined());
1711 S.Diag(PointOfInstantiation,
1712 diag::err_template_instantiate_within_definition)
1713 << (TSK != TSK_ImplicitInstantiation)
1714 << S.Context.getTypeDeclType(Instantiation);
1715 // Not much point in noting the template declaration here, since
1716 // we're lexically inside it.
1717 Instantiation->setInvalidDecl();
1718 } else if (InstantiatedFromMember) {
1719 S.Diag(PointOfInstantiation,
1720 diag::err_implicit_instantiate_member_undefined)
1721 << S.Context.getTypeDeclType(Instantiation);
1722 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1723 } else {
1724 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1725 << (TSK != TSK_ImplicitInstantiation)
1726 << S.Context.getTypeDeclType(Instantiation);
1727 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1728 }
1729
1730 // In general, Instantiation isn't marked invalid to get more than one
1731 // error for multiple undefined instantiations. But the code that does
1732 // explicit declaration -> explicit definition conversion can't handle
1733 // invalid declarations, so mark as invalid in that case.
1734 if (TSK == TSK_ExplicitInstantiationDeclaration)
1735 Instantiation->setInvalidDecl();
1736 return true;
1737}
1738
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001739/// \brief Instantiate the definition of a class from a given pattern.
1740///
1741/// \param PointOfInstantiation The point of instantiation within the
1742/// source code.
1743///
1744/// \param Instantiation is the declaration whose definition is being
1745/// instantiated. This will be either a class template specialization
1746/// or a member class of a class template specialization.
1747///
1748/// \param Pattern is the pattern from which the instantiation
1749/// occurs. This will be either the declaration of a class template or
1750/// the declaration of a member class of a class template.
1751///
1752/// \param TemplateArgs The template arguments to be substituted into
1753/// the pattern.
1754///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001755/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001756///
1757/// \param Complain whether to complain if the class cannot be instantiated due
1758/// to the lack of a definition.
1759///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001760/// \returns true if an error occurred, false otherwise.
1761bool
1762Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1763 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001764 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001765 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001766 bool Complain) {
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001767 bool Invalid = false;
John McCall87a44eb2009-08-20 01:44:21 +00001768
Mike Stump11289f42009-09-09 15:08:12 +00001769 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001770 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smith4b38ded2012-03-14 23:13:10 +00001771 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1772 Instantiation->getInstantiatedFromMemberClass(),
1773 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001774 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001775 Pattern = PatternDef;
1776
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001777 // \brief Record the point of instantiation.
1778 if (MemberSpecializationInfo *MSInfo
1779 = Instantiation->getMemberSpecializationInfo()) {
1780 MSInfo->setTemplateSpecializationKind(TSK);
1781 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001782 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001783 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001784 Spec->setTemplateSpecializationKind(TSK);
1785 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001786 }
1787
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001788 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001789 if (Inst)
1790 return true;
1791
1792 // Enter the scope of this instantiation. We don't use
1793 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001794 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001795 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001796 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001797
Douglas Gregor51121572010-03-24 01:33:17 +00001798 // If this is an instantiation of a local class, merge this local
1799 // instantiation scope with the enclosing scope. Otherwise, every
1800 // instantiation of a class has its own local instantiation scope.
1801 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001802 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001803
John McCall6602bb12010-08-01 02:01:53 +00001804 // Pull attributes from the pattern onto the instantiation.
1805 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1806
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001807 // Start the definition of this instantiation.
1808 Instantiation->startDefinition();
Douglas Gregore9029562010-05-06 00:28:52 +00001809
1810 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001811
John McCall76d824f2009-08-25 22:02:44 +00001812 // Do substitution on the base class specifiers.
1813 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001814 Invalid = true;
1815
Douglas Gregor869853e2010-11-10 19:44:59 +00001816 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001817 SmallVector<Decl*, 4> Fields;
1818 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith938f40b2011-06-11 17:19:42 +00001819 FieldsWithMemberInitializers;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001820 // Delay instantiation of late parsed attributes.
1821 LateInstantiatedAttrVec LateAttrs;
1822 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1823
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001824 for (RecordDecl::decl_iterator Member = Pattern->decls_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001825 MemberEnd = Pattern->decls_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001826 Member != MemberEnd; ++Member) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001827 // Don't instantiate members not belonging in this semantic context.
1828 // e.g. for:
1829 // @code
1830 // template <int i> class A {
1831 // class B *g;
1832 // };
1833 // @endcode
1834 // 'class B' has the template as lexical context but semantically it is
1835 // introduced in namespace scope.
1836 if ((*Member)->getDeclContext() != Pattern)
1837 continue;
1838
Douglas Gregor869853e2010-11-10 19:44:59 +00001839 if ((*Member)->isInvalidDecl()) {
1840 Invalid = true;
1841 continue;
1842 }
1843
1844 Decl *NewMember = Instantiator.Visit(*Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001845 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00001846 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00001847 Fields.push_back(Field);
Richard Smith938f40b2011-06-11 17:19:42 +00001848 FieldDecl *OldField = cast<FieldDecl>(*Member);
1849 if (OldField->getInClassInitializer())
1850 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
1851 Field));
Richard Smith7d137e32012-03-23 03:33:32 +00001852 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
1853 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1854 // specialization causes the implicit instantiation of the definitions
1855 // of unscoped member enumerations.
1856 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00001857 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
1858 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00001859 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
1860 assert(MSInfo && "no spec info for member enum specialization");
1861 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
1862 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1863 }
1864 }
1865
1866 if (NewMember->isInvalidDecl())
Eli Friedmand0e8de22009-12-07 00:22:08 +00001867 Invalid = true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001868 } else {
1869 // FIXME: Eventually, a NULL return will mean that one of the
Mike Stump87c57ac2009-05-16 07:39:55 +00001870 // instantiations was a semantic disaster, and we'll want to set Invalid =
1871 // true. For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001872 }
1873 }
1874
1875 // Finish checking fields.
David Blaikie751c5582011-09-22 02:58:26 +00001876 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
1877 SourceLocation(), SourceLocation(), 0);
Douglas Gregor0be31a22010-07-02 17:43:08 +00001878 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00001879
1880 // Attach any in-class member initializers now the class is complete.
1881 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
1882 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
1883 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
1884 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00001885
Sebastian Redla9351792012-02-11 23:51:47 +00001886 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
1887 /*CXXDirectInit=*/false);
1888 if (NewInit.isInvalid())
Richard Smith938f40b2011-06-11 17:19:42 +00001889 NewField->setInvalidDecl();
Richard Smithe3daab22011-07-20 00:12:52 +00001890 else {
Sebastian Redla9351792012-02-11 23:51:47 +00001891 Expr *Init = NewInit.take();
1892 assert(Init && "no-argument initializer in class");
1893 assert(!isa<ParenListExpr>(Init) && "call-style init in class");
1894 ActOnCXXInClassMemberInitializer(NewField,
1895 Init->getSourceRange().getBegin(), Init);
Richard Smithe3daab22011-07-20 00:12:52 +00001896 }
Richard Smith938f40b2011-06-11 17:19:42 +00001897 }
1898
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001899 // Instantiate late parsed attributes, and attach them to their decls.
1900 // See Sema::InstantiateAttrs
1901 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
1902 E = LateAttrs.end(); I != E; ++I) {
1903 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
1904 CurrentInstantiationScope = I->Scope;
1905 Attr *NewAttr =
1906 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
1907 I->NewDecl->addAttr(NewAttr);
1908 LocalInstantiationScope::deleteScopes(I->Scope,
1909 Instantiator.getStartingScope());
1910 }
1911 Instantiator.disableLateAttributeInstantiation();
1912 LateAttrs.clear();
1913
Richard Smith938f40b2011-06-11 17:19:42 +00001914 if (!FieldsWithMemberInitializers.empty())
1915 ActOnFinishDelayedMemberInitializers(Instantiation);
1916
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00001917 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00001918 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00001919 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00001920 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00001921 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00001922
Douglas Gregor3c74d412009-10-14 20:14:33 +00001923 if (Instantiation->isInvalidDecl())
1924 Invalid = true;
Douglas Gregor869853e2010-11-10 19:44:59 +00001925 else {
1926 // Instantiate any out-of-line class template partial
1927 // specializations now.
1928 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
1929 P = Instantiator.delayed_partial_spec_begin(),
1930 PEnd = Instantiator.delayed_partial_spec_end();
1931 P != PEnd; ++P) {
1932 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
1933 P->first,
1934 P->second)) {
1935 Invalid = true;
1936 break;
1937 }
1938 }
1939 }
1940
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001941 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00001942 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001943
Douglas Gregor88d292c2010-05-13 16:44:06 +00001944 if (!Invalid) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00001945 Consumer.HandleTagDeclDefinition(Instantiation);
1946
Douglas Gregor88d292c2010-05-13 16:44:06 +00001947 // Always emit the vtable for an explicit instantiation definition
1948 // of a polymorphic class template specialization.
1949 if (TSK == TSK_ExplicitInstantiationDefinition)
1950 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
1951 }
1952
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001953 return Invalid;
1954}
1955
Richard Smith4b38ded2012-03-14 23:13:10 +00001956/// \brief Instantiate the definition of an enum from a given pattern.
1957///
1958/// \param PointOfInstantiation The point of instantiation within the
1959/// source code.
1960/// \param Instantiation is the declaration whose definition is being
1961/// instantiated. This will be a member enumeration of a class
1962/// temploid specialization, or a local enumeration within a
1963/// function temploid specialization.
1964/// \param Pattern The templated declaration from which the instantiation
1965/// occurs.
1966/// \param TemplateArgs The template arguments to be substituted into
1967/// the pattern.
1968/// \param TSK The kind of implicit or explicit instantiation to perform.
1969///
1970/// \return \c true if an error occurred, \c false otherwise.
1971bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
1972 EnumDecl *Instantiation, EnumDecl *Pattern,
1973 const MultiLevelTemplateArgumentList &TemplateArgs,
1974 TemplateSpecializationKind TSK) {
1975 EnumDecl *PatternDef = Pattern->getDefinition();
1976 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1977 Instantiation->getInstantiatedFromMemberEnum(),
1978 Pattern, PatternDef, TSK,/*Complain*/true))
1979 return true;
1980 Pattern = PatternDef;
1981
1982 // Record the point of instantiation.
1983 if (MemberSpecializationInfo *MSInfo
1984 = Instantiation->getMemberSpecializationInfo()) {
1985 MSInfo->setTemplateSpecializationKind(TSK);
1986 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1987 }
1988
1989 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1990 if (Inst)
1991 return true;
1992
1993 // Enter the scope of this instantiation. We don't use
1994 // PushDeclContext because we don't have a scope.
1995 ContextRAII SavedContext(*this, Instantiation);
1996 EnterExpressionEvaluationContext EvalContext(*this,
1997 Sema::PotentiallyEvaluated);
1998
1999 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2000
2001 // Pull attributes from the pattern onto the instantiation.
2002 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2003
2004 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2005 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2006
2007 // Exit the scope of this instantiation.
2008 SavedContext.pop();
2009
2010 return Instantiation->isInvalidDecl();
2011}
2012
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002013namespace {
2014 /// \brief A partial specialization whose template arguments have matched
2015 /// a given template-id.
2016 struct PartialSpecMatchResult {
2017 ClassTemplatePartialSpecializationDecl *Partial;
2018 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002019 };
2020}
2021
Mike Stump11289f42009-09-09 15:08:12 +00002022bool
Douglas Gregor463421d2009-03-03 04:44:36 +00002023Sema::InstantiateClassTemplateSpecialization(
Douglas Gregoref6ab412009-10-27 06:26:26 +00002024 SourceLocation PointOfInstantiation,
Douglas Gregor463421d2009-03-03 04:44:36 +00002025 ClassTemplateSpecializationDecl *ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002026 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002027 bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002028 // Perform the actual instantiation on the canonical declaration.
2029 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002030 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor463421d2009-03-03 04:44:36 +00002031
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002032 // Check whether we have already instantiated or specialized this class
2033 // template specialization.
2034 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2035 if (ClassTemplateSpec->getSpecializationKind() ==
2036 TSK_ExplicitInstantiationDeclaration &&
2037 TSK == TSK_ExplicitInstantiationDefinition) {
2038 // An explicit instantiation definition follows an explicit instantiation
2039 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2040 // explicit instantiation.
2041 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor88d292c2010-05-13 16:44:06 +00002042
2043 // If this is an explicit instantiation definition, mark the
2044 // vtable as used.
Nico Weber3ffc4c92011-12-20 20:32:49 +00002045 if (TSK == TSK_ExplicitInstantiationDefinition &&
2046 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002047 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2048
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002049 return false;
2050 }
2051
2052 // We can only instantiate something that hasn't already been
2053 // instantiated or specialized. Fail without any diagnostics: our
2054 // caller will provide an error message.
Douglas Gregor463421d2009-03-03 04:44:36 +00002055 return true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002056 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002057
Douglas Gregor00a511f2009-09-15 16:51:42 +00002058 if (ClassTemplateSpec->isInvalidDecl())
2059 return true;
2060
Douglas Gregor463421d2009-03-03 04:44:36 +00002061 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor01afeef2009-08-28 20:31:08 +00002062 CXXRecordDecl *Pattern = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002063
Douglas Gregor170bc422009-06-12 22:31:52 +00002064 // C++ [temp.class.spec.match]p1:
2065 // When a class template is used in a context that requires an
2066 // instantiation of the class, it is necessary to determine
2067 // whether the instantiation is to be generated using the primary
2068 // template or one of the partial specializations. This is done by
2069 // matching the template arguments of the class template
2070 // specialization with the template argument lists of the partial
2071 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002072 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002073 SmallVector<MatchResult, 4> Matched;
2074 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002075 Template->getPartialSpecializations(PartialSpecs);
2076 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2077 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
John McCallbc077cf2010-02-08 23:07:23 +00002078 TemplateDeductionInfo Info(Context, PointOfInstantiation);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002079 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002080 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002081 ClassTemplateSpec->getTemplateArgs(),
2082 Info)) {
2083 // FIXME: Store the failed-deduction information for use in
2084 // diagnostics, later.
2085 (void)Result;
2086 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002087 Matched.push_back(PartialSpecMatchResult());
2088 Matched.back().Partial = Partial;
2089 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002090 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002091 }
2092
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002093 // If we're dealing with a member template where the template parameters
2094 // have been instantiated, this provides the original template parameters
2095 // from which the member template's parameters were instantiated.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002096 SmallVector<const NamedDecl *, 4> InstantiatedTemplateParameters;
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002097
Douglas Gregor21610382009-10-29 00:04:11 +00002098 if (Matched.size() >= 1) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002099 SmallVector<MatchResult, 4>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002100 if (Matched.size() == 1) {
2101 // -- If exactly one matching specialization is found, the
2102 // instantiation is generated from that specialization.
2103 // We don't need to do anything for this.
2104 } else {
2105 // -- If more than one matching specialization is found, the
2106 // partial order rules (14.5.4.2) are used to determine
2107 // whether one of the specializations is more specialized
2108 // than the others. If none of the specializations is more
2109 // specialized than all of the other matching
2110 // specializations, then the use of the class template is
2111 // ambiguous and the program is ill-formed.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002112 for (SmallVector<MatchResult, 4>::iterator P = Best + 1,
Douglas Gregor21610382009-10-29 00:04:11 +00002113 PEnd = Matched.end();
2114 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002115 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002116 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002117 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002118 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002119 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002120
Douglas Gregor21610382009-10-29 00:04:11 +00002121 // Determine if the best partial specialization is more specialized than
2122 // the others.
2123 bool Ambiguous = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002124 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregorbe999392009-09-15 16:23:51 +00002125 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002126 P != PEnd; ++P) {
2127 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002128 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002129 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002130 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002131 Ambiguous = true;
2132 break;
2133 }
2134 }
2135
2136 if (Ambiguous) {
2137 // Partial ordering did not produce a clear winner. Complain.
2138 ClassTemplateSpec->setInvalidDecl();
2139 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2140 << ClassTemplateSpec;
2141
2142 // Print the matching partial specializations.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002143 for (SmallVector<MatchResult, 4>::iterator P = Matched.begin(),
Douglas Gregor21610382009-10-29 00:04:11 +00002144 PEnd = Matched.end();
2145 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002146 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2147 << getTemplateArgumentBindingsText(
2148 P->Partial->getTemplateParameters(),
2149 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002150
Douglas Gregor21610382009-10-29 00:04:11 +00002151 return true;
2152 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002153 }
2154
2155 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002156 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002157 while (OrigPartialSpec->getInstantiatedFromMember()) {
2158 // If we've found an explicit specialization of this class template,
2159 // stop here and use that as the pattern.
2160 if (OrigPartialSpec->isMemberSpecialization())
2161 break;
2162
2163 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2164 }
2165
2166 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002167 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002168 } else {
2169 // -- If no matches are found, the instantiation is generated
2170 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002171 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002172 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2173 // If we've found an explicit specialization of this class template,
2174 // stop here and use that as the pattern.
2175 if (OrigTemplate->isMemberSpecialization())
2176 break;
2177
Douglas Gregor01afeef2009-08-28 20:31:08 +00002178 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002179 }
2180
Douglas Gregor01afeef2009-08-28 20:31:08 +00002181 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002182 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002183
Douglas Gregoref6ab412009-10-27 06:26:26 +00002184 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2185 Pattern,
2186 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002187 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002188 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002189
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002190 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002191}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002192
John McCall76d824f2009-08-25 22:02:44 +00002193/// \brief Instantiates the definitions of all of the member
2194/// of the given class, which is an instantiation of a class template
2195/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002196void
2197Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002198 CXXRecordDecl *Instantiation,
2199 const MultiLevelTemplateArgumentList &TemplateArgs,
2200 TemplateSpecializationKind TSK) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002201 for (DeclContext::decl_iterator D = Instantiation->decls_begin(),
2202 DEnd = Instantiation->decls_end();
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002203 D != DEnd; ++D) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002204 bool SuppressNew = false;
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002205 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(*D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002206 if (FunctionDecl *Pattern
2207 = Function->getInstantiatedFromMemberFunction()) {
2208 MemberSpecializationInfo *MSInfo
2209 = Function->getMemberSpecializationInfo();
2210 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002211 if (MSInfo->getTemplateSpecializationKind()
2212 == TSK_ExplicitSpecialization)
2213 continue;
2214
Douglas Gregor1d957a32009-10-27 18:42:08 +00002215 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2216 Function,
2217 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002218 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002219 SuppressNew) ||
2220 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002221 continue;
2222
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002223 if (Function->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002224 continue;
2225
2226 if (TSK == TSK_ExplicitInstantiationDefinition) {
2227 // C++0x [temp.explicit]p8:
2228 // An explicit instantiation definition that names a class template
2229 // specialization explicitly instantiates the class template
2230 // specialization and is only an explicit instantiation definition
2231 // of members whose definition is visible at the point of
2232 // instantiation.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002233 if (!Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002234 continue;
2235
2236 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2237
2238 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2239 } else {
2240 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2241 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002242 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002243 } else if (VarDecl *Var = dyn_cast<VarDecl>(*D)) {
Douglas Gregor86d142a2009-10-08 07:24:58 +00002244 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002245 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2246 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002247 if (MSInfo->getTemplateSpecializationKind()
2248 == TSK_ExplicitSpecialization)
2249 continue;
2250
Douglas Gregor1d957a32009-10-27 18:42:08 +00002251 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2252 Var,
2253 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002254 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002255 SuppressNew) ||
2256 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002257 continue;
2258
Douglas Gregor1d957a32009-10-27 18:42:08 +00002259 if (TSK == TSK_ExplicitInstantiationDefinition) {
2260 // C++0x [temp.explicit]p8:
2261 // An explicit instantiation definition that names a class template
2262 // specialization explicitly instantiates the class template
2263 // specialization and is only an explicit instantiation definition
2264 // of members whose definition is visible at the point of
2265 // instantiation.
2266 if (!Var->getInstantiatedFromStaticDataMember()
2267 ->getOutOfLineDefinition())
2268 continue;
2269
2270 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002271 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002272 } else {
2273 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2274 }
2275 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002276 } else if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(*D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002277 // Always skip the injected-class-name, along with any
2278 // redeclarations of nested classes, since both would cause us
2279 // to try to instantiate the members of a class twice.
Douglas Gregorec9fd132012-01-14 16:38:05 +00002280 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregord801b062009-10-07 23:56:10 +00002281 continue;
2282
Douglas Gregor1d957a32009-10-27 18:42:08 +00002283 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2284 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002285
2286 if (MSInfo->getTemplateSpecializationKind()
2287 == TSK_ExplicitSpecialization)
2288 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002289
Douglas Gregor1d957a32009-10-27 18:42:08 +00002290 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2291 Record,
2292 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002293 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002294 SuppressNew) ||
2295 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002296 continue;
2297
Douglas Gregor1d957a32009-10-27 18:42:08 +00002298 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2299 assert(Pattern && "Missing instantiated-from-template information");
2300
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002301 if (!Record->getDefinition()) {
2302 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002303 // C++0x [temp.explicit]p8:
2304 // An explicit instantiation definition that names a class template
2305 // specialization explicitly instantiates the class template
2306 // specialization and is only an explicit instantiation definition
2307 // of members whose definition is visible at the point of
2308 // instantiation.
2309 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2310 MSInfo->setTemplateSpecializationKind(TSK);
2311 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2312 }
2313
2314 continue;
2315 }
2316
2317 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002318 TemplateArgs,
2319 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002320 } else {
2321 if (TSK == TSK_ExplicitInstantiationDefinition &&
2322 Record->getTemplateSpecializationKind() ==
2323 TSK_ExplicitInstantiationDeclaration) {
2324 Record->setTemplateSpecializationKind(TSK);
2325 MarkVTableUsed(PointOfInstantiation, Record, true);
2326 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002327 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002328
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002329 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002330 if (Pattern)
2331 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2332 TSK);
Richard Smith4b38ded2012-03-14 23:13:10 +00002333 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(*D)) {
2334 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2335 assert(MSInfo && "No member specialization information?");
2336
2337 if (MSInfo->getTemplateSpecializationKind()
2338 == TSK_ExplicitSpecialization)
2339 continue;
2340
2341 if (CheckSpecializationInstantiationRedecl(
2342 PointOfInstantiation, TSK, Enum,
2343 MSInfo->getTemplateSpecializationKind(),
2344 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2345 SuppressNew)
2346 continue;
2347
2348 if (Enum->getDefinition())
2349 continue;
2350
2351 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2352 assert(Pattern && "Missing instantiated-from-template information");
2353
2354 if (TSK == TSK_ExplicitInstantiationDefinition) {
2355 if (!Pattern->getDefinition())
2356 continue;
2357
2358 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2359 } else {
2360 MSInfo->setTemplateSpecializationKind(TSK);
2361 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2362 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002363 }
2364 }
2365}
2366
2367/// \brief Instantiate the definitions of all of the members of the
2368/// given class template specialization, which was named as part of an
2369/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002370void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002371Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002372 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002373 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2374 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002375 // C++0x [temp.explicit]p7:
2376 // An explicit instantiation that names a class template
2377 // specialization is an explicit instantion of the same kind
2378 // (declaration or definition) of each of its members (not
2379 // including members inherited from base classes) that has not
2380 // been previously explicitly specialized in the translation unit
2381 // containing the explicit instantiation, except as described
2382 // below.
2383 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002384 getTemplateInstantiationArgs(ClassTemplateSpec),
2385 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002386}
2387
John McCalldadc5752010-08-24 06:29:42 +00002388StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002389Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002390 if (!S)
2391 return Owned(S);
2392
2393 TemplateInstantiator Instantiator(*this, TemplateArgs,
2394 SourceLocation(),
2395 DeclarationName());
2396 return Instantiator.TransformStmt(S);
2397}
2398
John McCalldadc5752010-08-24 06:29:42 +00002399ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002400Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002401 if (!E)
2402 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002403
Douglas Gregora16548e2009-08-11 05:31:07 +00002404 TemplateInstantiator Instantiator(*this, TemplateArgs,
2405 SourceLocation(),
2406 DeclarationName());
2407 return Instantiator.TransformExpr(E);
2408}
2409
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002410bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2411 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002412 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002413 if (NumExprs == 0)
2414 return false;
2415
2416 TemplateInstantiator Instantiator(*this, TemplateArgs,
2417 SourceLocation(),
2418 DeclarationName());
2419 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2420}
2421
Douglas Gregor14454802011-02-25 02:25:35 +00002422NestedNameSpecifierLoc
2423Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2424 const MultiLevelTemplateArgumentList &TemplateArgs) {
2425 if (!NNS)
2426 return NestedNameSpecifierLoc();
2427
2428 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2429 DeclarationName());
2430 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2431}
2432
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002433/// \brief Do template substitution on declaration name info.
2434DeclarationNameInfo
2435Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2436 const MultiLevelTemplateArgumentList &TemplateArgs) {
2437 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2438 NameInfo.getName());
2439 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2440}
2441
Douglas Gregoraa594892009-03-31 18:38:02 +00002442TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002443Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2444 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002445 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002446 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2447 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002448 CXXScopeSpec SS;
2449 SS.Adopt(QualifierLoc);
2450 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002451}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002452
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002453bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2454 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002455 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002456 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2457 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002458
2459 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002460}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002461
Douglas Gregorf3010112011-01-07 16:43:16 +00002462llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2463LocalInstantiationScope::findInstantiationOf(const Decl *D) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002464 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002465 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002466
Douglas Gregor14cf7522010-04-30 18:55:50 +00002467 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002468 const Decl *CheckD = D;
2469 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002470 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002471 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002472 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002473
2474 // If this is a tag declaration, it's possible that we need to look for
2475 // a previous declaration.
2476 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002477 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002478 else
2479 CheckD = 0;
2480 } while (CheckD);
2481
Douglas Gregor14cf7522010-04-30 18:55:50 +00002482 // If we aren't combined with our outer scope, we're done.
2483 if (!Current->CombineWithOuterScope)
2484 break;
2485 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002486
2487 // If we didn't find the decl, then we either have a sema bug, or we have a
2488 // forward reference to a label declaration. Return null to indicate that
2489 // we have an uninstantiated label.
2490 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor14cf7522010-04-30 18:55:50 +00002491 return 0;
2492}
2493
John McCall19c1bfd2010-08-25 05:32:35 +00002494void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
Douglas Gregorf3010112011-01-07 16:43:16 +00002495 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002496 if (Stored.isNull())
2497 Stored = Inst;
2498 else if (Stored.is<Decl *>()) {
2499 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2500 Stored = Inst;
2501 } else
2502 LocalDecls[D].get<DeclArgumentPack *>()->push_back(Inst);
Douglas Gregor14cf7522010-04-30 18:55:50 +00002503}
Douglas Gregorf3010112011-01-07 16:43:16 +00002504
2505void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2506 Decl *Inst) {
2507 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2508 Pack->push_back(Inst);
2509}
2510
2511void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2512 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2513 assert(Stored.isNull() && "Already instantiated this local");
2514 DeclArgumentPack *Pack = new DeclArgumentPack;
2515 Stored = Pack;
2516 ArgumentPacks.push_back(Pack);
2517}
2518
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002519void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2520 const TemplateArgument *ExplicitArgs,
2521 unsigned NumExplicitArgs) {
2522 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2523 "Already have a partially-substituted pack");
2524 assert((!PartiallySubstitutedPack
2525 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2526 "Wrong number of arguments in partially-substituted pack");
2527 PartiallySubstitutedPack = Pack;
2528 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2529 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2530}
2531
2532NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2533 const TemplateArgument **ExplicitArgs,
2534 unsigned *NumExplicitArgs) const {
2535 if (ExplicitArgs)
2536 *ExplicitArgs = 0;
2537 if (NumExplicitArgs)
2538 *NumExplicitArgs = 0;
2539
2540 for (const LocalInstantiationScope *Current = this; Current;
2541 Current = Current->Outer) {
2542 if (Current->PartiallySubstitutedPack) {
2543 if (ExplicitArgs)
2544 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2545 if (NumExplicitArgs)
2546 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2547
2548 return Current->PartiallySubstitutedPack;
2549 }
2550
2551 if (!Current->CombineWithOuterScope)
2552 break;
2553 }
2554
2555 return 0;
2556}