blob: a9aae009401fa93f8e9e12bb8fd0e2ae40043aeb [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
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000203void Sema::InstantiatingTemplate::Initialize(
204 ActiveTemplateInstantiation::InstantiationKind Kind,
205 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
206 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
207 sema::TemplateDeductionInfo *DeductionInfo) {
208 SavedInNonInstantiationSFINAEContext =
209 SemaRef.InNonInstantiationSFINAEContext;
210 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
211 if (!Invalid) {
212 ActiveTemplateInstantiation Inst;
213 Inst.Kind = Kind;
214 Inst.PointOfInstantiation = PointOfInstantiation;
215 Inst.Entity = Entity;
216 Inst.Template = Template;
217 Inst.TemplateArgs = TemplateArgs.data();
218 Inst.NumTemplateArgs = TemplateArgs.size();
219 Inst.DeductionInfo = DeductionInfo;
220 Inst.InstantiationRange = InstantiationRange;
221 SemaRef.InNonInstantiationSFINAEContext = false;
222 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
223 if (!Inst.isInstantiationRecord())
224 ++SemaRef.NonInstantiationEntries;
225 }
226}
227
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000228Sema::InstantiatingTemplate::
229InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Douglas Gregor85673582009-05-18 17:01:57 +0000230 Decl *Entity,
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000231 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000232 : SemaRef(SemaRef)
Douglas Gregoredb76852011-01-27 22:31:44 +0000233{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000234 Initialize(ActiveTemplateInstantiation::TemplateInstantiation,
235 PointOfInstantiation, InstantiationRange, Entity);
Douglas Gregor79cf6032009-03-10 20:44:00 +0000236}
237
Richard Smithf623c962012-04-17 00:58:00 +0000238Sema::InstantiatingTemplate::
239InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
240 FunctionDecl *Entity, ExceptionSpecification,
241 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000242 : SemaRef(SemaRef)
Richard Smithf623c962012-04-17 00:58:00 +0000243{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000244 Initialize(ActiveTemplateInstantiation::ExceptionSpecInstantiation,
245 PointOfInstantiation, InstantiationRange, Entity);
Richard Smithf623c962012-04-17 00:58:00 +0000246}
247
Richard Smith80934652012-07-16 01:09:10 +0000248Sema::InstantiatingTemplate::
249InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
250 TemplateDecl *Template,
251 ArrayRef<TemplateArgument> TemplateArgs,
252 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000253 : SemaRef(SemaRef)
Douglas Gregoredb76852011-01-27 22:31:44 +0000254{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000255 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
256 PointOfInstantiation, InstantiationRange,
257 Template, nullptr, TemplateArgs);
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000258}
259
Richard Smith80934652012-07-16 01:09:10 +0000260Sema::InstantiatingTemplate::
261InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
262 FunctionTemplateDecl *FunctionTemplate,
263 ArrayRef<TemplateArgument> TemplateArgs,
264 ActiveTemplateInstantiation::InstantiationKind Kind,
265 sema::TemplateDeductionInfo &DeductionInfo,
266 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000267 : SemaRef(SemaRef)
Douglas Gregoredb76852011-01-27 22:31:44 +0000268{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000269 Initialize(Kind, PointOfInstantiation, InstantiationRange,
270 FunctionTemplate, nullptr, TemplateArgs, &DeductionInfo);
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000271}
272
Richard Smith80934652012-07-16 01:09:10 +0000273Sema::InstantiatingTemplate::
274InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
275 ClassTemplatePartialSpecializationDecl *PartialSpec,
276 ArrayRef<TemplateArgument> TemplateArgs,
277 sema::TemplateDeductionInfo &DeductionInfo,
278 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000279 : SemaRef(SemaRef)
Douglas Gregoredb76852011-01-27 22:31:44 +0000280{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000281 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
282 PointOfInstantiation, InstantiationRange,
283 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
Douglas Gregor637d9982009-06-10 23:47:09 +0000284}
285
Larisse Voufo39a1e502013-08-06 01:03:05 +0000286Sema::InstantiatingTemplate::InstantiatingTemplate(
287 Sema &SemaRef, SourceLocation PointOfInstantiation,
288 VarTemplatePartialSpecializationDecl *PartialSpec,
289 ArrayRef<TemplateArgument> TemplateArgs,
290 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000291 : SemaRef(SemaRef)
292{
293 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
294 PointOfInstantiation, InstantiationRange,
295 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000296}
297
Richard Smith80934652012-07-16 01:09:10 +0000298Sema::InstantiatingTemplate::
299InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
300 ParmVarDecl *Param,
301 ArrayRef<TemplateArgument> TemplateArgs,
302 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000303 : SemaRef(SemaRef)
Douglas Gregoredb76852011-01-27 22:31:44 +0000304{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000305 Initialize(ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
306 PointOfInstantiation, InstantiationRange,
307 Param, nullptr, TemplateArgs);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000308}
309
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000310
Douglas Gregore62e6a02009-11-11 19:13:48 +0000311Sema::InstantiatingTemplate::
312InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith80934652012-07-16 01:09:10 +0000313 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
314 ArrayRef<TemplateArgument> TemplateArgs,
315 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000316 : SemaRef(SemaRef)
Douglas Gregoredb76852011-01-27 22:31:44 +0000317{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000318 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
319 PointOfInstantiation, InstantiationRange,
320 Param, Template, TemplateArgs);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000321}
322
323Sema::InstantiatingTemplate::
324InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith80934652012-07-16 01:09:10 +0000325 NamedDecl *Template, TemplateTemplateParmDecl *Param,
326 ArrayRef<TemplateArgument> TemplateArgs,
327 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000328 : SemaRef(SemaRef)
Douglas Gregoredb76852011-01-27 22:31:44 +0000329{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000330 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
331 PointOfInstantiation, InstantiationRange,
332 Param, Template, TemplateArgs);
Douglas Gregor84d49a22009-11-11 21:54:23 +0000333}
334
335Sema::InstantiatingTemplate::
336InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith80934652012-07-16 01:09:10 +0000337 TemplateDecl *Template, NamedDecl *Param,
338 ArrayRef<TemplateArgument> TemplateArgs,
339 SourceRange InstantiationRange)
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000340 : SemaRef(SemaRef)
Douglas Gregoredb76852011-01-27 22:31:44 +0000341{
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000342 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
343 PointOfInstantiation, InstantiationRange,
344 Param, Template, TemplateArgs);
Anders Carlsson657bad42009-09-05 05:14:19 +0000345}
346
Douglas Gregor85673582009-05-18 17:01:57 +0000347void Sema::InstantiatingTemplate::Clear() {
348 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000349 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
350 assert(SemaRef.NonInstantiationEntries > 0);
351 --SemaRef.NonInstantiationEntries;
352 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000353 SemaRef.InNonInstantiationSFINAEContext
354 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000355
356 // Name lookup no longer looks in this template's defining module.
357 assert(SemaRef.ActiveTemplateInstantiations.size() >=
358 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
359 "forgot to remove a lookup module for a template instantiation");
360 if (SemaRef.ActiveTemplateInstantiations.size() ==
361 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
362 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
363 SemaRef.LookupModulesCache.erase(M);
364 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
365 }
366
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000367 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000368 Invalid = true;
369 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000370}
371
Douglas Gregor79cf6032009-03-10 20:44:00 +0000372bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
373 SourceLocation PointOfInstantiation,
374 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000375 assert(SemaRef.NonInstantiationEntries <=
376 SemaRef.ActiveTemplateInstantiations.size());
377 if ((SemaRef.ActiveTemplateInstantiations.size() -
378 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000379 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000380 return false;
381
Mike Stump11289f42009-09-09 15:08:12 +0000382 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000383 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000384 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000385 << InstantiationRange;
386 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000387 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000388 return true;
389}
390
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000391/// \brief Prints the current instantiation stack through a series of
392/// notes.
393void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000394 // Determine which template instantiations to skip, if any.
395 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
396 unsigned Limit = Diags.getTemplateBacktraceLimit();
397 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
398 SkipStart = Limit / 2 + Limit % 2;
399 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
400 }
401
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000402 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000403 unsigned InstantiationIdx = 0;
Craig Topper2341c0d2013-07-04 03:08:24 +0000404 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000405 Active = ActiveTemplateInstantiations.rbegin(),
406 ActiveEnd = ActiveTemplateInstantiations.rend();
407 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000408 ++Active, ++InstantiationIdx) {
409 // Skip this instantiation?
410 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
411 if (InstantiationIdx == SkipStart) {
412 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000413 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000414 diag::note_instantiation_contexts_suppressed)
415 << unsigned(ActiveTemplateInstantiations.size() - Limit);
416 }
417 continue;
418 }
419
Douglas Gregor79cf6032009-03-10 20:44:00 +0000420 switch (Active->Kind) {
421 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000422 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000423 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
424 unsigned DiagID = diag::note_template_member_class_here;
425 if (isa<ClassTemplateSpecializationDecl>(Record))
426 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000427 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000428 << Context.getTypeDeclType(Record)
429 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000430 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000431 unsigned DiagID;
432 if (Function->getPrimaryTemplate())
433 DiagID = diag::note_function_template_spec_here;
434 else
435 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000436 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000437 << Function
438 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000439 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000440 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000441 VD->isStaticDataMember()?
442 diag::note_template_static_data_member_def_here
443 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000444 << VD
445 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000446 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
447 Diags.Report(Active->PointOfInstantiation,
448 diag::note_template_enum_def_here)
449 << ED
450 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000451 } else {
452 Diags.Report(Active->PointOfInstantiation,
453 diag::note_template_type_alias_instantiation_here)
454 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000455 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000456 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000457 break;
458 }
459
460 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000461 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000462 SmallVector<char, 128> TemplateArgsStr;
463 llvm::raw_svector_ostream OS(TemplateArgsStr);
464 Template->printName(OS);
465 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000466 Active->TemplateArgs,
Douglas Gregor7de59662009-05-29 20:38:28 +0000467 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000468 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000469 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000470 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000471 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000472 << Active->InstantiationRange;
473 break;
474 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000475
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000476 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000477 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000478 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000479 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000480 << FnTmpl
481 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
482 Active->TemplateArgs,
483 Active->NumTemplateArgs)
484 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000485 break;
486 }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000488 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000489 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
490 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000491 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000492 diag::note_partial_spec_deduct_instantiation_here)
493 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000494 << getTemplateArgumentBindingsText(
495 PartialSpec->getTemplateParameters(),
496 Active->TemplateArgs,
497 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000498 << Active->InstantiationRange;
499 } else {
500 FunctionTemplateDecl *FnTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000501 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000502 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000503 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000504 << FnTmpl
505 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
506 Active->TemplateArgs,
507 Active->NumTemplateArgs)
508 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000509 }
510 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000511
Anders Carlsson657bad42009-09-05 05:14:19 +0000512 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000513 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000514 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000515
Benjamin Kramer9170e912013-02-22 15:46:01 +0000516 SmallVector<char, 128> TemplateArgsStr;
517 llvm::raw_svector_ostream OS(TemplateArgsStr);
518 FD->printName(OS);
519 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000520 Active->TemplateArgs,
Anders Carlsson657bad42009-09-05 05:14:19 +0000521 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000522 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000523 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000524 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000525 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000526 << Active->InstantiationRange;
527 break;
528 }
Mike Stump11289f42009-09-09 15:08:12 +0000529
Douglas Gregore62e6a02009-11-11 19:13:48 +0000530 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000531 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000532 std::string Name;
533 if (!Parm->getName().empty())
534 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000535
536 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000537 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
538 TemplateParams = Template->getTemplateParameters();
539 else
540 TemplateParams =
541 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
542 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000543 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000544 diag::note_prior_template_arg_substitution)
545 << isa<TemplateTemplateParmDecl>(Parm)
546 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000547 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000548 Active->TemplateArgs,
549 Active->NumTemplateArgs)
550 << Active->InstantiationRange;
551 break;
552 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000553
554 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000555 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000556 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
557 TemplateParams = Template->getTemplateParameters();
558 else
559 TemplateParams =
560 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
561 ->getTemplateParameters();
562
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000563 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000564 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000565 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000566 Active->TemplateArgs,
567 Active->NumTemplateArgs)
568 << Active->InstantiationRange;
569 break;
570 }
Richard Smithf623c962012-04-17 00:58:00 +0000571
572 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
573 Diags.Report(Active->PointOfInstantiation,
574 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000575 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000576 << Active->InstantiationRange;
577 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000578 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000579 }
580}
581
David Blaikie05785d12013-02-20 22:23:23 +0000582Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000583 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000584 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000585
Craig Topper2341c0d2013-07-04 03:08:24 +0000586 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000587 Active = ActiveTemplateInstantiations.rbegin(),
588 ActiveEnd = ActiveTemplateInstantiations.rend();
589 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000590 ++Active)
591 {
Douglas Gregor33834512009-06-14 07:33:30 +0000592 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000593 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000594 // An instantiation of an alias template may or may not be a SFINAE
595 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000596 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000597 break;
598 // Fall through.
599 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000600 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000601 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000602 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000603
Douglas Gregor33834512009-06-14 07:33:30 +0000604 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000605 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000606 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000607 // A default template argument instantiation and substitution into
608 // template parameters with arguments for prior parameters may or may
609 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000610 break;
Mike Stump11289f42009-09-09 15:08:12 +0000611
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000612 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
613 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
614 // We're either substitution explicitly-specified template arguments
615 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000616 assert(Active->DeductionInfo && "Missing deduction info pointer");
617 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000618 }
619 }
620
David Blaikie7a30dc52013-02-21 01:47:18 +0000621 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000622}
623
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000624/// \brief Retrieve the depth and index of a parameter pack.
625static std::pair<unsigned, unsigned>
626getDepthAndIndex(NamedDecl *ND) {
627 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
628 return std::make_pair(TTP->getDepth(), TTP->getIndex());
629
630 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
631 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
632
633 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
634 return std::make_pair(TTP->getDepth(), TTP->getIndex());
635}
636
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000637//===----------------------------------------------------------------------===/
638// Template Instantiation for Types
639//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000640namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000641 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000642 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000643 SourceLocation Loc;
644 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000645
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000646 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000647 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000648
649 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000650 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000651 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000652 DeclarationName Entity)
653 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000654 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000655
Mike Stump11289f42009-09-09 15:08:12 +0000656 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000657 /// transformed.
658 ///
659 /// For the purposes of template instantiation, a type has already been
660 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000661 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000662
Douglas Gregord6ff3322009-08-04 16:50:30 +0000663 /// \brief Returns the location of the entity being instantiated, if known.
664 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000665
Douglas Gregord6ff3322009-08-04 16:50:30 +0000666 /// \brief Returns the name of the entity being instantiated, if any.
667 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000668
Douglas Gregoref6ab412009-10-27 06:26:26 +0000669 /// \brief Sets the "base" location and entity when that
670 /// information is known based on another transformation.
671 void setBase(SourceLocation Loc, DeclarationName Entity) {
672 this->Loc = Loc;
673 this->Entity = Entity;
674 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000675
676 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
677 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000678 ArrayRef<UnexpandedParameterPack> Unexpanded,
679 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000680 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000681 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
682 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000683 TemplateArgs,
684 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000685 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000686 NumExpansions);
687 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000688
Douglas Gregorf3010112011-01-07 16:43:16 +0000689 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
690 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
691 }
692
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000693 TemplateArgument ForgetPartiallySubstitutedPack() {
694 TemplateArgument Result;
695 if (NamedDecl *PartialPack
696 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
697 MultiLevelTemplateArgumentList &TemplateArgs
698 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
699 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000700 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000701 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
702 Result = TemplateArgs(Depth, Index);
703 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
704 }
705 }
706
707 return Result;
708 }
709
710 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
711 if (Arg.isNull())
712 return;
713
714 if (NamedDecl *PartialPack
715 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
716 MultiLevelTemplateArgumentList &TemplateArgs
717 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
718 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000719 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000720 TemplateArgs.setArgument(Depth, Index, Arg);
721 }
722 }
723
Douglas Gregord6ff3322009-08-04 16:50:30 +0000724 /// \brief Transform the given declaration by instantiating a reference to
725 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000726 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000727
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000728 void transformAttrs(Decl *Old, Decl *New) {
729 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
730 }
731
732 void transformedLocalDecl(Decl *Old, Decl *New) {
733 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
734 }
735
Mike Stump11289f42009-09-09 15:08:12 +0000736 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000737 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000738 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000739
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000740 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000741 /// declaration.
742 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
743
Douglas Gregorebe10102009-08-20 07:17:43 +0000744 /// \brief Rebuild the exception declaration and register the declaration
745 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000746 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000747 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000748 SourceLocation StartLoc,
749 SourceLocation NameLoc,
750 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000751
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000752 /// \brief Rebuild the Objective-C exception declaration and register the
753 /// declaration as an instantiated local.
754 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
755 TypeSourceInfo *TSInfo, QualType T);
756
John McCall7f41d982009-09-11 04:59:25 +0000757 /// \brief Check for tag mismatches when instantiating an
758 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000759 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
760 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000761 NestedNameSpecifierLoc QualifierLoc,
762 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000763
Craig Topperc3ec1492014-05-26 06:22:03 +0000764 TemplateName
765 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
766 SourceLocation NameLoc,
767 QualType ObjectType = QualType(),
768 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000769
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000770 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
771
John McCalldadc5752010-08-24 06:29:42 +0000772 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
773 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
774 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000775
John McCalldadc5752010-08-24 06:29:42 +0000776 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000777 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000778 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
779 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000780
781 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
782 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
783
784 /// \brief Transform a reference to a function parameter pack.
785 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
786 ParmVarDecl *PD);
787
788 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
789 /// expand a function parameter pack reference which refers to an expanded
790 /// pack.
791 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
792
Hans Wennborge113c202014-09-18 16:01:32 +0000793 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000794 FunctionProtoTypeLoc TL) {
795 // Call the base version; it will forward to our overridden version below.
796 return inherited::TransformFunctionProtoType(TLB, TL);
797 }
798
799 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000800 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
801 FunctionProtoTypeLoc TL,
802 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000803 unsigned ThisTypeQuals,
804 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000805
Douglas Gregor715e4612011-01-14 22:40:04 +0000806 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000807 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000808 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000809 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000810
Mike Stump11289f42009-09-09 15:08:12 +0000811 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000812 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000813 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000814 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000815
Douglas Gregorada4b792011-01-14 02:55:32 +0000816 /// \brief Transforms an already-substituted template type parameter pack
817 /// into either itself (if we aren't substituting into its pack expansion)
818 /// or the appropriate substituted argument.
819 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
820 SubstTemplateTypeParmPackTypeLoc TL);
821
John McCalldadc5752010-08-24 06:29:42 +0000822 ExprResult TransformCallExpr(CallExpr *CE) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000823 getSema().CallsUndergoingInstantiation.push_back(CE);
John McCalldadc5752010-08-24 06:29:42 +0000824 ExprResult Result =
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000825 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
826 getSema().CallsUndergoingInstantiation.pop_back();
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000827 return Result;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000828 }
John McCall7c454bb2011-07-15 05:09:51 +0000829
Richard Smith2589b9802012-07-25 03:56:55 +0000830 ExprResult TransformLambdaExpr(LambdaExpr *E) {
831 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
832 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
833 }
834
835 ExprResult TransformLambdaScope(LambdaExpr *E,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000836 CXXMethodDecl *NewCallOperator,
837 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
Faisal Vali2cba1332013-10-23 06:44:28 +0000838 CXXMethodDecl *const OldCallOperator = E->getCallOperator();
839 // In the generic lambda case, we set the NewTemplate to be considered
840 // an "instantiation" of the OldTemplate.
841 if (FunctionTemplateDecl *const NewCallOperatorTemplate =
842 NewCallOperator->getDescribedFunctionTemplate()) {
843
844 FunctionTemplateDecl *const OldCallOperatorTemplate =
845 OldCallOperator->getDescribedFunctionTemplate();
846 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
847 OldCallOperatorTemplate);
Faisal Vali2cba1332013-10-23 06:44:28 +0000848 } else
849 // For a non-generic lambda we set the NewCallOperator to
850 // be an instantiation of the OldCallOperator.
851 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
852 TSK_ImplicitInstantiation);
853
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000854 return inherited::TransformLambdaScope(E, NewCallOperator,
855 InitCaptureExprsAndTypes);
Rafael Espindola4b35f272013-10-04 14:28:51 +0000856 }
David Majnemerb1004102014-03-02 18:46:05 +0000857 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000858 TemplateParameterList *OrigTPL) {
859 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
860
861 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
862 TemplateDeclInstantiator DeclInstantiator(getSema(),
863 /* DeclContext *Owner */ Owner, TemplateArgs);
864 return DeclInstantiator.SubstTemplateParams(OrigTPL);
865 }
John McCall7c454bb2011-07-15 05:09:51 +0000866 private:
867 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
868 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000869 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000870 };
Douglas Gregor04318252009-07-06 15:59:29 +0000871}
872
Douglas Gregor5597ab42010-05-07 23:12:07 +0000873bool TemplateInstantiator::AlreadyTransformed(QualType T) {
874 if (T.isNull())
875 return true;
876
Douglas Gregor678d76c2011-07-01 01:22:09 +0000877 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000878 return false;
879
880 getSema().MarkDeclarationsReferencedInType(Loc, T);
881 return true;
882}
883
Eli Friedman8917ad52013-07-19 19:40:38 +0000884static TemplateArgument
885getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
886 assert(S.ArgumentPackSubstitutionIndex >= 0);
887 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
888 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
889 if (Arg.isPackExpansion())
890 Arg = Arg.getPackExpansionPattern();
891 return Arg;
892}
893
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000894Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000895 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000896 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000898 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000899 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000900 // If the corresponding template argument is NULL or non-existent, it's
901 // because we are performing instantiation from explicitly-specified
902 // template arguments in a function template, but there were some
903 // arguments left unspecified.
904 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
905 TTP->getPosition()))
906 return D;
907
Douglas Gregorf5500772011-01-05 15:48:55 +0000908 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
909
910 if (TTP->isParameterPack()) {
911 assert(Arg.getKind() == TemplateArgument::Pack &&
912 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000913 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000914 }
915
916 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000917 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000918 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000919 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000920 }
Mike Stump11289f42009-09-09 15:08:12 +0000921
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000922 // Fall through to find the instantiated declaration for this template
923 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000924 }
Mike Stump11289f42009-09-09 15:08:12 +0000925
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000926 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000927}
928
Douglas Gregor25289362010-03-01 17:25:41 +0000929Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000930 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000931 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000932 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000933
Douglas Gregorebe10102009-08-20 07:17:43 +0000934 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
935 return Inst;
936}
937
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000938NamedDecl *
939TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
940 SourceLocation Loc) {
941 // If the first part of the nested-name-specifier was a template type
942 // parameter, instantiate that type parameter down to a tag type.
943 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
944 const TemplateTypeParmType *TTP
945 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000946
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000947 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000948 // FIXME: This needs testing w/ member access expressions.
949 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
950
951 if (TTP->isParameterPack()) {
952 assert(Arg.getKind() == TemplateArgument::Pack &&
953 "Missing argument pack");
954
Douglas Gregore1d60df2011-01-14 23:41:42 +0000955 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000956 return nullptr;
957
Eli Friedman8917ad52013-07-19 19:40:38 +0000958 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000959 }
960
961 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000962 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000963 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000964
965 if (const TagType *Tag = T->getAs<TagType>())
966 return Tag->getDecl();
967
968 // The resulting type is not a tag; complain.
969 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000970 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000971 }
972 }
973
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000974 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000975}
976
Douglas Gregorebe10102009-08-20 07:17:43 +0000977VarDecl *
978TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000979 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000980 SourceLocation StartLoc,
981 SourceLocation NameLoc,
982 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000983 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000984 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000985 if (Var)
986 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
987 return Var;
988}
989
990VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
991 TypeSourceInfo *TSInfo,
992 QualType T) {
993 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
994 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000995 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
996 return Var;
997}
998
John McCall7f41d982009-09-11 04:59:25 +0000999QualType
John McCall954b5de2010-11-04 19:04:38 +00001000TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1001 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001002 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001003 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001004 if (const TagType *TT = T->getAs<TagType>()) {
1005 TagDecl* TD = TT->getDecl();
1006
John McCall954b5de2010-11-04 19:04:38 +00001007 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001008
John McCall7f41d982009-09-11 04:59:25 +00001009 IdentifierInfo *Id = TD->getIdentifier();
1010
1011 // TODO: should we even warn on struct/class mismatches for this? Seems
1012 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001013 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001014 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001015 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1016 TagLocation, *Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001017 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1018 << Id
1019 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1020 TD->getKindName());
1021 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1022 }
John McCall7f41d982009-09-11 04:59:25 +00001023 }
1024 }
1025
John McCall954b5de2010-11-04 19:04:38 +00001026 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1027 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001028 QualifierLoc,
1029 T);
John McCall7f41d982009-09-11 04:59:25 +00001030}
1031
Douglas Gregor9db53502011-03-02 18:07:45 +00001032TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1033 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001034 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001035 QualType ObjectType,
1036 NamedDecl *FirstQualifierInScope) {
1037 if (TemplateTemplateParmDecl *TTP
1038 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1039 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1040 // If the corresponding template argument is NULL or non-existent, it's
1041 // because we are performing instantiation from explicitly-specified
1042 // template arguments in a function template, but there were some
1043 // arguments left unspecified.
1044 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1045 TTP->getPosition()))
1046 return Name;
1047
1048 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1049
1050 if (TTP->isParameterPack()) {
1051 assert(Arg.getKind() == TemplateArgument::Pack &&
1052 "Missing argument pack");
1053
1054 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1055 // We have the template argument pack to substitute, but we're not
1056 // actually expanding the enclosing pack expansion yet. So, just
1057 // keep the entire argument pack.
1058 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1059 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001060
1061 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001062 }
1063
1064 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001065 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001066
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001067 // We don't ever want to substitute for a qualified template name, since
1068 // the qualifier is handled separately. So, look through the qualified
1069 // template name to its underlying declaration.
1070 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1071 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001072
1073 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001074 return Template;
1075 }
1076 }
1077
1078 if (SubstTemplateTemplateParmPackStorage *SubstPack
1079 = Name.getAsSubstTemplateTemplateParmPack()) {
1080 if (getSema().ArgumentPackSubstitutionIndex == -1)
1081 return Name;
1082
Eli Friedman8917ad52013-07-19 19:40:38 +00001083 TemplateArgument Arg = SubstPack->getArgumentPack();
1084 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1085 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001086 }
1087
1088 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1089 FirstQualifierInScope);
1090}
1091
John McCalldadc5752010-08-24 06:29:42 +00001092ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001093TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001094 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001095 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001096
Wei Panc354d212013-09-16 13:57:27 +00001097 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001098}
1099
John McCalldadc5752010-08-24 06:29:42 +00001100ExprResult
John McCall13481c52010-02-06 08:42:39 +00001101TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001102 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001103 // If the corresponding template argument is NULL or non-existent, it's
1104 // because we are performing instantiation from explicitly-specified
1105 // template arguments in a function template, but there were some
1106 // arguments left unspecified.
1107 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1108 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001109 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001110
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001111 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1112 if (NTTP->isParameterPack()) {
1113 assert(Arg.getKind() == TemplateArgument::Pack &&
1114 "Missing argument pack");
1115
1116 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001117 // We have an argument pack, but we can't select a particular argument
1118 // out of it yet. Therefore, we'll build an expression to hold on to that
1119 // argument pack.
1120 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1121 E->getLocation(),
1122 NTTP->getDeclName());
1123 if (TargetType.isNull())
1124 return ExprError();
1125
1126 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1127 NTTP,
1128 E->getLocation(),
1129 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001130 }
1131
Eli Friedman8917ad52013-07-19 19:40:38 +00001132 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001133 }
Mike Stump11289f42009-09-09 15:08:12 +00001134
John McCall7c454bb2011-07-15 05:09:51 +00001135 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1136}
1137
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001138const LoopHintAttr *
1139TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1140 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1141
1142 if (TransformedExpr == LH->getValue())
1143 return LH;
1144
1145 // Generate error if there is a problem with the value.
1146 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1147 return LH;
1148
1149 // Create new LoopHintValueAttr with integral expression in place of the
1150 // non-type template parameter.
1151 return LoopHintAttr::CreateImplicit(
1152 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1153 LH->getState(), TransformedExpr, LH->getRange());
1154}
1155
John McCall7c454bb2011-07-15 05:09:51 +00001156ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1157 NonTypeTemplateParmDecl *parm,
1158 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001159 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001160 ExprResult result;
1161 QualType type;
1162
John McCall13481c52010-02-06 08:42:39 +00001163 // The template argument itself might be an expression, in which
1164 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001165 if (arg.getKind() == TemplateArgument::Expression) {
1166 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001167 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001168 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001169
Eli Friedmanb826a002012-09-26 02:36:12 +00001170 } else if (arg.getKind() == TemplateArgument::Declaration ||
1171 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001172 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001173 if (arg.getKind() == TemplateArgument::Declaration) {
1174 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001175
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001176 // Find the instantiation of the template argument. This is
1177 // required for nested templates.
1178 VD = cast_or_null<ValueDecl>(
1179 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1180 if (!VD)
1181 return ExprError();
1182 } else {
1183 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001184 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001185 }
1186
John McCall15dda372010-02-06 10:23:53 +00001187 // Derive the type we want the substituted decl to have. This had
1188 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001189 if (parm->isExpandedParameterPack()) {
1190 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1191 } else if (parm->isParameterPack() &&
1192 isa<PackExpansionType>(parm->getType())) {
1193 type = SemaRef.SubstType(
1194 cast<PackExpansionType>(parm->getType())->getPattern(),
1195 TemplateArgs, loc, parm->getDeclName());
1196 } else {
1197 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1198 loc, parm->getDeclName());
1199 }
1200 assert(!type.isNull() && "type substitution failed for param type");
1201 assert(!type->isDependentType() && "param type still dependent");
1202 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001203
John McCall7c454bb2011-07-15 05:09:51 +00001204 if (!result.isInvalid()) type = result.get()->getType();
1205 } else {
1206 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1207
1208 // Note that this type can be different from the type of 'result',
1209 // e.g. if it's an enum type.
1210 type = arg.getIntegralType();
1211 }
1212 if (result.isInvalid()) return ExprError();
1213
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001214 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001215 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1216 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001217}
1218
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001219ExprResult
1220TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1221 SubstNonTypeTemplateParmPackExpr *E) {
1222 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1223 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001224 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001225 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001226
1227 TemplateArgument Arg = E->getArgumentPack();
1228 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001229 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1230 E->getParameterPackLocation(),
1231 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001232}
John McCall13481c52010-02-06 08:42:39 +00001233
John McCalldadc5752010-08-24 06:29:42 +00001234ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001235TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1236 SourceLocation Loc) {
1237 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1238 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1239}
1240
1241ExprResult
1242TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1243 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1244 // We can expand this parameter pack now.
1245 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1246 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1247 if (!VD)
1248 return ExprError();
1249 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1250 }
1251
1252 QualType T = TransformType(E->getType());
1253 if (T.isNull())
1254 return ExprError();
1255
1256 // Transform each of the parameter expansions into the corresponding
1257 // parameters in the instantiation of the function decl.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001258 SmallVector<Decl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001259 Parms.reserve(E->getNumExpansions());
1260 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1261 I != End; ++I) {
1262 ParmVarDecl *D =
1263 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1264 if (!D)
1265 return ExprError();
1266 Parms.push_back(D);
1267 }
1268
1269 return FunctionParmPackExpr::Create(getSema().Context, T,
1270 E->getParameterPack(),
1271 E->getParameterPackLocation(), Parms);
1272}
1273
1274ExprResult
1275TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1276 ParmVarDecl *PD) {
1277 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1278 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1279 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1280 assert(Found && "no instantiation for parameter pack");
1281
1282 Decl *TransformedDecl;
1283 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001284 // If this is a reference to a function parameter pack which we can
1285 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001286 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1287 QualType T = TransformType(E->getType());
1288 if (T.isNull())
1289 return ExprError();
1290 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1291 E->getExprLoc(), *Pack);
1292 }
1293
1294 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1295 } else {
1296 TransformedDecl = Found->get<Decl*>();
1297 }
1298
1299 // We have either an unexpanded pack or a specific expansion.
1300 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1301 E->getExprLoc());
1302}
1303
1304ExprResult
John McCall13481c52010-02-06 08:42:39 +00001305TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1306 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001307
1308 // Handle references to non-type template parameters and non-type template
1309 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001310 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1311 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1312 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001313
1314 // We have a non-type template parameter that isn't fully substituted;
1315 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001316 }
Mike Stump11289f42009-09-09 15:08:12 +00001317
Richard Smithb15fe3a2012-09-12 00:56:43 +00001318 // Handle references to function parameter packs.
1319 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1320 if (PD->isParameterPack())
1321 return TransformFunctionParmPackRefExpr(E, PD);
1322
John McCall47f29ea2009-12-08 09:21:05 +00001323 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001324}
1325
John McCalldadc5752010-08-24 06:29:42 +00001326ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001327 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001328 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1329 getDescribedFunctionTemplate() &&
1330 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001331 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1332 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1333 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001334}
1335
Richard Smith2e321552014-11-12 02:00:47 +00001336template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001337QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1338 FunctionProtoTypeLoc TL,
1339 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001340 unsigned ThisTypeQuals,
1341 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001342 // We need a local instantiation scope for this function prototype.
1343 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001344 return inherited::TransformFunctionProtoType(
1345 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001346}
1347
John McCall58f10c32010-03-11 09:03:00 +00001348ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001349TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001350 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001351 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001352 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001353 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001354 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001355}
1356
Mike Stump11289f42009-09-09 15:08:12 +00001357QualType
John McCall550e0c22009-10-21 00:40:46 +00001358TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001359 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001360 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001361 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001362 // Replace the template type parameter with its corresponding
1363 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001364
1365 // If the corresponding template argument is NULL or doesn't exist, it's
1366 // because we are performing instantiation from explicitly-specified
1367 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001368 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001369 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1370 TemplateTypeParmTypeLoc NewTL
1371 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1372 NewTL.setNameLoc(TL.getNameLoc());
1373 return TL.getType();
1374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001376 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1377
1378 if (T->isParameterPack()) {
1379 assert(Arg.getKind() == TemplateArgument::Pack &&
1380 "Missing argument pack");
1381
1382 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001383 // We have the template argument pack, but we're not expanding the
1384 // enclosing pack expansion yet. Just save the template argument
1385 // pack for later substitution.
1386 QualType Result
1387 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1388 SubstTemplateTypeParmPackTypeLoc NewTL
1389 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1390 NewTL.setNameLoc(TL.getNameLoc());
1391 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001392 }
1393
Eli Friedman8917ad52013-07-19 19:40:38 +00001394 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001395 }
1396
1397 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001398 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001399
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001400 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001401
1402 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001403 QualType Result
1404 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1405 SubstTemplateTypeParmTypeLoc NewTL
1406 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1407 NewTL.setNameLoc(TL.getNameLoc());
1408 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001409 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001410
1411 // The template type parameter comes from an inner template (e.g.,
1412 // the template parameter list of a member template inside the
1413 // template we are instantiating). Create a new template type
1414 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001415 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001416 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1417 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1418 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1419
John McCall550e0c22009-10-21 00:40:46 +00001420 QualType Result
1421 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1422 - TemplateArgs.getNumLevels(),
1423 T->getIndex(),
1424 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001425 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001426 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1427 NewTL.setNameLoc(TL.getNameLoc());
1428 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001429}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001430
Douglas Gregorada4b792011-01-14 02:55:32 +00001431QualType
1432TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1433 TypeLocBuilder &TLB,
1434 SubstTemplateTypeParmPackTypeLoc TL) {
1435 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1436 // We aren't expanding the parameter pack, so just return ourselves.
1437 SubstTemplateTypeParmPackTypeLoc NewTL
1438 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1439 NewTL.setNameLoc(TL.getNameLoc());
1440 return TL.getType();
1441 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001442
1443 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1444 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1445 QualType Result = Arg.getAsType();
1446
Douglas Gregorada4b792011-01-14 02:55:32 +00001447 Result = getSema().Context.getSubstTemplateTypeParmType(
1448 TL.getTypePtr()->getReplacedParameter(),
1449 Result);
1450 SubstTemplateTypeParmTypeLoc NewTL
1451 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1452 NewTL.setNameLoc(TL.getNameLoc());
1453 return Result;
1454}
1455
John McCall76d824f2009-08-25 22:02:44 +00001456/// \brief Perform substitution on the type T with a given set of template
1457/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001458///
1459/// This routine substitutes the given template arguments into the
1460/// type T and produces the instantiated type.
1461///
1462/// \param T the type into which the template arguments will be
1463/// substituted. If this type is not dependent, it will be returned
1464/// immediately.
1465///
James Dennett634962f2012-06-14 21:40:34 +00001466/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001467/// substituted for the top-level template parameters within T.
1468///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001469/// \param Loc the location in the source code where this substitution
1470/// is being performed. It will typically be the location of the
1471/// declarator (if we're instantiating the type of some declaration)
1472/// or the location of the type in the source code (if, e.g., we're
1473/// instantiating the type of a cast expression).
1474///
1475/// \param Entity the name of the entity associated with a declaration
1476/// being instantiated (if any). May be empty to indicate that there
1477/// is no such entity (if, e.g., this is a type that occurs as part of
1478/// a cast expression) or that the entity has no name (e.g., an
1479/// unnamed function parameter).
1480///
1481/// \returns If the instantiation succeeds, the instantiated
1482/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001483TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001484 const MultiLevelTemplateArgumentList &Args,
1485 SourceLocation Loc,
1486 DeclarationName Entity) {
1487 assert(!ActiveTemplateInstantiations.empty() &&
1488 "Cannot perform an instantiation without some context on the "
1489 "instantiation stack");
1490
Douglas Gregor678d76c2011-07-01 01:22:09 +00001491 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001492 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001493 return T;
1494
1495 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1496 return Instantiator.TransformType(T);
1497}
1498
Douglas Gregor5499af42011-01-05 23:12:31 +00001499TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1500 const MultiLevelTemplateArgumentList &Args,
1501 SourceLocation Loc,
1502 DeclarationName Entity) {
1503 assert(!ActiveTemplateInstantiations.empty() &&
1504 "Cannot perform an instantiation without some context on the "
1505 "instantiation stack");
1506
1507 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001508 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001509
Douglas Gregor678d76c2011-07-01 01:22:09 +00001510 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001511 !TL.getType()->isVariablyModifiedType()) {
1512 // FIXME: Make a copy of the TypeLoc data here, so that we can
1513 // return a new TypeSourceInfo. Inefficient!
1514 TypeLocBuilder TLB;
1515 TLB.pushFullCopy(TL);
1516 return TLB.getTypeSourceInfo(Context, TL.getType());
1517 }
1518
1519 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1520 TypeLocBuilder TLB;
1521 TLB.reserve(TL.getFullDataSize());
1522 QualType Result = Instantiator.TransformType(TLB, TL);
1523 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001524 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001525
1526 return TLB.getTypeSourceInfo(Context, Result);
1527}
1528
John McCall609459e2009-10-21 00:58:09 +00001529/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001530QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001531 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001532 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001533 assert(!ActiveTemplateInstantiations.empty() &&
1534 "Cannot perform an instantiation without some context on the "
1535 "instantiation stack");
1536
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001537 // If T is not a dependent type or a variably-modified type, there
1538 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001539 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001540 return T;
1541
Douglas Gregord6ff3322009-08-04 16:50:30 +00001542 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1543 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001544}
Douglas Gregor463421d2009-03-03 04:44:36 +00001545
John McCallb29f78f2010-04-09 17:38:44 +00001546static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Douglas Gregor678d76c2011-07-01 01:22:09 +00001547 if (T->getType()->isInstantiationDependentType() ||
1548 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001549 return true;
1550
Abramo Bagnara6d810632010-12-14 22:11:44 +00001551 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001552 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001553 return false;
1554
David Blaikie6adc78e2013-02-18 22:06:02 +00001555 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00001556 for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) {
1557 ParmVarDecl *P = FP.getParam(I);
John McCallb29f78f2010-04-09 17:38:44 +00001558
Reid Klecknera09e44c2013-07-31 21:00:18 +00001559 // This must be synthesized from a typedef.
1560 if (!P) continue;
1561
Douglas Gregora7203e52011-05-09 20:45:16 +00001562 // The parameter's type as written might be dependent even if the
1563 // decayed type was not dependent.
1564 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
Douglas Gregor678d76c2011-07-01 01:22:09 +00001565 if (TSInfo->getType()->isInstantiationDependentType())
Douglas Gregora7203e52011-05-09 20:45:16 +00001566 return true;
1567
John McCallb29f78f2010-04-09 17:38:44 +00001568 // TODO: currently we always rebuild expressions. When we
1569 // properly get lazier about this, we should use the same
1570 // logic to avoid rebuilding prototypes here.
Douglas Gregor9cc278222011-01-05 21:14:17 +00001571 if (P->hasDefaultArg())
John McCallb29f78f2010-04-09 17:38:44 +00001572 return true;
1573 }
1574
1575 return false;
1576}
1577
1578/// A form of SubstType intended specifically for instantiating the
1579/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001580/// instantiation of default-argument expressions and to avoid
1581/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001582TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1583 const MultiLevelTemplateArgumentList &Args,
1584 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001585 DeclarationName Entity,
1586 CXXRecordDecl *ThisContext,
1587 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001588 assert(!ActiveTemplateInstantiations.empty() &&
1589 "Cannot perform an instantiation without some context on the "
1590 "instantiation stack");
1591
1592 if (!NeedsInstantiationAsFunctionType(T))
1593 return T;
1594
1595 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1596
1597 TypeLocBuilder TLB;
1598
1599 TypeLoc TL = T->getTypeLoc();
1600 TLB.reserve(TL.getFullDataSize());
1601
Douglas Gregor3024f072012-04-16 07:05:22 +00001602 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001603
Richard Smith2e321552014-11-12 02:00:47 +00001604 if (FunctionProtoTypeLoc Proto =
1605 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1606 // Instantiate the type, other than its exception specification. The
1607 // exception specification is instantiated in InitFunctionInstantiation
1608 // once we've built the FunctionDecl.
1609 // FIXME: Set the exception specification to EST_Uninstantiated here,
1610 // instead of rebuilding the function type again later.
1611 Result = Instantiator.TransformFunctionProtoType(
1612 TLB, Proto, ThisContext, ThisTypeQuals,
1613 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1614 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001615 } else {
1616 Result = Instantiator.TransformType(TLB, TL);
1617 }
John McCallb29f78f2010-04-09 17:38:44 +00001618 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001619 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001620
1621 return TLB.getTypeSourceInfo(Context, Result);
1622}
1623
Richard Smith2e321552014-11-12 02:00:47 +00001624void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1625 const MultiLevelTemplateArgumentList &Args) {
1626 FunctionProtoType::ExceptionSpecInfo ESI =
1627 Proto->getExtProtoInfo().ExceptionSpec;
1628 assert(ESI.Type != EST_Uninstantiated);
1629
1630 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1631 New->getDeclName());
1632
1633 SmallVector<QualType, 4> ExceptionStorage;
1634 bool Changed = false;
1635 if (Instantiator.TransformExceptionSpec(
1636 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1637 ExceptionStorage, Changed))
1638 // On error, recover by dropping the exception specification.
1639 ESI.Type = EST_None;
1640
1641 UpdateExceptionSpec(New, ESI);
1642}
1643
Douglas Gregor940bca72010-04-12 07:48:19 +00001644ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001645 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001646 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001647 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001648 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001649 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001650 TypeSourceInfo *NewDI = nullptr;
1651
Douglas Gregor5499af42011-01-05 23:12:31 +00001652 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001653 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1654
Douglas Gregor5499af42011-01-05 23:12:31 +00001655 // We have a function parameter pack. Substitute into the pattern of the
1656 // expansion.
1657 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1658 OldParm->getLocation(), OldParm->getDeclName());
1659 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001660 return nullptr;
1661
Douglas Gregor5499af42011-01-05 23:12:31 +00001662 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1663 // We still have unexpanded parameter packs, which means that
1664 // our function parameter is still a function parameter pack.
1665 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001666 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001667 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001668 } else if (ExpectParameterPack) {
1669 // We expected to get a parameter pack but didn't (because the type
1670 // itself is not a pack expansion type), so complain. This can occur when
1671 // the substitution goes through an alias template that "loses" the
1672 // pack expansion.
1673 Diag(OldParm->getLocation(),
1674 diag::err_function_parameter_pack_without_parameter_packs)
1675 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001676 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001677 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001678 } else {
1679 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1680 OldParm->getDeclName());
1681 }
1682
Douglas Gregor940bca72010-04-12 07:48:19 +00001683 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001684 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001685
1686 if (NewDI->getType()->isVoidType()) {
1687 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001688 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001689 }
1690
1691 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001692 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001693 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001694 OldParm->getIdentifier(),
1695 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001696 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001697 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001698 return nullptr;
1699
Douglas Gregor940bca72010-04-12 07:48:19 +00001700 // Mark the (new) default argument as uninstantiated (if any).
1701 if (OldParm->hasUninstantiatedDefaultArg()) {
1702 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1703 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001704 } else if (OldParm->hasUnparsedDefaultArg()) {
1705 NewParm->setUnparsedDefaultArg();
1706 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
David Blaikie7afed5e2012-05-01 06:05:57 +00001707 } else if (Expr *Arg = OldParm->getDefaultArg())
1708 // FIXME: if we non-lazily instantiated non-dependent default args for
1709 // non-dependent parameter types we could remove a bunch of duplicate
1710 // conversion warnings for such arguments.
1711 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor940bca72010-04-12 07:48:19 +00001712
1713 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001714
Douglas Gregorf3010112011-01-07 16:43:16 +00001715 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001716 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001717 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1718 } else {
1719 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001720 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001721 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001722
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001723 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1724 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001725 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001726
1727 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1728 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001729
1730 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1731
Douglas Gregor940bca72010-04-12 07:48:19 +00001732 return NewParm;
1733}
1734
Douglas Gregordd472162011-01-07 00:20:55 +00001735/// \brief Substitute the given template arguments into the given set of
1736/// parameters, producing the set of parameter types that would be generated
1737/// from such a substitution.
1738bool Sema::SubstParmTypes(SourceLocation Loc,
1739 ParmVarDecl **Params, unsigned NumParams,
1740 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001741 SmallVectorImpl<QualType> &ParamTypes,
1742 SmallVectorImpl<ParmVarDecl *> *OutParams) {
Douglas Gregordd472162011-01-07 00:20:55 +00001743 assert(!ActiveTemplateInstantiations.empty() &&
1744 "Cannot perform an instantiation without some context on the "
1745 "instantiation stack");
1746
1747 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1748 DeclarationName());
Craig Topperc3ec1492014-05-26 06:22:03 +00001749 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
1750 nullptr, ParamTypes,
1751 OutParams);
Douglas Gregordd472162011-01-07 00:20:55 +00001752}
1753
John McCall76d824f2009-08-25 22:02:44 +00001754/// \brief Perform substitution on the base class specifiers of the
1755/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001756///
1757/// Produces a diagnostic and returns true on error, returns false and
1758/// attaches the instantiated base classes to the class template
1759/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001760bool
John McCall76d824f2009-08-25 22:02:44 +00001761Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1762 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001763 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001764 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001765 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Aaron Ballman574705e2014-03-13 15:41:46 +00001766 for (const auto Base : Pattern->bases()) {
1767 if (!Base.getType()->isDependentType()) {
1768 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001769 if (RD->isInvalidDecl())
1770 Instantiation->setInvalidDecl();
1771 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001772 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001773 continue;
1774 }
1775
Douglas Gregor752a5952011-01-03 22:36:02 +00001776 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001777 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001778 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001779 // This is a pack expansion. See whether we should expand it now, or
1780 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001781 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001782 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001783 Unexpanded);
1784 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001785 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001786 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001787 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1788 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001789 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001790 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001791 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001792 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001793 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001794 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001795 }
1796
1797 // If we should expand this pack expansion now, do so.
1798 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001799 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001800 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1801
Aaron Ballman574705e2014-03-13 15:41:46 +00001802 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001803 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001804 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001805 DeclarationName());
1806 if (!BaseTypeLoc) {
1807 Invalid = true;
1808 continue;
1809 }
1810
1811 if (CXXBaseSpecifier *InstantiatedBase
1812 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001813 Base.getSourceRange(),
1814 Base.isVirtual(),
1815 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001816 BaseTypeLoc,
1817 SourceLocation()))
1818 InstantiatedBases.push_back(InstantiatedBase);
1819 else
1820 Invalid = true;
1821 }
1822
1823 continue;
1824 }
1825
1826 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001827 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001828 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001829 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001830 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001831 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001832 DeclarationName());
1833 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001834 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001835 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001836 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001837 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001838 }
1839
Nick Lewycky19b9f952010-07-26 16:56:01 +00001840 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001841 Invalid = true;
1842 continue;
1843 }
1844
1845 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001846 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001847 Base.getSourceRange(),
1848 Base.isVirtual(),
1849 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001850 BaseTypeLoc,
1851 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001852 InstantiatedBases.push_back(InstantiatedBase);
1853 else
1854 Invalid = true;
1855 }
1856
Douglas Gregor2a72edd2009-03-10 18:52:44 +00001857 if (!Invalid &&
Jay Foad7d0479f2009-05-21 09:52:38 +00001858 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
Douglas Gregor463421d2009-03-03 04:44:36 +00001859 InstantiatedBases.size()))
1860 Invalid = true;
1861
1862 return Invalid;
1863}
1864
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001865// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001866namespace clang {
1867 namespace sema {
1868 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1869 const MultiLevelTemplateArgumentList &TemplateArgs);
1870 }
1871}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001872
Richard Smith4b38ded2012-03-14 23:13:10 +00001873/// Determine whether we would be unable to instantiate this template (because
1874/// it either has no definition, or is in the process of being instantiated).
1875static bool DiagnoseUninstantiableTemplate(Sema &S,
1876 SourceLocation PointOfInstantiation,
1877 TagDecl *Instantiation,
1878 bool InstantiatedFromMember,
1879 TagDecl *Pattern,
1880 TagDecl *PatternDef,
1881 TemplateSpecializationKind TSK,
1882 bool Complain = true) {
1883 if (PatternDef && !PatternDef->isBeingDefined())
1884 return false;
1885
1886 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1887 // Say nothing
1888 } else if (PatternDef) {
1889 assert(PatternDef->isBeingDefined());
1890 S.Diag(PointOfInstantiation,
1891 diag::err_template_instantiate_within_definition)
1892 << (TSK != TSK_ImplicitInstantiation)
1893 << S.Context.getTypeDeclType(Instantiation);
1894 // Not much point in noting the template declaration here, since
1895 // we're lexically inside it.
1896 Instantiation->setInvalidDecl();
1897 } else if (InstantiatedFromMember) {
1898 S.Diag(PointOfInstantiation,
1899 diag::err_implicit_instantiate_member_undefined)
1900 << S.Context.getTypeDeclType(Instantiation);
Alp Toker2afa8782014-05-28 12:20:14 +00001901 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
Richard Smith4b38ded2012-03-14 23:13:10 +00001902 } else {
1903 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1904 << (TSK != TSK_ImplicitInstantiation)
1905 << S.Context.getTypeDeclType(Instantiation);
1906 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1907 }
1908
1909 // In general, Instantiation isn't marked invalid to get more than one
1910 // error for multiple undefined instantiations. But the code that does
1911 // explicit declaration -> explicit definition conversion can't handle
1912 // invalid declarations, so mark as invalid in that case.
1913 if (TSK == TSK_ExplicitInstantiationDeclaration)
1914 Instantiation->setInvalidDecl();
1915 return true;
1916}
1917
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001918/// \brief Instantiate the definition of a class from a given pattern.
1919///
1920/// \param PointOfInstantiation The point of instantiation within the
1921/// source code.
1922///
1923/// \param Instantiation is the declaration whose definition is being
1924/// instantiated. This will be either a class template specialization
1925/// or a member class of a class template specialization.
1926///
1927/// \param Pattern is the pattern from which the instantiation
1928/// occurs. This will be either the declaration of a class template or
1929/// the declaration of a member class of a class template.
1930///
1931/// \param TemplateArgs The template arguments to be substituted into
1932/// the pattern.
1933///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001934/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001935///
1936/// \param Complain whether to complain if the class cannot be instantiated due
1937/// to the lack of a definition.
1938///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001939/// \returns true if an error occurred, false otherwise.
1940bool
1941Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1942 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001943 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001944 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001945 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001946 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001947 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smith4b38ded2012-03-14 23:13:10 +00001948 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1949 Instantiation->getInstantiatedFromMemberClass(),
1950 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001951 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001952 Pattern = PatternDef;
1953
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001954 // \brief Record the point of instantiation.
1955 if (MemberSpecializationInfo *MSInfo
1956 = Instantiation->getMemberSpecializationInfo()) {
1957 MSInfo->setTemplateSpecializationKind(TSK);
1958 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001959 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001960 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001961 Spec->setTemplateSpecializationKind(TSK);
1962 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001963 }
Richard Smitha1087602014-03-10 00:04:29 +00001964
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001965 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001966 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001967 return true;
1968
1969 // Enter the scope of this instantiation. We don't use
1970 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001971 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001972 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001973 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001974
Douglas Gregor51121572010-03-24 01:33:17 +00001975 // If this is an instantiation of a local class, merge this local
1976 // instantiation scope with the enclosing scope. Otherwise, every
1977 // instantiation of a class has its own local instantiation scope.
1978 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001979 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001980
John McCall6602bb12010-08-01 02:01:53 +00001981 // Pull attributes from the pattern onto the instantiation.
1982 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1983
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001984 // Start the definition of this instantiation.
1985 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001986
1987 // The instantiation is visible here, even if it was first declared in an
1988 // unimported module.
1989 Instantiation->setHidden(false);
1990
1991 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001992 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001993
John McCall76d824f2009-08-25 22:02:44 +00001994 // Do substitution on the base class specifiers.
1995 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001996 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001997
Douglas Gregor869853e2010-11-10 19:44:59 +00001998 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001999 SmallVector<Decl*, 4> Fields;
2000 SmallVector<std::pair<FieldDecl*, FieldDecl*>, 4>
Richard Smith938f40b2011-06-11 17:19:42 +00002001 FieldsWithMemberInitializers;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002002 // Delay instantiation of late parsed attributes.
2003 LateInstantiatedAttrVec LateAttrs;
2004 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2005
Aaron Ballman629afae2014-03-07 19:56:05 +00002006 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002007 // Don't instantiate members not belonging in this semantic context.
2008 // e.g. for:
2009 // @code
2010 // template <int i> class A {
2011 // class B *g;
2012 // };
2013 // @endcode
2014 // 'class B' has the template as lexical context but semantically it is
2015 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002016 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002017 continue;
2018
Aaron Ballman629afae2014-03-07 19:56:05 +00002019 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002020 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002021 continue;
2022 }
2023
Aaron Ballman629afae2014-03-07 19:56:05 +00002024 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002025 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002026 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002027 Fields.push_back(Field);
Aaron Ballman629afae2014-03-07 19:56:05 +00002028 FieldDecl *OldField = cast<FieldDecl>(Member);
Richard Smith938f40b2011-06-11 17:19:42 +00002029 if (OldField->getInClassInitializer())
2030 FieldsWithMemberInitializers.push_back(std::make_pair(OldField,
2031 Field));
Richard Smith7d137e32012-03-23 03:33:32 +00002032 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2033 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2034 // specialization causes the implicit instantiation of the definitions
2035 // of unscoped member enumerations.
2036 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002037 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2038 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002039 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2040 assert(MSInfo && "no spec info for member enum specialization");
2041 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2042 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2043 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002044 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2045 if (SA->isFailed()) {
2046 // A static_assert failed. Bail out; instantiating this
2047 // class is probably not meaningful.
2048 Instantiation->setInvalidDecl();
2049 break;
2050 }
Richard Smith7d137e32012-03-23 03:33:32 +00002051 }
2052
2053 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002054 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002055 } else {
2056 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002057 // instantiations was a semantic disaster, and we'll want to mark the
2058 // declaration invalid.
2059 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002060 }
2061 }
2062
2063 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002064 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2065 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002066 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002067
2068 // Attach any in-class member initializers now the class is complete.
Richard Smith189aba92012-12-08 02:13:02 +00002069 // FIXME: We are supposed to defer instantiating these until they are needed.
Benjamin Kramer1d373c62012-05-17 12:01:52 +00002070 if (!FieldsWithMemberInitializers.empty()) {
Douglas Gregor3024f072012-04-16 07:05:22 +00002071 // C++11 [expr.prim.general]p4:
2072 // Otherwise, if a member-declarator declares a non-static data member
2073 // (9.2) of a class X, the expression this is a prvalue of type "pointer
2074 // to X" within the optional brace-or-equal-initializer. It shall not
2075 // appear elsewhere in the member-declarator.
2076 CXXThisScopeRAII ThisScope(*this, Instantiation, (unsigned)0);
2077
2078 for (unsigned I = 0, N = FieldsWithMemberInitializers.size(); I != N; ++I) {
2079 FieldDecl *OldField = FieldsWithMemberInitializers[I].first;
2080 FieldDecl *NewField = FieldsWithMemberInitializers[I].second;
2081 Expr *OldInit = OldField->getInClassInitializer();
Richard Smith938f40b2011-06-11 17:19:42 +00002082
Richard Smith74108172014-01-17 03:11:34 +00002083 ActOnStartCXXInClassMemberInitializer();
Douglas Gregor3024f072012-04-16 07:05:22 +00002084 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2085 /*CXXDirectInit=*/false);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002086 Expr *Init = NewInit.get();
Richard Smith74108172014-01-17 03:11:34 +00002087 assert((!Init || !isa<ParenListExpr>(Init)) &&
2088 "call-style init in class");
Fariborz Jahaniana99119a2014-07-03 21:06:20 +00002089 ActOnFinishCXXInClassMemberInitializer(NewField,
2090 Init ? Init->getLocStart() : SourceLocation(), Init);
Richard Smithe3daab22011-07-20 00:12:52 +00002091 }
Richard Smith938f40b2011-06-11 17:19:42 +00002092 }
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002093 // Instantiate late parsed attributes, and attach them to their decls.
2094 // See Sema::InstantiateAttrs
2095 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2096 E = LateAttrs.end(); I != E; ++I) {
2097 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2098 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002099
2100 // Allow 'this' within late-parsed attributes.
2101 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2102 CXXRecordDecl *ThisContext =
2103 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2104 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2105 ND && ND->isCXXInstanceMember());
2106
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002107 Attr *NewAttr =
2108 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2109 I->NewDecl->addAttr(NewAttr);
2110 LocalInstantiationScope::deleteScopes(I->Scope,
2111 Instantiator.getStartingScope());
2112 }
2113 Instantiator.disableLateAttributeInstantiation();
2114 LateAttrs.clear();
2115
Richard Smithd3b5c9082012-07-27 04:22:15 +00002116 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002117
Richard Smitha1087602014-03-10 00:04:29 +00002118 // FIXME: We should do something similar for explicit instantiations so they
2119 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002120 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002121 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002122 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002123 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002124 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002125
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002126 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002127 // Perform any dependent diagnostics from the pattern.
2128 PerformDependentDiagnostics(Pattern, TemplateArgs);
2129
Douglas Gregor869853e2010-11-10 19:44:59 +00002130 // Instantiate any out-of-line class template partial
2131 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002132 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002133 P = Instantiator.delayed_partial_spec_begin(),
2134 PEnd = Instantiator.delayed_partial_spec_end();
2135 P != PEnd; ++P) {
2136 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002137 P->first, P->second)) {
2138 Instantiation->setInvalidDecl();
2139 break;
2140 }
2141 }
2142
2143 // Instantiate any out-of-line variable template partial
2144 // specializations now.
2145 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2146 P = Instantiator.delayed_var_partial_spec_begin(),
2147 PEnd = Instantiator.delayed_var_partial_spec_end();
2148 P != PEnd; ++P) {
2149 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2150 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002151 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002152 break;
2153 }
2154 }
2155 }
2156
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002157 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002158 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002159
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002160 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002161 Consumer.HandleTagDeclDefinition(Instantiation);
2162
Douglas Gregor88d292c2010-05-13 16:44:06 +00002163 // Always emit the vtable for an explicit instantiation definition
2164 // of a polymorphic class template specialization.
2165 if (TSK == TSK_ExplicitInstantiationDefinition)
2166 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2167 }
2168
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002169 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002170}
2171
Richard Smith4b38ded2012-03-14 23:13:10 +00002172/// \brief Instantiate the definition of an enum from a given pattern.
2173///
2174/// \param PointOfInstantiation The point of instantiation within the
2175/// source code.
2176/// \param Instantiation is the declaration whose definition is being
2177/// instantiated. This will be a member enumeration of a class
2178/// temploid specialization, or a local enumeration within a
2179/// function temploid specialization.
2180/// \param Pattern The templated declaration from which the instantiation
2181/// occurs.
2182/// \param TemplateArgs The template arguments to be substituted into
2183/// the pattern.
2184/// \param TSK The kind of implicit or explicit instantiation to perform.
2185///
2186/// \return \c true if an error occurred, \c false otherwise.
2187bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2188 EnumDecl *Instantiation, EnumDecl *Pattern,
2189 const MultiLevelTemplateArgumentList &TemplateArgs,
2190 TemplateSpecializationKind TSK) {
2191 EnumDecl *PatternDef = Pattern->getDefinition();
2192 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2193 Instantiation->getInstantiatedFromMemberEnum(),
2194 Pattern, PatternDef, TSK,/*Complain*/true))
2195 return true;
2196 Pattern = PatternDef;
2197
2198 // Record the point of instantiation.
2199 if (MemberSpecializationInfo *MSInfo
2200 = Instantiation->getMemberSpecializationInfo()) {
2201 MSInfo->setTemplateSpecializationKind(TSK);
2202 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2203 }
2204
2205 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002206 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002207 return true;
2208
Richard Smitha1087602014-03-10 00:04:29 +00002209 // The instantiation is visible here, even if it was first declared in an
2210 // unimported module.
2211 Instantiation->setHidden(false);
2212
Richard Smith4b38ded2012-03-14 23:13:10 +00002213 // Enter the scope of this instantiation. We don't use
2214 // PushDeclContext because we don't have a scope.
2215 ContextRAII SavedContext(*this, Instantiation);
2216 EnterExpressionEvaluationContext EvalContext(*this,
2217 Sema::PotentiallyEvaluated);
2218
2219 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2220
2221 // Pull attributes from the pattern onto the instantiation.
2222 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2223
2224 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2225 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2226
2227 // Exit the scope of this instantiation.
2228 SavedContext.pop();
2229
2230 return Instantiation->isInvalidDecl();
2231}
2232
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002233namespace {
2234 /// \brief A partial specialization whose template arguments have matched
2235 /// a given template-id.
2236 struct PartialSpecMatchResult {
2237 ClassTemplatePartialSpecializationDecl *Partial;
2238 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002239 };
2240}
2241
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002242bool Sema::InstantiateClassTemplateSpecialization(
2243 SourceLocation PointOfInstantiation,
2244 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2245 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002246 // Perform the actual instantiation on the canonical declaration.
2247 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002248 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor463421d2009-03-03 04:44:36 +00002249
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002250 // Check whether we have already instantiated or specialized this class
2251 // template specialization.
2252 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2253 if (ClassTemplateSpec->getSpecializationKind() ==
2254 TSK_ExplicitInstantiationDeclaration &&
2255 TSK == TSK_ExplicitInstantiationDefinition) {
2256 // An explicit instantiation definition follows an explicit instantiation
2257 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2258 // explicit instantiation.
2259 ClassTemplateSpec->setSpecializationKind(TSK);
Douglas Gregor88d292c2010-05-13 16:44:06 +00002260
2261 // If this is an explicit instantiation definition, mark the
2262 // vtable as used.
Nico Weber3ffc4c92011-12-20 20:32:49 +00002263 if (TSK == TSK_ExplicitInstantiationDefinition &&
2264 !ClassTemplateSpec->isInvalidDecl())
Douglas Gregor88d292c2010-05-13 16:44:06 +00002265 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2266
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002267 return false;
2268 }
2269
2270 // We can only instantiate something that hasn't already been
2271 // instantiated or specialized. Fail without any diagnostics: our
2272 // caller will provide an error message.
Douglas Gregor463421d2009-03-03 04:44:36 +00002273 return true;
Douglas Gregor4aa04b12009-09-11 21:19:12 +00002274 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002275
Douglas Gregor00a511f2009-09-15 16:51:42 +00002276 if (ClassTemplateSpec->isInvalidDecl())
2277 return true;
2278
Douglas Gregor463421d2009-03-03 04:44:36 +00002279 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002280 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002281
Douglas Gregor170bc422009-06-12 22:31:52 +00002282 // C++ [temp.class.spec.match]p1:
2283 // When a class template is used in a context that requires an
2284 // instantiation of the class, it is necessary to determine
2285 // whether the instantiation is to be generated using the primary
2286 // template or one of the partial specializations. This is done by
2287 // matching the template arguments of the class template
2288 // specialization with the template argument lists of the partial
2289 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002290 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002291 SmallVector<MatchResult, 4> Matched;
2292 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002293 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002294 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002295 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2296 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002297 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002298 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002299 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002300 ClassTemplateSpec->getTemplateArgs(),
2301 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002302 // Store the failed-deduction information for use in diagnostics, later.
2303 // TODO: Actually use the failed-deduction info?
2304 FailedCandidates.addCandidate()
2305 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002306 (void)Result;
2307 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002308 Matched.push_back(PartialSpecMatchResult());
2309 Matched.back().Partial = Partial;
2310 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002311 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002312 }
2313
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002314 // If we're dealing with a member template where the template parameters
2315 // have been instantiated, this provides the original template parameters
2316 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002317
Douglas Gregor21610382009-10-29 00:04:11 +00002318 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002319 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002320 if (Matched.size() == 1) {
2321 // -- If exactly one matching specialization is found, the
2322 // instantiation is generated from that specialization.
2323 // We don't need to do anything for this.
2324 } else {
2325 // -- If more than one matching specialization is found, the
2326 // partial order rules (14.5.4.2) are used to determine
2327 // whether one of the specializations is more specialized
2328 // than the others. If none of the specializations is more
2329 // specialized than all of the other matching
2330 // specializations, then the use of the class template is
2331 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002332 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2333 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002334 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002335 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002336 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002337 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002338 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002339 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002340
Douglas Gregor21610382009-10-29 00:04:11 +00002341 // Determine if the best partial specialization is more specialized than
2342 // the others.
2343 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002344 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2345 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002346 P != PEnd; ++P) {
2347 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002348 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002349 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002350 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002351 Ambiguous = true;
2352 break;
2353 }
2354 }
2355
2356 if (Ambiguous) {
2357 // Partial ordering did not produce a clear winner. Complain.
2358 ClassTemplateSpec->setInvalidDecl();
2359 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2360 << ClassTemplateSpec;
2361
2362 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002363 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2364 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002365 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002366 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2367 << getTemplateArgumentBindingsText(
2368 P->Partial->getTemplateParameters(),
2369 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002370
Douglas Gregor21610382009-10-29 00:04:11 +00002371 return true;
2372 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002373 }
2374
2375 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002376 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002377 while (OrigPartialSpec->getInstantiatedFromMember()) {
2378 // If we've found an explicit specialization of this class template,
2379 // stop here and use that as the pattern.
2380 if (OrigPartialSpec->isMemberSpecialization())
2381 break;
2382
2383 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2384 }
2385
2386 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002387 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002388 } else {
2389 // -- If no matches are found, the instantiation is generated
2390 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002391 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002392 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2393 // If we've found an explicit specialization of this class template,
2394 // stop here and use that as the pattern.
2395 if (OrigTemplate->isMemberSpecialization())
2396 break;
2397
Douglas Gregor01afeef2009-08-28 20:31:08 +00002398 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002399 }
2400
Douglas Gregor01afeef2009-08-28 20:31:08 +00002401 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002402 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002403
Douglas Gregoref6ab412009-10-27 06:26:26 +00002404 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2405 Pattern,
2406 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002407 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002408 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002409
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002410 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002411}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002412
John McCall76d824f2009-08-25 22:02:44 +00002413/// \brief Instantiates the definitions of all of the member
2414/// of the given class, which is an instantiation of a class template
2415/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002416void
2417Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002418 CXXRecordDecl *Instantiation,
2419 const MultiLevelTemplateArgumentList &TemplateArgs,
2420 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002421 // FIXME: We need to notify the ASTMutationListener that we did all of these
2422 // things, in case we have an explicit instantiation definition in a PCM, a
2423 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002424 assert(
2425 (TSK == TSK_ExplicitInstantiationDefinition ||
2426 TSK == TSK_ExplicitInstantiationDeclaration ||
2427 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2428 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002429 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002430 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002431 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002432 if (FunctionDecl *Pattern
2433 = Function->getInstantiatedFromMemberFunction()) {
2434 MemberSpecializationInfo *MSInfo
2435 = Function->getMemberSpecializationInfo();
2436 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002437 if (MSInfo->getTemplateSpecializationKind()
2438 == TSK_ExplicitSpecialization)
2439 continue;
2440
Douglas Gregor1d957a32009-10-27 18:42:08 +00002441 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2442 Function,
2443 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002444 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002445 SuppressNew) ||
2446 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002447 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002448
2449 // C++11 [temp.explicit]p8:
2450 // An explicit instantiation definition that names a class template
2451 // specialization explicitly instantiates the class template
2452 // specialization and is only an explicit instantiation definition
2453 // of members whose definition is visible at the point of
2454 // instantiation.
2455 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002456 continue;
2457
Richard Smitheb36ddf2014-04-24 22:45:46 +00002458 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2459
2460 if (Function->isDefined()) {
2461 // Let the ASTConsumer know that this function has been explicitly
2462 // instantiated now, and its linkage might have changed.
2463 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2464 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002465 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002466 } else if (TSK == TSK_ImplicitInstantiation) {
2467 PendingLocalImplicitInstantiations.push_back(
2468 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002469 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002470 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002471 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002472 if (isa<VarTemplateSpecializationDecl>(Var))
2473 continue;
2474
Douglas Gregor86d142a2009-10-08 07:24:58 +00002475 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002476 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2477 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002478 if (MSInfo->getTemplateSpecializationKind()
2479 == TSK_ExplicitSpecialization)
2480 continue;
2481
Douglas Gregor1d957a32009-10-27 18:42:08 +00002482 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2483 Var,
2484 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002485 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002486 SuppressNew) ||
2487 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002488 continue;
2489
Douglas Gregor1d957a32009-10-27 18:42:08 +00002490 if (TSK == TSK_ExplicitInstantiationDefinition) {
2491 // C++0x [temp.explicit]p8:
2492 // An explicit instantiation definition that names a class template
2493 // specialization explicitly instantiates the class template
2494 // specialization and is only an explicit instantiation definition
2495 // of members whose definition is visible at the point of
2496 // instantiation.
2497 if (!Var->getInstantiatedFromStaticDataMember()
2498 ->getOutOfLineDefinition())
2499 continue;
2500
2501 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002502 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002503 } else {
2504 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2505 }
2506 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002507 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002508 // Always skip the injected-class-name, along with any
2509 // redeclarations of nested classes, since both would cause us
2510 // to try to instantiate the members of a class twice.
Douglas Gregorec9fd132012-01-14 16:38:05 +00002511 if (Record->isInjectedClassName() || Record->getPreviousDecl())
Douglas Gregord801b062009-10-07 23:56:10 +00002512 continue;
2513
Douglas Gregor1d957a32009-10-27 18:42:08 +00002514 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2515 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002516
2517 if (MSInfo->getTemplateSpecializationKind()
2518 == TSK_ExplicitSpecialization)
2519 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002520
Douglas Gregor1d957a32009-10-27 18:42:08 +00002521 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2522 Record,
2523 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002524 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002525 SuppressNew) ||
2526 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002527 continue;
2528
Douglas Gregor1d957a32009-10-27 18:42:08 +00002529 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2530 assert(Pattern && "Missing instantiated-from-template information");
2531
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002532 if (!Record->getDefinition()) {
2533 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002534 // C++0x [temp.explicit]p8:
2535 // An explicit instantiation definition that names a class template
2536 // specialization explicitly instantiates the class template
2537 // specialization and is only an explicit instantiation definition
2538 // of members whose definition is visible at the point of
2539 // instantiation.
2540 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2541 MSInfo->setTemplateSpecializationKind(TSK);
2542 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2543 }
2544
2545 continue;
2546 }
2547
2548 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002549 TemplateArgs,
2550 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002551 } else {
2552 if (TSK == TSK_ExplicitInstantiationDefinition &&
2553 Record->getTemplateSpecializationKind() ==
2554 TSK_ExplicitInstantiationDeclaration) {
2555 Record->setTemplateSpecializationKind(TSK);
2556 MarkVTableUsed(PointOfInstantiation, Record, true);
2557 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002558 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002559
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002560 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002561 if (Pattern)
2562 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2563 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002564 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002565 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2566 assert(MSInfo && "No member specialization information?");
2567
2568 if (MSInfo->getTemplateSpecializationKind()
2569 == TSK_ExplicitSpecialization)
2570 continue;
2571
2572 if (CheckSpecializationInstantiationRedecl(
2573 PointOfInstantiation, TSK, Enum,
2574 MSInfo->getTemplateSpecializationKind(),
2575 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2576 SuppressNew)
2577 continue;
2578
2579 if (Enum->getDefinition())
2580 continue;
2581
2582 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2583 assert(Pattern && "Missing instantiated-from-template information");
2584
2585 if (TSK == TSK_ExplicitInstantiationDefinition) {
2586 if (!Pattern->getDefinition())
2587 continue;
2588
2589 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2590 } else {
2591 MSInfo->setTemplateSpecializationKind(TSK);
2592 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2593 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002594 }
2595 }
2596}
2597
2598/// \brief Instantiate the definitions of all of the members of the
2599/// given class template specialization, which was named as part of an
2600/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002601void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002602Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002603 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002604 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2605 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002606 // C++0x [temp.explicit]p7:
2607 // An explicit instantiation that names a class template
2608 // specialization is an explicit instantion of the same kind
2609 // (declaration or definition) of each of its members (not
2610 // including members inherited from base classes) that has not
2611 // been previously explicitly specialized in the translation unit
2612 // containing the explicit instantiation, except as described
2613 // below.
2614 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002615 getTemplateInstantiationArgs(ClassTemplateSpec),
2616 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002617}
2618
John McCalldadc5752010-08-24 06:29:42 +00002619StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002620Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002621 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002622 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002623
2624 TemplateInstantiator Instantiator(*this, TemplateArgs,
2625 SourceLocation(),
2626 DeclarationName());
2627 return Instantiator.TransformStmt(S);
2628}
2629
John McCalldadc5752010-08-24 06:29:42 +00002630ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002631Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002632 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002633 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002634
Douglas Gregora16548e2009-08-11 05:31:07 +00002635 TemplateInstantiator Instantiator(*this, TemplateArgs,
2636 SourceLocation(),
2637 DeclarationName());
2638 return Instantiator.TransformExpr(E);
2639}
2640
Richard Smithd59b8322012-12-19 01:39:02 +00002641ExprResult Sema::SubstInitializer(Expr *Init,
2642 const MultiLevelTemplateArgumentList &TemplateArgs,
2643 bool CXXDirectInit) {
2644 TemplateInstantiator Instantiator(*this, TemplateArgs,
2645 SourceLocation(),
2646 DeclarationName());
2647 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2648}
2649
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002650bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2651 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002652 SmallVectorImpl<Expr *> &Outputs) {
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002653 if (NumExprs == 0)
2654 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002655
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002656 TemplateInstantiator Instantiator(*this, TemplateArgs,
2657 SourceLocation(),
2658 DeclarationName());
2659 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2660}
2661
Douglas Gregor14454802011-02-25 02:25:35 +00002662NestedNameSpecifierLoc
2663Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2664 const MultiLevelTemplateArgumentList &TemplateArgs) {
2665 if (!NNS)
2666 return NestedNameSpecifierLoc();
2667
2668 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2669 DeclarationName());
2670 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2671}
2672
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002673/// \brief Do template substitution on declaration name info.
2674DeclarationNameInfo
2675Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2676 const MultiLevelTemplateArgumentList &TemplateArgs) {
2677 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2678 NameInfo.getName());
2679 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2680}
2681
Douglas Gregoraa594892009-03-31 18:38:02 +00002682TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002683Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2684 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002685 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002686 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2687 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002688 CXXScopeSpec SS;
2689 SS.Adopt(QualifierLoc);
2690 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002691}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002692
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002693bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2694 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002695 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002696 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2697 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002698
2699 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002700}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002701
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002702
2703static const Decl* getCanonicalParmVarDecl(const Decl *D) {
2704 // When storing ParmVarDecls in the local instantiation scope, we always
2705 // want to use the ParmVarDecl from the canonical function declaration,
2706 // since the map is then valid for any redeclaration or definition of that
2707 // function.
2708 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2709 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2710 unsigned i = PV->getFunctionScopeIndex();
2711 return FD->getCanonicalDecl()->getParamDecl(i);
2712 }
2713 }
2714 return D;
2715}
2716
2717
Douglas Gregorf3010112011-01-07 16:43:16 +00002718llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2719LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002720 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002721 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002722 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002723
Douglas Gregor14cf7522010-04-30 18:55:50 +00002724 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002725 const Decl *CheckD = D;
2726 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002727 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002728 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002729 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002730
2731 // If this is a tag declaration, it's possible that we need to look for
2732 // a previous declaration.
2733 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002734 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002735 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002736 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002737 } while (CheckD);
2738
Douglas Gregor14cf7522010-04-30 18:55:50 +00002739 // If we aren't combined with our outer scope, we're done.
2740 if (!Current->CombineWithOuterScope)
2741 break;
2742 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002743
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002744 // If we're performing a partial substitution during template argument
2745 // deduction, we may not have values for template parameters yet.
2746 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2747 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002748 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002749
Chris Lattnercab02a62011-02-17 20:34:02 +00002750 // If we didn't find the decl, then we either have a sema bug, or we have a
2751 // forward reference to a label declaration. Return null to indicate that
2752 // we have an uninstantiated label.
2753 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002754 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002755}
2756
John McCall19c1bfd2010-08-25 05:32:35 +00002757void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002758 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002759 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002760 if (Stored.isNull())
2761 Stored = Inst;
Benjamin Kramer1b4342d2013-04-12 15:22:25 +00002762 else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>())
2763 Pack->push_back(Inst);
2764 else
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002765 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Douglas Gregor14cf7522010-04-30 18:55:50 +00002766}
Douglas Gregorf3010112011-01-07 16:43:16 +00002767
2768void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2769 Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002770 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002771 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2772 Pack->push_back(Inst);
2773}
2774
2775void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002776 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002777 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2778 assert(Stored.isNull() && "Already instantiated this local");
2779 DeclArgumentPack *Pack = new DeclArgumentPack;
2780 Stored = Pack;
2781 ArgumentPacks.push_back(Pack);
2782}
2783
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002784void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2785 const TemplateArgument *ExplicitArgs,
2786 unsigned NumExplicitArgs) {
2787 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2788 "Already have a partially-substituted pack");
2789 assert((!PartiallySubstitutedPack
2790 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2791 "Wrong number of arguments in partially-substituted pack");
2792 PartiallySubstitutedPack = Pack;
2793 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2794 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2795}
2796
2797NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2798 const TemplateArgument **ExplicitArgs,
2799 unsigned *NumExplicitArgs) const {
2800 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002801 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002802 if (NumExplicitArgs)
2803 *NumExplicitArgs = 0;
2804
2805 for (const LocalInstantiationScope *Current = this; Current;
2806 Current = Current->Outer) {
2807 if (Current->PartiallySubstitutedPack) {
2808 if (ExplicitArgs)
2809 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2810 if (NumExplicitArgs)
2811 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2812
2813 return Current->PartiallySubstitutedPack;
2814 }
2815
2816 if (!Current->CombineWithOuterScope)
2817 break;
2818 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002819
2820 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002821}