blob: 50663f9f4baa7523b9cefdcdb420e738bfa75104 [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"
Richard Smith4b054b22016-08-24 21:25:37 +000018#include "clang/AST/ASTMutationListener.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000023#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000024#include "clang/Sema/Lookup.h"
Richard Smithe19b95d2016-05-26 20:23:13 +000025#include "clang/Sema/PrettyDeclStackTrace.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000027#include "clang/Sema/TemplateDeduction.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000028
29using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000030using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000031
Douglas Gregor4ea568f2009-03-10 18:03:33 +000032//===----------------------------------------------------------------------===/
33// Template Instantiation Support
34//===----------------------------------------------------------------------===/
35
Douglas Gregor01afeef2009-08-28 20:31:08 +000036/// \brief Retrieve the template argument list(s) that should be used to
37/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000038///
39/// \param D the declaration for which we are computing template instantiation
40/// arguments.
41///
42/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000043///
44/// \param RelativeToPrimary true if we should get the template
45/// arguments relative to the primary template, even when we're
46/// dealing with a specialization. This is only relevant for function
47/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000048///
49/// \param Pattern If non-NULL, indicates the pattern from which we will be
50/// instantiating the definition of the given declaration, \p D. This is
51/// used to determine the proper set of template instantiation arguments for
52/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000053MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000054Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000055 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000056 bool RelativeToPrimary,
57 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000058 // Accumulate the set of template argument lists in this structure.
59 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000061 if (Innermost)
62 Result.addOuterTemplateArguments(Innermost);
63
Douglas Gregora654dd82009-08-28 17:37:35 +000064 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000065 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000066 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000067
68 // Add template arguments from a variable template instantiation.
69 if (VarTemplateSpecializationDecl *Spec =
70 dyn_cast<VarTemplateSpecializationDecl>(D)) {
71 // We're done when we hit an explicit specialization.
72 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
73 !isa<VarTemplatePartialSpecializationDecl>(Spec))
74 return Result;
75
76 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
77
78 // If this variable template specialization was instantiated from a
79 // specialized member that is a variable template, we're done.
80 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000081 llvm::PointerUnion<VarTemplateDecl*,
82 VarTemplatePartialSpecializationDecl*> Specialized
83 = Spec->getSpecializedTemplateOrPartial();
84 if (VarTemplatePartialSpecializationDecl *Partial =
85 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
86 if (Partial->isMemberSpecialization())
87 return Result;
88 } else {
89 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
90 if (Tmpl->isMemberSpecialization())
91 return Result;
92 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000093 }
94
Douglas Gregor55462622011-06-15 14:20:42 +000095 // If we have a template template parameter with translation unit context,
96 // then we're performing substitution into a default template argument of
97 // this template template parameter before we've constructed the template
98 // that will own this template template parameter. In this case, we
99 // use empty template parameter lists for all of the outer templates
100 // to avoid performing any substitutions.
101 if (Ctx->isTranslationUnit()) {
102 if (TemplateTemplateParmDecl *TTP
103 = dyn_cast<TemplateTemplateParmDecl>(D)) {
104 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000105 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000106 return Result;
107 }
108 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000109 }
110
John McCall970d5302009-08-29 03:16:09 +0000111 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000112 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000113 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000114 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
115 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000116 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
117 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000118 break;
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregora654dd82009-08-28 17:37:35 +0000120 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000121
122 // If this class template specialization was instantiated from a
123 // specialized member that is a class template, we're done.
124 assert(Spec->getSpecializedTemplate() && "No class template?");
125 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
126 break;
Mike Stump11289f42009-09-09 15:08:12 +0000127 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000128 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000129 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000130 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000131 (Function->getTemplateSpecializationKind() ==
132 TSK_ExplicitSpecialization &&
133 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000134 break;
135
Douglas Gregora654dd82009-08-28 17:37:35 +0000136 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000137 = Function->getTemplateSpecializationArgs()) {
138 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000139 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000140
Douglas Gregorcf915552009-10-13 16:30:37 +0000141 // If this function was instantiated from a specialized member that is
142 // a function template, we're done.
143 assert(Function->getPrimaryTemplate() && "No function template?");
144 if (Function->getPrimaryTemplate()->isMemberSpecialization())
145 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000146
147 // If this function is a generic lambda specialization, we are done.
148 if (isGenericLambdaCallOperatorSpecialization(Function))
149 break;
150
Douglas Gregor43669f82011-03-05 17:54:25 +0000151 } else if (FunctionTemplateDecl *FunTmpl
152 = Function->getDescribedFunctionTemplate()) {
153 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000154 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000155 }
156
John McCall970d5302009-08-29 03:16:09 +0000157 // If this is a friend declaration and it declares an entity at
158 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000159 // instead of its semantic parent, unless of course the pattern we're
160 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000161 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000162 Function->getDeclContext()->isFileContext() &&
163 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000164 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000165 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000166 continue;
167 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000168 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
169 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
170 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000171 const TemplateSpecializationType *TST =
172 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
173 Result.addOuterTemplateArguments(
174 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000175 if (ClassTemplate->isMemberSpecialization())
176 break;
177 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000178 }
John McCall970d5302009-08-29 03:16:09 +0000179
180 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000181 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000182 }
Mike Stump11289f42009-09-09 15:08:12 +0000183
Douglas Gregora654dd82009-08-28 17:37:35 +0000184 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000185}
186
Douglas Gregor84d49a22009-11-11 21:54:23 +0000187bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
188 switch (Kind) {
189 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000190 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000191 case DefaultTemplateArgumentInstantiation:
192 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000193 case ExplicitTemplateArgumentSubstitution:
194 case DeducedTemplateArgumentSubstitution:
195 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000196 return true;
197
Douglas Gregor84d49a22009-11-11 21:54:23 +0000198 case DefaultTemplateArgumentChecking:
199 return false;
200 }
David Blaikie8a40f702012-01-17 06:56:22 +0000201
202 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000203}
204
Benjamin Kramer7761a042015-03-06 16:36:50 +0000205Sema::InstantiatingTemplate::InstantiatingTemplate(
206 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000207 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
208 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000209 sema::TemplateDeductionInfo *DeductionInfo)
210 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
211 SemaRef.InNonInstantiationSFINAEContext) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000212 // Don't allow further instantiation if a fatal error has occcured. Any
213 // diagnostics we might have raised will not be visible.
214 if (SemaRef.Diags.hasFatalErrorOccurred()) {
215 Invalid = true;
216 return;
217 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000218 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
219 if (!Invalid) {
220 ActiveTemplateInstantiation Inst;
221 Inst.Kind = Kind;
222 Inst.PointOfInstantiation = PointOfInstantiation;
223 Inst.Entity = Entity;
224 Inst.Template = Template;
225 Inst.TemplateArgs = TemplateArgs.data();
226 Inst.NumTemplateArgs = TemplateArgs.size();
227 Inst.DeductionInfo = DeductionInfo;
228 Inst.InstantiationRange = InstantiationRange;
Richard Smith54f18e82016-08-31 02:15:21 +0000229 AlreadyInstantiating =
230 !SemaRef.InstantiatingSpecializations
231 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
232 .second;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000233 SemaRef.InNonInstantiationSFINAEContext = false;
234 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
235 if (!Inst.isInstantiationRecord())
236 ++SemaRef.NonInstantiationEntries;
237 }
238}
239
Benjamin Kramer7761a042015-03-06 16:36:50 +0000240Sema::InstantiatingTemplate::InstantiatingTemplate(
241 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
242 SourceRange InstantiationRange)
243 : InstantiatingTemplate(SemaRef,
244 ActiveTemplateInstantiation::TemplateInstantiation,
245 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000246
Benjamin Kramer7761a042015-03-06 16:36:50 +0000247Sema::InstantiatingTemplate::InstantiatingTemplate(
248 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
249 ExceptionSpecification, SourceRange InstantiationRange)
250 : InstantiatingTemplate(
251 SemaRef, ActiveTemplateInstantiation::ExceptionSpecInstantiation,
252 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000253
Benjamin Kramer7761a042015-03-06 16:36:50 +0000254Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith54f18e82016-08-31 02:15:21 +0000255 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
256 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
257 SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000258 : InstantiatingTemplate(
259 SemaRef,
260 ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
Richard Smith54f18e82016-08-31 02:15:21 +0000261 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
262 Template, TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000263
Benjamin Kramer7761a042015-03-06 16:36:50 +0000264Sema::InstantiatingTemplate::InstantiatingTemplate(
265 Sema &SemaRef, SourceLocation PointOfInstantiation,
266 FunctionTemplateDecl *FunctionTemplate,
267 ArrayRef<TemplateArgument> TemplateArgs,
268 ActiveTemplateInstantiation::InstantiationKind Kind,
269 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
270 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
271 InstantiationRange, FunctionTemplate, nullptr,
Richard Smith54f18e82016-08-31 02:15:21 +0000272 TemplateArgs, &DeductionInfo) {
273 assert(
274 Kind == ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution ||
275 Kind == ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution);
276}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000277
Benjamin Kramer7761a042015-03-06 16:36:50 +0000278Sema::InstantiatingTemplate::InstantiatingTemplate(
279 Sema &SemaRef, SourceLocation PointOfInstantiation,
280 ClassTemplatePartialSpecializationDecl *PartialSpec,
281 ArrayRef<TemplateArgument> TemplateArgs,
282 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
283 : InstantiatingTemplate(
284 SemaRef,
285 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
286 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
287 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000288
Larisse Voufo39a1e502013-08-06 01:03:05 +0000289Sema::InstantiatingTemplate::InstantiatingTemplate(
290 Sema &SemaRef, SourceLocation PointOfInstantiation,
291 VarTemplatePartialSpecializationDecl *PartialSpec,
292 ArrayRef<TemplateArgument> TemplateArgs,
293 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000294 : InstantiatingTemplate(
295 SemaRef,
296 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
297 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
298 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000299
Benjamin Kramer7761a042015-03-06 16:36:50 +0000300Sema::InstantiatingTemplate::InstantiatingTemplate(
301 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
302 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
303 : InstantiatingTemplate(
304 SemaRef,
305 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
306 PointOfInstantiation, InstantiationRange, Param, nullptr,
307 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000308
Benjamin Kramer7761a042015-03-06 16:36:50 +0000309Sema::InstantiatingTemplate::InstantiatingTemplate(
310 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
311 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
312 SourceRange InstantiationRange)
313 : InstantiatingTemplate(
314 SemaRef,
315 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
316 PointOfInstantiation, InstantiationRange, Param, Template,
317 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000318
Benjamin Kramer7761a042015-03-06 16:36:50 +0000319Sema::InstantiatingTemplate::InstantiatingTemplate(
320 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
321 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
322 SourceRange InstantiationRange)
323 : InstantiatingTemplate(
324 SemaRef,
325 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
326 PointOfInstantiation, InstantiationRange, Param, Template,
327 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000328
Benjamin Kramer7761a042015-03-06 16:36:50 +0000329Sema::InstantiatingTemplate::InstantiatingTemplate(
330 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
331 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
332 SourceRange InstantiationRange)
333 : InstantiatingTemplate(
334 SemaRef, ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
335 PointOfInstantiation, InstantiationRange, Param, Template,
336 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000337
Douglas Gregor85673582009-05-18 17:01:57 +0000338void Sema::InstantiatingTemplate::Clear() {
339 if (!Invalid) {
Richard Smith54f18e82016-08-31 02:15:21 +0000340 auto &Active = SemaRef.ActiveTemplateInstantiations.back();
341 if (!Active.isInstantiationRecord()) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000342 assert(SemaRef.NonInstantiationEntries > 0);
343 --SemaRef.NonInstantiationEntries;
344 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000345 SemaRef.InNonInstantiationSFINAEContext
346 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000347
348 // Name lookup no longer looks in this template's defining module.
349 assert(SemaRef.ActiveTemplateInstantiations.size() >=
350 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
351 "forgot to remove a lookup module for a template instantiation");
352 if (SemaRef.ActiveTemplateInstantiations.size() ==
353 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
354 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
355 SemaRef.LookupModulesCache.erase(M);
356 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
357 }
358
Richard Smith54f18e82016-08-31 02:15:21 +0000359 if (!AlreadyInstantiating)
360 SemaRef.InstantiatingSpecializations.erase(
361 std::make_pair(Active.Entity, Active.Kind));
362
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000363 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000364 Invalid = true;
365 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000366}
367
Douglas Gregor79cf6032009-03-10 20:44:00 +0000368bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
369 SourceLocation PointOfInstantiation,
370 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000371 assert(SemaRef.NonInstantiationEntries <=
372 SemaRef.ActiveTemplateInstantiations.size());
373 if ((SemaRef.ActiveTemplateInstantiations.size() -
374 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000375 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000376 return false;
377
Mike Stump11289f42009-09-09 15:08:12 +0000378 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000379 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000380 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000381 << InstantiationRange;
382 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000383 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000384 return true;
385}
386
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000387/// \brief Prints the current instantiation stack through a series of
388/// notes.
389void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000390 // Determine which template instantiations to skip, if any.
391 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
392 unsigned Limit = Diags.getTemplateBacktraceLimit();
393 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
394 SkipStart = Limit / 2 + Limit % 2;
395 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
396 }
397
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000398 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000399 unsigned InstantiationIdx = 0;
Craig Topper2341c0d2013-07-04 03:08:24 +0000400 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000401 Active = ActiveTemplateInstantiations.rbegin(),
402 ActiveEnd = ActiveTemplateInstantiations.rend();
403 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000404 ++Active, ++InstantiationIdx) {
405 // Skip this instantiation?
406 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
407 if (InstantiationIdx == SkipStart) {
408 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000409 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000410 diag::note_instantiation_contexts_suppressed)
411 << unsigned(ActiveTemplateInstantiations.size() - Limit);
412 }
413 continue;
414 }
415
Douglas Gregor79cf6032009-03-10 20:44:00 +0000416 switch (Active->Kind) {
417 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000418 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000419 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
420 unsigned DiagID = diag::note_template_member_class_here;
421 if (isa<ClassTemplateSpecializationDecl>(Record))
422 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000423 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000424 << Context.getTypeDeclType(Record)
425 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000426 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000427 unsigned DiagID;
428 if (Function->getPrimaryTemplate())
429 DiagID = diag::note_function_template_spec_here;
430 else
431 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000432 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000433 << Function
434 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000435 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000436 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000437 VD->isStaticDataMember()?
438 diag::note_template_static_data_member_def_here
439 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000440 << VD
441 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000442 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
443 Diags.Report(Active->PointOfInstantiation,
444 diag::note_template_enum_def_here)
445 << ED
446 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000447 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
448 Diags.Report(Active->PointOfInstantiation,
449 diag::note_template_nsdmi_here)
450 << FD << 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: {
Richard Smith54f18e82016-08-31 02:15:21 +0000461 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000462 SmallVector<char, 128> TemplateArgsStr;
463 llvm::raw_svector_ostream OS(TemplateArgsStr);
464 Template->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000465 TemplateSpecializationType::PrintTemplateArgumentList(
466 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000467 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000468 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000469 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000470 << Active->InstantiationRange;
471 break;
472 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000473
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000474 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000475 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000476 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000477 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000478 << FnTmpl
479 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
480 Active->TemplateArgs,
481 Active->NumTemplateArgs)
482 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000483 break;
484 }
Mike Stump11289f42009-09-09 15:08:12 +0000485
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000486 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000487 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
488 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000489 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000490 diag::note_partial_spec_deduct_instantiation_here)
491 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000492 << getTemplateArgumentBindingsText(
493 PartialSpec->getTemplateParameters(),
494 Active->TemplateArgs,
495 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000496 << Active->InstantiationRange;
497 } else {
498 FunctionTemplateDecl *FnTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000499 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000500 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000501 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000502 << FnTmpl
503 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
504 Active->TemplateArgs,
505 Active->NumTemplateArgs)
506 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000507 }
508 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000509
Anders Carlsson657bad42009-09-05 05:14:19 +0000510 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000511 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000512 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000513
Benjamin Kramer9170e912013-02-22 15:46:01 +0000514 SmallVector<char, 128> TemplateArgsStr;
515 llvm::raw_svector_ostream OS(TemplateArgsStr);
516 FD->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000517 TemplateSpecializationType::PrintTemplateArgumentList(
518 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000519 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000520 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000521 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000522 << Active->InstantiationRange;
523 break;
524 }
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregore62e6a02009-11-11 19:13:48 +0000526 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000527 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000528 std::string Name;
529 if (!Parm->getName().empty())
530 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000531
532 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000533 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
534 TemplateParams = Template->getTemplateParameters();
535 else
536 TemplateParams =
537 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
538 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000539 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000540 diag::note_prior_template_arg_substitution)
541 << isa<TemplateTemplateParmDecl>(Parm)
542 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000543 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000544 Active->TemplateArgs,
545 Active->NumTemplateArgs)
546 << Active->InstantiationRange;
547 break;
548 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000549
550 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000551 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000552 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
553 TemplateParams = Template->getTemplateParameters();
554 else
555 TemplateParams =
556 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
557 ->getTemplateParameters();
558
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000559 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000560 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000561 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000562 Active->TemplateArgs,
563 Active->NumTemplateArgs)
564 << Active->InstantiationRange;
565 break;
566 }
Richard Smithf623c962012-04-17 00:58:00 +0000567
568 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
569 Diags.Report(Active->PointOfInstantiation,
570 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000571 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000572 << Active->InstantiationRange;
573 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000574 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000575 }
576}
577
David Blaikie05785d12013-02-20 22:23:23 +0000578Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000579 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000580 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000581
Craig Topper2341c0d2013-07-04 03:08:24 +0000582 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000583 Active = ActiveTemplateInstantiations.rbegin(),
584 ActiveEnd = ActiveTemplateInstantiations.rend();
585 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000586 ++Active)
587 {
Douglas Gregor33834512009-06-14 07:33:30 +0000588 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000589 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000590 // An instantiation of an alias template may or may not be a SFINAE
591 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000592 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000593 break;
594 // Fall through.
595 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000596 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000597 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000598 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000599
Douglas Gregor33834512009-06-14 07:33:30 +0000600 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000601 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000602 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000603 // A default template argument instantiation and substitution into
604 // template parameters with arguments for prior parameters may or may
605 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000606 break;
Mike Stump11289f42009-09-09 15:08:12 +0000607
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000608 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
609 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
610 // We're either substitution explicitly-specified template arguments
611 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000612 assert(Active->DeductionInfo && "Missing deduction info pointer");
613 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000614 }
615 }
616
David Blaikie7a30dc52013-02-21 01:47:18 +0000617 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000618}
619
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000620/// \brief Retrieve the depth and index of a parameter pack.
621static std::pair<unsigned, unsigned>
622getDepthAndIndex(NamedDecl *ND) {
623 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
624 return std::make_pair(TTP->getDepth(), TTP->getIndex());
625
626 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
627 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
628
629 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
630 return std::make_pair(TTP->getDepth(), TTP->getIndex());
631}
632
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000633//===----------------------------------------------------------------------===/
634// Template Instantiation for Types
635//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000636namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000637 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000638 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000639 SourceLocation Loc;
640 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000641
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000642 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000643 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000644
645 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000646 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000647 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000648 DeclarationName Entity)
649 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000650 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000651
Mike Stump11289f42009-09-09 15:08:12 +0000652 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000653 /// transformed.
654 ///
655 /// For the purposes of template instantiation, a type has already been
656 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000657 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000658
Douglas Gregord6ff3322009-08-04 16:50:30 +0000659 /// \brief Returns the location of the entity being instantiated, if known.
660 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000661
Douglas Gregord6ff3322009-08-04 16:50:30 +0000662 /// \brief Returns the name of the entity being instantiated, if any.
663 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000664
Douglas Gregoref6ab412009-10-27 06:26:26 +0000665 /// \brief Sets the "base" location and entity when that
666 /// information is known based on another transformation.
667 void setBase(SourceLocation Loc, DeclarationName Entity) {
668 this->Loc = Loc;
669 this->Entity = Entity;
670 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000671
672 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
673 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000674 ArrayRef<UnexpandedParameterPack> Unexpanded,
675 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000676 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000677 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
678 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000679 TemplateArgs,
680 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000681 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000682 NumExpansions);
683 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000684
Douglas Gregorf3010112011-01-07 16:43:16 +0000685 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
686 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
687 }
688
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000689 TemplateArgument ForgetPartiallySubstitutedPack() {
690 TemplateArgument Result;
691 if (NamedDecl *PartialPack
692 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
693 MultiLevelTemplateArgumentList &TemplateArgs
694 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
695 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000696 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000697 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
698 Result = TemplateArgs(Depth, Index);
699 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
700 }
701 }
702
703 return Result;
704 }
705
706 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
707 if (Arg.isNull())
708 return;
709
710 if (NamedDecl *PartialPack
711 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
712 MultiLevelTemplateArgumentList &TemplateArgs
713 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
714 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000715 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000716 TemplateArgs.setArgument(Depth, Index, Arg);
717 }
718 }
719
Douglas Gregord6ff3322009-08-04 16:50:30 +0000720 /// \brief Transform the given declaration by instantiating a reference to
721 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000722 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000723
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000724 void transformAttrs(Decl *Old, Decl *New) {
725 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
726 }
727
728 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000729 // If we've instantiated the call operator of a lambda or the call
730 // operator template of a generic lambda, update the "instantiation of"
731 // information.
732 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
733 if (NewMD && isLambdaCallOperator(NewMD)) {
734 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
735 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
736 NewTD->setInstantiatedFromMemberTemplate(
737 OldMD->getDescribedFunctionTemplate());
738 else
739 NewMD->setInstantiationOfMemberFunction(OldMD,
740 TSK_ImplicitInstantiation);
741 }
742
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000743 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000744
745 // We recreated a local declaration, but not by instantiating it. There
746 // may be pending dependent diagnostics to produce.
747 if (auto *DC = dyn_cast<DeclContext>(Old))
748 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000749 }
750
Mike Stump11289f42009-09-09 15:08:12 +0000751 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000752 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000753 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000754
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000755 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000756 /// declaration.
757 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
758
Douglas Gregorebe10102009-08-20 07:17:43 +0000759 /// \brief Rebuild the exception declaration and register the declaration
760 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000761 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000762 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000763 SourceLocation StartLoc,
764 SourceLocation NameLoc,
765 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000766
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000767 /// \brief Rebuild the Objective-C exception declaration and register the
768 /// declaration as an instantiated local.
769 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
770 TypeSourceInfo *TSInfo, QualType T);
771
John McCall7f41d982009-09-11 04:59:25 +0000772 /// \brief Check for tag mismatches when instantiating an
773 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000774 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
775 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000776 NestedNameSpecifierLoc QualifierLoc,
777 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000778
Craig Topperc3ec1492014-05-26 06:22:03 +0000779 TemplateName
780 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
781 SourceLocation NameLoc,
782 QualType ObjectType = QualType(),
783 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000784
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000785 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
786
John McCalldadc5752010-08-24 06:29:42 +0000787 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
788 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
789 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000790
John McCalldadc5752010-08-24 06:29:42 +0000791 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000792 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000793 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
794 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000795
796 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
797 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
798
799 /// \brief Transform a reference to a function parameter pack.
800 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
801 ParmVarDecl *PD);
802
803 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
804 /// expand a function parameter pack reference which refers to an expanded
805 /// pack.
806 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
807
Hans Wennborge113c202014-09-18 16:01:32 +0000808 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000809 FunctionProtoTypeLoc TL) {
810 // Call the base version; it will forward to our overridden version below.
811 return inherited::TransformFunctionProtoType(TLB, TL);
812 }
813
814 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000815 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
816 FunctionProtoTypeLoc TL,
817 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000818 unsigned ThisTypeQuals,
819 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000820
Douglas Gregor715e4612011-01-14 22:40:04 +0000821 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000822 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000823 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000824 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000825
Mike Stump11289f42009-09-09 15:08:12 +0000826 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000827 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000828 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000829 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000830
Douglas Gregorada4b792011-01-14 02:55:32 +0000831 /// \brief Transforms an already-substituted template type parameter pack
832 /// into either itself (if we aren't substituting into its pack expansion)
833 /// or the appropriate substituted argument.
834 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
835 SubstTemplateTypeParmPackTypeLoc TL);
836
Richard Smith2589b9802012-07-25 03:56:55 +0000837 ExprResult TransformLambdaExpr(LambdaExpr *E) {
838 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
839 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
840 }
841
David Majnemerb1004102014-03-02 18:46:05 +0000842 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000843 TemplateParameterList *OrigTPL) {
844 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
845
846 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
847 TemplateDeclInstantiator DeclInstantiator(getSema(),
848 /* DeclContext *Owner */ Owner, TemplateArgs);
849 return DeclInstantiator.SubstTemplateParams(OrigTPL);
850 }
John McCall7c454bb2011-07-15 05:09:51 +0000851 private:
852 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
853 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000854 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000855 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000856}
Douglas Gregor04318252009-07-06 15:59:29 +0000857
Douglas Gregor5597ab42010-05-07 23:12:07 +0000858bool TemplateInstantiator::AlreadyTransformed(QualType T) {
859 if (T.isNull())
860 return true;
861
Douglas Gregor678d76c2011-07-01 01:22:09 +0000862 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000863 return false;
864
865 getSema().MarkDeclarationsReferencedInType(Loc, T);
866 return true;
867}
868
Eli Friedman8917ad52013-07-19 19:40:38 +0000869static TemplateArgument
870getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
871 assert(S.ArgumentPackSubstitutionIndex >= 0);
872 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
873 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
874 if (Arg.isPackExpansion())
875 Arg = Arg.getPackExpansionPattern();
876 return Arg;
877}
878
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000879Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000880 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000881 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000882
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000883 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000884 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000885 // If the corresponding template argument is NULL or non-existent, it's
886 // because we are performing instantiation from explicitly-specified
887 // template arguments in a function template, but there were some
888 // arguments left unspecified.
889 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
890 TTP->getPosition()))
891 return D;
892
Douglas Gregorf5500772011-01-05 15:48:55 +0000893 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
894
895 if (TTP->isParameterPack()) {
896 assert(Arg.getKind() == TemplateArgument::Pack &&
897 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000898 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000899 }
900
901 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000902 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000903 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000904 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000905 }
Mike Stump11289f42009-09-09 15:08:12 +0000906
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000907 // Fall through to find the instantiated declaration for this template
908 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000909 }
Mike Stump11289f42009-09-09 15:08:12 +0000910
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000911 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000912}
913
Douglas Gregor25289362010-03-01 17:25:41 +0000914Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000915 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000916 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000917 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000918
Douglas Gregorebe10102009-08-20 07:17:43 +0000919 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
920 return Inst;
921}
922
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000923NamedDecl *
924TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
925 SourceLocation Loc) {
926 // If the first part of the nested-name-specifier was a template type
927 // parameter, instantiate that type parameter down to a tag type.
928 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
929 const TemplateTypeParmType *TTP
930 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000931
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000932 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000933 // FIXME: This needs testing w/ member access expressions.
934 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
935
936 if (TTP->isParameterPack()) {
937 assert(Arg.getKind() == TemplateArgument::Pack &&
938 "Missing argument pack");
939
Douglas Gregore1d60df2011-01-14 23:41:42 +0000940 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000941 return nullptr;
942
Eli Friedman8917ad52013-07-19 19:40:38 +0000943 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000944 }
945
946 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000947 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000948 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000949
950 if (const TagType *Tag = T->getAs<TagType>())
951 return Tag->getDecl();
952
953 // The resulting type is not a tag; complain.
954 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000955 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000956 }
957 }
958
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000959 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000960}
961
Douglas Gregorebe10102009-08-20 07:17:43 +0000962VarDecl *
963TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000964 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000965 SourceLocation StartLoc,
966 SourceLocation NameLoc,
967 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000968 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000969 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000970 if (Var)
971 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
972 return Var;
973}
974
975VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
976 TypeSourceInfo *TSInfo,
977 QualType T) {
978 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
979 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000980 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
981 return Var;
982}
983
John McCall7f41d982009-09-11 04:59:25 +0000984QualType
John McCall954b5de2010-11-04 19:04:38 +0000985TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
986 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000987 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000988 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000989 if (const TagType *TT = T->getAs<TagType>()) {
990 TagDecl* TD = TT->getDecl();
991
John McCall954b5de2010-11-04 19:04:38 +0000992 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000993
John McCall7f41d982009-09-11 04:59:25 +0000994 IdentifierInfo *Id = TD->getIdentifier();
995
996 // TODO: should we even warn on struct/class mismatches for this? Seems
997 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +0000998 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000999 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001000 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001001 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001002 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1003 << Id
1004 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1005 TD->getKindName());
1006 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1007 }
John McCall7f41d982009-09-11 04:59:25 +00001008 }
1009 }
1010
John McCall954b5de2010-11-04 19:04:38 +00001011 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1012 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001013 QualifierLoc,
1014 T);
John McCall7f41d982009-09-11 04:59:25 +00001015}
1016
Douglas Gregor9db53502011-03-02 18:07:45 +00001017TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1018 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001019 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001020 QualType ObjectType,
1021 NamedDecl *FirstQualifierInScope) {
1022 if (TemplateTemplateParmDecl *TTP
1023 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1024 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1025 // If the corresponding template argument is NULL or non-existent, it's
1026 // because we are performing instantiation from explicitly-specified
1027 // template arguments in a function template, but there were some
1028 // arguments left unspecified.
1029 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1030 TTP->getPosition()))
1031 return Name;
1032
1033 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1034
1035 if (TTP->isParameterPack()) {
1036 assert(Arg.getKind() == TemplateArgument::Pack &&
1037 "Missing argument pack");
1038
1039 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1040 // We have the template argument pack to substitute, but we're not
1041 // actually expanding the enclosing pack expansion yet. So, just
1042 // keep the entire argument pack.
1043 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1044 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001045
1046 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001047 }
1048
1049 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001050 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001051
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001052 // We don't ever want to substitute for a qualified template name, since
1053 // the qualifier is handled separately. So, look through the qualified
1054 // template name to its underlying declaration.
1055 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1056 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001057
1058 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001059 return Template;
1060 }
1061 }
1062
1063 if (SubstTemplateTemplateParmPackStorage *SubstPack
1064 = Name.getAsSubstTemplateTemplateParmPack()) {
1065 if (getSema().ArgumentPackSubstitutionIndex == -1)
1066 return Name;
1067
Eli Friedman8917ad52013-07-19 19:40:38 +00001068 TemplateArgument Arg = SubstPack->getArgumentPack();
1069 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1070 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001071 }
1072
1073 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1074 FirstQualifierInScope);
1075}
1076
John McCalldadc5752010-08-24 06:29:42 +00001077ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001078TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001079 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001080 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001081
Wei Panc354d212013-09-16 13:57:27 +00001082 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001083}
1084
John McCalldadc5752010-08-24 06:29:42 +00001085ExprResult
John McCall13481c52010-02-06 08:42:39 +00001086TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001087 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001088 // If the corresponding template argument is NULL or non-existent, it's
1089 // because we are performing instantiation from explicitly-specified
1090 // template arguments in a function template, but there were some
1091 // arguments left unspecified.
1092 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1093 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001094 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001095
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001096 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1097 if (NTTP->isParameterPack()) {
1098 assert(Arg.getKind() == TemplateArgument::Pack &&
1099 "Missing argument pack");
1100
1101 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001102 // We have an argument pack, but we can't select a particular argument
1103 // out of it yet. Therefore, we'll build an expression to hold on to that
1104 // argument pack.
1105 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1106 E->getLocation(),
1107 NTTP->getDeclName());
1108 if (TargetType.isNull())
1109 return ExprError();
1110
1111 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1112 NTTP,
1113 E->getLocation(),
1114 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001115 }
1116
Eli Friedman8917ad52013-07-19 19:40:38 +00001117 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001118 }
Mike Stump11289f42009-09-09 15:08:12 +00001119
John McCall7c454bb2011-07-15 05:09:51 +00001120 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1121}
1122
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001123const LoopHintAttr *
1124TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1125 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1126
1127 if (TransformedExpr == LH->getValue())
1128 return LH;
1129
1130 // Generate error if there is a problem with the value.
1131 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1132 return LH;
1133
1134 // Create new LoopHintValueAttr with integral expression in place of the
1135 // non-type template parameter.
1136 return LoopHintAttr::CreateImplicit(
1137 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1138 LH->getState(), TransformedExpr, LH->getRange());
1139}
1140
John McCall7c454bb2011-07-15 05:09:51 +00001141ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1142 NonTypeTemplateParmDecl *parm,
1143 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001144 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001145 ExprResult result;
1146 QualType type;
1147
John McCall13481c52010-02-06 08:42:39 +00001148 // The template argument itself might be an expression, in which
1149 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001150 if (arg.getKind() == TemplateArgument::Expression) {
1151 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001152 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001153 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001154
Eli Friedmanb826a002012-09-26 02:36:12 +00001155 } else if (arg.getKind() == TemplateArgument::Declaration ||
1156 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001157 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001158 if (arg.getKind() == TemplateArgument::Declaration) {
1159 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001160
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001161 // Find the instantiation of the template argument. This is
1162 // required for nested templates.
1163 VD = cast_or_null<ValueDecl>(
1164 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1165 if (!VD)
1166 return ExprError();
1167 } else {
1168 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001169 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001170 }
1171
John McCall15dda372010-02-06 10:23:53 +00001172 // Derive the type we want the substituted decl to have. This had
1173 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001174 if (parm->isExpandedParameterPack()) {
1175 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1176 } else if (parm->isParameterPack() &&
1177 isa<PackExpansionType>(parm->getType())) {
1178 type = SemaRef.SubstType(
1179 cast<PackExpansionType>(parm->getType())->getPattern(),
1180 TemplateArgs, loc, parm->getDeclName());
1181 } else {
1182 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1183 loc, parm->getDeclName());
1184 }
1185 assert(!type.isNull() && "type substitution failed for param type");
1186 assert(!type->isDependentType() && "param type still dependent");
1187 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001188
John McCall7c454bb2011-07-15 05:09:51 +00001189 if (!result.isInvalid()) type = result.get()->getType();
1190 } else {
1191 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1192
1193 // Note that this type can be different from the type of 'result',
1194 // e.g. if it's an enum type.
1195 type = arg.getIntegralType();
1196 }
1197 if (result.isInvalid()) return ExprError();
1198
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001199 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001200 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1201 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001202}
1203
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001204ExprResult
1205TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1206 SubstNonTypeTemplateParmPackExpr *E) {
1207 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1208 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001209 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001210 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001211
1212 TemplateArgument Arg = E->getArgumentPack();
1213 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001214 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1215 E->getParameterPackLocation(),
1216 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001217}
John McCall13481c52010-02-06 08:42:39 +00001218
John McCalldadc5752010-08-24 06:29:42 +00001219ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001220TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1221 SourceLocation Loc) {
1222 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1223 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1224}
1225
1226ExprResult
1227TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1228 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1229 // We can expand this parameter pack now.
1230 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1231 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1232 if (!VD)
1233 return ExprError();
1234 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1235 }
1236
1237 QualType T = TransformType(E->getType());
1238 if (T.isNull())
1239 return ExprError();
1240
1241 // Transform each of the parameter expansions into the corresponding
1242 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001243 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001244 Parms.reserve(E->getNumExpansions());
1245 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1246 I != End; ++I) {
1247 ParmVarDecl *D =
1248 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1249 if (!D)
1250 return ExprError();
1251 Parms.push_back(D);
1252 }
1253
1254 return FunctionParmPackExpr::Create(getSema().Context, T,
1255 E->getParameterPack(),
1256 E->getParameterPackLocation(), Parms);
1257}
1258
1259ExprResult
1260TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1261 ParmVarDecl *PD) {
1262 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1263 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1264 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1265 assert(Found && "no instantiation for parameter pack");
1266
1267 Decl *TransformedDecl;
1268 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001269 // If this is a reference to a function parameter pack which we can
1270 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001271 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1272 QualType T = TransformType(E->getType());
1273 if (T.isNull())
1274 return ExprError();
1275 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1276 E->getExprLoc(), *Pack);
1277 }
1278
1279 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1280 } else {
1281 TransformedDecl = Found->get<Decl*>();
1282 }
1283
1284 // We have either an unexpanded pack or a specific expansion.
1285 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1286 E->getExprLoc());
1287}
1288
1289ExprResult
John McCall13481c52010-02-06 08:42:39 +00001290TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1291 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001292
1293 // Handle references to non-type template parameters and non-type template
1294 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001295 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1296 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1297 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001298
1299 // We have a non-type template parameter that isn't fully substituted;
1300 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001301 }
Mike Stump11289f42009-09-09 15:08:12 +00001302
Richard Smithb15fe3a2012-09-12 00:56:43 +00001303 // Handle references to function parameter packs.
1304 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1305 if (PD->isParameterPack())
1306 return TransformFunctionParmPackRefExpr(E, PD);
1307
John McCall47f29ea2009-12-08 09:21:05 +00001308 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001309}
1310
John McCalldadc5752010-08-24 06:29:42 +00001311ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001312 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001313 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1314 getDescribedFunctionTemplate() &&
1315 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001316 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1317 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1318 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001319}
1320
Richard Smith2e321552014-11-12 02:00:47 +00001321template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001322QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1323 FunctionProtoTypeLoc TL,
1324 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001325 unsigned ThisTypeQuals,
1326 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001327 // We need a local instantiation scope for this function prototype.
1328 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001329 return inherited::TransformFunctionProtoType(
1330 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001331}
1332
John McCall58f10c32010-03-11 09:03:00 +00001333ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001334TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001335 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001336 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001337 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001338 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001339 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001340}
1341
Mike Stump11289f42009-09-09 15:08:12 +00001342QualType
John McCall550e0c22009-10-21 00:40:46 +00001343TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001344 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001345 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001346 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001347 // Replace the template type parameter with its corresponding
1348 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001349
1350 // If the corresponding template argument is NULL or doesn't exist, it's
1351 // because we are performing instantiation from explicitly-specified
1352 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001353 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001354 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1355 TemplateTypeParmTypeLoc NewTL
1356 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1357 NewTL.setNameLoc(TL.getNameLoc());
1358 return TL.getType();
1359 }
Mike Stump11289f42009-09-09 15:08:12 +00001360
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001361 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1362
1363 if (T->isParameterPack()) {
1364 assert(Arg.getKind() == TemplateArgument::Pack &&
1365 "Missing argument pack");
1366
1367 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001368 // We have the template argument pack, but we're not expanding the
1369 // enclosing pack expansion yet. Just save the template argument
1370 // pack for later substitution.
1371 QualType Result
1372 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1373 SubstTemplateTypeParmPackTypeLoc NewTL
1374 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1375 NewTL.setNameLoc(TL.getNameLoc());
1376 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001377 }
1378
Eli Friedman8917ad52013-07-19 19:40:38 +00001379 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001380 }
1381
1382 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001383 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001384
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001385 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001386
1387 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001388 QualType Result
1389 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1390 SubstTemplateTypeParmTypeLoc NewTL
1391 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1392 NewTL.setNameLoc(TL.getNameLoc());
1393 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001394 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001395
1396 // The template type parameter comes from an inner template (e.g.,
1397 // the template parameter list of a member template inside the
1398 // template we are instantiating). Create a new template type
1399 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001400 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001401 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1402 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1403 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1404
John McCall550e0c22009-10-21 00:40:46 +00001405 QualType Result
1406 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1407 - TemplateArgs.getNumLevels(),
1408 T->getIndex(),
1409 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001410 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001411 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1412 NewTL.setNameLoc(TL.getNameLoc());
1413 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001414}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001415
Douglas Gregorada4b792011-01-14 02:55:32 +00001416QualType
1417TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1418 TypeLocBuilder &TLB,
1419 SubstTemplateTypeParmPackTypeLoc TL) {
1420 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1421 // We aren't expanding the parameter pack, so just return ourselves.
1422 SubstTemplateTypeParmPackTypeLoc NewTL
1423 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1424 NewTL.setNameLoc(TL.getNameLoc());
1425 return TL.getType();
1426 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001427
1428 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1429 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1430 QualType Result = Arg.getAsType();
1431
Douglas Gregorada4b792011-01-14 02:55:32 +00001432 Result = getSema().Context.getSubstTemplateTypeParmType(
1433 TL.getTypePtr()->getReplacedParameter(),
1434 Result);
1435 SubstTemplateTypeParmTypeLoc NewTL
1436 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1437 NewTL.setNameLoc(TL.getNameLoc());
1438 return Result;
1439}
1440
John McCall76d824f2009-08-25 22:02:44 +00001441/// \brief Perform substitution on the type T with a given set of template
1442/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001443///
1444/// This routine substitutes the given template arguments into the
1445/// type T and produces the instantiated type.
1446///
1447/// \param T the type into which the template arguments will be
1448/// substituted. If this type is not dependent, it will be returned
1449/// immediately.
1450///
James Dennett634962f2012-06-14 21:40:34 +00001451/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001452/// substituted for the top-level template parameters within T.
1453///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001454/// \param Loc the location in the source code where this substitution
1455/// is being performed. It will typically be the location of the
1456/// declarator (if we're instantiating the type of some declaration)
1457/// or the location of the type in the source code (if, e.g., we're
1458/// instantiating the type of a cast expression).
1459///
1460/// \param Entity the name of the entity associated with a declaration
1461/// being instantiated (if any). May be empty to indicate that there
1462/// is no such entity (if, e.g., this is a type that occurs as part of
1463/// a cast expression) or that the entity has no name (e.g., an
1464/// unnamed function parameter).
1465///
1466/// \returns If the instantiation succeeds, the instantiated
1467/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001468TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001469 const MultiLevelTemplateArgumentList &Args,
1470 SourceLocation Loc,
1471 DeclarationName Entity) {
1472 assert(!ActiveTemplateInstantiations.empty() &&
1473 "Cannot perform an instantiation without some context on the "
1474 "instantiation stack");
1475
Douglas Gregor678d76c2011-07-01 01:22:09 +00001476 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001477 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001478 return T;
1479
1480 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1481 return Instantiator.TransformType(T);
1482}
1483
Douglas Gregor5499af42011-01-05 23:12:31 +00001484TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1485 const MultiLevelTemplateArgumentList &Args,
1486 SourceLocation Loc,
1487 DeclarationName Entity) {
1488 assert(!ActiveTemplateInstantiations.empty() &&
1489 "Cannot perform an instantiation without some context on the "
1490 "instantiation stack");
1491
1492 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001493 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001494
Douglas Gregor678d76c2011-07-01 01:22:09 +00001495 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001496 !TL.getType()->isVariablyModifiedType()) {
1497 // FIXME: Make a copy of the TypeLoc data here, so that we can
1498 // return a new TypeSourceInfo. Inefficient!
1499 TypeLocBuilder TLB;
1500 TLB.pushFullCopy(TL);
1501 return TLB.getTypeSourceInfo(Context, TL.getType());
1502 }
1503
1504 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1505 TypeLocBuilder TLB;
1506 TLB.reserve(TL.getFullDataSize());
1507 QualType Result = Instantiator.TransformType(TLB, TL);
1508 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001509 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001510
1511 return TLB.getTypeSourceInfo(Context, Result);
1512}
1513
John McCall609459e2009-10-21 00:58:09 +00001514/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001515QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001516 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001517 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001518 assert(!ActiveTemplateInstantiations.empty() &&
1519 "Cannot perform an instantiation without some context on the "
1520 "instantiation stack");
1521
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001522 // If T is not a dependent type or a variably-modified type, there
1523 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001524 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001525 return T;
1526
Douglas Gregord6ff3322009-08-04 16:50:30 +00001527 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1528 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001529}
Douglas Gregor463421d2009-03-03 04:44:36 +00001530
John McCallb29f78f2010-04-09 17:38:44 +00001531static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001532 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001533 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001534 return true;
1535
Abramo Bagnara6d810632010-12-14 22:11:44 +00001536 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001537 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001538 return false;
1539
David Blaikie6adc78e2013-02-18 22:06:02 +00001540 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001541 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001542 // This must be synthesized from a typedef.
1543 if (!P) continue;
1544
Nico Weberc0973372016-02-01 22:31:51 +00001545 // If there are any parameters, a new TypeSourceInfo that refers to the
1546 // instantiated parameters must be built.
1547 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001548 }
1549
1550 return false;
1551}
1552
1553/// A form of SubstType intended specifically for instantiating the
1554/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001555/// instantiation of default-argument expressions and to avoid
1556/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001557TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1558 const MultiLevelTemplateArgumentList &Args,
1559 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001560 DeclarationName Entity,
1561 CXXRecordDecl *ThisContext,
1562 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001563 assert(!ActiveTemplateInstantiations.empty() &&
1564 "Cannot perform an instantiation without some context on the "
1565 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001566
John McCallb29f78f2010-04-09 17:38:44 +00001567 if (!NeedsInstantiationAsFunctionType(T))
1568 return T;
1569
1570 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1571
1572 TypeLocBuilder TLB;
1573
1574 TypeLoc TL = T->getTypeLoc();
1575 TLB.reserve(TL.getFullDataSize());
1576
Douglas Gregor3024f072012-04-16 07:05:22 +00001577 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001578
Richard Smith2e321552014-11-12 02:00:47 +00001579 if (FunctionProtoTypeLoc Proto =
1580 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1581 // Instantiate the type, other than its exception specification. The
1582 // exception specification is instantiated in InitFunctionInstantiation
1583 // once we've built the FunctionDecl.
1584 // FIXME: Set the exception specification to EST_Uninstantiated here,
1585 // instead of rebuilding the function type again later.
1586 Result = Instantiator.TransformFunctionProtoType(
1587 TLB, Proto, ThisContext, ThisTypeQuals,
1588 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1589 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001590 } else {
1591 Result = Instantiator.TransformType(TLB, TL);
1592 }
John McCallb29f78f2010-04-09 17:38:44 +00001593 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001594 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001595
1596 return TLB.getTypeSourceInfo(Context, Result);
1597}
1598
Richard Smith2e321552014-11-12 02:00:47 +00001599void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1600 const MultiLevelTemplateArgumentList &Args) {
1601 FunctionProtoType::ExceptionSpecInfo ESI =
1602 Proto->getExtProtoInfo().ExceptionSpec;
1603 assert(ESI.Type != EST_Uninstantiated);
1604
1605 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1606 New->getDeclName());
1607
1608 SmallVector<QualType, 4> ExceptionStorage;
1609 bool Changed = false;
1610 if (Instantiator.TransformExceptionSpec(
1611 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1612 ExceptionStorage, Changed))
1613 // On error, recover by dropping the exception specification.
1614 ESI.Type = EST_None;
1615
1616 UpdateExceptionSpec(New, ESI);
1617}
1618
Douglas Gregor940bca72010-04-12 07:48:19 +00001619ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001620 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001621 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001622 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001623 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001624 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001625 TypeSourceInfo *NewDI = nullptr;
1626
Douglas Gregor5499af42011-01-05 23:12:31 +00001627 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001628 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1629
Douglas Gregor5499af42011-01-05 23:12:31 +00001630 // We have a function parameter pack. Substitute into the pattern of the
1631 // expansion.
1632 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1633 OldParm->getLocation(), OldParm->getDeclName());
1634 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001635 return nullptr;
1636
Douglas Gregor5499af42011-01-05 23:12:31 +00001637 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1638 // We still have unexpanded parameter packs, which means that
1639 // our function parameter is still a function parameter pack.
1640 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001641 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001642 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001643 } else if (ExpectParameterPack) {
1644 // We expected to get a parameter pack but didn't (because the type
1645 // itself is not a pack expansion type), so complain. This can occur when
1646 // the substitution goes through an alias template that "loses" the
1647 // pack expansion.
1648 Diag(OldParm->getLocation(),
1649 diag::err_function_parameter_pack_without_parameter_packs)
1650 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001651 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001652 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001653 } else {
1654 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1655 OldParm->getDeclName());
1656 }
1657
Douglas Gregor940bca72010-04-12 07:48:19 +00001658 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001659 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001660
1661 if (NewDI->getType()->isVoidType()) {
1662 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001663 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001664 }
1665
1666 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001667 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001668 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001669 OldParm->getIdentifier(),
1670 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001671 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001672 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001673 return nullptr;
1674
Douglas Gregor940bca72010-04-12 07:48:19 +00001675 // Mark the (new) default argument as uninstantiated (if any).
1676 if (OldParm->hasUninstantiatedDefaultArg()) {
1677 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1678 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001679 } else if (OldParm->hasUnparsedDefaultArg()) {
1680 NewParm->setUnparsedDefaultArg();
1681 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001682 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1683 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001684 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1685 // Instantiate default arguments for methods of local classes (DR1484)
1686 // and non-defining declarations.
1687 Sema::ContextRAII SavedContext(*this, OwningFunc);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001688 LocalInstantiationScope Local(*this);
1689 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001690 if (NewArg.isUsable()) {
1691 // It would be nice if we still had this.
1692 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1693 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1694 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001695 } else {
1696 // FIXME: if we non-lazily instantiated non-dependent default args for
1697 // non-dependent parameter types we could remove a bunch of duplicate
1698 // conversion warnings for such arguments.
1699 NewParm->setUninstantiatedDefaultArg(Arg);
1700 }
1701 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001702
1703 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001704
Douglas Gregorf3010112011-01-07 16:43:16 +00001705 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001706 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001707 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1708 } else {
1709 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001710 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001711 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001712
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001713 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1714 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001715 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001716
1717 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1718 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001719
1720 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1721
Douglas Gregor940bca72010-04-12 07:48:19 +00001722 return NewParm;
1723}
1724
Douglas Gregordd472162011-01-07 00:20:55 +00001725/// \brief Substitute the given template arguments into the given set of
1726/// parameters, producing the set of parameter types that would be generated
1727/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001728bool Sema::SubstParmTypes(
1729 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1730 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1731 const MultiLevelTemplateArgumentList &TemplateArgs,
1732 SmallVectorImpl<QualType> &ParamTypes,
1733 SmallVectorImpl<ParmVarDecl *> *OutParams,
1734 ExtParameterInfoBuilder &ParamInfos) {
Douglas Gregordd472162011-01-07 00:20:55 +00001735 assert(!ActiveTemplateInstantiations.empty() &&
1736 "Cannot perform an instantiation without some context on the "
1737 "instantiation stack");
1738
1739 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1740 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001741 return Instantiator.TransformFunctionTypeParams(
1742 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001743}
1744
John McCall76d824f2009-08-25 22:02:44 +00001745/// \brief Perform substitution on the base class specifiers of the
1746/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001747///
1748/// Produces a diagnostic and returns true on error, returns false and
1749/// attaches the instantiated base classes to the class template
1750/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001751bool
John McCall76d824f2009-08-25 22:02:44 +00001752Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1753 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001754 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001755 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001756 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001757 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001758 if (!Base.getType()->isDependentType()) {
1759 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001760 if (RD->isInvalidDecl())
1761 Instantiation->setInvalidDecl();
1762 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001763 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001764 continue;
1765 }
1766
Douglas Gregor752a5952011-01-03 22:36:02 +00001767 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001768 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001769 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001770 // This is a pack expansion. See whether we should expand it now, or
1771 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001772 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001773 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001774 Unexpanded);
1775 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001776 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001777 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001778 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1779 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001780 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001781 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001782 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001783 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001784 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001785 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001786 }
1787
1788 // If we should expand this pack expansion now, do so.
1789 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001790 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001791 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1792
Aaron Ballman574705e2014-03-13 15:41:46 +00001793 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001794 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001795 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001796 DeclarationName());
1797 if (!BaseTypeLoc) {
1798 Invalid = true;
1799 continue;
1800 }
1801
1802 if (CXXBaseSpecifier *InstantiatedBase
1803 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001804 Base.getSourceRange(),
1805 Base.isVirtual(),
1806 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001807 BaseTypeLoc,
1808 SourceLocation()))
1809 InstantiatedBases.push_back(InstantiatedBase);
1810 else
1811 Invalid = true;
1812 }
1813
1814 continue;
1815 }
1816
1817 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001818 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001819 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001820 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001821 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001822 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001823 DeclarationName());
1824 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001825 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001826 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001827 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001828 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001829 }
1830
Nick Lewycky19b9f952010-07-26 16:56:01 +00001831 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001832 Invalid = true;
1833 continue;
1834 }
1835
1836 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001837 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001838 Base.getSourceRange(),
1839 Base.isVirtual(),
1840 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001841 BaseTypeLoc,
1842 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001843 InstantiatedBases.push_back(InstantiatedBase);
1844 else
1845 Invalid = true;
1846 }
1847
Craig Topperaa700cb2015-12-27 21:55:19 +00001848 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001849 Invalid = true;
1850
1851 return Invalid;
1852}
1853
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001854// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001855namespace clang {
1856 namespace sema {
1857 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1858 const MultiLevelTemplateArgumentList &TemplateArgs);
1859 }
1860}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001861
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001862/// \brief Instantiate the definition of a class from a given pattern.
1863///
1864/// \param PointOfInstantiation The point of instantiation within the
1865/// source code.
1866///
1867/// \param Instantiation is the declaration whose definition is being
1868/// instantiated. This will be either a class template specialization
1869/// or a member class of a class template specialization.
1870///
1871/// \param Pattern is the pattern from which the instantiation
1872/// occurs. This will be either the declaration of a class template or
1873/// the declaration of a member class of a class template.
1874///
1875/// \param TemplateArgs The template arguments to be substituted into
1876/// the pattern.
1877///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001878/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001879///
1880/// \param Complain whether to complain if the class cannot be instantiated due
1881/// to the lack of a definition.
1882///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001883/// \returns true if an error occurred, false otherwise.
1884bool
1885Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1886 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001887 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001888 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001889 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001890 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001891 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00001892 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00001893 Instantiation->getInstantiatedFromMemberClass(),
1894 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001895 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001896 Pattern = PatternDef;
1897
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001898 // \brief Record the point of instantiation.
1899 if (MemberSpecializationInfo *MSInfo
1900 = Instantiation->getMemberSpecializationInfo()) {
1901 MSInfo->setTemplateSpecializationKind(TSK);
1902 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001903 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001904 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001905 Spec->setTemplateSpecializationKind(TSK);
1906 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001907 }
Richard Smitha1087602014-03-10 00:04:29 +00001908
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001909 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001910 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001911 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00001912 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Richard Smithe19b95d2016-05-26 20:23:13 +00001913 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1914 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001915
1916 // Enter the scope of this instantiation. We don't use
1917 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001918 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001919 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001920 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001921
Douglas Gregor51121572010-03-24 01:33:17 +00001922 // If this is an instantiation of a local class, merge this local
1923 // instantiation scope with the enclosing scope. Otherwise, every
1924 // instantiation of a class has its own local instantiation scope.
1925 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001926 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001927
Reid Kleckner5b640342016-02-26 19:51:02 +00001928 // All dllexported classes created during instantiation should be fully
1929 // emitted after instantiation completes. We may not be ready to emit any
1930 // delayed classes already on the stack, so save them away and put them back
1931 // later.
1932 decltype(DelayedDllExportClasses) ExportedClasses;
1933 std::swap(ExportedClasses, DelayedDllExportClasses);
1934
John McCall6602bb12010-08-01 02:01:53 +00001935 // Pull attributes from the pattern onto the instantiation.
1936 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1937
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001938 // Start the definition of this instantiation.
1939 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001940
1941 // The instantiation is visible here, even if it was first declared in an
1942 // unimported module.
1943 Instantiation->setHidden(false);
1944
1945 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001946 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001947
John McCall76d824f2009-08-25 22:02:44 +00001948 // Do substitution on the base class specifiers.
1949 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001950 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001951
Douglas Gregor869853e2010-11-10 19:44:59 +00001952 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001953 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001954 // Delay instantiation of late parsed attributes.
1955 LateInstantiatedAttrVec LateAttrs;
1956 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1957
Aaron Ballman629afae2014-03-07 19:56:05 +00001958 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001959 // Don't instantiate members not belonging in this semantic context.
1960 // e.g. for:
1961 // @code
1962 // template <int i> class A {
1963 // class B *g;
1964 // };
1965 // @endcode
1966 // 'class B' has the template as lexical context but semantically it is
1967 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00001968 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001969 continue;
1970
Aaron Ballman629afae2014-03-07 19:56:05 +00001971 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00001972 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00001973 continue;
1974 }
1975
Aaron Ballman629afae2014-03-07 19:56:05 +00001976 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001977 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00001978 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00001979 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00001980 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
1981 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1982 // specialization causes the implicit instantiation of the definitions
1983 // of unscoped member enumerations.
1984 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00001985 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
1986 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00001987 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
1988 assert(MSInfo && "no spec info for member enum specialization");
1989 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
1990 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1991 }
Richard Smithded9c2e2012-07-11 22:37:56 +00001992 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
1993 if (SA->isFailed()) {
1994 // A static_assert failed. Bail out; instantiating this
1995 // class is probably not meaningful.
1996 Instantiation->setInvalidDecl();
1997 break;
1998 }
Richard Smith7d137e32012-03-23 03:33:32 +00001999 }
2000
2001 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002002 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002003 } else {
2004 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002005 // instantiations was a semantic disaster, and we'll want to mark the
2006 // declaration invalid.
2007 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002008 }
2009 }
2010
2011 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002012 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2013 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002014 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002015
Reid Kleckner93f661a2015-03-17 21:51:43 +00002016 // Default arguments are parsed, if not instantiated. We can go instantiate
2017 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002018 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002019
Reid Kleckner5b640342016-02-26 19:51:02 +00002020 // Put back the delayed exported classes that we moved out of the way.
2021 std::swap(ExportedClasses, DelayedDllExportClasses);
2022
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002023 // Instantiate late parsed attributes, and attach them to their decls.
2024 // See Sema::InstantiateAttrs
2025 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2026 E = LateAttrs.end(); I != E; ++I) {
2027 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2028 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002029
2030 // Allow 'this' within late-parsed attributes.
2031 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2032 CXXRecordDecl *ThisContext =
2033 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2034 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2035 ND && ND->isCXXInstanceMember());
2036
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002037 Attr *NewAttr =
2038 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2039 I->NewDecl->addAttr(NewAttr);
2040 LocalInstantiationScope::deleteScopes(I->Scope,
2041 Instantiator.getStartingScope());
2042 }
2043 Instantiator.disableLateAttributeInstantiation();
2044 LateAttrs.clear();
2045
Richard Smithd3b5c9082012-07-27 04:22:15 +00002046 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002047
Richard Smitha1087602014-03-10 00:04:29 +00002048 // FIXME: We should do something similar for explicit instantiations so they
2049 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002050 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002051 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002052 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002053 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002054 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002055
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002056 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002057 // Perform any dependent diagnostics from the pattern.
2058 PerformDependentDiagnostics(Pattern, TemplateArgs);
2059
Douglas Gregor869853e2010-11-10 19:44:59 +00002060 // Instantiate any out-of-line class template partial
2061 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002062 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002063 P = Instantiator.delayed_partial_spec_begin(),
2064 PEnd = Instantiator.delayed_partial_spec_end();
2065 P != PEnd; ++P) {
2066 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002067 P->first, P->second)) {
2068 Instantiation->setInvalidDecl();
2069 break;
2070 }
2071 }
2072
2073 // Instantiate any out-of-line variable template partial
2074 // specializations now.
2075 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2076 P = Instantiator.delayed_var_partial_spec_begin(),
2077 PEnd = Instantiator.delayed_var_partial_spec_end();
2078 P != PEnd; ++P) {
2079 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2080 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002081 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002082 break;
2083 }
2084 }
2085 }
2086
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002087 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002088 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002089
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002090 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002091 Consumer.HandleTagDeclDefinition(Instantiation);
2092
Douglas Gregor88d292c2010-05-13 16:44:06 +00002093 // Always emit the vtable for an explicit instantiation definition
2094 // of a polymorphic class template specialization.
2095 if (TSK == TSK_ExplicitInstantiationDefinition)
2096 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2097 }
2098
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002099 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002100}
2101
Richard Smith4b38ded2012-03-14 23:13:10 +00002102/// \brief Instantiate the definition of an enum from a given pattern.
2103///
2104/// \param PointOfInstantiation The point of instantiation within the
2105/// source code.
2106/// \param Instantiation is the declaration whose definition is being
2107/// instantiated. This will be a member enumeration of a class
2108/// temploid specialization, or a local enumeration within a
2109/// function temploid specialization.
2110/// \param Pattern The templated declaration from which the instantiation
2111/// occurs.
2112/// \param TemplateArgs The template arguments to be substituted into
2113/// the pattern.
2114/// \param TSK The kind of implicit or explicit instantiation to perform.
2115///
2116/// \return \c true if an error occurred, \c false otherwise.
2117bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2118 EnumDecl *Instantiation, EnumDecl *Pattern,
2119 const MultiLevelTemplateArgumentList &TemplateArgs,
2120 TemplateSpecializationKind TSK) {
2121 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002122 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002123 Instantiation->getInstantiatedFromMemberEnum(),
2124 Pattern, PatternDef, TSK,/*Complain*/true))
2125 return true;
2126 Pattern = PatternDef;
2127
2128 // Record the point of instantiation.
2129 if (MemberSpecializationInfo *MSInfo
2130 = Instantiation->getMemberSpecializationInfo()) {
2131 MSInfo->setTemplateSpecializationKind(TSK);
2132 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2133 }
2134
2135 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002136 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002137 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002138 if (Inst.isAlreadyInstantiating())
2139 return false;
Richard Smithe19b95d2016-05-26 20:23:13 +00002140 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2141 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002142
Richard Smitha1087602014-03-10 00:04:29 +00002143 // The instantiation is visible here, even if it was first declared in an
2144 // unimported module.
2145 Instantiation->setHidden(false);
2146
Richard Smith4b38ded2012-03-14 23:13:10 +00002147 // Enter the scope of this instantiation. We don't use
2148 // PushDeclContext because we don't have a scope.
2149 ContextRAII SavedContext(*this, Instantiation);
2150 EnterExpressionEvaluationContext EvalContext(*this,
2151 Sema::PotentiallyEvaluated);
2152
2153 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2154
2155 // Pull attributes from the pattern onto the instantiation.
2156 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2157
2158 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2159 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2160
2161 // Exit the scope of this instantiation.
2162 SavedContext.pop();
2163
2164 return Instantiation->isInvalidDecl();
2165}
2166
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002167
2168/// \brief Instantiate the definition of a field from the given pattern.
2169///
2170/// \param PointOfInstantiation The point of instantiation within the
2171/// source code.
2172/// \param Instantiation is the declaration whose definition is being
2173/// instantiated. This will be a class of a class temploid
2174/// specialization, or a local enumeration within a function temploid
2175/// specialization.
2176/// \param Pattern The templated declaration from which the instantiation
2177/// occurs.
2178/// \param TemplateArgs The template arguments to be substituted into
2179/// the pattern.
2180///
2181/// \return \c true if an error occurred, \c false otherwise.
2182bool Sema::InstantiateInClassInitializer(
2183 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2184 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2185 // If there is no initializer, we don't need to do anything.
2186 if (!Pattern->hasInClassInitializer())
2187 return false;
2188
2189 assert(Instantiation->getInClassInitStyle() ==
2190 Pattern->getInClassInitStyle() &&
2191 "pattern and instantiation disagree about init style");
2192
2193 // Error out if we haven't parsed the initializer of the pattern yet because
2194 // we are waiting for the closing brace of the outer class.
2195 Expr *OldInit = Pattern->getInClassInitializer();
2196 if (!OldInit) {
2197 RecordDecl *PatternRD = Pattern->getParent();
2198 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2199 if (OutermostClass == PatternRD) {
2200 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2201 << PatternRD << Pattern;
2202 } else {
2203 Diag(Pattern->getLocEnd(),
2204 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2205 << PatternRD << OutermostClass << Pattern;
2206 }
2207 Instantiation->setInvalidDecl();
2208 return true;
2209 }
2210
2211 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2212 if (Inst.isInvalid())
2213 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002214 if (Inst.isAlreadyInstantiating()) {
2215 // Error out if we hit an instantiation cycle for this initializer.
2216 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2217 << Instantiation;
2218 return true;
2219 }
Richard Smithe19b95d2016-05-26 20:23:13 +00002220 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2221 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002222
2223 // Enter the scope of this instantiation. We don't use PushDeclContext because
2224 // we don't have a scope.
2225 ContextRAII SavedContext(*this, Instantiation->getParent());
2226 EnterExpressionEvaluationContext EvalContext(*this,
2227 Sema::PotentiallyEvaluated);
2228
Serge Pavlov907233f2015-04-28 17:58:47 +00002229 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002230
2231 // Instantiate the initializer.
2232 ActOnStartCXXInClassMemberInitializer();
2233 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2234
2235 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2236 /*CXXDirectInit=*/false);
2237 Expr *Init = NewInit.get();
2238 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2239 ActOnFinishCXXInClassMemberInitializer(
2240 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2241
Richard Smith4b054b22016-08-24 21:25:37 +00002242 if (auto *L = getASTMutationListener())
2243 L->DefaultMemberInitializerInstantiated(Instantiation);
2244
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002245 // Exit the scope of this instantiation.
2246 SavedContext.pop();
2247
2248 // Return true if the in-class initializer is still missing.
2249 return !Instantiation->getInClassInitializer();
2250}
2251
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002252namespace {
2253 /// \brief A partial specialization whose template arguments have matched
2254 /// a given template-id.
2255 struct PartialSpecMatchResult {
2256 ClassTemplatePartialSpecializationDecl *Partial;
2257 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002258 };
2259}
2260
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002261bool Sema::InstantiateClassTemplateSpecialization(
2262 SourceLocation PointOfInstantiation,
2263 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2264 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002265 // Perform the actual instantiation on the canonical declaration.
2266 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002267 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor00a511f2009-09-15 16:51:42 +00002268 if (ClassTemplateSpec->isInvalidDecl())
2269 return true;
2270
Douglas Gregor463421d2009-03-03 04:44:36 +00002271 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002272 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002273
Douglas Gregor170bc422009-06-12 22:31:52 +00002274 // C++ [temp.class.spec.match]p1:
2275 // When a class template is used in a context that requires an
2276 // instantiation of the class, it is necessary to determine
2277 // whether the instantiation is to be generated using the primary
2278 // template or one of the partial specializations. This is done by
2279 // matching the template arguments of the class template
2280 // specialization with the template argument lists of the partial
2281 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002282 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002283 SmallVector<MatchResult, 4> Matched;
2284 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002285 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002286 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002287 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2288 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002289 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002290 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002291 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002292 ClassTemplateSpec->getTemplateArgs(),
2293 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002294 // Store the failed-deduction information for use in diagnostics, later.
2295 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002296 FailedCandidates.addCandidate().set(
2297 DeclAccessPair::make(Template, AS_public), Partial,
2298 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002299 (void)Result;
2300 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002301 Matched.push_back(PartialSpecMatchResult());
2302 Matched.back().Partial = Partial;
2303 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002304 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002305 }
2306
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002307 // If we're dealing with a member template where the template parameters
2308 // have been instantiated, this provides the original template parameters
2309 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002310
Douglas Gregor21610382009-10-29 00:04:11 +00002311 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002312 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002313 if (Matched.size() == 1) {
2314 // -- If exactly one matching specialization is found, the
2315 // instantiation is generated from that specialization.
2316 // We don't need to do anything for this.
2317 } else {
2318 // -- If more than one matching specialization is found, the
2319 // partial order rules (14.5.4.2) are used to determine
2320 // whether one of the specializations is more specialized
2321 // than the others. If none of the specializations is more
2322 // specialized than all of the other matching
2323 // specializations, then the use of the class template is
2324 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002325 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2326 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002327 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002328 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002329 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002330 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002331 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002332 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002333
Douglas Gregor21610382009-10-29 00:04:11 +00002334 // Determine if the best partial specialization is more specialized than
2335 // the others.
2336 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002337 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2338 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002339 P != PEnd; ++P) {
2340 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002341 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002342 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002343 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002344 Ambiguous = true;
2345 break;
2346 }
2347 }
2348
2349 if (Ambiguous) {
2350 // Partial ordering did not produce a clear winner. Complain.
2351 ClassTemplateSpec->setInvalidDecl();
2352 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2353 << ClassTemplateSpec;
2354
2355 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002356 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2357 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002358 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002359 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2360 << getTemplateArgumentBindingsText(
2361 P->Partial->getTemplateParameters(),
2362 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002363
Douglas Gregor21610382009-10-29 00:04:11 +00002364 return true;
2365 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002366 }
2367
2368 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002369 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002370 while (OrigPartialSpec->getInstantiatedFromMember()) {
2371 // If we've found an explicit specialization of this class template,
2372 // stop here and use that as the pattern.
2373 if (OrigPartialSpec->isMemberSpecialization())
2374 break;
2375
2376 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2377 }
2378
2379 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002380 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002381 } else {
2382 // -- If no matches are found, the instantiation is generated
2383 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002384 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002385 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2386 // If we've found an explicit specialization of this class template,
2387 // stop here and use that as the pattern.
2388 if (OrigTemplate->isMemberSpecialization())
2389 break;
2390
Douglas Gregor01afeef2009-08-28 20:31:08 +00002391 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002392 }
2393
Douglas Gregor01afeef2009-08-28 20:31:08 +00002394 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002395 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002396
Douglas Gregoref6ab412009-10-27 06:26:26 +00002397 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2398 Pattern,
2399 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002400 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002401 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002402
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002403 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002404}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002405
John McCall76d824f2009-08-25 22:02:44 +00002406/// \brief Instantiates the definitions of all of the member
2407/// of the given class, which is an instantiation of a class template
2408/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002409void
2410Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002411 CXXRecordDecl *Instantiation,
2412 const MultiLevelTemplateArgumentList &TemplateArgs,
2413 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002414 // FIXME: We need to notify the ASTMutationListener that we did all of these
2415 // things, in case we have an explicit instantiation definition in a PCM, a
2416 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002417 assert(
2418 (TSK == TSK_ExplicitInstantiationDefinition ||
2419 TSK == TSK_ExplicitInstantiationDeclaration ||
2420 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2421 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002422 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002423 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002424 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002425 if (FunctionDecl *Pattern
2426 = Function->getInstantiatedFromMemberFunction()) {
2427 MemberSpecializationInfo *MSInfo
2428 = Function->getMemberSpecializationInfo();
2429 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002430 if (MSInfo->getTemplateSpecializationKind()
2431 == TSK_ExplicitSpecialization)
2432 continue;
2433
Douglas Gregor1d957a32009-10-27 18:42:08 +00002434 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2435 Function,
2436 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002437 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002438 SuppressNew) ||
2439 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002440 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002441
2442 // C++11 [temp.explicit]p8:
2443 // An explicit instantiation definition that names a class template
2444 // specialization explicitly instantiates the class template
2445 // specialization and is only an explicit instantiation definition
2446 // of members whose definition is visible at the point of
2447 // instantiation.
2448 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002449 continue;
2450
Richard Smitheb36ddf2014-04-24 22:45:46 +00002451 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2452
2453 if (Function->isDefined()) {
2454 // Let the ASTConsumer know that this function has been explicitly
2455 // instantiated now, and its linkage might have changed.
2456 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2457 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002458 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002459 } else if (TSK == TSK_ImplicitInstantiation) {
2460 PendingLocalImplicitInstantiations.push_back(
2461 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002462 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002463 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002464 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002465 if (isa<VarTemplateSpecializationDecl>(Var))
2466 continue;
2467
Douglas Gregor86d142a2009-10-08 07:24:58 +00002468 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002469 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2470 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002471 if (MSInfo->getTemplateSpecializationKind()
2472 == TSK_ExplicitSpecialization)
2473 continue;
2474
Douglas Gregor1d957a32009-10-27 18:42:08 +00002475 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2476 Var,
2477 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002478 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002479 SuppressNew) ||
2480 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002481 continue;
2482
Douglas Gregor1d957a32009-10-27 18:42:08 +00002483 if (TSK == TSK_ExplicitInstantiationDefinition) {
2484 // C++0x [temp.explicit]p8:
2485 // An explicit instantiation definition that names a class template
2486 // specialization explicitly instantiates the class template
2487 // specialization and is only an explicit instantiation definition
2488 // of members whose definition is visible at the point of
2489 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002490 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002491 continue;
2492
2493 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002494 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002495 } else {
2496 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2497 }
2498 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002499 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002500 // Always skip the injected-class-name, along with any
2501 // redeclarations of nested classes, since both would cause us
2502 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002503 // Skip closure types; they'll get instantiated when we instantiate
2504 // the corresponding lambda-expression.
2505 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2506 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002507 continue;
2508
Douglas Gregor1d957a32009-10-27 18:42:08 +00002509 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2510 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002511
2512 if (MSInfo->getTemplateSpecializationKind()
2513 == TSK_ExplicitSpecialization)
2514 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002515
Hans Wennborga86a83b2016-05-26 19:42:56 +00002516 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2517 TSK == TSK_ExplicitInstantiationDeclaration) {
2518 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2519 // affect the inner class.
2520 continue;
2521 }
2522
Douglas Gregor1d957a32009-10-27 18:42:08 +00002523 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2524 Record,
2525 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002526 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002527 SuppressNew) ||
2528 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002529 continue;
2530
Douglas Gregor1d957a32009-10-27 18:42:08 +00002531 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2532 assert(Pattern && "Missing instantiated-from-template information");
2533
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002534 if (!Record->getDefinition()) {
2535 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002536 // C++0x [temp.explicit]p8:
2537 // An explicit instantiation definition that names a class template
2538 // specialization explicitly instantiates the class template
2539 // specialization and is only an explicit instantiation definition
2540 // of members whose definition is visible at the point of
2541 // instantiation.
2542 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2543 MSInfo->setTemplateSpecializationKind(TSK);
2544 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2545 }
2546
2547 continue;
2548 }
2549
2550 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002551 TemplateArgs,
2552 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002553 } else {
2554 if (TSK == TSK_ExplicitInstantiationDefinition &&
2555 Record->getTemplateSpecializationKind() ==
2556 TSK_ExplicitInstantiationDeclaration) {
2557 Record->setTemplateSpecializationKind(TSK);
2558 MarkVTableUsed(PointOfInstantiation, Record, true);
2559 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002560 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002561
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002562 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002563 if (Pattern)
2564 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2565 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002566 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002567 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2568 assert(MSInfo && "No member specialization information?");
2569
2570 if (MSInfo->getTemplateSpecializationKind()
2571 == TSK_ExplicitSpecialization)
2572 continue;
2573
2574 if (CheckSpecializationInstantiationRedecl(
2575 PointOfInstantiation, TSK, Enum,
2576 MSInfo->getTemplateSpecializationKind(),
2577 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2578 SuppressNew)
2579 continue;
2580
2581 if (Enum->getDefinition())
2582 continue;
2583
Richard Smith6739a102016-05-05 00:56:12 +00002584 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002585 assert(Pattern && "Missing instantiated-from-template information");
2586
2587 if (TSK == TSK_ExplicitInstantiationDefinition) {
2588 if (!Pattern->getDefinition())
2589 continue;
2590
2591 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2592 } else {
2593 MSInfo->setTemplateSpecializationKind(TSK);
2594 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2595 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002596 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2597 // No need to instantiate in-class initializers during explicit
2598 // instantiation.
2599 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2600 CXXRecordDecl *ClassPattern =
2601 Instantiation->getTemplateInstantiationPattern();
2602 DeclContext::lookup_result Lookup =
2603 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002604 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002605 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2606 TemplateArgs);
2607 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002608 }
2609 }
2610}
2611
2612/// \brief Instantiate the definitions of all of the members of the
2613/// given class template specialization, which was named as part of an
2614/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002615void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002616Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002617 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002618 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2619 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002620 // C++0x [temp.explicit]p7:
2621 // An explicit instantiation that names a class template
2622 // specialization is an explicit instantion of the same kind
2623 // (declaration or definition) of each of its members (not
2624 // including members inherited from base classes) that has not
2625 // been previously explicitly specialized in the translation unit
2626 // containing the explicit instantiation, except as described
2627 // below.
2628 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002629 getTemplateInstantiationArgs(ClassTemplateSpec),
2630 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002631}
2632
John McCalldadc5752010-08-24 06:29:42 +00002633StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002634Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002635 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002636 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002637
2638 TemplateInstantiator Instantiator(*this, TemplateArgs,
2639 SourceLocation(),
2640 DeclarationName());
2641 return Instantiator.TransformStmt(S);
2642}
2643
John McCalldadc5752010-08-24 06:29:42 +00002644ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002645Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002646 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002647 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002648
Douglas Gregora16548e2009-08-11 05:31:07 +00002649 TemplateInstantiator Instantiator(*this, TemplateArgs,
2650 SourceLocation(),
2651 DeclarationName());
2652 return Instantiator.TransformExpr(E);
2653}
2654
Richard Smithd59b8322012-12-19 01:39:02 +00002655ExprResult Sema::SubstInitializer(Expr *Init,
2656 const MultiLevelTemplateArgumentList &TemplateArgs,
2657 bool CXXDirectInit) {
2658 TemplateInstantiator Instantiator(*this, TemplateArgs,
2659 SourceLocation(),
2660 DeclarationName());
2661 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2662}
2663
Craig Topper99d23532015-12-24 23:58:29 +00002664bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002665 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002666 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002667 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002668 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002669
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002670 TemplateInstantiator Instantiator(*this, TemplateArgs,
2671 SourceLocation(),
2672 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002673 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2674 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002675}
2676
Douglas Gregor14454802011-02-25 02:25:35 +00002677NestedNameSpecifierLoc
2678Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2679 const MultiLevelTemplateArgumentList &TemplateArgs) {
2680 if (!NNS)
2681 return NestedNameSpecifierLoc();
2682
2683 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2684 DeclarationName());
2685 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2686}
2687
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002688/// \brief Do template substitution on declaration name info.
2689DeclarationNameInfo
2690Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2691 const MultiLevelTemplateArgumentList &TemplateArgs) {
2692 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2693 NameInfo.getName());
2694 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2695}
2696
Douglas Gregoraa594892009-03-31 18:38:02 +00002697TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002698Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2699 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002700 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002701 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2702 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002703 CXXScopeSpec SS;
2704 SS.Adopt(QualifierLoc);
2705 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002706}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002707
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002708bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2709 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002710 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002711 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2712 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002713
2714 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002715}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002716
Richard Smith70b13042015-01-09 01:19:56 +00002717static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002718 // When storing ParmVarDecls in the local instantiation scope, we always
2719 // want to use the ParmVarDecl from the canonical function declaration,
2720 // since the map is then valid for any redeclaration or definition of that
2721 // function.
2722 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2723 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2724 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002725 // This parameter might be from a freestanding function type within the
2726 // function and isn't necessarily referring to one of FD's parameters.
2727 if (FD->getParamDecl(i) == PV)
2728 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002729 }
2730 }
2731 return D;
2732}
2733
2734
Douglas Gregorf3010112011-01-07 16:43:16 +00002735llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2736LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002737 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002738 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002739 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002740
Douglas Gregor14cf7522010-04-30 18:55:50 +00002741 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002742 const Decl *CheckD = D;
2743 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002744 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002745 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002746 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002747
2748 // If this is a tag declaration, it's possible that we need to look for
2749 // a previous declaration.
2750 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002751 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002752 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002753 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002754 } while (CheckD);
2755
Douglas Gregor14cf7522010-04-30 18:55:50 +00002756 // If we aren't combined with our outer scope, we're done.
2757 if (!Current->CombineWithOuterScope)
2758 break;
2759 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002760
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002761 // If we're performing a partial substitution during template argument
2762 // deduction, we may not have values for template parameters yet.
2763 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2764 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002765 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002766
Serge Pavlove7ad8312015-05-15 10:10:28 +00002767 // Local types referenced prior to definition may require instantiation.
2768 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2769 if (RD->isLocalClass())
2770 return nullptr;
2771
2772 // Enumeration types referenced prior to definition may appear as a result of
2773 // error recovery.
2774 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002775 return nullptr;
2776
Chris Lattnercab02a62011-02-17 20:34:02 +00002777 // If we didn't find the decl, then we either have a sema bug, or we have a
2778 // forward reference to a label declaration. Return null to indicate that
2779 // we have an uninstantiated label.
2780 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002781 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002782}
2783
John McCall19c1bfd2010-08-25 05:32:35 +00002784void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002785 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002786 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002787 if (Stored.isNull()) {
2788#ifndef NDEBUG
2789 // It should not be present in any surrounding scope either.
2790 LocalInstantiationScope *Current = this;
2791 while (Current->CombineWithOuterScope && Current->Outer) {
2792 Current = Current->Outer;
2793 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2794 "Instantiated local in inner and outer scopes");
2795 }
2796#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002797 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002798 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002799 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002800 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002801 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002802 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002803}
Douglas Gregorf3010112011-01-07 16:43:16 +00002804
James Y Knight48fefa32015-09-30 14:04:23 +00002805void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2806 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002807 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002808 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2809 Pack->push_back(Inst);
2810}
2811
2812void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002813#ifndef NDEBUG
2814 // This should be the first time we've been told about this decl.
2815 for (LocalInstantiationScope *Current = this;
2816 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2817 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2818 "Creating local pack after instantiation of local");
2819#endif
2820
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002821 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002822 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002823 DeclArgumentPack *Pack = new DeclArgumentPack;
2824 Stored = Pack;
2825 ArgumentPacks.push_back(Pack);
2826}
2827
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002828void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2829 const TemplateArgument *ExplicitArgs,
2830 unsigned NumExplicitArgs) {
2831 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2832 "Already have a partially-substituted pack");
2833 assert((!PartiallySubstitutedPack
2834 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2835 "Wrong number of arguments in partially-substituted pack");
2836 PartiallySubstitutedPack = Pack;
2837 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2838 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2839}
2840
2841NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2842 const TemplateArgument **ExplicitArgs,
2843 unsigned *NumExplicitArgs) const {
2844 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002845 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002846 if (NumExplicitArgs)
2847 *NumExplicitArgs = 0;
2848
2849 for (const LocalInstantiationScope *Current = this; Current;
2850 Current = Current->Outer) {
2851 if (Current->PartiallySubstitutedPack) {
2852 if (ExplicitArgs)
2853 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2854 if (NumExplicitArgs)
2855 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2856
2857 return Current->PartiallySubstitutedPack;
2858 }
2859
2860 if (!Current->CombineWithOuterScope)
2861 break;
2862 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002863
2864 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002865}