blob: 7b3fc77eb05e81ae5f97222cdbd5a88b579544be [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000022#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000023#include "clang/Sema/Lookup.h"
John McCallde6836a2010-08-24 07:21:54 +000024#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000025#include "clang/Sema/TemplateDeduction.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000026
27using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000028using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000029
Douglas Gregor4ea568f2009-03-10 18:03:33 +000030//===----------------------------------------------------------------------===/
31// Template Instantiation Support
32//===----------------------------------------------------------------------===/
33
Douglas Gregor01afeef2009-08-28 20:31:08 +000034/// \brief Retrieve the template argument list(s) that should be used to
35/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000036///
37/// \param D the declaration for which we are computing template instantiation
38/// arguments.
39///
40/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000041///
42/// \param RelativeToPrimary true if we should get the template
43/// arguments relative to the primary template, even when we're
44/// dealing with a specialization. This is only relevant for function
45/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000046///
47/// \param Pattern If non-NULL, indicates the pattern from which we will be
48/// instantiating the definition of the given declaration, \p D. This is
49/// used to determine the proper set of template instantiation arguments for
50/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000051MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000052Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000053 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000054 bool RelativeToPrimary,
55 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000056 // Accumulate the set of template argument lists in this structure.
57 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000058
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000059 if (Innermost)
60 Result.addOuterTemplateArguments(Innermost);
61
Douglas Gregora654dd82009-08-28 17:37:35 +000062 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000063 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000064 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000065
66 // Add template arguments from a variable template instantiation.
67 if (VarTemplateSpecializationDecl *Spec =
68 dyn_cast<VarTemplateSpecializationDecl>(D)) {
69 // We're done when we hit an explicit specialization.
70 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
71 !isa<VarTemplatePartialSpecializationDecl>(Spec))
72 return Result;
73
74 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
75
76 // If this variable template specialization was instantiated from a
77 // specialized member that is a variable template, we're done.
78 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000079 llvm::PointerUnion<VarTemplateDecl*,
80 VarTemplatePartialSpecializationDecl*> Specialized
81 = Spec->getSpecializedTemplateOrPartial();
82 if (VarTemplatePartialSpecializationDecl *Partial =
83 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
84 if (Partial->isMemberSpecialization())
85 return Result;
86 } else {
87 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
88 if (Tmpl->isMemberSpecialization())
89 return Result;
90 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000091 }
92
Douglas Gregor55462622011-06-15 14:20:42 +000093 // If we have a template template parameter with translation unit context,
94 // then we're performing substitution into a default template argument of
95 // this template template parameter before we've constructed the template
96 // that will own this template template parameter. In this case, we
97 // use empty template parameter lists for all of the outer templates
98 // to avoid performing any substitutions.
99 if (Ctx->isTranslationUnit()) {
100 if (TemplateTemplateParmDecl *TTP
101 = dyn_cast<TemplateTemplateParmDecl>(D)) {
102 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000103 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000104 return Result;
105 }
106 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000107 }
108
John McCall970d5302009-08-29 03:16:09 +0000109 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000110 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000111 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000112 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
113 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000114 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
115 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000116 break;
Mike Stump11289f42009-09-09 15:08:12 +0000117
Douglas Gregora654dd82009-08-28 17:37:35 +0000118 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000119
120 // If this class template specialization was instantiated from a
121 // specialized member that is a class template, we're done.
122 assert(Spec->getSpecializedTemplate() && "No class template?");
123 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
124 break;
Mike Stump11289f42009-09-09 15:08:12 +0000125 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000126 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000127 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000128 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000129 (Function->getTemplateSpecializationKind() ==
130 TSK_ExplicitSpecialization &&
131 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000132 break;
133
Douglas Gregora654dd82009-08-28 17:37:35 +0000134 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000135 = Function->getTemplateSpecializationArgs()) {
136 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000137 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000138
Douglas Gregorcf915552009-10-13 16:30:37 +0000139 // If this function was instantiated from a specialized member that is
140 // a function template, we're done.
141 assert(Function->getPrimaryTemplate() && "No function template?");
142 if (Function->getPrimaryTemplate()->isMemberSpecialization())
143 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000144
145 // If this function is a generic lambda specialization, we are done.
146 if (isGenericLambdaCallOperatorSpecialization(Function))
147 break;
148
Douglas Gregor43669f82011-03-05 17:54:25 +0000149 } else if (FunctionTemplateDecl *FunTmpl
150 = Function->getDescribedFunctionTemplate()) {
151 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000152 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000153 }
154
John McCall970d5302009-08-29 03:16:09 +0000155 // If this is a friend declaration and it declares an entity at
156 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000157 // instead of its semantic parent, unless of course the pattern we're
158 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000159 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000160 Function->getDeclContext()->isFileContext() &&
161 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000162 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000163 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000164 continue;
165 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000166 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
167 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
168 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000169 const TemplateSpecializationType *TST =
170 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
171 Result.addOuterTemplateArguments(
172 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000173 if (ClassTemplate->isMemberSpecialization())
174 break;
175 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000176 }
John McCall970d5302009-08-29 03:16:09 +0000177
178 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000179 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000180 }
Mike Stump11289f42009-09-09 15:08:12 +0000181
Douglas Gregora654dd82009-08-28 17:37:35 +0000182 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000183}
184
Douglas Gregor84d49a22009-11-11 21:54:23 +0000185bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
186 switch (Kind) {
187 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000188 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000189 case DefaultTemplateArgumentInstantiation:
190 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000191 case ExplicitTemplateArgumentSubstitution:
192 case DeducedTemplateArgumentSubstitution:
193 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000194 return true;
195
Douglas Gregor84d49a22009-11-11 21:54:23 +0000196 case DefaultTemplateArgumentChecking:
197 return false;
198 }
David Blaikie8a40f702012-01-17 06:56:22 +0000199
200 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000201}
202
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000203Sema::InstantiatingTemplate::
204InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor85673582009-05-18 17:01:57 +0000205 Decl *Entity,
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000206 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000207 : SemaRef(SemaRef),
208 SavedInNonInstantiationSFINAEContext(
209 SemaRef.InNonInstantiationSFINAEContext)
210{
Douglas Gregor79cf6032009-03-10 20:44:00 +0000211 Invalid = CheckInstantiationDepth(PointOfInstantiation,
212 InstantiationRange);
213 if (!Invalid) {
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000214 ActiveTemplateInstantiation Inst;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000215 Inst.Kind = ActiveTemplateInstantiation::TemplateInstantiation;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000216 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000217 Inst.Entity = Entity;
Douglas Gregorc9220832009-03-12 18:36:18 +0000218 Inst.TemplateArgs = 0;
219 Inst.NumTemplateArgs = 0;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000220 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000221 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000222 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor79cf6032009-03-10 20:44:00 +0000223 }
224}
225
Richard Smithf623c962012-04-17 00:58:00 +0000226Sema::InstantiatingTemplate::
227InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
228 FunctionDecl *Entity, ExceptionSpecification,
229 SourceRange InstantiationRange)
230 : SemaRef(SemaRef),
231 SavedInNonInstantiationSFINAEContext(
232 SemaRef.InNonInstantiationSFINAEContext)
233{
234 Invalid = CheckInstantiationDepth(PointOfInstantiation,
235 InstantiationRange);
236 if (!Invalid) {
237 ActiveTemplateInstantiation Inst;
238 Inst.Kind = ActiveTemplateInstantiation::ExceptionSpecInstantiation;
239 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000240 Inst.Entity = Entity;
Richard Smithf623c962012-04-17 00:58:00 +0000241 Inst.TemplateArgs = 0;
242 Inst.NumTemplateArgs = 0;
243 Inst.InstantiationRange = InstantiationRange;
244 SemaRef.InNonInstantiationSFINAEContext = false;
245 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
246 }
247}
248
Richard Smith80934652012-07-16 01:09:10 +0000249Sema::InstantiatingTemplate::
250InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
251 TemplateDecl *Template,
252 ArrayRef<TemplateArgument> TemplateArgs,
253 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000254 : SemaRef(SemaRef),
255 SavedInNonInstantiationSFINAEContext(
256 SemaRef.InNonInstantiationSFINAEContext)
257{
Douglas Gregor79cf6032009-03-10 20:44:00 +0000258 Invalid = CheckInstantiationDepth(PointOfInstantiation,
259 InstantiationRange);
260 if (!Invalid) {
261 ActiveTemplateInstantiation Inst;
Mike Stump11289f42009-09-09 15:08:12 +0000262 Inst.Kind
Douglas Gregor79cf6032009-03-10 20:44:00 +0000263 = ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation;
264 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000265 Inst.Entity = Template;
Richard Smith80934652012-07-16 01:09:10 +0000266 Inst.TemplateArgs = TemplateArgs.data();
267 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000268 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000269 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000270 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000271 }
272}
273
Richard Smith80934652012-07-16 01:09:10 +0000274Sema::InstantiatingTemplate::
275InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
276 FunctionTemplateDecl *FunctionTemplate,
277 ArrayRef<TemplateArgument> TemplateArgs,
278 ActiveTemplateInstantiation::InstantiationKind Kind,
279 sema::TemplateDeductionInfo &DeductionInfo,
280 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000281 : SemaRef(SemaRef),
282 SavedInNonInstantiationSFINAEContext(
283 SemaRef.InNonInstantiationSFINAEContext)
284{
Richard Smith8a874c92012-07-08 02:38:24 +0000285 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000286 if (!Invalid) {
287 ActiveTemplateInstantiation Inst;
288 Inst.Kind = Kind;
289 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000290 Inst.Entity = FunctionTemplate;
Richard Smith80934652012-07-16 01:09:10 +0000291 Inst.TemplateArgs = TemplateArgs.data();
292 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000293 Inst.DeductionInfo = &DeductionInfo;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000294 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000295 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000296 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregor84d49a22009-11-11 21:54:23 +0000297
298 if (!Inst.isInstantiationRecord())
299 ++SemaRef.NonInstantiationEntries;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000300 }
301}
302
Richard Smith80934652012-07-16 01:09:10 +0000303Sema::InstantiatingTemplate::
304InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
305 ClassTemplatePartialSpecializationDecl *PartialSpec,
306 ArrayRef<TemplateArgument> TemplateArgs,
307 sema::TemplateDeductionInfo &DeductionInfo,
308 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000309 : SemaRef(SemaRef),
310 SavedInNonInstantiationSFINAEContext(
311 SemaRef.InNonInstantiationSFINAEContext)
312{
Richard Smith8a874c92012-07-08 02:38:24 +0000313 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
314 if (!Invalid) {
315 ActiveTemplateInstantiation Inst;
316 Inst.Kind = ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
317 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000318 Inst.Entity = PartialSpec;
Richard Smith80934652012-07-16 01:09:10 +0000319 Inst.TemplateArgs = TemplateArgs.data();
320 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smith8a874c92012-07-08 02:38:24 +0000321 Inst.DeductionInfo = &DeductionInfo;
322 Inst.InstantiationRange = InstantiationRange;
323 SemaRef.InNonInstantiationSFINAEContext = false;
324 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
325 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000326}
327
Larisse Voufo39a1e502013-08-06 01:03:05 +0000328Sema::InstantiatingTemplate::InstantiatingTemplate(
329 Sema &SemaRef, SourceLocation PointOfInstantiation,
330 VarTemplatePartialSpecializationDecl *PartialSpec,
331 ArrayRef<TemplateArgument> TemplateArgs,
332 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
333 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
334 SemaRef.InNonInstantiationSFINAEContext) {
335 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
336 if (!Invalid) {
337 ActiveTemplateInstantiation Inst;
338 Inst.Kind =
339 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution;
340 Inst.PointOfInstantiation = PointOfInstantiation;
341 Inst.Entity = PartialSpec;
342 Inst.TemplateArgs = TemplateArgs.data();
343 Inst.NumTemplateArgs = TemplateArgs.size();
344 Inst.DeductionInfo = &DeductionInfo;
345 Inst.InstantiationRange = InstantiationRange;
346 SemaRef.InNonInstantiationSFINAEContext = false;
347 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
348 }
349}
350
Richard Smith80934652012-07-16 01:09:10 +0000351Sema::InstantiatingTemplate::
352InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
353 ParmVarDecl *Param,
354 ArrayRef<TemplateArgument> TemplateArgs,
355 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000356 : SemaRef(SemaRef),
357 SavedInNonInstantiationSFINAEContext(
358 SemaRef.InNonInstantiationSFINAEContext)
359{
Douglas Gregore62e6a02009-11-11 19:13:48 +0000360 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
Anders Carlsson657bad42009-09-05 05:14:19 +0000361 if (!Invalid) {
362 ActiveTemplateInstantiation Inst;
363 Inst.Kind
364 = ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
Douglas Gregore62e6a02009-11-11 19:13:48 +0000365 Inst.PointOfInstantiation = PointOfInstantiation;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000366 Inst.Entity = Param;
Richard Smith80934652012-07-16 01:09:10 +0000367 Inst.TemplateArgs = TemplateArgs.data();
368 Inst.NumTemplateArgs = TemplateArgs.size();
Anders Carlsson657bad42009-09-05 05:14:19 +0000369 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000370 SemaRef.InNonInstantiationSFINAEContext = false;
Anders Carlsson657bad42009-09-05 05:14:19 +0000371 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000372 }
373}
374
375Sema::InstantiatingTemplate::
376InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith80934652012-07-16 01:09:10 +0000377 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
378 ArrayRef<TemplateArgument> TemplateArgs,
379 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000380 : SemaRef(SemaRef),
381 SavedInNonInstantiationSFINAEContext(
382 SemaRef.InNonInstantiationSFINAEContext)
383{
Richard Smith8a874c92012-07-08 02:38:24 +0000384 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
385 if (!Invalid) {
386 ActiveTemplateInstantiation Inst;
387 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
388 Inst.PointOfInstantiation = PointOfInstantiation;
389 Inst.Template = Template;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000390 Inst.Entity = Param;
Richard Smith80934652012-07-16 01:09:10 +0000391 Inst.TemplateArgs = TemplateArgs.data();
392 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smith8a874c92012-07-08 02:38:24 +0000393 Inst.InstantiationRange = InstantiationRange;
394 SemaRef.InNonInstantiationSFINAEContext = false;
395 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
396 }
Douglas Gregore62e6a02009-11-11 19:13:48 +0000397}
398
399Sema::InstantiatingTemplate::
400InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith80934652012-07-16 01:09:10 +0000401 NamedDecl *Template, TemplateTemplateParmDecl *Param,
402 ArrayRef<TemplateArgument> TemplateArgs,
403 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000404 : SemaRef(SemaRef),
405 SavedInNonInstantiationSFINAEContext(
406 SemaRef.InNonInstantiationSFINAEContext)
407{
Richard Smith8a874c92012-07-08 02:38:24 +0000408 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
409 if (!Invalid) {
410 ActiveTemplateInstantiation Inst;
411 Inst.Kind = ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution;
412 Inst.PointOfInstantiation = PointOfInstantiation;
413 Inst.Template = Template;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000414 Inst.Entity = Param;
Richard Smith80934652012-07-16 01:09:10 +0000415 Inst.TemplateArgs = TemplateArgs.data();
416 Inst.NumTemplateArgs = TemplateArgs.size();
Richard Smith8a874c92012-07-08 02:38:24 +0000417 Inst.InstantiationRange = InstantiationRange;
418 SemaRef.InNonInstantiationSFINAEContext = false;
419 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
420 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000421}
422
423Sema::InstantiatingTemplate::
424InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith80934652012-07-16 01:09:10 +0000425 TemplateDecl *Template, NamedDecl *Param,
426 ArrayRef<TemplateArgument> TemplateArgs,
427 SourceRange InstantiationRange)
Douglas Gregoredb76852011-01-27 22:31:44 +0000428 : SemaRef(SemaRef),
429 SavedInNonInstantiationSFINAEContext(
430 SemaRef.InNonInstantiationSFINAEContext)
431{
Douglas Gregor84d49a22009-11-11 21:54:23 +0000432 Invalid = false;
433
434 ActiveTemplateInstantiation Inst;
435 Inst.Kind = ActiveTemplateInstantiation::DefaultTemplateArgumentChecking;
436 Inst.PointOfInstantiation = PointOfInstantiation;
437 Inst.Template = Template;
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000438 Inst.Entity = Param;
Richard Smith80934652012-07-16 01:09:10 +0000439 Inst.TemplateArgs = TemplateArgs.data();
440 Inst.NumTemplateArgs = TemplateArgs.size();
Douglas Gregor84d49a22009-11-11 21:54:23 +0000441 Inst.InstantiationRange = InstantiationRange;
Douglas Gregoredb76852011-01-27 22:31:44 +0000442 SemaRef.InNonInstantiationSFINAEContext = false;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000443 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
444
445 assert(!Inst.isInstantiationRecord());
446 ++SemaRef.NonInstantiationEntries;
Anders Carlsson657bad42009-09-05 05:14:19 +0000447}
448
Douglas Gregor85673582009-05-18 17:01:57 +0000449void Sema::InstantiatingTemplate::Clear() {
450 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000451 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
452 assert(SemaRef.NonInstantiationEntries > 0);
453 --SemaRef.NonInstantiationEntries;
454 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000455 SemaRef.InNonInstantiationSFINAEContext
456 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000457
458 // Name lookup no longer looks in this template's defining module.
459 assert(SemaRef.ActiveTemplateInstantiations.size() >=
460 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
461 "forgot to remove a lookup module for a template instantiation");
462 if (SemaRef.ActiveTemplateInstantiations.size() ==
463 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
464 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
465 SemaRef.LookupModulesCache.erase(M);
466 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
467 }
468
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000469 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000470 Invalid = true;
471 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000472}
473
Douglas Gregor79cf6032009-03-10 20:44:00 +0000474bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
475 SourceLocation PointOfInstantiation,
476 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000477 assert(SemaRef.NonInstantiationEntries <=
478 SemaRef.ActiveTemplateInstantiations.size());
479 if ((SemaRef.ActiveTemplateInstantiations.size() -
480 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000481 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000482 return false;
483
Mike Stump11289f42009-09-09 15:08:12 +0000484 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000485 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000486 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000487 << InstantiationRange;
488 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000489 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000490 return true;
491}
492
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000493/// \brief Prints the current instantiation stack through a series of
494/// notes.
495void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000496 // Determine which template instantiations to skip, if any.
497 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
498 unsigned Limit = Diags.getTemplateBacktraceLimit();
499 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
500 SkipStart = Limit / 2 + Limit % 2;
501 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
502 }
503
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000504 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000505 unsigned InstantiationIdx = 0;
Craig Topper2341c0d2013-07-04 03:08:24 +0000506 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000507 Active = ActiveTemplateInstantiations.rbegin(),
508 ActiveEnd = ActiveTemplateInstantiations.rend();
509 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000510 ++Active, ++InstantiationIdx) {
511 // Skip this instantiation?
512 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
513 if (InstantiationIdx == SkipStart) {
514 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000515 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000516 diag::note_instantiation_contexts_suppressed)
517 << unsigned(ActiveTemplateInstantiations.size() - Limit);
518 }
519 continue;
520 }
521
Douglas Gregor79cf6032009-03-10 20:44:00 +0000522 switch (Active->Kind) {
523 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000524 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000525 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
526 unsigned DiagID = diag::note_template_member_class_here;
527 if (isa<ClassTemplateSpecializationDecl>(Record))
528 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000529 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000530 << Context.getTypeDeclType(Record)
531 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000532 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000533 unsigned DiagID;
534 if (Function->getPrimaryTemplate())
535 DiagID = diag::note_function_template_spec_here;
536 else
537 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000538 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000539 << Function
540 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000541 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000542 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000543 VD->isStaticDataMember()?
544 diag::note_template_static_data_member_def_here
545 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000546 << VD
547 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000548 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
549 Diags.Report(Active->PointOfInstantiation,
550 diag::note_template_enum_def_here)
551 << ED
552 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000553 } else {
554 Diags.Report(Active->PointOfInstantiation,
555 diag::note_template_type_alias_instantiation_here)
556 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000557 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000558 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000559 break;
560 }
561
562 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000563 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000564 SmallVector<char, 128> TemplateArgsStr;
565 llvm::raw_svector_ostream OS(TemplateArgsStr);
566 Template->printName(OS);
567 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000568 Active->TemplateArgs,
Douglas Gregor7de59662009-05-29 20:38:28 +0000569 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000570 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000571 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000572 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000573 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000574 << Active->InstantiationRange;
575 break;
576 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000577
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000578 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000579 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000580 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000581 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000582 << FnTmpl
583 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
584 Active->TemplateArgs,
585 Active->NumTemplateArgs)
586 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000587 break;
588 }
Mike Stump11289f42009-09-09 15:08:12 +0000589
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000590 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000591 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
592 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000593 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000594 diag::note_partial_spec_deduct_instantiation_here)
595 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000596 << getTemplateArgumentBindingsText(
597 PartialSpec->getTemplateParameters(),
598 Active->TemplateArgs,
599 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000600 << Active->InstantiationRange;
601 } else {
602 FunctionTemplateDecl *FnTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000603 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000604 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000605 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000606 << FnTmpl
607 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
608 Active->TemplateArgs,
609 Active->NumTemplateArgs)
610 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000611 }
612 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000613
Anders Carlsson657bad42009-09-05 05:14:19 +0000614 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000615 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000616 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000617
Benjamin Kramer9170e912013-02-22 15:46:01 +0000618 SmallVector<char, 128> TemplateArgsStr;
619 llvm::raw_svector_ostream OS(TemplateArgsStr);
620 FD->printName(OS);
621 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000622 Active->TemplateArgs,
Anders Carlsson657bad42009-09-05 05:14:19 +0000623 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000624 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000625 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000626 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000627 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000628 << Active->InstantiationRange;
629 break;
630 }
Mike Stump11289f42009-09-09 15:08:12 +0000631
Douglas Gregore62e6a02009-11-11 19:13:48 +0000632 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000633 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000634 std::string Name;
635 if (!Parm->getName().empty())
636 Name = std::string(" '") + Parm->getName().str() + "'";
Douglas Gregorca4686d2011-01-04 23:35:54 +0000637
638 TemplateParameterList *TemplateParams = 0;
639 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
640 TemplateParams = Template->getTemplateParameters();
641 else
642 TemplateParams =
643 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
644 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000645 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000646 diag::note_prior_template_arg_substitution)
647 << isa<TemplateTemplateParmDecl>(Parm)
648 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000649 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000650 Active->TemplateArgs,
651 Active->NumTemplateArgs)
652 << Active->InstantiationRange;
653 break;
654 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000655
656 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Douglas Gregorca4686d2011-01-04 23:35:54 +0000657 TemplateParameterList *TemplateParams = 0;
658 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
659 TemplateParams = Template->getTemplateParameters();
660 else
661 TemplateParams =
662 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
663 ->getTemplateParameters();
664
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000665 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000666 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000667 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000668 Active->TemplateArgs,
669 Active->NumTemplateArgs)
670 << Active->InstantiationRange;
671 break;
672 }
Richard Smithf623c962012-04-17 00:58:00 +0000673
674 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
675 Diags.Report(Active->PointOfInstantiation,
676 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000677 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000678 << Active->InstantiationRange;
679 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000680 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000681 }
682}
683
David Blaikie05785d12013-02-20 22:23:23 +0000684Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000685 if (InNonInstantiationSFINAEContext)
David Blaikie05785d12013-02-20 22:23:23 +0000686 return Optional<TemplateDeductionInfo *>(0);
Douglas Gregoredb76852011-01-27 22:31:44 +0000687
Craig Topper2341c0d2013-07-04 03:08:24 +0000688 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000689 Active = ActiveTemplateInstantiations.rbegin(),
690 ActiveEnd = ActiveTemplateInstantiations.rend();
691 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000692 ++Active)
693 {
Douglas Gregor33834512009-06-14 07:33:30 +0000694 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000695 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000696 // An instantiation of an alias template may or may not be a SFINAE
697 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000698 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000699 break;
700 // Fall through.
701 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000702 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000703 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000704 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000705
Douglas Gregor33834512009-06-14 07:33:30 +0000706 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000707 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000708 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000709 // A default template argument instantiation and substitution into
710 // template parameters with arguments for prior parameters may or may
711 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000712 break;
Mike Stump11289f42009-09-09 15:08:12 +0000713
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000714 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
715 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
716 // We're either substitution explicitly-specified template arguments
717 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000718 assert(Active->DeductionInfo && "Missing deduction info pointer");
719 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000720 }
721 }
722
David Blaikie7a30dc52013-02-21 01:47:18 +0000723 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000724}
725
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000726/// \brief Retrieve the depth and index of a parameter pack.
727static std::pair<unsigned, unsigned>
728getDepthAndIndex(NamedDecl *ND) {
729 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
730 return std::make_pair(TTP->getDepth(), TTP->getIndex());
731
732 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
733 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
734
735 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
736 return std::make_pair(TTP->getDepth(), TTP->getIndex());
737}
738
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000739//===----------------------------------------------------------------------===/
740// Template Instantiation for Types
741//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000742namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000743 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000744 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000745 SourceLocation Loc;
746 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000747
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000748 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000749 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000750
751 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000752 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000753 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000754 DeclarationName Entity)
755 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000756 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000757
Mike Stump11289f42009-09-09 15:08:12 +0000758 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000759 /// transformed.
760 ///
761 /// For the purposes of template instantiation, a type has already been
762 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000763 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000764
Douglas Gregord6ff3322009-08-04 16:50:30 +0000765 /// \brief Returns the location of the entity being instantiated, if known.
766 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000767
Douglas Gregord6ff3322009-08-04 16:50:30 +0000768 /// \brief Returns the name of the entity being instantiated, if any.
769 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000770
Douglas Gregoref6ab412009-10-27 06:26:26 +0000771 /// \brief Sets the "base" location and entity when that
772 /// information is known based on another transformation.
773 void setBase(SourceLocation Loc, DeclarationName Entity) {
774 this->Loc = Loc;
775 this->Entity = Entity;
776 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000777
778 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
779 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000780 ArrayRef<UnexpandedParameterPack> Unexpanded,
781 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000782 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000783 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
784 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000785 TemplateArgs,
786 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000787 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000788 NumExpansions);
789 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000790
Douglas Gregorf3010112011-01-07 16:43:16 +0000791 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
792 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
793 }
794
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000795 TemplateArgument ForgetPartiallySubstitutedPack() {
796 TemplateArgument Result;
797 if (NamedDecl *PartialPack
798 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
799 MultiLevelTemplateArgumentList &TemplateArgs
800 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
801 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000802 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000803 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
804 Result = TemplateArgs(Depth, Index);
805 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
806 }
807 }
808
809 return Result;
810 }
811
812 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
813 if (Arg.isNull())
814 return;
815
816 if (NamedDecl *PartialPack
817 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
818 MultiLevelTemplateArgumentList &TemplateArgs
819 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
820 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000821 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000822 TemplateArgs.setArgument(Depth, Index, Arg);
823 }
824 }
825
Douglas Gregord6ff3322009-08-04 16:50:30 +0000826 /// \brief Transform the given declaration by instantiating a reference to
827 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000828 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000829
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000830 void transformAttrs(Decl *Old, Decl *New) {
831 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
832 }
833
834 void transformedLocalDecl(Decl *Old, Decl *New) {
835 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
836 }
837
Mike Stump11289f42009-09-09 15:08:12 +0000838 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000839 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000840 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000841
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000842 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000843 /// declaration.
844 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
845
Douglas Gregorebe10102009-08-20 07:17:43 +0000846 /// \brief Rebuild the exception declaration and register the declaration
847 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000848 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000849 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000850 SourceLocation StartLoc,
851 SourceLocation NameLoc,
852 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000853
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000854 /// \brief Rebuild the Objective-C exception declaration and register the
855 /// declaration as an instantiated local.
856 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
857 TypeSourceInfo *TSInfo, QualType T);
858
John McCall7f41d982009-09-11 04:59:25 +0000859 /// \brief Check for tag mismatches when instantiating an
860 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000861 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
862 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000863 NestedNameSpecifierLoc QualifierLoc,
864 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000865
Douglas Gregor9db53502011-03-02 18:07:45 +0000866 TemplateName TransformTemplateName(CXXScopeSpec &SS,
867 TemplateName Name,
868 SourceLocation NameLoc,
869 QualType ObjectType = QualType(),
870 NamedDecl *FirstQualifierInScope = 0);
871
John McCalldadc5752010-08-24 06:29:42 +0000872 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
873 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
874 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000875
John McCalldadc5752010-08-24 06:29:42 +0000876 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000877 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000878 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
879 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000880
881 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
882 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
883
884 /// \brief Transform a reference to a function parameter pack.
885 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
886 ParmVarDecl *PD);
887
888 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
889 /// expand a function parameter pack reference which refers to an expanded
890 /// pack.
891 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
892
Douglas Gregor14cf7522010-04-30 18:55:50 +0000893 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000894 FunctionProtoTypeLoc TL);
Douglas Gregor3024f072012-04-16 07:05:22 +0000895 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
896 FunctionProtoTypeLoc TL,
897 CXXRecordDecl *ThisContext,
898 unsigned ThisTypeQuals);
899
Douglas Gregor715e4612011-01-14 22:40:04 +0000900 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000901 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000902 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000903 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000904
Mike Stump11289f42009-09-09 15:08:12 +0000905 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000906 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000907 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000908 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000909
Douglas Gregorada4b792011-01-14 02:55:32 +0000910 /// \brief Transforms an already-substituted template type parameter pack
911 /// into either itself (if we aren't substituting into its pack expansion)
912 /// or the appropriate substituted argument.
913 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
914 SubstTemplateTypeParmPackTypeLoc TL);
915
John McCalldadc5752010-08-24 06:29:42 +0000916 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000917 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCalldadc5752010-08-24 06:29:42 +0000918 ExprResult Result =
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000919 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
920 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000921 return Result;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000922 }
John McCall7c454bb2011-07-15 05:09:51 +0000923
Richard Smith2589b9802012-07-25 03:56:55 +0000924 ExprResult TransformLambdaExpr(LambdaExpr *E) {
925 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
926 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
927 }
928
929 ExprResult TransformLambdaScope(LambdaExpr *E,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000930 CXXMethodDecl *NewCallOperator,
931 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
Faisal Vali2cba1332013-10-23 06:44:28 +0000932 CXXMethodDecl *const OldCallOperator = E->getCallOperator();
933 // In the generic lambda case, we set the NewTemplate to be considered
934 // an "instantiation" of the OldTemplate.
935 if (FunctionTemplateDecl *const NewCallOperatorTemplate =
936 NewCallOperator->getDescribedFunctionTemplate()) {
937
938 FunctionTemplateDecl *const OldCallOperatorTemplate =
939 OldCallOperator->getDescribedFunctionTemplate();
940 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
941 OldCallOperatorTemplate);
942 // Mark the NewCallOperatorTemplate a specialization.
943 NewCallOperatorTemplate->setMemberSpecialization();
944 } else
945 // For a non-generic lambda we set the NewCallOperator to
946 // be an instantiation of the OldCallOperator.
947 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
948 TSK_ImplicitInstantiation);
949
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000950 return inherited::TransformLambdaScope(E, NewCallOperator,
951 InitCaptureExprsAndTypes);
Rafael Espindola4b35f272013-10-04 14:28:51 +0000952 }
David Majnemerb1004102014-03-02 18:46:05 +0000953 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000954 TemplateParameterList *OrigTPL) {
955 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
956
957 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
958 TemplateDeclInstantiator DeclInstantiator(getSema(),
959 /* DeclContext *Owner */ Owner, TemplateArgs);
960 return DeclInstantiator.SubstTemplateParams(OrigTPL);
961 }
John McCall7c454bb2011-07-15 05:09:51 +0000962 private:
963 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
964 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000965 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000966 };
Douglas Gregor04318252009-07-06 15:59:29 +0000967}
968
Douglas Gregor5597ab42010-05-07 23:12:07 +0000969bool TemplateInstantiator::AlreadyTransformed(QualType T) {
970 if (T.isNull())
971 return true;
972
Douglas Gregor678d76c2011-07-01 01:22:09 +0000973 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000974 return false;
975
976 getSema().MarkDeclarationsReferencedInType(Loc, T);
977 return true;
978}
979
Eli Friedman8917ad52013-07-19 19:40:38 +0000980static TemplateArgument
981getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
982 assert(S.ArgumentPackSubstitutionIndex >= 0);
983 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
984 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
985 if (Arg.isPackExpansion())
986 Arg = Arg.getPackExpansionPattern();
987 return Arg;
988}
989
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000990Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000991 if (!D)
992 return 0;
Mike Stump11289f42009-09-09 15:08:12 +0000993
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000994 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000995 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000996 // If the corresponding template argument is NULL or non-existent, it's
997 // because we are performing instantiation from explicitly-specified
998 // template arguments in a function template, but there were some
999 // arguments left unspecified.
1000 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1001 TTP->getPosition()))
1002 return D;
1003
Douglas Gregorf5500772011-01-05 15:48:55 +00001004 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1005
1006 if (TTP->isParameterPack()) {
1007 assert(Arg.getKind() == TemplateArgument::Pack &&
1008 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +00001009 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +00001010 }
1011
1012 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001013 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +00001014 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001015 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001016 }
Mike Stump11289f42009-09-09 15:08:12 +00001017
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001018 // Fall through to find the instantiated declaration for this template
1019 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +00001020 }
Mike Stump11289f42009-09-09 15:08:12 +00001021
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001022 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001023}
1024
Douglas Gregor25289362010-03-01 17:25:41 +00001025Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +00001026 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +00001027 if (!Inst)
1028 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00001029
Douglas Gregorebe10102009-08-20 07:17:43 +00001030 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1031 return Inst;
1032}
1033
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001034NamedDecl *
1035TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1036 SourceLocation Loc) {
1037 // If the first part of the nested-name-specifier was a template type
1038 // parameter, instantiate that type parameter down to a tag type.
1039 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1040 const TemplateTypeParmType *TTP
1041 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001042
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001043 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001044 // FIXME: This needs testing w/ member access expressions.
1045 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1046
1047 if (TTP->isParameterPack()) {
1048 assert(Arg.getKind() == TemplateArgument::Pack &&
1049 "Missing argument pack");
1050
Douglas Gregore1d60df2011-01-14 23:41:42 +00001051 if (getSema().ArgumentPackSubstitutionIndex == -1)
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001052 return 0;
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001053
Eli Friedman8917ad52013-07-19 19:40:38 +00001054 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001055 }
1056
1057 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001058 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001059 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001060
1061 if (const TagType *Tag = T->getAs<TagType>())
1062 return Tag->getDecl();
1063
1064 // The resulting type is not a tag; complain.
1065 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1066 return 0;
1067 }
1068 }
1069
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001070 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001071}
1072
Douglas Gregorebe10102009-08-20 07:17:43 +00001073VarDecl *
1074TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +00001075 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001076 SourceLocation StartLoc,
1077 SourceLocation NameLoc,
1078 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00001079 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001080 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001081 if (Var)
1082 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1083 return Var;
1084}
1085
1086VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1087 TypeSourceInfo *TSInfo,
1088 QualType T) {
1089 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1090 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +00001091 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1092 return Var;
1093}
1094
John McCall7f41d982009-09-11 04:59:25 +00001095QualType
John McCall954b5de2010-11-04 19:04:38 +00001096TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1097 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001098 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001099 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001100 if (const TagType *TT = T->getAs<TagType>()) {
1101 TagDecl* TD = TT->getDecl();
1102
John McCall954b5de2010-11-04 19:04:38 +00001103 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001104
John McCall7f41d982009-09-11 04:59:25 +00001105 IdentifierInfo *Id = TD->getIdentifier();
1106
1107 // TODO: should we even warn on struct/class mismatches for this? Seems
1108 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001109 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001110 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001111 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1112 TagLocation, *Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001113 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1114 << Id
1115 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1116 TD->getKindName());
1117 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1118 }
John McCall7f41d982009-09-11 04:59:25 +00001119 }
1120 }
1121
John McCall954b5de2010-11-04 19:04:38 +00001122 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1123 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001124 QualifierLoc,
1125 T);
John McCall7f41d982009-09-11 04:59:25 +00001126}
1127
Douglas Gregor9db53502011-03-02 18:07:45 +00001128TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1129 TemplateName Name,
1130 SourceLocation NameLoc,
1131 QualType ObjectType,
1132 NamedDecl *FirstQualifierInScope) {
1133 if (TemplateTemplateParmDecl *TTP
1134 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1135 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1136 // If the corresponding template argument is NULL or non-existent, it's
1137 // because we are performing instantiation from explicitly-specified
1138 // template arguments in a function template, but there were some
1139 // arguments left unspecified.
1140 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1141 TTP->getPosition()))
1142 return Name;
1143
1144 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1145
1146 if (TTP->isParameterPack()) {
1147 assert(Arg.getKind() == TemplateArgument::Pack &&
1148 "Missing argument pack");
1149
1150 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1151 // We have the template argument pack to substitute, but we're not
1152 // actually expanding the enclosing pack expansion yet. So, just
1153 // keep the entire argument pack.
1154 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1155 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001156
1157 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001158 }
1159
1160 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001161 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001162
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001163 // We don't ever want to substitute for a qualified template name, since
1164 // the qualifier is handled separately. So, look through the qualified
1165 // template name to its underlying declaration.
1166 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1167 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001168
1169 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001170 return Template;
1171 }
1172 }
1173
1174 if (SubstTemplateTemplateParmPackStorage *SubstPack
1175 = Name.getAsSubstTemplateTemplateParmPack()) {
1176 if (getSema().ArgumentPackSubstitutionIndex == -1)
1177 return Name;
1178
Eli Friedman8917ad52013-07-19 19:40:38 +00001179 TemplateArgument Arg = SubstPack->getArgumentPack();
1180 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1181 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001182 }
1183
1184 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1185 FirstQualifierInScope);
1186}
1187
John McCalldadc5752010-08-24 06:29:42 +00001188ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001189TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001190 if (!E->isTypeDependent())
John McCallc3007a22010-10-26 07:05:15 +00001191 return SemaRef.Owned(E);
Anders Carlsson0b209a82009-09-11 01:22:35 +00001192
Wei Panc354d212013-09-16 13:57:27 +00001193 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001194}
1195
John McCalldadc5752010-08-24 06:29:42 +00001196ExprResult
John McCall13481c52010-02-06 08:42:39 +00001197TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001198 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001199 // If the corresponding template argument is NULL or non-existent, it's
1200 // because we are performing instantiation from explicitly-specified
1201 // template arguments in a function template, but there were some
1202 // arguments left unspecified.
1203 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1204 NTTP->getPosition()))
John McCallc3007a22010-10-26 07:05:15 +00001205 return SemaRef.Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00001206
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001207 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1208 if (NTTP->isParameterPack()) {
1209 assert(Arg.getKind() == TemplateArgument::Pack &&
1210 "Missing argument pack");
1211
1212 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001213 // We have an argument pack, but we can't select a particular argument
1214 // out of it yet. Therefore, we'll build an expression to hold on to that
1215 // argument pack.
1216 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1217 E->getLocation(),
1218 NTTP->getDeclName());
1219 if (TargetType.isNull())
1220 return ExprError();
1221
1222 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1223 NTTP,
1224 E->getLocation(),
1225 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001226 }
1227
Eli Friedman8917ad52013-07-19 19:40:38 +00001228 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001229 }
Mike Stump11289f42009-09-09 15:08:12 +00001230
John McCall7c454bb2011-07-15 05:09:51 +00001231 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1232}
1233
1234ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1235 NonTypeTemplateParmDecl *parm,
1236 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001237 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001238 ExprResult result;
1239 QualType type;
1240
John McCall13481c52010-02-06 08:42:39 +00001241 // The template argument itself might be an expression, in which
1242 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001243 if (arg.getKind() == TemplateArgument::Expression) {
1244 Expr *argExpr = arg.getAsExpr();
1245 result = SemaRef.Owned(argExpr);
1246 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001247
Eli Friedmanb826a002012-09-26 02:36:12 +00001248 } else if (arg.getKind() == TemplateArgument::Declaration ||
1249 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001250 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001251 if (arg.getKind() == TemplateArgument::Declaration) {
1252 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001253
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001254 // Find the instantiation of the template argument. This is
1255 // required for nested templates.
1256 VD = cast_or_null<ValueDecl>(
1257 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1258 if (!VD)
1259 return ExprError();
1260 } else {
1261 // Propagate NULL template argument.
1262 VD = 0;
1263 }
1264
John McCall15dda372010-02-06 10:23:53 +00001265 // Derive the type we want the substituted decl to have. This had
1266 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001267 if (parm->isExpandedParameterPack()) {
1268 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1269 } else if (parm->isParameterPack() &&
1270 isa<PackExpansionType>(parm->getType())) {
1271 type = SemaRef.SubstType(
1272 cast<PackExpansionType>(parm->getType())->getPattern(),
1273 TemplateArgs, loc, parm->getDeclName());
1274 } else {
1275 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1276 loc, parm->getDeclName());
1277 }
1278 assert(!type.isNull() && "type substitution failed for param type");
1279 assert(!type->isDependentType() && "param type still dependent");
1280 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001281
John McCall7c454bb2011-07-15 05:09:51 +00001282 if (!result.isInvalid()) type = result.get()->getType();
1283 } else {
1284 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1285
1286 // Note that this type can be different from the type of 'result',
1287 // e.g. if it's an enum type.
1288 type = arg.getIntegralType();
1289 }
1290 if (result.isInvalid()) return ExprError();
1291
1292 Expr *resultExpr = result.take();
1293 return SemaRef.Owned(new (SemaRef.Context)
1294 SubstNonTypeTemplateParmExpr(type,
1295 resultExpr->getValueKind(),
1296 loc, parm, resultExpr));
John McCall13481c52010-02-06 08:42:39 +00001297}
1298
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001299ExprResult
1300TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1301 SubstNonTypeTemplateParmPackExpr *E) {
1302 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1303 // We aren't expanding the parameter pack, so just return ourselves.
1304 return getSema().Owned(E);
1305 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001306
1307 TemplateArgument Arg = E->getArgumentPack();
1308 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001309 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1310 E->getParameterPackLocation(),
1311 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001312}
John McCall13481c52010-02-06 08:42:39 +00001313
John McCalldadc5752010-08-24 06:29:42 +00001314ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001315TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1316 SourceLocation Loc) {
1317 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1318 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1319}
1320
1321ExprResult
1322TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1323 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1324 // We can expand this parameter pack now.
1325 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1326 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1327 if (!VD)
1328 return ExprError();
1329 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1330 }
1331
1332 QualType T = TransformType(E->getType());
1333 if (T.isNull())
1334 return ExprError();
1335
1336 // Transform each of the parameter expansions into the corresponding
1337 // parameters in the instantiation of the function decl.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001338 SmallVector<Decl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001339 Parms.reserve(E->getNumExpansions());
1340 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1341 I != End; ++I) {
1342 ParmVarDecl *D =
1343 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1344 if (!D)
1345 return ExprError();
1346 Parms.push_back(D);
1347 }
1348
1349 return FunctionParmPackExpr::Create(getSema().Context, T,
1350 E->getParameterPack(),
1351 E->getParameterPackLocation(), Parms);
1352}
1353
1354ExprResult
1355TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1356 ParmVarDecl *PD) {
1357 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1358 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1359 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1360 assert(Found && "no instantiation for parameter pack");
1361
1362 Decl *TransformedDecl;
1363 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1364 // If this is a reference to a function parameter pack which we can substitute
1365 // but can't yet expand, build a FunctionParmPackExpr for it.
1366 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1367 QualType T = TransformType(E->getType());
1368 if (T.isNull())
1369 return ExprError();
1370 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1371 E->getExprLoc(), *Pack);
1372 }
1373
1374 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1375 } else {
1376 TransformedDecl = Found->get<Decl*>();
1377 }
1378
1379 // We have either an unexpanded pack or a specific expansion.
1380 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1381 E->getExprLoc());
1382}
1383
1384ExprResult
John McCall13481c52010-02-06 08:42:39 +00001385TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1386 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001387
1388 // Handle references to non-type template parameters and non-type template
1389 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001390 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1391 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1392 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001393
1394 // We have a non-type template parameter that isn't fully substituted;
1395 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001396 }
Mike Stump11289f42009-09-09 15:08:12 +00001397
Richard Smithb15fe3a2012-09-12 00:56:43 +00001398 // Handle references to function parameter packs.
1399 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1400 if (PD->isParameterPack())
1401 return TransformFunctionParmPackRefExpr(E, PD);
1402
John McCall47f29ea2009-12-08 09:21:05 +00001403 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001404}
1405
John McCalldadc5752010-08-24 06:29:42 +00001406ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001407 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001408 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1409 getDescribedFunctionTemplate() &&
1410 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001411 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1412 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1413 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001414}
1415
Douglas Gregor14cf7522010-04-30 18:55:50 +00001416QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001417 FunctionProtoTypeLoc TL) {
Douglas Gregor14cf7522010-04-30 18:55:50 +00001418 // We need a local instantiation scope for this function prototype.
John McCall19c1bfd2010-08-25 05:32:35 +00001419 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
John McCall31f82722010-11-12 08:19:04 +00001420 return inherited::TransformFunctionProtoType(TLB, TL);
John McCall58f10c32010-03-11 09:03:00 +00001421}
1422
Douglas Gregor3024f072012-04-16 07:05:22 +00001423QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1424 FunctionProtoTypeLoc TL,
1425 CXXRecordDecl *ThisContext,
1426 unsigned ThisTypeQuals) {
1427 // We need a local instantiation scope for this function prototype.
1428 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1429 return inherited::TransformFunctionProtoType(TLB, TL, ThisContext,
1430 ThisTypeQuals);
1431}
1432
John McCall58f10c32010-03-11 09:03:00 +00001433ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001434TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001435 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001436 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001437 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001438 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001439 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001440}
1441
Mike Stump11289f42009-09-09 15:08:12 +00001442QualType
John McCall550e0c22009-10-21 00:40:46 +00001443TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001444 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001445 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001446 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001447 // Replace the template type parameter with its corresponding
1448 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001449
1450 // If the corresponding template argument is NULL or doesn't exist, it's
1451 // because we are performing instantiation from explicitly-specified
1452 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001453 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001454 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1455 TemplateTypeParmTypeLoc NewTL
1456 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1457 NewTL.setNameLoc(TL.getNameLoc());
1458 return TL.getType();
1459 }
Mike Stump11289f42009-09-09 15:08:12 +00001460
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001461 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1462
1463 if (T->isParameterPack()) {
1464 assert(Arg.getKind() == TemplateArgument::Pack &&
1465 "Missing argument pack");
1466
1467 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001468 // We have the template argument pack, but we're not expanding the
1469 // enclosing pack expansion yet. Just save the template argument
1470 // pack for later substitution.
1471 QualType Result
1472 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1473 SubstTemplateTypeParmPackTypeLoc NewTL
1474 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1475 NewTL.setNameLoc(TL.getNameLoc());
1476 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001477 }
1478
Eli Friedman8917ad52013-07-19 19:40:38 +00001479 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001480 }
1481
1482 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001483 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001484
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001485 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001486
1487 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001488 QualType Result
1489 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1490 SubstTemplateTypeParmTypeLoc NewTL
1491 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1492 NewTL.setNameLoc(TL.getNameLoc());
1493 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001494 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001495
1496 // The template type parameter comes from an inner template (e.g.,
1497 // the template parameter list of a member template inside the
1498 // template we are instantiating). Create a new template type
1499 // parameter with the template "level" reduced by one.
Chandler Carruth08836322011-05-01 00:51:33 +00001500 TemplateTypeParmDecl *NewTTPDecl = 0;
1501 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1502 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1503 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1504
John McCall550e0c22009-10-21 00:40:46 +00001505 QualType Result
1506 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1507 - TemplateArgs.getNumLevels(),
1508 T->getIndex(),
1509 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001510 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001511 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1512 NewTL.setNameLoc(TL.getNameLoc());
1513 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001514}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001515
Douglas Gregorada4b792011-01-14 02:55:32 +00001516QualType
1517TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1518 TypeLocBuilder &TLB,
1519 SubstTemplateTypeParmPackTypeLoc TL) {
1520 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1521 // We aren't expanding the parameter pack, so just return ourselves.
1522 SubstTemplateTypeParmPackTypeLoc NewTL
1523 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1524 NewTL.setNameLoc(TL.getNameLoc());
1525 return TL.getType();
1526 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001527
1528 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1529 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1530 QualType Result = Arg.getAsType();
1531
Douglas Gregorada4b792011-01-14 02:55:32 +00001532 Result = getSema().Context.getSubstTemplateTypeParmType(
1533 TL.getTypePtr()->getReplacedParameter(),
1534 Result);
1535 SubstTemplateTypeParmTypeLoc NewTL
1536 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1537 NewTL.setNameLoc(TL.getNameLoc());
1538 return Result;
1539}
1540
John McCall76d824f2009-08-25 22:02:44 +00001541/// \brief Perform substitution on the type T with a given set of template
1542/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001543///
1544/// This routine substitutes the given template arguments into the
1545/// type T and produces the instantiated type.
1546///
1547/// \param T the type into which the template arguments will be
1548/// substituted. If this type is not dependent, it will be returned
1549/// immediately.
1550///
James Dennett634962f2012-06-14 21:40:34 +00001551/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001552/// substituted for the top-level template parameters within T.
1553///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001554/// \param Loc the location in the source code where this substitution
1555/// is being performed. It will typically be the location of the
1556/// declarator (if we're instantiating the type of some declaration)
1557/// or the location of the type in the source code (if, e.g., we're
1558/// instantiating the type of a cast expression).
1559///
1560/// \param Entity the name of the entity associated with a declaration
1561/// being instantiated (if any). May be empty to indicate that there
1562/// is no such entity (if, e.g., this is a type that occurs as part of
1563/// a cast expression) or that the entity has no name (e.g., an
1564/// unnamed function parameter).
1565///
1566/// \returns If the instantiation succeeds, the instantiated
1567/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001568TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001569 const MultiLevelTemplateArgumentList &Args,
1570 SourceLocation Loc,
1571 DeclarationName Entity) {
1572 assert(!ActiveTemplateInstantiations.empty() &&
1573 "Cannot perform an instantiation without some context on the "
1574 "instantiation stack");
1575
Douglas Gregor678d76c2011-07-01 01:22:09 +00001576 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001577 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001578 return T;
1579
1580 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1581 return Instantiator.TransformType(T);
1582}
1583
Douglas Gregor5499af42011-01-05 23:12:31 +00001584TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1585 const MultiLevelTemplateArgumentList &Args,
1586 SourceLocation Loc,
1587 DeclarationName Entity) {
1588 assert(!ActiveTemplateInstantiations.empty() &&
1589 "Cannot perform an instantiation without some context on the "
1590 "instantiation stack");
1591
1592 if (TL.getType().isNull())
1593 return 0;
1594
Douglas Gregor678d76c2011-07-01 01:22:09 +00001595 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001596 !TL.getType()->isVariablyModifiedType()) {
1597 // FIXME: Make a copy of the TypeLoc data here, so that we can
1598 // return a new TypeSourceInfo. Inefficient!
1599 TypeLocBuilder TLB;
1600 TLB.pushFullCopy(TL);
1601 return TLB.getTypeSourceInfo(Context, TL.getType());
1602 }
1603
1604 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1605 TypeLocBuilder TLB;
1606 TLB.reserve(TL.getFullDataSize());
1607 QualType Result = Instantiator.TransformType(TLB, TL);
1608 if (Result.isNull())
1609 return 0;
1610
1611 return TLB.getTypeSourceInfo(Context, Result);
1612}
1613
John McCall609459e2009-10-21 00:58:09 +00001614/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001615QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001616 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001617 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001618 assert(!ActiveTemplateInstantiations.empty() &&
1619 "Cannot perform an instantiation without some context on the "
1620 "instantiation stack");
1621
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001622 // If T is not a dependent type or a variably-modified type, there
1623 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001624 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001625 return T;
1626
Douglas Gregord6ff3322009-08-04 16:50:30 +00001627 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1628 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001629}
Douglas Gregor463421d2009-03-03 04:44:36 +00001630
John McCallb29f78f2010-04-09 17:38:44 +00001631static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001632 if (T->getType()->isInstantiationDependentType() ||
1633 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001634 return true;
1635
Abramo Bagnara6d810632010-12-14 22:11:44 +00001636 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001637 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001638 return false;
1639
David Blaikie6adc78e2013-02-18 22:06:02 +00001640 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001641 for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) {
1642 ParmVarDecl *P = FP.getParam(I);
John McCallb29f78f2010-04-09 17:38:44 +00001643
Reid Klecknera09e44c2013-07-31 21:00:18 +00001644 // This must be synthesized from a typedef.
1645 if (!P) continue;
1646
Douglas Gregora7203e52011-05-09 20:45:16 +00001647 // The parameter's type as written might be dependent even if the
1648 // decayed type was not dependent.
1649 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001650 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregora7203e52011-05-09 20:45:16 +00001651 return true;
1652
John McCallb29f78f2010-04-09 17:38:44 +00001653 // TODO: currently we always rebuild expressions. When we
1654 // properly get lazier about this, we should use the same
1655 // logic to avoid rebuilding prototypes here.
Douglas Gregor9cc278222011-01-05 21:14:17 +00001656 if (P->hasDefaultArg())
John McCallb29f78f2010-04-09 17:38:44 +00001657 return true;
1658 }
1659
1660 return false;
1661}
1662
1663/// A form of SubstType intended specifically for instantiating the
1664/// type of a FunctionDecl. Its purpose is solely to force the
1665/// instantiation of default-argument expressions.
1666TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1667 const MultiLevelTemplateArgumentList &Args,
1668 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001669 DeclarationName Entity,
1670 CXXRecordDecl *ThisContext,
1671 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001672 assert(!ActiveTemplateInstantiations.empty() &&
1673 "Cannot perform an instantiation without some context on the "
1674 "instantiation stack");
1675
1676 if (!NeedsInstantiationAsFunctionType(T))
1677 return T;
1678
1679 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1680
1681 TypeLocBuilder TLB;
1682
1683 TypeLoc TL = T->getTypeLoc();
1684 TLB.reserve(TL.getFullDataSize());
1685
Douglas Gregor3024f072012-04-16 07:05:22 +00001686 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001687
1688 if (FunctionProtoTypeLoc Proto = TL.getAs<FunctionProtoTypeLoc>()) {
1689 Result = Instantiator.TransformFunctionProtoType(TLB, Proto, ThisContext,
Douglas Gregor3024f072012-04-16 07:05:22 +00001690 ThisTypeQuals);
1691 } else {
1692 Result = Instantiator.TransformType(TLB, TL);
1693 }
John McCallb29f78f2010-04-09 17:38:44 +00001694 if (Result.isNull())
1695 return 0;
1696
1697 return TLB.getTypeSourceInfo(Context, Result);
1698}
1699
Douglas Gregor940bca72010-04-12 07:48:19 +00001700ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001701 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001702 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001703 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001704 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001705 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Douglas Gregor5499af42011-01-05 23:12:31 +00001706 TypeSourceInfo *NewDI = 0;
1707
Douglas Gregor5499af42011-01-05 23:12:31 +00001708 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001709 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1710
Douglas Gregor5499af42011-01-05 23:12:31 +00001711 // We have a function parameter pack. Substitute into the pattern of the
1712 // expansion.
1713 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1714 OldParm->getLocation(), OldParm->getDeclName());
1715 if (!NewDI)
1716 return 0;
1717
1718 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1719 // We still have unexpanded parameter packs, which means that
1720 // our function parameter is still a function parameter pack.
1721 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001722 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001723 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001724 } else if (ExpectParameterPack) {
1725 // We expected to get a parameter pack but didn't (because the type
1726 // itself is not a pack expansion type), so complain. This can occur when
1727 // the substitution goes through an alias template that "loses" the
1728 // pack expansion.
1729 Diag(OldParm->getLocation(),
1730 diag::err_function_parameter_pack_without_parameter_packs)
1731 << NewDI->getType();
1732 return 0;
1733 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001734 } else {
1735 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1736 OldParm->getDeclName());
1737 }
1738
Douglas Gregor940bca72010-04-12 07:48:19 +00001739 if (!NewDI)
1740 return 0;
1741
1742 if (NewDI->getType()->isVoidType()) {
1743 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1744 return 0;
1745 }
1746
1747 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001748 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001749 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001750 OldParm->getIdentifier(),
1751 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001752 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001753 if (!NewParm)
1754 return 0;
Douglas Gregor6044d692010-05-19 17:02:24 +00001755
Douglas Gregor940bca72010-04-12 07:48:19 +00001756 // Mark the (new) default argument as uninstantiated (if any).
1757 if (OldParm->hasUninstantiatedDefaultArg()) {
1758 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1759 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001760 } else if (OldParm->hasUnparsedDefaultArg()) {
1761 NewParm->setUnparsedDefaultArg();
1762 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie7afed5e2012-05-01 06:05:57 +00001763 } else if (Expr *Arg = OldParm->getDefaultArg())
1764 // FIXME: if we non-lazily instantiated non-dependent default args for
1765 // non-dependent parameter types we could remove a bunch of duplicate
1766 // conversion warnings for such arguments.
1767 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor940bca72010-04-12 07:48:19 +00001768
1769 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001770
Douglas Gregorf3010112011-01-07 16:43:16 +00001771 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001772 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001773 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1774 } else {
1775 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001776 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001777 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001778
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001779 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1780 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001781 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001782
1783 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1784 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001785
1786 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1787
Douglas Gregor940bca72010-04-12 07:48:19 +00001788 return NewParm;
1789}
1790
Douglas Gregordd472162011-01-07 00:20:55 +00001791/// \brief Substitute the given template arguments into the given set of
1792/// parameters, producing the set of parameter types that would be generated
1793/// from such a substitution.
1794bool Sema::SubstParmTypes(SourceLocation Loc,
1795 ParmVarDecl **Params, unsigned NumParams,
1796 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001797 SmallVectorImpl<QualType> &ParamTypes,
1798 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregordd472162011-01-07 00:20:55 +00001799 assert(!ActiveTemplateInstantiations.empty() &&
1800 "Cannot perform an instantiation without some context on the "
1801 "instantiation stack");
1802
1803 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1804 DeclarationName());
1805 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams, 0,
Douglas Gregorf3010112011-01-07 16:43:16 +00001806 ParamTypes, OutParams);
Douglas Gregordd472162011-01-07 00:20:55 +00001807}
1808
John McCall76d824f2009-08-25 22:02:44 +00001809/// \brief Perform substitution on the base class specifiers of the
1810/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001811///
1812/// Produces a diagnostic and returns true on error, returns false and
1813/// attaches the instantiated base classes to the class template
1814/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001815bool
John McCall76d824f2009-08-25 22:02:44 +00001816Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1817 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001818 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001819 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001820 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00001821 for (const auto Base : Pattern->bases()) {
1822 if (!Base.getType()->isDependentType()) {
1823 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001824 if (RD->isInvalidDecl())
1825 Instantiation->setInvalidDecl();
1826 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001827 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001828 continue;
1829 }
1830
Douglas Gregor752a5952011-01-03 22:36:02 +00001831 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001832 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001833 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001834 // This is a pack expansion. See whether we should expand it now, or
1835 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001836 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001837 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001838 Unexpanded);
1839 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001840 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001841 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001842 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1843 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001844 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001845 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001846 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001847 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001848 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001849 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001850 }
1851
1852 // If we should expand this pack expansion now, do so.
1853 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001854 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001855 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1856
Aaron Ballman574705e2014-03-13 15:41:46 +00001857 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001858 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001859 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001860 DeclarationName());
1861 if (!BaseTypeLoc) {
1862 Invalid = true;
1863 continue;
1864 }
1865
1866 if (CXXBaseSpecifier *InstantiatedBase
1867 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001868 Base.getSourceRange(),
1869 Base.isVirtual(),
1870 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001871 BaseTypeLoc,
1872 SourceLocation()))
1873 InstantiatedBases.push_back(InstantiatedBase);
1874 else
1875 Invalid = true;
1876 }
1877
1878 continue;
1879 }
1880
1881 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001882 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001883 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001884 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001885 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001886 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001887 DeclarationName());
1888 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001889 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001890 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001891 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001892 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001893 }
1894
Nick Lewycky19b9f952010-07-26 16:56:01 +00001895 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001896 Invalid = true;
1897 continue;
1898 }
1899
1900 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001901 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001902 Base.getSourceRange(),
1903 Base.isVirtual(),
1904 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001905 BaseTypeLoc,
1906 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001907 InstantiatedBases.push_back(InstantiatedBase);
1908 else
1909 Invalid = true;
1910 }
1911
Douglas Gregor2a72edd2009-03-10 18:52:44 +00001912 if (!Invalid &&
Jay Foad7d0479f2009-05-21 09:52:38 +00001913 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor463421d2009-03-03 04:44:36 +00001914 InstantiatedBases.size()))
1915 Invalid = true;
1916
1917 return Invalid;
1918}
1919
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001920// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001921namespace clang {
1922 namespace sema {
1923 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1924 const MultiLevelTemplateArgumentList &TemplateArgs);
1925 }
1926}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001927
Richard Smith4b38ded2012-03-14 23:13:10 +00001928/// Determine whether we would be unable to instantiate this template (because
1929/// it either has no definition, or is in the process of being instantiated).
1930static bool DiagnoseUninstantiableTemplate(Sema &S,
1931 SourceLocation PointOfInstantiation,
1932 TagDecl *Instantiation,
1933 bool InstantiatedFromMember,
1934 TagDecl *Pattern,
1935 TagDecl *PatternDef,
1936 TemplateSpecializationKind TSK,
1937 bool Complain = true) {
1938 if (PatternDef && !PatternDef->isBeingDefined())
1939 return false;
1940
1941 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1942 // Say nothing
1943 } else if (PatternDef) {
1944 assert(PatternDef->isBeingDefined());
1945 S.Diag(PointOfInstantiation,
1946 diag::err_template_instantiate_within_definition)
1947 << (TSK != TSK_ImplicitInstantiation)
1948 << S.Context.getTypeDeclType(Instantiation);
1949 // Not much point in noting the template declaration here, since
1950 // we're lexically inside it.
1951 Instantiation->setInvalidDecl();
1952 } else if (InstantiatedFromMember) {
1953 S.Diag(PointOfInstantiation,
1954 diag::err_implicit_instantiate_member_undefined)
1955 << S.Context.getTypeDeclType(Instantiation);
1956 S.Diag(Pattern->getLocation(), diag::note_member_of_template_here);
1957 } else {
1958 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1959 << (TSK != TSK_ImplicitInstantiation)
1960 << S.Context.getTypeDeclType(Instantiation);
1961 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1962 }
1963
1964 // In general, Instantiation isn't marked invalid to get more than one
1965 // error for multiple undefined instantiations. But the code that does
1966 // explicit declaration -> explicit definition conversion can't handle
1967 // invalid declarations, so mark as invalid in that case.
1968 if (TSK == TSK_ExplicitInstantiationDeclaration)
1969 Instantiation->setInvalidDecl();
1970 return true;
1971}
1972
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001973/// \brief Instantiate the definition of a class from a given pattern.
1974///
1975/// \param PointOfInstantiation The point of instantiation within the
1976/// source code.
1977///
1978/// \param Instantiation is the declaration whose definition is being
1979/// instantiated. This will be either a class template specialization
1980/// or a member class of a class template specialization.
1981///
1982/// \param Pattern is the pattern from which the instantiation
1983/// occurs. This will be either the declaration of a class template or
1984/// the declaration of a member class of a class template.
1985///
1986/// \param TemplateArgs The template arguments to be substituted into
1987/// the pattern.
1988///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001989/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001990///
1991/// \param Complain whether to complain if the class cannot be instantiated due
1992/// to the lack of a definition.
1993///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001994/// \returns true if an error occurred, false otherwise.
1995bool
1996Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1997 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001998 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001999 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002000 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00002001 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002002 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smith4b38ded2012-03-14 23:13:10 +00002003 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2004 Instantiation->getInstantiatedFromMemberClass(),
2005 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002006 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002007 Pattern = PatternDef;
2008
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002009 // \brief Record the point of instantiation.
2010 if (MemberSpecializationInfo *MSInfo
2011 = Instantiation->getMemberSpecializationInfo()) {
2012 MSInfo->setTemplateSpecializationKind(TSK);
2013 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00002014 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00002015 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00002016 Spec->setTemplateSpecializationKind(TSK);
2017 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002018 }
Richard Smitha1087602014-03-10 00:04:29 +00002019
Douglas Gregorf3430ae2009-03-25 21:23:52 +00002020 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002021 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002022 return true;
2023
2024 // Enter the scope of this instantiation. We don't use
2025 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00002026 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00002027 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00002028 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002029
Douglas Gregor51121572010-03-24 01:33:17 +00002030 // If this is an instantiation of a local class, merge this local
2031 // instantiation scope with the enclosing scope. Otherwise, every
2032 // instantiation of a class has its own local instantiation scope.
2033 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00002034 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00002035
John McCall6602bb12010-08-01 02:01:53 +00002036 // Pull attributes from the pattern onto the instantiation.
2037 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2038
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002039 // Start the definition of this instantiation.
2040 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00002041
2042 // The instantiation is visible here, even if it was first declared in an
2043 // unimported module.
2044 Instantiation->setHidden(false);
2045
2046 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00002047 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002048
John McCall76d824f2009-08-25 22:02:44 +00002049 // Do substitution on the base class specifiers.
2050 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002051 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002052
Douglas Gregor869853e2010-11-10 19:44:59 +00002053 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002054 SmallVector<Decl*, 4> Fields;
2055 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith938f40b2011-06-11 17:19:42 +00002056 FieldsWithMemberInitializers;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002057 // Delay instantiation of late parsed attributes.
2058 LateInstantiatedAttrVec LateAttrs;
2059 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2060
Aaron Ballman629afae2014-03-07 19:56:05 +00002061 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002062 // Don't instantiate members not belonging in this semantic context.
2063 // e.g. for:
2064 // @code
2065 // template <int i> class A {
2066 // class B *g;
2067 // };
2068 // @endcode
2069 // 'class B' has the template as lexical context but semantically it is
2070 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002071 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002072 continue;
2073
Aaron Ballman629afae2014-03-07 19:56:05 +00002074 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002075 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002076 continue;
2077 }
2078
Aaron Ballman629afae2014-03-07 19:56:05 +00002079 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002080 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002081 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002082 Fields.push_back(Field);
Aaron Ballman629afae2014-03-07 19:56:05 +00002083 FieldDecl *OldField = cast<FieldDecl>(Member);
Richard Smith938f40b2011-06-11 17:19:42 +00002084 if (OldField->getInClassInitializer())
2085 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2086 Field));
Richard Smith7d137e32012-03-23 03:33:32 +00002087 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2088 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2089 // specialization causes the implicit instantiation of the definitions
2090 // of unscoped member enumerations.
2091 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002092 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2093 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002094 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2095 assert(MSInfo && "no spec info for member enum specialization");
2096 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2097 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2098 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002099 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2100 if (SA->isFailed()) {
2101 // A static_assert failed. Bail out; instantiating this
2102 // class is probably not meaningful.
2103 Instantiation->setInvalidDecl();
2104 break;
2105 }
Richard Smith7d137e32012-03-23 03:33:32 +00002106 }
2107
2108 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002109 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002110 } else {
2111 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002112 // instantiations was a semantic disaster, and we'll want to mark the
2113 // declaration invalid.
2114 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002115 }
2116 }
2117
2118 // Finish checking fields.
David Blaikie751c5582011-09-22 02:58:26 +00002119 ActOnFields(0, Instantiation->getLocation(), Instantiation, Fields,
2120 SourceLocation(), SourceLocation(), 0);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002121 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002122
2123 // Attach any in-class member initializers now the class is complete.
Richard Smith189aba92012-12-08 02:13:02 +00002124 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer1d373c62012-05-17 12:01:52 +00002125 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00002126 // C++11 [expr.prim.general]p4:
2127 // Otherwise, if a member-declarator declares a non-static data member
2128 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2129 // to X" within the optional brace-or-equal-initializer. It shall not
2130 // appear elsewhere in the member-declarator.
2131 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2132
2133 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2134 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2135 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2136 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002137
Richard Smith74108172014-01-17 03:11:34 +00002138 ActOnStartCXXInClassMemberInitializer();
Douglas Gregor3024f072012-04-16 07:05:22 +00002139 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2140 /*CXXDirectInit=*/false);
Richard Smith74108172014-01-17 03:11:34 +00002141 Expr *Init = NewInit.take();
2142 assert((!Init || !isa<ParenListExpr>(Init)) &&
2143 "call-style init in class");
2144 ActOnFinishCXXInClassMemberInitializer(NewField, Init->getLocStart(),
2145 Init);
Richard Smithe3daab22011-07-20 00:12:52 +00002146 }
Richard Smith938f40b2011-06-11 17:19:42 +00002147 }
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002148 // Instantiate late parsed attributes, and attach them to their decls.
2149 // See Sema::InstantiateAttrs
2150 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2151 E = LateAttrs.end(); I != E; ++I) {
2152 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2153 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002154
2155 // Allow 'this' within late-parsed attributes.
2156 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2157 CXXRecordDecl *ThisContext =
2158 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2159 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2160 ND && ND->isCXXInstanceMember());
2161
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002162 Attr *NewAttr =
2163 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2164 I->NewDecl->addAttr(NewAttr);
2165 LocalInstantiationScope::deleteScopes(I->Scope,
2166 Instantiator.getStartingScope());
2167 }
2168 Instantiator.disableLateAttributeInstantiation();
2169 LateAttrs.clear();
2170
Richard Smithd3b5c9082012-07-27 04:22:15 +00002171 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002172
Richard Smitha1087602014-03-10 00:04:29 +00002173 // FIXME: We should do something similar for explicit instantiations so they
2174 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002175 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002176 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002177 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002178 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002179 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002180
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002181 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002182 // Perform any dependent diagnostics from the pattern.
2183 PerformDependentDiagnostics(Pattern, TemplateArgs);
2184
Douglas Gregor869853e2010-11-10 19:44:59 +00002185 // Instantiate any out-of-line class template partial
2186 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002187 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002188 P = Instantiator.delayed_partial_spec_begin(),
2189 PEnd = Instantiator.delayed_partial_spec_end();
2190 P != PEnd; ++P) {
2191 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002192 P->first, P->second)) {
2193 Instantiation->setInvalidDecl();
2194 break;
2195 }
2196 }
2197
2198 // Instantiate any out-of-line variable template partial
2199 // specializations now.
2200 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2201 P = Instantiator.delayed_var_partial_spec_begin(),
2202 PEnd = Instantiator.delayed_var_partial_spec_end();
2203 P != PEnd; ++P) {
2204 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2205 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002206 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002207 break;
2208 }
2209 }
2210 }
2211
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002212 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002213 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002214
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002215 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002216 Consumer.HandleTagDeclDefinition(Instantiation);
2217
Douglas Gregor88d292c2010-05-13 16:44:06 +00002218 // Always emit the vtable for an explicit instantiation definition
2219 // of a polymorphic class template specialization.
2220 if (TSK == TSK_ExplicitInstantiationDefinition)
2221 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2222 }
2223
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002224 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002225}
2226
Richard Smith4b38ded2012-03-14 23:13:10 +00002227/// \brief Instantiate the definition of an enum from a given pattern.
2228///
2229/// \param PointOfInstantiation The point of instantiation within the
2230/// source code.
2231/// \param Instantiation is the declaration whose definition is being
2232/// instantiated. This will be a member enumeration of a class
2233/// temploid specialization, or a local enumeration within a
2234/// function temploid specialization.
2235/// \param Pattern The templated declaration from which the instantiation
2236/// occurs.
2237/// \param TemplateArgs The template arguments to be substituted into
2238/// the pattern.
2239/// \param TSK The kind of implicit or explicit instantiation to perform.
2240///
2241/// \return \c true if an error occurred, \c false otherwise.
2242bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2243 EnumDecl *Instantiation, EnumDecl *Pattern,
2244 const MultiLevelTemplateArgumentList &TemplateArgs,
2245 TemplateSpecializationKind TSK) {
2246 EnumDecl *PatternDef = Pattern->getDefinition();
2247 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2248 Instantiation->getInstantiatedFromMemberEnum(),
2249 Pattern, PatternDef, TSK,/*Complain*/true))
2250 return true;
2251 Pattern = PatternDef;
2252
2253 // Record the point of instantiation.
2254 if (MemberSpecializationInfo *MSInfo
2255 = Instantiation->getMemberSpecializationInfo()) {
2256 MSInfo->setTemplateSpecializationKind(TSK);
2257 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2258 }
2259
2260 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002261 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002262 return true;
2263
Richard Smitha1087602014-03-10 00:04:29 +00002264 // The instantiation is visible here, even if it was first declared in an
2265 // unimported module.
2266 Instantiation->setHidden(false);
2267
Richard Smith4b38ded2012-03-14 23:13:10 +00002268 // Enter the scope of this instantiation. We don't use
2269 // PushDeclContext because we don't have a scope.
2270 ContextRAII SavedContext(*this, Instantiation);
2271 EnterExpressionEvaluationContext EvalContext(*this,
2272 Sema::PotentiallyEvaluated);
2273
2274 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2275
2276 // Pull attributes from the pattern onto the instantiation.
2277 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2278
2279 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2280 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2281
2282 // Exit the scope of this instantiation.
2283 SavedContext.pop();
2284
2285 return Instantiation->isInvalidDecl();
2286}
2287
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002288namespace {
2289 /// \brief A partial specialization whose template arguments have matched
2290 /// a given template-id.
2291 struct PartialSpecMatchResult {
2292 ClassTemplatePartialSpecializationDecl *Partial;
2293 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002294 };
2295}
2296
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002297bool Sema::InstantiateClassTemplateSpecialization(
2298 SourceLocation PointOfInstantiation,
2299 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2300 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002301 // Perform the actual instantiation on the canonical declaration.
2302 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002303 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor463421d2009-03-03 04:44:36 +00002304
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002305 // Check whether we have already instantiated or specialized this class
2306 // template specialization.
2307 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2308 if (ClassTemplateSpec->getSpecializationKind() ==
2309 TSK_ExplicitInstantiationDeclaration &&
2310 TSK == TSK_ExplicitInstantiationDefinition) {
2311 // An explicit instantiation definition follows an explicit instantiation
2312 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2313 // explicit instantiation.
2314 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor88d292c2010-05-13 16:44:06 +00002315
2316 // If this is an explicit instantiation definition, mark the
2317 // vtable as used.
Nico Weber3ffc4c92011-12-20 20:32:49 +00002318 if (TSK == TSK_ExplicitInstantiationDefinition &&
2319 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002320 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2321
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002322 return false;
2323 }
2324
2325 // We can only instantiate something that hasn't already been
2326 // instantiated or specialized. Fail without any diagnostics: our
2327 // caller will provide an error message.
Douglas Gregor463421d2009-03-03 04:44:36 +00002328 return true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002329 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002330
Douglas Gregor00a511f2009-09-15 16:51:42 +00002331 if (ClassTemplateSpec->isInvalidDecl())
2332 return true;
2333
Douglas Gregor463421d2009-03-03 04:44:36 +00002334 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor01afeef2009-08-28 20:31:08 +00002335 CXXRecordDecl *Pattern = 0;
Douglas Gregor2373c592009-05-31 09:31:02 +00002336
Douglas Gregor170bc422009-06-12 22:31:52 +00002337 // C++ [temp.class.spec.match]p1:
2338 // When a class template is used in a context that requires an
2339 // instantiation of the class, it is necessary to determine
2340 // whether the instantiation is to be generated using the primary
2341 // template or one of the partial specializations. This is done by
2342 // matching the template arguments of the class template
2343 // specialization with the template argument lists of the partial
2344 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002345 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002346 SmallVector<MatchResult, 4> Matched;
2347 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002348 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002349 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002350 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2351 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002352 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002353 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002354 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002355 ClassTemplateSpec->getTemplateArgs(),
2356 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002357 // Store the failed-deduction information for use in diagnostics, later.
2358 // TODO: Actually use the failed-deduction info?
2359 FailedCandidates.addCandidate()
2360 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002361 (void)Result;
2362 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002363 Matched.push_back(PartialSpecMatchResult());
2364 Matched.back().Partial = Partial;
2365 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002366 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002367 }
2368
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002369 // If we're dealing with a member template where the template parameters
2370 // have been instantiated, this provides the original template parameters
2371 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002372
Douglas Gregor21610382009-10-29 00:04:11 +00002373 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002374 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002375 if (Matched.size() == 1) {
2376 // -- If exactly one matching specialization is found, the
2377 // instantiation is generated from that specialization.
2378 // We don't need to do anything for this.
2379 } else {
2380 // -- If more than one matching specialization is found, the
2381 // partial order rules (14.5.4.2) are used to determine
2382 // whether one of the specializations is more specialized
2383 // than the others. If none of the specializations is more
2384 // specialized than all of the other matching
2385 // specializations, then the use of the class template is
2386 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002387 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2388 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002389 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002390 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002391 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002392 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002393 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002394 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002395
Douglas Gregor21610382009-10-29 00:04:11 +00002396 // Determine if the best partial specialization is more specialized than
2397 // the others.
2398 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002399 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2400 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002401 P != PEnd; ++P) {
2402 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002403 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002404 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002405 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002406 Ambiguous = true;
2407 break;
2408 }
2409 }
2410
2411 if (Ambiguous) {
2412 // Partial ordering did not produce a clear winner. Complain.
2413 ClassTemplateSpec->setInvalidDecl();
2414 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2415 << ClassTemplateSpec;
2416
2417 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002418 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2419 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002420 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002421 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2422 << getTemplateArgumentBindingsText(
2423 P->Partial->getTemplateParameters(),
2424 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002425
Douglas Gregor21610382009-10-29 00:04:11 +00002426 return true;
2427 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002428 }
2429
2430 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002431 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002432 while (OrigPartialSpec->getInstantiatedFromMember()) {
2433 // If we've found an explicit specialization of this class template,
2434 // stop here and use that as the pattern.
2435 if (OrigPartialSpec->isMemberSpecialization())
2436 break;
2437
2438 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2439 }
2440
2441 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002442 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002443 } else {
2444 // -- If no matches are found, the instantiation is generated
2445 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002446 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002447 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2448 // If we've found an explicit specialization of this class template,
2449 // stop here and use that as the pattern.
2450 if (OrigTemplate->isMemberSpecialization())
2451 break;
2452
Douglas Gregor01afeef2009-08-28 20:31:08 +00002453 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002454 }
2455
Douglas Gregor01afeef2009-08-28 20:31:08 +00002456 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002457 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002458
Douglas Gregoref6ab412009-10-27 06:26:26 +00002459 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2460 Pattern,
2461 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002462 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002463 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002464
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002465 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002466}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002467
John McCall76d824f2009-08-25 22:02:44 +00002468/// \brief Instantiates the definitions of all of the member
2469/// of the given class, which is an instantiation of a class template
2470/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002471void
2472Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002473 CXXRecordDecl *Instantiation,
2474 const MultiLevelTemplateArgumentList &TemplateArgs,
2475 TemplateSpecializationKind TSK) {
David Majnemer192d1792013-11-27 08:20:38 +00002476 assert(
2477 (TSK == TSK_ExplicitInstantiationDefinition ||
2478 TSK == TSK_ExplicitInstantiationDeclaration ||
2479 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2480 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002481 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002482 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002483 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002484 if (FunctionDecl *Pattern
2485 = Function->getInstantiatedFromMemberFunction()) {
2486 MemberSpecializationInfo *MSInfo
2487 = Function->getMemberSpecializationInfo();
2488 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002489 if (MSInfo->getTemplateSpecializationKind()
2490 == TSK_ExplicitSpecialization)
2491 continue;
2492
Douglas Gregor1d957a32009-10-27 18:42:08 +00002493 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2494 Function,
2495 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002496 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002497 SuppressNew) ||
2498 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002499 continue;
2500
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002501 if (Function->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002502 continue;
2503
2504 if (TSK == TSK_ExplicitInstantiationDefinition) {
2505 // C++0x [temp.explicit]p8:
2506 // An explicit instantiation definition that names a class template
2507 // specialization explicitly instantiates the class template
2508 // specialization and is only an explicit instantiation definition
2509 // of members whose definition is visible at the point of
2510 // instantiation.
Alexis Hunt4a8ea102011-05-06 20:44:56 +00002511 if (!Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002512 continue;
2513
2514 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2515
2516 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2517 } else {
2518 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
David Majnemer192d1792013-11-27 08:20:38 +00002519 if (TSK == TSK_ImplicitInstantiation)
2520 PendingLocalImplicitInstantiations.push_back(
2521 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002522 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002523 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002524 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002525 if (isa<VarTemplateSpecializationDecl>(Var))
2526 continue;
2527
Douglas Gregor86d142a2009-10-08 07:24:58 +00002528 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002529 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2530 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002531 if (MSInfo->getTemplateSpecializationKind()
2532 == TSK_ExplicitSpecialization)
2533 continue;
2534
Douglas Gregor1d957a32009-10-27 18:42:08 +00002535 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2536 Var,
2537 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002538 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002539 SuppressNew) ||
2540 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002541 continue;
2542
Douglas Gregor1d957a32009-10-27 18:42:08 +00002543 if (TSK == TSK_ExplicitInstantiationDefinition) {
2544 // C++0x [temp.explicit]p8:
2545 // An explicit instantiation definition that names a class template
2546 // specialization explicitly instantiates the class template
2547 // specialization and is only an explicit instantiation definition
2548 // of members whose definition is visible at the point of
2549 // instantiation.
2550 if (!Var->getInstantiatedFromStaticDataMember()
2551 ->getOutOfLineDefinition())
2552 continue;
2553
2554 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002555 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002556 } else {
2557 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2558 }
2559 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002560 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002561 // Always skip the injected-class-name, along with any
2562 // redeclarations of nested classes, since both would cause us
2563 // to try to instantiate the members of a class twice.
Douglas Gregorec9fd132012-01-14 16:38:05 +00002564 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregord801b062009-10-07 23:56:10 +00002565 continue;
2566
Douglas Gregor1d957a32009-10-27 18:42:08 +00002567 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2568 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002569
2570 if (MSInfo->getTemplateSpecializationKind()
2571 == TSK_ExplicitSpecialization)
2572 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002573
Douglas Gregor1d957a32009-10-27 18:42:08 +00002574 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2575 Record,
2576 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002577 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002578 SuppressNew) ||
2579 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002580 continue;
2581
Douglas Gregor1d957a32009-10-27 18:42:08 +00002582 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2583 assert(Pattern && "Missing instantiated-from-template information");
2584
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002585 if (!Record->getDefinition()) {
2586 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002587 // C++0x [temp.explicit]p8:
2588 // An explicit instantiation definition that names a class template
2589 // specialization explicitly instantiates the class template
2590 // specialization and is only an explicit instantiation definition
2591 // of members whose definition is visible at the point of
2592 // instantiation.
2593 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2594 MSInfo->setTemplateSpecializationKind(TSK);
2595 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2596 }
2597
2598 continue;
2599 }
2600
2601 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002602 TemplateArgs,
2603 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002604 } else {
2605 if (TSK == TSK_ExplicitInstantiationDefinition &&
2606 Record->getTemplateSpecializationKind() ==
2607 TSK_ExplicitInstantiationDeclaration) {
2608 Record->setTemplateSpecializationKind(TSK);
2609 MarkVTableUsed(PointOfInstantiation, Record, true);
2610 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002611 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002612
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002613 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002614 if (Pattern)
2615 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2616 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002617 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002618 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2619 assert(MSInfo && "No member specialization information?");
2620
2621 if (MSInfo->getTemplateSpecializationKind()
2622 == TSK_ExplicitSpecialization)
2623 continue;
2624
2625 if (CheckSpecializationInstantiationRedecl(
2626 PointOfInstantiation, TSK, Enum,
2627 MSInfo->getTemplateSpecializationKind(),
2628 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2629 SuppressNew)
2630 continue;
2631
2632 if (Enum->getDefinition())
2633 continue;
2634
2635 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2636 assert(Pattern && "Missing instantiated-from-template information");
2637
2638 if (TSK == TSK_ExplicitInstantiationDefinition) {
2639 if (!Pattern->getDefinition())
2640 continue;
2641
2642 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2643 } else {
2644 MSInfo->setTemplateSpecializationKind(TSK);
2645 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2646 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002647 }
2648 }
2649}
2650
2651/// \brief Instantiate the definitions of all of the members of the
2652/// given class template specialization, which was named as part of an
2653/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002654void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002655Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002656 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002657 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2658 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002659 // C++0x [temp.explicit]p7:
2660 // An explicit instantiation that names a class template
2661 // specialization is an explicit instantion of the same kind
2662 // (declaration or definition) of each of its members (not
2663 // including members inherited from base classes) that has not
2664 // been previously explicitly specialized in the translation unit
2665 // containing the explicit instantiation, except as described
2666 // below.
2667 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002668 getTemplateInstantiationArgs(ClassTemplateSpec),
2669 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002670}
2671
John McCalldadc5752010-08-24 06:29:42 +00002672StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002673Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002674 if (!S)
2675 return Owned(S);
2676
2677 TemplateInstantiator Instantiator(*this, TemplateArgs,
2678 SourceLocation(),
2679 DeclarationName());
2680 return Instantiator.TransformStmt(S);
2681}
2682
John McCalldadc5752010-08-24 06:29:42 +00002683ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002684Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002685 if (!E)
2686 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00002687
Douglas Gregora16548e2009-08-11 05:31:07 +00002688 TemplateInstantiator Instantiator(*this, TemplateArgs,
2689 SourceLocation(),
2690 DeclarationName());
2691 return Instantiator.TransformExpr(E);
2692}
2693
Richard Smithd59b8322012-12-19 01:39:02 +00002694ExprResult Sema::SubstInitializer(Expr *Init,
2695 const MultiLevelTemplateArgumentList &TemplateArgs,
2696 bool CXXDirectInit) {
2697 TemplateInstantiator Instantiator(*this, TemplateArgs,
2698 SourceLocation(),
2699 DeclarationName());
2700 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2701}
2702
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002703bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2704 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002705 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002706 if (NumExprs == 0)
2707 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002708
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002709 TemplateInstantiator Instantiator(*this, TemplateArgs,
2710 SourceLocation(),
2711 DeclarationName());
2712 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2713}
2714
Douglas Gregor14454802011-02-25 02:25:35 +00002715NestedNameSpecifierLoc
2716Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2717 const MultiLevelTemplateArgumentList &TemplateArgs) {
2718 if (!NNS)
2719 return NestedNameSpecifierLoc();
2720
2721 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2722 DeclarationName());
2723 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2724}
2725
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002726/// \brief Do template substitution on declaration name info.
2727DeclarationNameInfo
2728Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2729 const MultiLevelTemplateArgumentList &TemplateArgs) {
2730 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2731 NameInfo.getName());
2732 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2733}
2734
Douglas Gregoraa594892009-03-31 18:38:02 +00002735TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002736Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2737 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002738 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002739 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2740 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002741 CXXScopeSpec SS;
2742 SS.Adopt(QualifierLoc);
2743 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002744}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002745
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002746bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2747 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002748 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002749 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2750 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002751
2752 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002753}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002754
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002755
2756static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2757 // When storing ParmVarDecls in the local instantiation scope, we always
2758 // want to use the ParmVarDecl from the canonical function declaration,
2759 // since the map is then valid for any redeclaration or definition of that
2760 // function.
2761 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2762 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2763 unsigned i = PV->getFunctionScopeIndex();
2764 return FD->getCanonicalDecl()->getParamDecl(i);
2765 }
2766 }
2767 return D;
2768}
2769
2770
Douglas Gregorf3010112011-01-07 16:43:16 +00002771llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2772LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002773 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002774 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002775 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002776
Douglas Gregor14cf7522010-04-30 18:55:50 +00002777 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002778 const Decl *CheckD = D;
2779 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002780 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002781 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002782 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002783
2784 // If this is a tag declaration, it's possible that we need to look for
2785 // a previous declaration.
2786 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002787 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002788 else
2789 CheckD = 0;
2790 } while (CheckD);
2791
Douglas Gregor14cf7522010-04-30 18:55:50 +00002792 // If we aren't combined with our outer scope, we're done.
2793 if (!Current->CombineWithOuterScope)
2794 break;
2795 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002796
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002797 // If we're performing a partial substitution during template argument
2798 // deduction, we may not have values for template parameters yet.
2799 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2800 isa<TemplateTemplateParmDecl>(D))
2801 return 0;
2802
Chris Lattnercab02a62011-02-17 20:34:02 +00002803 // If we didn't find the decl, then we either have a sema bug, or we have a
2804 // forward reference to a label declaration. Return null to indicate that
2805 // we have an uninstantiated label.
2806 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Douglas Gregor14cf7522010-04-30 18:55:50 +00002807 return 0;
2808}
2809
John McCall19c1bfd2010-08-25 05:32:35 +00002810void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002811 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002812 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002813 if (Stored.isNull())
2814 Stored = Inst;
Benjamin Kramer1b4342d2013-04-12 15:22:25 +00002815 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2816 Pack->push_back(Inst);
2817 else
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002818 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor14cf7522010-04-30 18:55:50 +00002819}
Douglas Gregorf3010112011-01-07 16:43:16 +00002820
2821void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2822 Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002823 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002824 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2825 Pack->push_back(Inst);
2826}
2827
2828void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002829 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002830 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2831 assert(Stored.isNull() && "Already instantiated this local");
2832 DeclArgumentPack *Pack = new DeclArgumentPack;
2833 Stored = Pack;
2834 ArgumentPacks.push_back(Pack);
2835}
2836
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002837void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2838 const TemplateArgument *ExplicitArgs,
2839 unsigned NumExplicitArgs) {
2840 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2841 "Already have a partially-substituted pack");
2842 assert((!PartiallySubstitutedPack
2843 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2844 "Wrong number of arguments in partially-substituted pack");
2845 PartiallySubstitutedPack = Pack;
2846 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2847 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2848}
2849
2850NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2851 const TemplateArgument **ExplicitArgs,
2852 unsigned *NumExplicitArgs) const {
2853 if (ExplicitArgs)
2854 *ExplicitArgs = 0;
2855 if (NumExplicitArgs)
2856 *NumExplicitArgs = 0;
2857
2858 for (const LocalInstantiationScope *Current = this; Current;
2859 Current = Current->Outer) {
2860 if (Current->PartiallySubstitutedPack) {
2861 if (ExplicitArgs)
2862 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2863 if (NumExplicitArgs)
2864 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2865
2866 return Current->PartiallySubstitutedPack;
2867 }
2868
2869 if (!Current->CombineWithOuterScope)
2870 break;
2871 }
2872
2873 return 0;
2874}