blob: 973f564d305838ac7afa721562c82404efce1210 [file] [log] [blame]
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Douglas Gregorfe1e1102009-02-27 19:31:52 +00006//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
John McCall83024632010-08-25 22:03:47 +000012#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000013#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000016#include "clang/AST/ASTLambda.h"
Richard Smith4b054b22016-08-24 21:25:37 +000017#include "clang/AST/ASTMutationListener.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
Jordan Rose1e879d82018-03-23 00:07:18 +000020#include "clang/AST/PrettyDeclStackTrace.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#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"
John McCallde6836a2010-08-24 07:21:54 +000025#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000026#include "clang/Sema/TemplateDeduction.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000027#include "clang/Sema/TemplateInstCallback.h"
Anton Afanasyevd880de22019-03-30 08:42:48 +000028#include "llvm/Support/TimeProfiler.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000029
30using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000031using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000032
Douglas Gregor4ea568f2009-03-10 18:03:33 +000033//===----------------------------------------------------------------------===/
34// Template Instantiation Support
35//===----------------------------------------------------------------------===/
36
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000037/// Retrieve the template argument list(s) that should be used to
Douglas Gregor01afeef2009-08-28 20:31:08 +000038/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000039///
40/// \param D the declaration for which we are computing template instantiation
41/// arguments.
42///
43/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000044///
45/// \param RelativeToPrimary true if we should get the template
46/// arguments relative to the primary template, even when we're
47/// dealing with a specialization. This is only relevant for function
48/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000049///
50/// \param Pattern If non-NULL, indicates the pattern from which we will be
51/// instantiating the definition of the given declaration, \p D. This is
52/// used to determine the proper set of template instantiation arguments for
53/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000054MultiLevelTemplateArgumentList
Fangrui Song6907ce22018-07-30 19:24:48 +000055Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000056 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000057 bool RelativeToPrimary,
58 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000059 // Accumulate the set of template argument lists in this structure.
60 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000061
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000062 if (Innermost)
63 Result.addOuterTemplateArguments(Innermost);
Fangrui Song6907ce22018-07-30 19:24:48 +000064
Douglas Gregora654dd82009-08-28 17:37:35 +000065 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000066 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000067 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000068
Richard Smith59d05002019-04-26 02:11:23 +000069 // Add template arguments from a variable template instantiation. For a
70 // class-scope explicit specialization, there are no template arguments
71 // at this level, but there may be enclosing template arguments.
72 VarTemplateSpecializationDecl *Spec =
73 dyn_cast<VarTemplateSpecializationDecl>(D);
74 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
Larisse Voufo39a1e502013-08-06 01:03:05 +000075 // We're done when we hit an explicit specialization.
76 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
77 !isa<VarTemplatePartialSpecializationDecl>(Spec))
78 return Result;
79
80 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
81
82 // If this variable template specialization was instantiated from a
83 // specialized member that is a variable template, we're done.
84 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000085 llvm::PointerUnion<VarTemplateDecl*,
86 VarTemplatePartialSpecializationDecl*> Specialized
87 = Spec->getSpecializedTemplateOrPartial();
88 if (VarTemplatePartialSpecializationDecl *Partial =
89 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
90 if (Partial->isMemberSpecialization())
91 return Result;
92 } else {
93 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
94 if (Tmpl->isMemberSpecialization())
95 return Result;
96 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000097 }
98
Douglas Gregor55462622011-06-15 14:20:42 +000099 // If we have a template template parameter with translation unit context,
100 // then we're performing substitution into a default template argument of
101 // this template template parameter before we've constructed the template
102 // that will own this template template parameter. In this case, we
103 // use empty template parameter lists for all of the outer templates
104 // to avoid performing any substitutions.
105 if (Ctx->isTranslationUnit()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000106 if (TemplateTemplateParmDecl *TTP
Douglas Gregor55462622011-06-15 14:20:42 +0000107 = dyn_cast<TemplateTemplateParmDecl>(D)) {
108 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000109 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000110 return Result;
111 }
112 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000113 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000114
John McCall970d5302009-08-29 03:16:09 +0000115 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000116 // Add template arguments from a class template instantiation.
Richard Smith59d05002019-04-26 02:11:23 +0000117 ClassTemplateSpecializationDecl *Spec
118 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
119 if (Spec && !Spec->isClassScopeExplicitSpecialization()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000120 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000121 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
122 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000123 break;
Mike Stump11289f42009-09-09 15:08:12 +0000124
Douglas Gregora654dd82009-08-28 17:37:35 +0000125 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Fangrui Song6907ce22018-07-30 19:24:48 +0000126
127 // If this class template specialization was instantiated from a
Douglas Gregorcf915552009-10-13 16:30:37 +0000128 // specialized member that is a class template, we're done.
129 assert(Spec->getSpecializedTemplate() && "No class template?");
130 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
131 break;
Mike Stump11289f42009-09-09 15:08:12 +0000132 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000133 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000134 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000135 if (!RelativeToPrimary &&
Richard Smithf19a8b02019-05-02 00:49:14 +0000136 Function->getTemplateSpecializationKindForInstantiation() ==
137 TSK_ExplicitSpecialization)
Douglas Gregorcf915552009-10-13 16:30:37 +0000138 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000139
Douglas Gregora654dd82009-08-28 17:37:35 +0000140 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000141 = Function->getTemplateSpecializationArgs()) {
142 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000143 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000144
Douglas Gregorcf915552009-10-13 16:30:37 +0000145 // If this function was instantiated from a specialized member that is
146 // a function template, we're done.
147 assert(Function->getPrimaryTemplate() && "No function template?");
148 if (Function->getPrimaryTemplate()->isMemberSpecialization())
149 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000150
151 // If this function is a generic lambda specialization, we are done.
152 if (isGenericLambdaCallOperatorSpecialization(Function))
153 break;
154
Douglas Gregor43669f82011-03-05 17:54:25 +0000155 } else if (FunctionTemplateDecl *FunTmpl
156 = Function->getDescribedFunctionTemplate()) {
157 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000158 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000159 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000160
John McCall970d5302009-08-29 03:16:09 +0000161 // If this is a friend declaration and it declares an entity at
162 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000163 // instead of its semantic parent, unless of course the pattern we're
164 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000165 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000166 Function->getDeclContext()->isFileContext() &&
167 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000168 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000169 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000170 continue;
171 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000172 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
173 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
174 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000175 const TemplateSpecializationType *TST =
176 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
177 Result.addOuterTemplateArguments(
178 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000179 if (ClassTemplate->isMemberSpecialization())
180 break;
181 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000182 }
John McCall970d5302009-08-29 03:16:09 +0000183
184 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000185 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000186 }
Mike Stump11289f42009-09-09 15:08:12 +0000187
Douglas Gregora654dd82009-08-28 17:37:35 +0000188 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000189}
190
Richard Smith696e3122017-02-23 01:43:54 +0000191bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000192 switch (Kind) {
193 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000194 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000195 case DefaultTemplateArgumentInstantiation:
196 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000197 case ExplicitTemplateArgumentSubstitution:
198 case DeducedTemplateArgumentSubstitution:
199 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000200 return true;
201
Douglas Gregor84d49a22009-11-11 21:54:23 +0000202 case DefaultTemplateArgumentChecking:
Richard Smith13381222017-02-23 21:43:43 +0000203 case DeclaringSpecialMember:
Richard Smith883dbc42017-05-25 22:47:05 +0000204 case DefiningSynthesizedFunction:
Richard Smith5159bbad2018-09-05 22:30:37 +0000205 case ExceptionSpecEvaluation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000206 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000207
Gabor Horvath207e7b12018-02-10 14:04:45 +0000208 // This function should never be called when Kind's value is Memoization.
209 case Memoization:
210 break;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000211 }
David Blaikie8a40f702012-01-17 06:56:22 +0000212
Richard Smith696e3122017-02-23 01:43:54 +0000213 llvm_unreachable("Invalid SynthesisKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000214}
215
Benjamin Kramer7761a042015-03-06 16:36:50 +0000216Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000217 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000218 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
219 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000220 sema::TemplateDeductionInfo *DeductionInfo)
Richard Smith13381222017-02-23 21:43:43 +0000221 : SemaRef(SemaRef) {
Akira Hatanaka43556c12016-11-03 15:04:58 +0000222 // Don't allow further instantiation if a fatal error and an uncompilable
Akira Hatanaka40c15ab2016-11-03 17:11:28 +0000223 // error have occurred. Any diagnostics we might have raised will not be
Akira Hatanaka43556c12016-11-03 15:04:58 +0000224 // visible, and we do not need to construct a correct AST.
225 if (SemaRef.Diags.hasFatalErrorOccurred() &&
226 SemaRef.Diags.hasUncompilableErrorOccurred()) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000227 Invalid = true;
228 return;
229 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000230 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
231 if (!Invalid) {
Richard Smith696e3122017-02-23 01:43:54 +0000232 CodeSynthesisContext Inst;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000233 Inst.Kind = Kind;
234 Inst.PointOfInstantiation = PointOfInstantiation;
235 Inst.Entity = Entity;
236 Inst.Template = Template;
237 Inst.TemplateArgs = TemplateArgs.data();
238 Inst.NumTemplateArgs = TemplateArgs.size();
239 Inst.DeductionInfo = DeductionInfo;
240 Inst.InstantiationRange = InstantiationRange;
Richard Smith13381222017-02-23 21:43:43 +0000241 SemaRef.pushCodeSynthesisContext(Inst);
242
Richard Smith54f18e82016-08-31 02:15:21 +0000243 AlreadyInstantiating =
244 !SemaRef.InstantiatingSpecializations
245 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
246 .second;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000247 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000248 }
249}
250
Benjamin Kramer7761a042015-03-06 16:36:50 +0000251Sema::InstantiatingTemplate::InstantiatingTemplate(
252 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
253 SourceRange InstantiationRange)
254 : InstantiatingTemplate(SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000255 CodeSynthesisContext::TemplateInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000256 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000257
Benjamin Kramer7761a042015-03-06 16:36:50 +0000258Sema::InstantiatingTemplate::InstantiatingTemplate(
259 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
260 ExceptionSpecification, SourceRange InstantiationRange)
261 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000262 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000263 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000264
Benjamin Kramer7761a042015-03-06 16:36:50 +0000265Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith54f18e82016-08-31 02:15:21 +0000266 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
267 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
268 SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000269 : InstantiatingTemplate(
270 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000271 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
Richard Smith54f18e82016-08-31 02:15:21 +0000272 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
273 Template, TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000274
Benjamin Kramer7761a042015-03-06 16:36:50 +0000275Sema::InstantiatingTemplate::InstantiatingTemplate(
276 Sema &SemaRef, SourceLocation PointOfInstantiation,
277 FunctionTemplateDecl *FunctionTemplate,
278 ArrayRef<TemplateArgument> TemplateArgs,
Richard Smith696e3122017-02-23 01:43:54 +0000279 CodeSynthesisContext::SynthesisKind Kind,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000280 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
281 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
282 InstantiationRange, FunctionTemplate, nullptr,
Richard Smith54f18e82016-08-31 02:15:21 +0000283 TemplateArgs, &DeductionInfo) {
284 assert(
Richard Smith696e3122017-02-23 01:43:54 +0000285 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||
286 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution);
Richard Smith54f18e82016-08-31 02:15:21 +0000287}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000288
Benjamin Kramer7761a042015-03-06 16:36:50 +0000289Sema::InstantiatingTemplate::InstantiatingTemplate(
290 Sema &SemaRef, SourceLocation PointOfInstantiation,
Richard Smith0e617ec2016-12-27 07:56:27 +0000291 TemplateDecl *Template,
292 ArrayRef<TemplateArgument> TemplateArgs,
293 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
294 : InstantiatingTemplate(
295 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000296 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Richard Smith0e617ec2016-12-27 07:56:27 +0000297 PointOfInstantiation, InstantiationRange, Template, nullptr,
298 TemplateArgs, &DeductionInfo) {}
299
300Sema::InstantiatingTemplate::InstantiatingTemplate(
301 Sema &SemaRef, SourceLocation PointOfInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000302 ClassTemplatePartialSpecializationDecl *PartialSpec,
303 ArrayRef<TemplateArgument> TemplateArgs,
304 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
305 : InstantiatingTemplate(
306 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000307 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000308 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
309 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000310
Larisse Voufo39a1e502013-08-06 01:03:05 +0000311Sema::InstantiatingTemplate::InstantiatingTemplate(
312 Sema &SemaRef, SourceLocation PointOfInstantiation,
313 VarTemplatePartialSpecializationDecl *PartialSpec,
314 ArrayRef<TemplateArgument> TemplateArgs,
315 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000316 : InstantiatingTemplate(
317 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000318 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000319 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
320 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000321
Benjamin Kramer7761a042015-03-06 16:36:50 +0000322Sema::InstantiatingTemplate::InstantiatingTemplate(
323 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
324 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
325 : InstantiatingTemplate(
326 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000327 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000328 PointOfInstantiation, InstantiationRange, Param, nullptr,
329 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000330
Benjamin Kramer7761a042015-03-06 16:36:50 +0000331Sema::InstantiatingTemplate::InstantiatingTemplate(
332 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
333 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
334 SourceRange InstantiationRange)
335 : InstantiatingTemplate(
336 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000337 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000338 PointOfInstantiation, InstantiationRange, Param, Template,
339 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000340
Benjamin Kramer7761a042015-03-06 16:36:50 +0000341Sema::InstantiatingTemplate::InstantiatingTemplate(
342 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
343 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
344 SourceRange InstantiationRange)
345 : InstantiatingTemplate(
346 SemaRef,
Richard Smith696e3122017-02-23 01:43:54 +0000347 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000348 PointOfInstantiation, InstantiationRange, Param, Template,
349 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000350
Benjamin Kramer7761a042015-03-06 16:36:50 +0000351Sema::InstantiatingTemplate::InstantiatingTemplate(
352 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
353 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
354 SourceRange InstantiationRange)
355 : InstantiatingTemplate(
Richard Smith696e3122017-02-23 01:43:54 +0000356 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000357 PointOfInstantiation, InstantiationRange, Param, Template,
358 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000359
Richard Smith13381222017-02-23 21:43:43 +0000360void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
361 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
362 InNonInstantiationSFINAEContext = false;
363
364 CodeSynthesisContexts.push_back(Ctx);
365
366 if (!Ctx.isInstantiationRecord())
367 ++NonInstantiationEntries;
368}
369
370void Sema::popCodeSynthesisContext() {
371 auto &Active = CodeSynthesisContexts.back();
372 if (!Active.isInstantiationRecord()) {
373 assert(NonInstantiationEntries > 0);
374 --NonInstantiationEntries;
375 }
376
377 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
378
379 // Name lookup no longer looks in this template's defining module.
380 assert(CodeSynthesisContexts.size() >=
381 CodeSynthesisContextLookupModules.size() &&
382 "forgot to remove a lookup module for a template instantiation");
383 if (CodeSynthesisContexts.size() ==
384 CodeSynthesisContextLookupModules.size()) {
385 if (Module *M = CodeSynthesisContextLookupModules.back())
386 LookupModulesCache.erase(M);
387 CodeSynthesisContextLookupModules.pop_back();
388 }
389
390 // If we've left the code synthesis context for the current context stack,
391 // stop remembering that we've emitted that stack.
392 if (CodeSynthesisContexts.size() ==
393 LastEmittedCodeSynthesisContextDepth)
394 LastEmittedCodeSynthesisContextDepth = 0;
395
396 CodeSynthesisContexts.pop_back();
397}
398
Douglas Gregor85673582009-05-18 17:01:57 +0000399void Sema::InstantiatingTemplate::Clear() {
400 if (!Invalid) {
Richard Smith13381222017-02-23 21:43:43 +0000401 if (!AlreadyInstantiating) {
402 auto &Active = SemaRef.CodeSynthesisContexts.back();
Richard Smith54f18e82016-08-31 02:15:21 +0000403 SemaRef.InstantiatingSpecializations.erase(
404 std::make_pair(Active.Entity, Active.Kind));
Richard Smith13381222017-02-23 21:43:43 +0000405 }
Richard Smith54f18e82016-08-31 02:15:21 +0000406
Gabor Horvath207e7b12018-02-10 14:04:45 +0000407 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
408 SemaRef.CodeSynthesisContexts.back());
Richard Smith13381222017-02-23 21:43:43 +0000409
Gabor Horvath207e7b12018-02-10 14:04:45 +0000410 SemaRef.popCodeSynthesisContext();
Douglas Gregor85673582009-05-18 17:01:57 +0000411 Invalid = true;
412 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000413}
414
Douglas Gregor79cf6032009-03-10 20:44:00 +0000415bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
416 SourceLocation PointOfInstantiation,
417 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000418 assert(SemaRef.NonInstantiationEntries <=
Richard Smith696e3122017-02-23 01:43:54 +0000419 SemaRef.CodeSynthesisContexts.size());
Fangrui Song6907ce22018-07-30 19:24:48 +0000420 if ((SemaRef.CodeSynthesisContexts.size() -
Douglas Gregor84d49a22009-11-11 21:54:23 +0000421 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000422 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000423 return false;
424
Mike Stump11289f42009-09-09 15:08:12 +0000425 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000426 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000427 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000428 << InstantiationRange;
429 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000430 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000431 return true;
432}
433
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000434/// Prints the current instantiation stack through a series of
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000435/// notes.
436void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000437 // Determine which template instantiations to skip, if any.
Richard Smith696e3122017-02-23 01:43:54 +0000438 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000439 unsigned Limit = Diags.getTemplateBacktraceLimit();
Richard Smith696e3122017-02-23 01:43:54 +0000440 if (Limit && Limit < CodeSynthesisContexts.size()) {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000441 SkipStart = Limit / 2 + Limit % 2;
Richard Smith696e3122017-02-23 01:43:54 +0000442 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000443 }
444
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000445 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000446 unsigned InstantiationIdx = 0;
Richard Smith696e3122017-02-23 01:43:54 +0000447 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
448 Active = CodeSynthesisContexts.rbegin(),
449 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000450 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000451 ++Active, ++InstantiationIdx) {
452 // Skip this instantiation?
453 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
454 if (InstantiationIdx == SkipStart) {
455 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000456 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000457 diag::note_instantiation_contexts_suppressed)
Richard Smith696e3122017-02-23 01:43:54 +0000458 << unsigned(CodeSynthesisContexts.size() - Limit);
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000459 }
460 continue;
461 }
462
Douglas Gregor79cf6032009-03-10 20:44:00 +0000463 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000464 case CodeSynthesisContext::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000465 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000466 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
467 unsigned DiagID = diag::note_template_member_class_here;
468 if (isa<ClassTemplateSpecializationDecl>(Record))
469 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000470 Diags.Report(Active->PointOfInstantiation, DiagID)
Richard Smith792c22d2016-12-24 04:09:05 +0000471 << Record << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000472 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000473 unsigned DiagID;
474 if (Function->getPrimaryTemplate())
475 DiagID = diag::note_function_template_spec_here;
476 else
477 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000478 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000479 << Function
480 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000481 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000482 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000483 VD->isStaticDataMember()?
484 diag::note_template_static_data_member_def_here
485 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000486 << VD
487 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000488 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
489 Diags.Report(Active->PointOfInstantiation,
490 diag::note_template_enum_def_here)
491 << ED
492 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000493 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
494 Diags.Report(Active->PointOfInstantiation,
495 diag::note_template_nsdmi_here)
496 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000497 } else {
498 Diags.Report(Active->PointOfInstantiation,
499 diag::note_template_type_alias_instantiation_here)
500 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000501 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000502 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000503 break;
504 }
505
Richard Smith696e3122017-02-23 01:43:54 +0000506 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
Richard Smith54f18e82016-08-31 02:15:21 +0000507 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000508 SmallVector<char, 128> TemplateArgsStr;
509 llvm::raw_svector_ostream OS(TemplateArgsStr);
510 Template->printName(OS);
Serge Pavlov03e672c2017-11-28 16:14:14 +0000511 printTemplateArgumentList(OS, Active->template_arguments(),
512 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000513 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000514 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000515 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000516 << Active->InstantiationRange;
517 break;
518 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000519
Richard Smith696e3122017-02-23 01:43:54 +0000520 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000521 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000522 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000523 diag::note_explicit_template_arg_substitution_here)
Fangrui Song6907ce22018-07-30 19:24:48 +0000524 << FnTmpl
525 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
526 Active->TemplateArgs,
Douglas Gregor607f1412010-03-30 20:35:20 +0000527 Active->NumTemplateArgs)
528 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000529 break;
530 }
Mike Stump11289f42009-09-09 15:08:12 +0000531
Richard Smith696e3122017-02-23 01:43:54 +0000532 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
Richard Smithe68a38f2016-12-24 04:20:31 +0000533 if (FunctionTemplateDecl *FnTmpl =
534 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000535 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000536 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000537 << FnTmpl
Fangrui Song6907ce22018-07-30 19:24:48 +0000538 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
539 Active->TemplateArgs,
Douglas Gregor607f1412010-03-30 20:35:20 +0000540 Active->NumTemplateArgs)
541 << Active->InstantiationRange;
Richard Smithe68a38f2016-12-24 04:20:31 +0000542 } else {
543 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
544 isa<VarTemplateSpecializationDecl>(Active->Entity);
Richard Smith0e617ec2016-12-27 07:56:27 +0000545 bool IsTemplate = false;
Richard Smithe68a38f2016-12-24 04:20:31 +0000546 TemplateParameterList *Params;
Richard Smith0e617ec2016-12-27 07:56:27 +0000547 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
548 IsTemplate = true;
549 Params = D->getTemplateParameters();
550 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
Richard Smithe68a38f2016-12-24 04:20:31 +0000551 Active->Entity)) {
552 Params = D->getTemplateParameters();
553 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
554 Active->Entity)) {
555 Params = D->getTemplateParameters();
556 } else {
557 llvm_unreachable("unexpected template kind");
558 }
559
Richard Smithe68a38f2016-12-24 04:20:31 +0000560 Diags.Report(Active->PointOfInstantiation,
561 diag::note_deduced_template_arg_substitution_here)
Richard Smith0e617ec2016-12-27 07:56:27 +0000562 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
Fangrui Song6907ce22018-07-30 19:24:48 +0000563 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
Richard Smithe68a38f2016-12-24 04:20:31 +0000564 Active->NumTemplateArgs)
565 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000566 }
567 break;
Richard Smithe68a38f2016-12-24 04:20:31 +0000568 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000569
Richard Smith696e3122017-02-23 01:43:54 +0000570 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000571 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000572 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000573
Benjamin Kramer9170e912013-02-22 15:46:01 +0000574 SmallVector<char, 128> TemplateArgsStr;
575 llvm::raw_svector_ostream OS(TemplateArgsStr);
576 FD->printName(OS);
Serge Pavlov03e672c2017-11-28 16:14:14 +0000577 printTemplateArgumentList(OS, Active->template_arguments(),
578 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000579 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000580 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000581 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000582 << Active->InstantiationRange;
583 break;
584 }
Mike Stump11289f42009-09-09 15:08:12 +0000585
Richard Smith696e3122017-02-23 01:43:54 +0000586 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000587 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000588 std::string Name;
589 if (!Parm->getName().empty())
590 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000591
592 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000593 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
594 TemplateParams = Template->getTemplateParameters();
595 else
596 TemplateParams =
597 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
598 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000599 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000600 diag::note_prior_template_arg_substitution)
601 << isa<TemplateTemplateParmDecl>(Parm)
602 << Name
Fangrui Song6907ce22018-07-30 19:24:48 +0000603 << getTemplateArgumentBindingsText(TemplateParams,
604 Active->TemplateArgs,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000605 Active->NumTemplateArgs)
606 << Active->InstantiationRange;
607 break;
608 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000609
Richard Smith696e3122017-02-23 01:43:54 +0000610 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000611 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000612 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
613 TemplateParams = Template->getTemplateParameters();
614 else
615 TemplateParams =
616 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
617 ->getTemplateParameters();
618
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000619 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000620 diag::note_template_default_arg_checking)
Fangrui Song6907ce22018-07-30 19:24:48 +0000621 << getTemplateArgumentBindingsText(TemplateParams,
622 Active->TemplateArgs,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000623 Active->NumTemplateArgs)
624 << Active->InstantiationRange;
625 break;
626 }
Richard Smithf623c962012-04-17 00:58:00 +0000627
Richard Smith5159bbad2018-09-05 22:30:37 +0000628 case CodeSynthesisContext::ExceptionSpecEvaluation:
629 Diags.Report(Active->PointOfInstantiation,
630 diag::note_evaluating_exception_spec_here)
631 << cast<FunctionDecl>(Active->Entity);
632 break;
633
Richard Smith696e3122017-02-23 01:43:54 +0000634 case CodeSynthesisContext::ExceptionSpecInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000635 Diags.Report(Active->PointOfInstantiation,
636 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000637 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000638 << Active->InstantiationRange;
639 break;
Richard Smith13381222017-02-23 21:43:43 +0000640
641 case CodeSynthesisContext::DeclaringSpecialMember:
642 Diags.Report(Active->PointOfInstantiation,
643 diag::note_in_declaration_of_implicit_special_member)
644 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
645 break;
Richard Smith883dbc42017-05-25 22:47:05 +0000646
Gabor Horvath207e7b12018-02-10 14:04:45 +0000647 case CodeSynthesisContext::DefiningSynthesizedFunction: {
Richard Smith883dbc42017-05-25 22:47:05 +0000648 // FIXME: For synthesized members other than special members, produce a note.
649 auto *MD = dyn_cast<CXXMethodDecl>(Active->Entity);
650 auto CSM = MD ? getSpecialMember(MD) : CXXInvalid;
651 if (CSM != CXXInvalid) {
652 Diags.Report(Active->PointOfInstantiation,
653 diag::note_member_synthesized_at)
654 << CSM << Context.getTagDeclType(MD->getParent());
655 }
656 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000657 }
Gabor Horvath207e7b12018-02-10 14:04:45 +0000658
659 case CodeSynthesisContext::Memoization:
660 break;
661 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000662 }
663}
664
David Blaikie05785d12013-02-20 22:23:23 +0000665Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000666 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000667 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000668
Richard Smith696e3122017-02-23 01:43:54 +0000669 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
670 Active = CodeSynthesisContexts.rbegin(),
671 ActiveEnd = CodeSynthesisContexts.rend();
Douglas Gregor33834512009-06-14 07:33:30 +0000672 Active != ActiveEnd;
Fangrui Song6907ce22018-07-30 19:24:48 +0000673 ++Active)
Douglas Gregor84d49a22009-11-11 21:54:23 +0000674 {
Richard Smith13381222017-02-23 21:43:43 +0000675 switch (Active->Kind) {
Richard Smith696e3122017-02-23 01:43:54 +0000676 case CodeSynthesisContext::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000677 // An instantiation of an alias template may or may not be a SFINAE
678 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000679 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000680 break;
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000681 LLVM_FALLTHROUGH;
Richard Smith696e3122017-02-23 01:43:54 +0000682 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
683 case CodeSynthesisContext::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000684 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000685 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000686
Richard Smith696e3122017-02-23 01:43:54 +0000687 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
688 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
689 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000690 // A default template argument instantiation and substitution into
Fangrui Song6907ce22018-07-30 19:24:48 +0000691 // template parameters with arguments for prior parameters may or may
Douglas Gregore62e6a02009-11-11 19:13:48 +0000692 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000693 break;
Mike Stump11289f42009-09-09 15:08:12 +0000694
Richard Smith696e3122017-02-23 01:43:54 +0000695 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
696 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000697 // We're either substitution explicitly-specified template arguments
698 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000699 assert(Active->DeductionInfo && "Missing deduction info pointer");
700 return Active->DeductionInfo;
Richard Smith13381222017-02-23 21:43:43 +0000701
702 case CodeSynthesisContext::DeclaringSpecialMember:
Richard Smith883dbc42017-05-25 22:47:05 +0000703 case CodeSynthesisContext::DefiningSynthesizedFunction:
Richard Smith13381222017-02-23 21:43:43 +0000704 // This happens in a context unrelated to template instantiation, so
705 // there is no SFINAE.
706 return None;
Gabor Horvath207e7b12018-02-10 14:04:45 +0000707
Richard Smith5159bbad2018-09-05 22:30:37 +0000708 case CodeSynthesisContext::ExceptionSpecEvaluation:
709 // FIXME: This should not be treated as a SFINAE context, because
710 // we will cache an incorrect exception specification. However, clang
711 // bootstrap relies this! See PR31692.
712 break;
713
Gabor Horvath207e7b12018-02-10 14:04:45 +0000714 case CodeSynthesisContext::Memoization:
715 break;
Douglas Gregor33834512009-06-14 07:33:30 +0000716 }
Richard Smith13381222017-02-23 21:43:43 +0000717
718 // The inner context was transparent for SFINAE. If it occurred within a
719 // non-instantiation SFINAE context, then SFINAE applies.
720 if (Active->SavedInNonInstantiationSFINAEContext)
721 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregor33834512009-06-14 07:33:30 +0000722 }
723
David Blaikie7a30dc52013-02-21 01:47:18 +0000724 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000725}
726
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000727//===----------------------------------------------------------------------===/
728// Template Instantiation for Types
729//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000730namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000731 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000732 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000733 SourceLocation Loc;
734 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000735
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000736 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000737 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000738
739 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000740 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000741 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000742 DeclarationName Entity)
743 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000744 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000745
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000746 /// Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000747 /// transformed.
748 ///
749 /// For the purposes of template instantiation, a type has already been
750 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000751 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000752
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000753 /// Returns the location of the entity being instantiated, if known.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000754 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000756 /// Returns the name of the entity being instantiated, if any.
Douglas Gregord6ff3322009-08-04 16:50:30 +0000757 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000759 /// Sets the "base" location and entity when that
Douglas Gregoref6ab412009-10-27 06:26:26 +0000760 /// information is known based on another transformation.
761 void setBase(SourceLocation Loc, DeclarationName Entity) {
762 this->Loc = Loc;
763 this->Entity = Entity;
764 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000765
766 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
767 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000768 ArrayRef<UnexpandedParameterPack> Unexpanded,
769 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000770 Optional<unsigned> &NumExpansions) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000771 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000772 PatternRange, Unexpanded,
Fangrui Song6907ce22018-07-30 19:24:48 +0000773 TemplateArgs,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000774 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000775 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000776 NumExpansions);
777 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000778
Fangrui Song6907ce22018-07-30 19:24:48 +0000779 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
Douglas Gregorf3010112011-01-07 16:43:16 +0000780 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
781 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000782
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000783 TemplateArgument ForgetPartiallySubstitutedPack() {
784 TemplateArgument Result;
785 if (NamedDecl *PartialPack
786 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
787 MultiLevelTemplateArgumentList &TemplateArgs
788 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
789 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000790 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000791 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
792 Result = TemplateArgs(Depth, Index);
793 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
794 }
795 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000796
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000797 return Result;
798 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000799
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000800 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
801 if (Arg.isNull())
802 return;
Fangrui Song6907ce22018-07-30 19:24:48 +0000803
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000804 if (NamedDecl *PartialPack
805 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
806 MultiLevelTemplateArgumentList &TemplateArgs
807 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
808 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000809 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000810 TemplateArgs.setArgument(Depth, Index, Arg);
811 }
812 }
813
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000814 /// Transform the given declaration by instantiating a reference to
Douglas Gregord6ff3322009-08-04 16:50:30 +0000815 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000816 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000817
Fangrui Song6907ce22018-07-30 19:24:48 +0000818 void transformAttrs(Decl *Old, Decl *New) {
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000819 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
820 }
821
Richard Smithb2997f52019-05-21 20:10:50 +0000822 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
823 if (Old->isParameterPack()) {
824 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
825 for (auto *New : NewDecls)
826 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
827 Old, cast<VarDecl>(New));
828 return;
829 }
830
831 assert(NewDecls.size() == 1 &&
832 "should only have multiple expansions for a pack");
833 Decl *New = NewDecls.front();
834
Richard Smithc38498f2015-04-27 21:27:54 +0000835 // If we've instantiated the call operator of a lambda or the call
836 // operator template of a generic lambda, update the "instantiation of"
837 // information.
838 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
839 if (NewMD && isLambdaCallOperator(NewMD)) {
840 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
841 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
842 NewTD->setInstantiatedFromMemberTemplate(
843 OldMD->getDescribedFunctionTemplate());
844 else
845 NewMD->setInstantiationOfMemberFunction(OldMD,
846 TSK_ImplicitInstantiation);
847 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000848
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000849 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000850
851 // We recreated a local declaration, but not by instantiating it. There
852 // may be pending dependent diagnostics to produce.
853 if (auto *DC = dyn_cast<DeclContext>(Old))
854 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000855 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000856
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000857 /// Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000858 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000859 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000860
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000861 /// Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000862 /// declaration.
863 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
Fangrui Song6907ce22018-07-30 19:24:48 +0000864
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000865 /// Rebuild the exception declaration and register the declaration
Douglas Gregorebe10102009-08-20 07:17:43 +0000866 /// as an instantiated local.
Fangrui Song6907ce22018-07-30 19:24:48 +0000867 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000868 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000869 SourceLocation StartLoc,
870 SourceLocation NameLoc,
871 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000872
Fangrui Song6907ce22018-07-30 19:24:48 +0000873 /// Rebuild the Objective-C exception declaration and register the
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000874 /// declaration as an instantiated local.
Fangrui Song6907ce22018-07-30 19:24:48 +0000875 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000876 TypeSourceInfo *TSInfo, QualType T);
Fangrui Song6907ce22018-07-30 19:24:48 +0000877
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000878 /// Check for tag mismatches when instantiating an
John McCall7f41d982009-09-11 04:59:25 +0000879 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000880 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
881 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000882 NestedNameSpecifierLoc QualifierLoc,
883 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000884
Craig Topperc3ec1492014-05-26 06:22:03 +0000885 TemplateName
886 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
887 SourceLocation NameLoc,
888 QualType ObjectType = QualType(),
Richard Smithfd3dae02017-01-20 00:20:39 +0000889 NamedDecl *FirstQualifierInScope = nullptr,
890 bool AllowInjectedClassName = false);
Douglas Gregor9db53502011-03-02 18:07:45 +0000891
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000892 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
893
John McCalldadc5752010-08-24 06:29:42 +0000894 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
895 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
896 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000897
John McCalldadc5752010-08-24 06:29:42 +0000898 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000899 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000900 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
901 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000902
Richard Smithb2997f52019-05-21 20:10:50 +0000903 /// Rebuild a DeclRefExpr for a VarDecl reference.
904 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000905
Richard Smithb2997f52019-05-21 20:10:50 +0000906 /// Transform a reference to a function or init-capture parameter pack.
907 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000908
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000909 /// Transform a FunctionParmPackExpr which was built when we couldn't
Richard Smithb15fe3a2012-09-12 00:56:43 +0000910 /// expand a function parameter pack reference which refers to an expanded
911 /// pack.
912 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
913
Hans Wennborge113c202014-09-18 16:01:32 +0000914 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000915 FunctionProtoTypeLoc TL) {
916 // Call the base version; it will forward to our overridden version below.
917 return inherited::TransformFunctionProtoType(TLB, TL);
918 }
919
920 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000921 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
922 FunctionProtoTypeLoc TL,
923 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +0000924 Qualifiers ThisTypeQuals,
Richard Smith2e321552014-11-12 02:00:47 +0000925 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000926
Douglas Gregor715e4612011-01-14 22:40:04 +0000927 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000928 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000929 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000930 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000931
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000932 /// Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000933 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000934 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000935 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000936
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000937 /// Transforms an already-substituted template type parameter pack
Douglas Gregorada4b792011-01-14 02:55:32 +0000938 /// into either itself (if we aren't substituting into its pack expansion)
939 /// or the appropriate substituted argument.
940 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
941 SubstTemplateTypeParmPackTypeLoc TL);
942
Richard Smith2589b9802012-07-25 03:56:55 +0000943 ExprResult TransformLambdaExpr(LambdaExpr *E) {
944 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
945 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
946 }
947
David Majnemerb1004102014-03-02 18:46:05 +0000948 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000949 TemplateParameterList *OrigTPL) {
950 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
Fangrui Song6907ce22018-07-30 19:24:48 +0000951
Faisal Vali2cba1332013-10-23 06:44:28 +0000952 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
Fangrui Song6907ce22018-07-30 19:24:48 +0000953 TemplateDeclInstantiator DeclInstantiator(getSema(),
Faisal Vali2cba1332013-10-23 06:44:28 +0000954 /* DeclContext *Owner */ Owner, TemplateArgs);
Fangrui Song6907ce22018-07-30 19:24:48 +0000955 return DeclInstantiator.SubstTemplateParams(OrigTPL);
Faisal Vali2cba1332013-10-23 06:44:28 +0000956 }
John McCall7c454bb2011-07-15 05:09:51 +0000957 private:
958 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
959 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000960 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000961 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000962}
Douglas Gregor04318252009-07-06 15:59:29 +0000963
Douglas Gregor5597ab42010-05-07 23:12:07 +0000964bool TemplateInstantiator::AlreadyTransformed(QualType T) {
965 if (T.isNull())
966 return true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000967
Douglas Gregor678d76c2011-07-01 01:22:09 +0000968 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000969 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000970
Douglas Gregor5597ab42010-05-07 23:12:07 +0000971 getSema().MarkDeclarationsReferencedInType(Loc, T);
972 return true;
973}
974
Eli Friedman8917ad52013-07-19 19:40:38 +0000975static TemplateArgument
976getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000977 assert(S.ArgumentPackSubstitutionIndex >= 0);
Eli Friedman8917ad52013-07-19 19:40:38 +0000978 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
979 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
980 if (Arg.isPackExpansion())
981 Arg = Arg.getPackExpansionPattern();
982 return Arg;
983}
984
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000985Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000986 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000987 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000988
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000989 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000990 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000991 // If the corresponding template argument is NULL or non-existent, it's
992 // because we are performing instantiation from explicitly-specified
993 // template arguments in a function template, but there were some
994 // arguments left unspecified.
995 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
996 TTP->getPosition()))
997 return D;
998
Douglas Gregorf5500772011-01-05 15:48:55 +0000999 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001000
Douglas Gregorf5500772011-01-05 15:48:55 +00001001 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001002 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregorf5500772011-01-05 15:48:55 +00001003 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +00001004 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +00001005 }
1006
Richard Smith1abacfc2017-08-29 22:14:43 +00001007 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001008 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +00001009 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001010 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001011 }
Mike Stump11289f42009-09-09 15:08:12 +00001012
Douglas Gregor9167f8b2009-11-11 01:00:40 +00001013 // Fall through to find the instantiated declaration for this template
1014 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +00001015 }
Mike Stump11289f42009-09-09 15:08:12 +00001016
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001017 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +00001018}
1019
Douglas Gregor25289362010-03-01 17:25:41 +00001020Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +00001021 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +00001022 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +00001023 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +00001024
Douglas Gregorebe10102009-08-20 07:17:43 +00001025 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1026 return Inst;
1027}
1028
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001029NamedDecl *
Fangrui Song6907ce22018-07-30 19:24:48 +00001030TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001031 SourceLocation Loc) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001032 // If the first part of the nested-name-specifier was a template type
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001033 // parameter, instantiate that type parameter down to a tag type.
1034 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001035 const TemplateTypeParmType *TTP
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001036 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Fangrui Song6907ce22018-07-30 19:24:48 +00001037
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001038 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001039 // FIXME: This needs testing w/ member access expressions.
1040 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
Fangrui Song6907ce22018-07-30 19:24:48 +00001041
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001042 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001043 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001044 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001045
Douglas Gregore1d60df2011-01-14 23:41:42 +00001046 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +00001047 return nullptr;
1048
Eli Friedman8917ad52013-07-19 19:40:38 +00001049 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +00001050 }
1051
1052 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001053 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001054 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Fangrui Song6907ce22018-07-30 19:24:48 +00001055
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001056 if (const TagType *Tag = T->getAs<TagType>())
1057 return Tag->getDecl();
Fangrui Song6907ce22018-07-30 19:24:48 +00001058
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001059 // The resulting type is not a tag; complain.
1060 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +00001061 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001062 }
1063 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001064
Douglas Gregora04f2ca2010-03-01 15:56:25 +00001065 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +00001066}
1067
Douglas Gregorebe10102009-08-20 07:17:43 +00001068VarDecl *
1069TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +00001070 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001071 SourceLocation StartLoc,
1072 SourceLocation NameLoc,
1073 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +00001074 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +00001075 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001076 if (Var)
1077 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1078 return Var;
1079}
1080
Fangrui Song6907ce22018-07-30 19:24:48 +00001081VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1082 TypeSourceInfo *TSInfo,
Douglas Gregorf4e837f2010-04-26 17:57:08 +00001083 QualType T) {
1084 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1085 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +00001086 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1087 return Var;
1088}
1089
John McCall7f41d982009-09-11 04:59:25 +00001090QualType
John McCall954b5de2010-11-04 19:04:38 +00001091TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1092 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001093 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001094 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001095 if (const TagType *TT = T->getAs<TagType>()) {
1096 TagDecl* TD = TT->getDecl();
1097
John McCall954b5de2010-11-04 19:04:38 +00001098 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001099
John McCall7f41d982009-09-11 04:59:25 +00001100 IdentifierInfo *Id = TD->getIdentifier();
1101
1102 // TODO: should we even warn on struct/class mismatches for this? Seems
1103 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001104 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001105 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001106 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001107 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001108 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1109 << Id
1110 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1111 TD->getKindName());
1112 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1113 }
John McCall7f41d982009-09-11 04:59:25 +00001114 }
1115 }
1116
John McCall954b5de2010-11-04 19:04:38 +00001117 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1118 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001119 QualifierLoc,
1120 T);
John McCall7f41d982009-09-11 04:59:25 +00001121}
1122
Richard Smithfd3dae02017-01-20 00:20:39 +00001123TemplateName TemplateInstantiator::TransformTemplateName(
1124 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1125 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1126 bool AllowInjectedClassName) {
Douglas Gregor9db53502011-03-02 18:07:45 +00001127 if (TemplateTemplateParmDecl *TTP
1128 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1129 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1130 // If the corresponding template argument is NULL or non-existent, it's
1131 // because we are performing instantiation from explicitly-specified
1132 // template arguments in a function template, but there were some
1133 // arguments left unspecified.
1134 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1135 TTP->getPosition()))
1136 return Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00001137
Douglas Gregor9db53502011-03-02 18:07:45 +00001138 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
Fangrui Song6907ce22018-07-30 19:24:48 +00001139
Douglas Gregor9db53502011-03-02 18:07:45 +00001140 if (TTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001141 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor9db53502011-03-02 18:07:45 +00001142 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001143
Douglas Gregor9db53502011-03-02 18:07:45 +00001144 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1145 // We have the template argument pack to substitute, but we're not
1146 // actually expanding the enclosing pack expansion yet. So, just
1147 // keep the entire argument pack.
1148 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1149 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001150
1151 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001152 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001153
Richard Smith1abacfc2017-08-29 22:14:43 +00001154 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001155 assert(!Template.isNull() && "Null template template argument");
Richard Smith1abacfc2017-08-29 22:14:43 +00001156 assert(!Template.getAsQualifiedTemplateName() &&
1157 "template decl to substitute is qualified?");
John McCalld9dfe3a2011-06-30 08:33:18 +00001158
1159 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001160 return Template;
1161 }
1162 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001163
Douglas Gregor9db53502011-03-02 18:07:45 +00001164 if (SubstTemplateTemplateParmPackStorage *SubstPack
1165 = Name.getAsSubstTemplateTemplateParmPack()) {
1166 if (getSema().ArgumentPackSubstitutionIndex == -1)
1167 return Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00001168
Eli Friedman8917ad52013-07-19 19:40:38 +00001169 TemplateArgument Arg = SubstPack->getArgumentPack();
1170 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Richard Smith1abacfc2017-08-29 22:14:43 +00001171 return Arg.getAsTemplate().getNameToSubstitute();
Douglas Gregor9db53502011-03-02 18:07:45 +00001172 }
Richard Smithfd3dae02017-01-20 00:20:39 +00001173
1174 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1175 FirstQualifierInScope,
1176 AllowInjectedClassName);
Douglas Gregor9db53502011-03-02 18:07:45 +00001177}
1178
Fangrui Song6907ce22018-07-30 19:24:48 +00001179ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001180TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001181 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001182 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001183
Bruno Ricci17ff0262018-10-27 19:21:19 +00001184 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001185}
1186
John McCalldadc5752010-08-24 06:29:42 +00001187ExprResult
John McCall13481c52010-02-06 08:42:39 +00001188TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001189 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001190 // If the corresponding template argument is NULL or non-existent, it's
1191 // because we are performing instantiation from explicitly-specified
1192 // template arguments in a function template, but there were some
1193 // arguments left unspecified.
1194 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1195 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001196 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001197
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001198 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
Richard Smithb4f96252017-02-21 06:30:38 +00001199
1200 if (TemplateArgs.getNumLevels() != TemplateArgs.getNumSubstitutedLevels()) {
1201 // We're performing a partial substitution, so the substituted argument
1202 // could be dependent. As a result we can't create a SubstNonType*Expr
1203 // node now, since that represents a fully-substituted argument.
1204 // FIXME: We should have some AST representation for this.
1205 if (Arg.getKind() == TemplateArgument::Pack) {
1206 // FIXME: This won't work for alias templates.
1207 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1208 "unexpected pack arguments in partial substitution");
1209 Arg = Arg.pack_begin()->getPackExpansionPattern();
1210 }
1211 assert(Arg.getKind() == TemplateArgument::Expression &&
1212 "unexpected nontype template argument kind in partial substitution");
1213 return Arg.getAsExpr();
1214 }
1215
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001216 if (NTTP->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001217 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001218 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001219
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001220 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001221 // We have an argument pack, but we can't select a particular argument
1222 // out of it yet. Therefore, we'll build an expression to hold on to that
1223 // argument pack.
1224 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
Fangrui Song6907ce22018-07-30 19:24:48 +00001225 E->getLocation(),
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001226 NTTP->getDeclName());
1227 if (TargetType.isNull())
1228 return ExprError();
Richard Smithf1f20e62018-02-14 02:07:53 +00001229
1230 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1231 TargetType.getNonLValueExprType(SemaRef.Context),
1232 TargetType->isReferenceType() ? VK_LValue : VK_RValue, NTTP,
1233 E->getLocation(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001234 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001235
Eli Friedman8917ad52013-07-19 19:40:38 +00001236 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001237 }
Mike Stump11289f42009-09-09 15:08:12 +00001238
John McCall7c454bb2011-07-15 05:09:51 +00001239 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1240}
1241
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001242const LoopHintAttr *
1243TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1244 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1245
1246 if (TransformedExpr == LH->getValue())
1247 return LH;
1248
1249 // Generate error if there is a problem with the value.
1250 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1251 return LH;
1252
1253 // Create new LoopHintValueAttr with integral expression in place of the
1254 // non-type template parameter.
1255 return LoopHintAttr::CreateImplicit(
1256 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1257 LH->getState(), TransformedExpr, LH->getRange());
1258}
1259
John McCall7c454bb2011-07-15 05:09:51 +00001260ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1261 NonTypeTemplateParmDecl *parm,
1262 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001263 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001264 ExprResult result;
1265 QualType type;
1266
John McCall13481c52010-02-06 08:42:39 +00001267 // The template argument itself might be an expression, in which
1268 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001269 if (arg.getKind() == TemplateArgument::Expression) {
1270 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001271 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001272 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001273
Eli Friedmanb826a002012-09-26 02:36:12 +00001274 } else if (arg.getKind() == TemplateArgument::Declaration ||
1275 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001276 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001277 if (arg.getKind() == TemplateArgument::Declaration) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00001278 VD = arg.getAsDecl();
Mike Stump11289f42009-09-09 15:08:12 +00001279
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001280 // Find the instantiation of the template argument. This is
1281 // required for nested templates.
1282 VD = cast_or_null<ValueDecl>(
1283 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1284 if (!VD)
1285 return ExprError();
1286 } else {
1287 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001288 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001289 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001290
John McCall15dda372010-02-06 10:23:53 +00001291 // Derive the type we want the substituted decl to have. This had
1292 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001293 if (parm->isExpandedParameterPack()) {
1294 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
Fangrui Song6907ce22018-07-30 19:24:48 +00001295 } else if (parm->isParameterPack() &&
John McCall7c454bb2011-07-15 05:09:51 +00001296 isa<PackExpansionType>(parm->getType())) {
1297 type = SemaRef.SubstType(
1298 cast<PackExpansionType>(parm->getType())->getPattern(),
1299 TemplateArgs, loc, parm->getDeclName());
1300 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001301 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1302 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001303 }
1304 assert(!type.isNull() && "type substitution failed for param type");
1305 assert(!type->isDependentType() && "param type still dependent");
1306 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001307
John McCall7c454bb2011-07-15 05:09:51 +00001308 if (!result.isInvalid()) type = result.get()->getType();
1309 } else {
1310 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1311
1312 // Note that this type can be different from the type of 'result',
1313 // e.g. if it's an enum type.
1314 type = arg.getIntegralType();
1315 }
1316 if (result.isInvalid()) return ExprError();
1317
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001318 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001319 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1320 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001321}
Fangrui Song6907ce22018-07-30 19:24:48 +00001322
1323ExprResult
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001324TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1325 SubstNonTypeTemplateParmPackExpr *E) {
1326 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1327 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001328 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001329 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001330
1331 TemplateArgument Arg = E->getArgumentPack();
1332 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001333 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1334 E->getParameterPackLocation(),
1335 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001336}
John McCall13481c52010-02-06 08:42:39 +00001337
Richard Smithb2997f52019-05-21 20:10:50 +00001338ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1339 SourceLocation Loc) {
Richard Smithb15fe3a2012-09-12 00:56:43 +00001340 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1341 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1342}
1343
1344ExprResult
1345TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1346 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1347 // We can expand this parameter pack now.
Richard Smithb2997f52019-05-21 20:10:50 +00001348 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1349 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
Richard Smithb15fe3a2012-09-12 00:56:43 +00001350 if (!VD)
1351 return ExprError();
Richard Smithb2997f52019-05-21 20:10:50 +00001352 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001353 }
1354
1355 QualType T = TransformType(E->getType());
1356 if (T.isNull())
1357 return ExprError();
1358
1359 // Transform each of the parameter expansions into the corresponding
1360 // parameters in the instantiation of the function decl.
Richard Smithb2997f52019-05-21 20:10:50 +00001361 SmallVector<VarDecl *, 8> Vars;
1362 Vars.reserve(E->getNumExpansions());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001363 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1364 I != End; ++I) {
Richard Smithb2997f52019-05-21 20:10:50 +00001365 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
Richard Smithb15fe3a2012-09-12 00:56:43 +00001366 if (!D)
1367 return ExprError();
Richard Smithb2997f52019-05-21 20:10:50 +00001368 Vars.push_back(D);
Richard Smithb15fe3a2012-09-12 00:56:43 +00001369 }
1370
Richard Smith7bf8f6f2019-06-04 17:17:20 +00001371 auto *PackExpr =
1372 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1373 E->getParameterPackLocation(), Vars);
1374 getSema().MarkFunctionParmPackReferenced(PackExpr);
1375 return PackExpr;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001376}
1377
1378ExprResult
1379TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
Richard Smithb2997f52019-05-21 20:10:50 +00001380 VarDecl *PD) {
Richard Smithb15fe3a2012-09-12 00:56:43 +00001381 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1382 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1383 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1384 assert(Found && "no instantiation for parameter pack");
1385
1386 Decl *TransformedDecl;
1387 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001388 // If this is a reference to a function parameter pack which we can
1389 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001390 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1391 QualType T = TransformType(E->getType());
1392 if (T.isNull())
1393 return ExprError();
Richard Smith7bf8f6f2019-06-04 17:17:20 +00001394 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1395 E->getExprLoc(), *Pack);
1396 getSema().MarkFunctionParmPackReferenced(PackExpr);
1397 return PackExpr;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001398 }
1399
1400 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1401 } else {
1402 TransformedDecl = Found->get<Decl*>();
1403 }
1404
1405 // We have either an unexpanded pack or a specific expansion.
Richard Smithb2997f52019-05-21 20:10:50 +00001406 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
Richard Smithb15fe3a2012-09-12 00:56:43 +00001407}
1408
1409ExprResult
John McCall13481c52010-02-06 08:42:39 +00001410TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1411 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001412
1413 // Handle references to non-type template parameters and non-type template
1414 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001415 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1416 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1417 return TransformTemplateParmRefExpr(E, NTTP);
Fangrui Song6907ce22018-07-30 19:24:48 +00001418
Douglas Gregor954de172009-10-31 17:21:17 +00001419 // We have a non-type template parameter that isn't fully substituted;
1420 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001421 }
Mike Stump11289f42009-09-09 15:08:12 +00001422
Richard Smithb15fe3a2012-09-12 00:56:43 +00001423 // Handle references to function parameter packs.
Richard Smithb2997f52019-05-21 20:10:50 +00001424 if (VarDecl *PD = dyn_cast<VarDecl>(D))
Richard Smithb15fe3a2012-09-12 00:56:43 +00001425 if (PD->isParameterPack())
1426 return TransformFunctionParmPackRefExpr(E, PD);
1427
John McCall47f29ea2009-12-08 09:21:05 +00001428 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001429}
1430
John McCalldadc5752010-08-24 06:29:42 +00001431ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001432 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001433 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1434 getDescribedFunctionTemplate() &&
1435 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001436 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
Fangrui Song6907ce22018-07-30 19:24:48 +00001437 cast<FunctionDecl>(E->getParam()->getDeclContext()),
Douglas Gregor033f6752009-12-23 23:03:06 +00001438 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001439}
1440
Richard Smith2e321552014-11-12 02:00:47 +00001441template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001442QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1443 FunctionProtoTypeLoc TL,
1444 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001445 Qualifiers ThisTypeQuals,
Richard Smith2e321552014-11-12 02:00:47 +00001446 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001447 // We need a local instantiation scope for this function prototype.
1448 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001449 return inherited::TransformFunctionProtoType(
1450 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001451}
1452
John McCall58f10c32010-03-11 09:03:00 +00001453ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001454TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001455 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001456 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001457 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001458 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001459 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001460}
1461
Mike Stump11289f42009-09-09 15:08:12 +00001462QualType
John McCall550e0c22009-10-21 00:40:46 +00001463TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001464 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001465 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001466 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001467 // Replace the template type parameter with its corresponding
1468 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001469
1470 // If the corresponding template argument is NULL or doesn't exist, it's
1471 // because we are performing instantiation from explicitly-specified
1472 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001473 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001474 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1475 TemplateTypeParmTypeLoc NewTL
1476 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1477 NewTL.setNameLoc(TL.getNameLoc());
1478 return TL.getType();
1479 }
Mike Stump11289f42009-09-09 15:08:12 +00001480
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001481 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
Fangrui Song6907ce22018-07-30 19:24:48 +00001482
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001483 if (T->isParameterPack()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001484 assert(Arg.getKind() == TemplateArgument::Pack &&
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001485 "Missing argument pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001486
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001487 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001488 // We have the template argument pack, but we're not expanding the
1489 // enclosing pack expansion yet. Just save the template argument
1490 // pack for later substitution.
1491 QualType Result
1492 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1493 SubstTemplateTypeParmPackTypeLoc NewTL
1494 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1495 NewTL.setNameLoc(TL.getNameLoc());
1496 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001497 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001498
Eli Friedman8917ad52013-07-19 19:40:38 +00001499 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001500 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001501
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001502 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001503 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001504
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001505 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001506
1507 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001508 QualType Result
1509 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1510 SubstTemplateTypeParmTypeLoc NewTL
1511 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1512 NewTL.setNameLoc(TL.getNameLoc());
1513 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001514 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001515
1516 // The template type parameter comes from an inner template (e.g.,
1517 // the template parameter list of a member template inside the
1518 // template we are instantiating). Create a new template type
1519 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001520 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001521 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1522 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1523 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1524
Richard Smithb4f96252017-02-21 06:30:38 +00001525 QualType Result = getSema().Context.getTemplateTypeParmType(
1526 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
1527 T->isParameterPack(), NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001528 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1529 NewTL.setNameLoc(TL.getNameLoc());
1530 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001531}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001532
Fangrui Song6907ce22018-07-30 19:24:48 +00001533QualType
Douglas Gregorada4b792011-01-14 02:55:32 +00001534TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1535 TypeLocBuilder &TLB,
1536 SubstTemplateTypeParmPackTypeLoc TL) {
1537 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1538 // We aren't expanding the parameter pack, so just return ourselves.
1539 SubstTemplateTypeParmPackTypeLoc NewTL
1540 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1541 NewTL.setNameLoc(TL.getNameLoc());
1542 return TL.getType();
1543 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001544
1545 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1546 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1547 QualType Result = Arg.getAsType();
1548
Douglas Gregorada4b792011-01-14 02:55:32 +00001549 Result = getSema().Context.getSubstTemplateTypeParmType(
1550 TL.getTypePtr()->getReplacedParameter(),
1551 Result);
1552 SubstTemplateTypeParmTypeLoc NewTL
1553 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1554 NewTL.setNameLoc(TL.getNameLoc());
1555 return Result;
1556}
1557
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001558/// Perform substitution on the type T with a given set of template
John McCall76d824f2009-08-25 22:02:44 +00001559/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001560///
1561/// This routine substitutes the given template arguments into the
1562/// type T and produces the instantiated type.
1563///
1564/// \param T the type into which the template arguments will be
1565/// substituted. If this type is not dependent, it will be returned
1566/// immediately.
1567///
James Dennett634962f2012-06-14 21:40:34 +00001568/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001569/// substituted for the top-level template parameters within T.
1570///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001571/// \param Loc the location in the source code where this substitution
1572/// is being performed. It will typically be the location of the
1573/// declarator (if we're instantiating the type of some declaration)
1574/// or the location of the type in the source code (if, e.g., we're
1575/// instantiating the type of a cast expression).
1576///
1577/// \param Entity the name of the entity associated with a declaration
1578/// being instantiated (if any). May be empty to indicate that there
1579/// is no such entity (if, e.g., this is a type that occurs as part of
1580/// a cast expression) or that the entity has no name (e.g., an
1581/// unnamed function parameter).
1582///
Richard Smithee579842017-01-30 20:39:26 +00001583/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
1584/// acceptable as the top level type of the result.
1585///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001586/// \returns If the instantiation succeeds, the instantiated
1587/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001588TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001589 const MultiLevelTemplateArgumentList &Args,
1590 SourceLocation Loc,
Richard Smithee579842017-01-30 20:39:26 +00001591 DeclarationName Entity,
1592 bool AllowDeducedTST) {
Richard Smith696e3122017-02-23 01:43:54 +00001593 assert(!CodeSynthesisContexts.empty() &&
John McCall609459e2009-10-21 00:58:09 +00001594 "Cannot perform an instantiation without some context on the "
1595 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001596
1597 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001598 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001599 return T;
1600
1601 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
Richard Smithee579842017-01-30 20:39:26 +00001602 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
1603 : Instantiator.TransformType(T);
John McCall609459e2009-10-21 00:58:09 +00001604}
1605
Douglas Gregor5499af42011-01-05 23:12:31 +00001606TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1607 const MultiLevelTemplateArgumentList &Args,
1608 SourceLocation Loc,
1609 DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001610 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001611 "Cannot perform an instantiation without some context on the "
1612 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001613
Douglas Gregor5499af42011-01-05 23:12:31 +00001614 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001615 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001616
Fangrui Song6907ce22018-07-30 19:24:48 +00001617 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001618 !TL.getType()->isVariablyModifiedType()) {
1619 // FIXME: Make a copy of the TypeLoc data here, so that we can
1620 // return a new TypeSourceInfo. Inefficient!
1621 TypeLocBuilder TLB;
1622 TLB.pushFullCopy(TL);
1623 return TLB.getTypeSourceInfo(Context, TL.getType());
1624 }
1625
1626 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1627 TypeLocBuilder TLB;
1628 TLB.reserve(TL.getFullDataSize());
1629 QualType Result = Instantiator.TransformType(TLB, TL);
1630 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001631 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001632
1633 return TLB.getTypeSourceInfo(Context, Result);
1634}
1635
John McCall609459e2009-10-21 00:58:09 +00001636/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001637QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001638 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001639 SourceLocation Loc, DeclarationName Entity) {
Richard Smith696e3122017-02-23 01:43:54 +00001640 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregor79cf6032009-03-10 20:44:00 +00001641 "Cannot perform an instantiation without some context on the "
1642 "instantiation stack");
1643
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001644 // If T is not a dependent type or a variably-modified type, there
1645 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001646 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001647 return T;
1648
Douglas Gregord6ff3322009-08-04 16:50:30 +00001649 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1650 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001651}
Douglas Gregor463421d2009-03-03 04:44:36 +00001652
John McCallb29f78f2010-04-09 17:38:44 +00001653static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001654 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001655 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001656 return true;
1657
Abramo Bagnara6d810632010-12-14 22:11:44 +00001658 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001659 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001660 return false;
1661
David Blaikie6adc78e2013-02-18 22:06:02 +00001662 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001663 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001664 // This must be synthesized from a typedef.
1665 if (!P) continue;
1666
Nico Weberc0973372016-02-01 22:31:51 +00001667 // If there are any parameters, a new TypeSourceInfo that refers to the
1668 // instantiated parameters must be built.
1669 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001670 }
1671
1672 return false;
1673}
1674
1675/// A form of SubstType intended specifically for instantiating the
1676/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001677/// instantiation of default-argument expressions and to avoid
1678/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001679TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1680 const MultiLevelTemplateArgumentList &Args,
1681 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001682 DeclarationName Entity,
1683 CXXRecordDecl *ThisContext,
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00001684 Qualifiers ThisTypeQuals) {
Richard Smith696e3122017-02-23 01:43:54 +00001685 assert(!CodeSynthesisContexts.empty() &&
John McCallb29f78f2010-04-09 17:38:44 +00001686 "Cannot perform an instantiation without some context on the "
1687 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001688
John McCallb29f78f2010-04-09 17:38:44 +00001689 if (!NeedsInstantiationAsFunctionType(T))
1690 return T;
1691
1692 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1693
1694 TypeLocBuilder TLB;
1695
1696 TypeLoc TL = T->getTypeLoc();
1697 TLB.reserve(TL.getFullDataSize());
1698
Douglas Gregor3024f072012-04-16 07:05:22 +00001699 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001700
Richard Smith2e321552014-11-12 02:00:47 +00001701 if (FunctionProtoTypeLoc Proto =
1702 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1703 // Instantiate the type, other than its exception specification. The
1704 // exception specification is instantiated in InitFunctionInstantiation
1705 // once we've built the FunctionDecl.
1706 // FIXME: Set the exception specification to EST_Uninstantiated here,
1707 // instead of rebuilding the function type again later.
1708 Result = Instantiator.TransformFunctionProtoType(
1709 TLB, Proto, ThisContext, ThisTypeQuals,
1710 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1711 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001712 } else {
1713 Result = Instantiator.TransformType(TLB, TL);
1714 }
John McCallb29f78f2010-04-09 17:38:44 +00001715 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001716 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001717
1718 return TLB.getTypeSourceInfo(Context, Result);
1719}
1720
Richard Smithcd198152017-06-07 21:46:22 +00001721bool Sema::SubstExceptionSpec(SourceLocation Loc,
1722 FunctionProtoType::ExceptionSpecInfo &ESI,
1723 SmallVectorImpl<QualType> &ExceptionStorage,
1724 const MultiLevelTemplateArgumentList &Args) {
1725 assert(ESI.Type != EST_Uninstantiated);
1726
1727 bool Changed = false;
1728 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
1729 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
1730 Changed);
1731}
1732
Richard Smith2e321552014-11-12 02:00:47 +00001733void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1734 const MultiLevelTemplateArgumentList &Args) {
1735 FunctionProtoType::ExceptionSpecInfo ESI =
1736 Proto->getExtProtoInfo().ExceptionSpec;
Richard Smith2e321552014-11-12 02:00:47 +00001737
1738 SmallVector<QualType, 4> ExceptionStorage;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00001739 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
Richard Smithcd198152017-06-07 21:46:22 +00001740 ESI, ExceptionStorage, Args))
Richard Smith2e321552014-11-12 02:00:47 +00001741 // On error, recover by dropping the exception specification.
1742 ESI.Type = EST_None;
1743
1744 UpdateExceptionSpec(New, ESI);
1745}
1746
Fangrui Song6907ce22018-07-30 19:24:48 +00001747ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001748 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001749 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001750 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001751 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001752 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001753 TypeSourceInfo *NewDI = nullptr;
1754
Douglas Gregor5499af42011-01-05 23:12:31 +00001755 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001756 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1757
Fangrui Song6907ce22018-07-30 19:24:48 +00001758 // We have a function parameter pack. Substitute into the pattern of the
Douglas Gregor5499af42011-01-05 23:12:31 +00001759 // expansion.
Fangrui Song6907ce22018-07-30 19:24:48 +00001760 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
Douglas Gregor5499af42011-01-05 23:12:31 +00001761 OldParm->getLocation(), OldParm->getDeclName());
1762 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001763 return nullptr;
1764
Douglas Gregor5499af42011-01-05 23:12:31 +00001765 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1766 // We still have unexpanded parameter packs, which means that
1767 // our function parameter is still a function parameter pack.
1768 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001769 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001770 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001771 } else if (ExpectParameterPack) {
1772 // We expected to get a parameter pack but didn't (because the type
1773 // itself is not a pack expansion type), so complain. This can occur when
1774 // the substitution goes through an alias template that "loses" the
1775 // pack expansion.
Fangrui Song6907ce22018-07-30 19:24:48 +00001776 Diag(OldParm->getLocation(),
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001777 diag::err_function_parameter_pack_without_parameter_packs)
1778 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001779 return nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +00001780 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001781 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +00001782 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
Douglas Gregor5499af42011-01-05 23:12:31 +00001783 OldParm->getDeclName());
1784 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001785
Douglas Gregor940bca72010-04-12 07:48:19 +00001786 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001787 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001788
1789 if (NewDI->getType()->isVoidType()) {
1790 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001791 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001792 }
1793
1794 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001795 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001796 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001797 OldParm->getIdentifier(),
1798 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001799 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001800 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001801 return nullptr;
1802
Douglas Gregor940bca72010-04-12 07:48:19 +00001803 // Mark the (new) default argument as uninstantiated (if any).
1804 if (OldParm->hasUninstantiatedDefaultArg()) {
1805 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1806 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001807 } else if (OldParm->hasUnparsedDefaultArg()) {
1808 NewParm->setUnparsedDefaultArg();
1809 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001810 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1811 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001812 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1813 // Instantiate default arguments for methods of local classes (DR1484)
1814 // and non-defining declarations.
1815 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001816 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001817 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001818 if (NewArg.isUsable()) {
1819 // It would be nice if we still had this.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00001820 SourceLocation EqualLoc = NewArg.get()->getBeginLoc();
John McCalldc40b612015-12-11 01:56:36 +00001821 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1822 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001823 } else {
1824 // FIXME: if we non-lazily instantiated non-dependent default args for
1825 // non-dependent parameter types we could remove a bunch of duplicate
1826 // conversion warnings for such arguments.
1827 NewParm->setUninstantiatedDefaultArg(Arg);
1828 }
1829 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001830
1831 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Fangrui Song6907ce22018-07-30 19:24:48 +00001832
Douglas Gregorf3010112011-01-07 16:43:16 +00001833 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001834 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001835 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1836 } else {
1837 // Introduce an Old -> New mapping
Fangrui Song6907ce22018-07-30 19:24:48 +00001838 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001839 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001840
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001841 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1842 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001843 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001844
1845 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1846 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001847
1848 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1849
Fangrui Song6907ce22018-07-30 19:24:48 +00001850 return NewParm;
Douglas Gregor940bca72010-04-12 07:48:19 +00001851}
1852
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001853/// Substitute the given template arguments into the given set of
Douglas Gregordd472162011-01-07 00:20:55 +00001854/// parameters, producing the set of parameter types that would be generated
1855/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001856bool Sema::SubstParmTypes(
1857 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1858 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1859 const MultiLevelTemplateArgumentList &TemplateArgs,
1860 SmallVectorImpl<QualType> &ParamTypes,
1861 SmallVectorImpl<ParmVarDecl *> *OutParams,
1862 ExtParameterInfoBuilder &ParamInfos) {
Richard Smith696e3122017-02-23 01:43:54 +00001863 assert(!CodeSynthesisContexts.empty() &&
Douglas Gregordd472162011-01-07 00:20:55 +00001864 "Cannot perform an instantiation without some context on the "
1865 "instantiation stack");
Fangrui Song6907ce22018-07-30 19:24:48 +00001866
1867 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
Douglas Gregordd472162011-01-07 00:20:55 +00001868 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001869 return Instantiator.TransformFunctionTypeParams(
1870 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001871}
1872
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001873/// Perform substitution on the base class specifiers of the
John McCall76d824f2009-08-25 22:02:44 +00001874/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001875///
1876/// Produces a diagnostic and returns true on error, returns false and
1877/// attaches the instantiated base classes to the class template
1878/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001879bool
John McCall76d824f2009-08-25 22:02:44 +00001880Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1881 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001882 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001883 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001884 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001885 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001886 if (!Base.getType()->isDependentType()) {
1887 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001888 if (RD->isInvalidDecl())
1889 Instantiation->setInvalidDecl();
1890 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001891 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001892 continue;
1893 }
1894
Douglas Gregor752a5952011-01-03 22:36:02 +00001895 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001896 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001897 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001898 // This is a pack expansion. See whether we should expand it now, or
1899 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001900 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001901 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001902 Unexpanded);
1903 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001904 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001905 Optional<unsigned> NumExpansions;
Fangrui Song6907ce22018-07-30 19:24:48 +00001906 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
Aaron Ballman574705e2014-03-13 15:41:46 +00001907 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001908 Unexpanded,
Fangrui Song6907ce22018-07-30 19:24:48 +00001909 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001910 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001911 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001912 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001913 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001914 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001915
Douglas Gregor752a5952011-01-03 22:36:02 +00001916 // If we should expand this pack expansion now, do so.
1917 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001918 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001919 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
Fangrui Song6907ce22018-07-30 19:24:48 +00001920
Aaron Ballman574705e2014-03-13 15:41:46 +00001921 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001922 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001923 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001924 DeclarationName());
1925 if (!BaseTypeLoc) {
1926 Invalid = true;
1927 continue;
1928 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001929
Douglas Gregor752a5952011-01-03 22:36:02 +00001930 if (CXXBaseSpecifier *InstantiatedBase
1931 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001932 Base.getSourceRange(),
1933 Base.isVirtual(),
1934 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001935 BaseTypeLoc,
1936 SourceLocation()))
1937 InstantiatedBases.push_back(InstantiatedBase);
1938 else
1939 Invalid = true;
1940 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001941
Douglas Gregor752a5952011-01-03 22:36:02 +00001942 continue;
1943 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001944
Douglas Gregor752a5952011-01-03 22:36:02 +00001945 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001946 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001947 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001948 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001949 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001950 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001951 DeclarationName());
1952 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001953 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001954 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001955 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001956 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001957 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001958
Nick Lewycky19b9f952010-07-26 16:56:01 +00001959 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001960 Invalid = true;
1961 continue;
1962 }
1963
1964 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001965 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001966 Base.getSourceRange(),
1967 Base.isVirtual(),
1968 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001969 BaseTypeLoc,
1970 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001971 InstantiatedBases.push_back(InstantiatedBase);
1972 else
1973 Invalid = true;
1974 }
1975
Craig Topperaa700cb2015-12-27 21:55:19 +00001976 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001977 Invalid = true;
1978
1979 return Invalid;
1980}
1981
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001982// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001983namespace clang {
1984 namespace sema {
1985 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1986 const MultiLevelTemplateArgumentList &TemplateArgs);
Erich Keanea32910d2017-03-23 18:51:54 +00001987 Attr *instantiateTemplateAttributeForDecl(
1988 const Attr *At, ASTContext &C, Sema &S,
1989 const MultiLevelTemplateArgumentList &TemplateArgs);
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001990 }
1991}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001992
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001993/// Instantiate the definition of a class from a given pattern.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001994///
1995/// \param PointOfInstantiation The point of instantiation within the
1996/// source code.
1997///
1998/// \param Instantiation is the declaration whose definition is being
1999/// instantiated. This will be either a class template specialization
2000/// or a member class of a class template specialization.
2001///
2002/// \param Pattern is the pattern from which the instantiation
2003/// occurs. This will be either the declaration of a class template or
2004/// the declaration of a member class of a class template.
2005///
2006/// \param TemplateArgs The template arguments to be substituted into
2007/// the pattern.
2008///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002009/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002010///
2011/// \param Complain whether to complain if the class cannot be instantiated due
2012/// to the lack of a definition.
2013///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002014/// \returns true if an error occurred, false otherwise.
2015bool
2016Sema::InstantiateClass(SourceLocation PointOfInstantiation,
2017 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002018 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002019 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002020 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00002021 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002022 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002023 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002024 Instantiation->getInstantiatedFromMemberClass(),
2025 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002026 return true;
Anton Afanasyevd880de22019-03-30 08:42:48 +00002027
2028 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
Lubos Lunakab8cde42019-05-12 10:39:21 +00002029 std::string Name;
2030 llvm::raw_string_ostream OS(Name);
2031 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
2032 /*Qualified=*/true);
2033 return Name;
Anton Afanasyevd880de22019-03-30 08:42:48 +00002034 });
2035
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002036 Pattern = PatternDef;
2037
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002038 // Record the point of instantiation.
Fangrui Song6907ce22018-07-30 19:24:48 +00002039 if (MemberSpecializationInfo *MSInfo
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002040 = Instantiation->getMemberSpecializationInfo()) {
2041 MSInfo->setTemplateSpecializationKind(TSK);
2042 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Fangrui Song6907ce22018-07-30 19:24:48 +00002043 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00002044 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00002045 Spec->setTemplateSpecializationKind(TSK);
2046 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00002047 }
Richard Smitha1087602014-03-10 00:04:29 +00002048
Douglas Gregorf3430ae2009-03-25 21:23:52 +00002049 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002050 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002051 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002052 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Jordan Rose1e879d82018-03-23 00:07:18 +00002053 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002054 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002055
2056 // Enter the scope of this instantiation. We don't use
2057 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00002058 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002059 EnterExpressionEvaluationContext EvalContext(
2060 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002061
Douglas Gregor51121572010-03-24 01:33:17 +00002062 // If this is an instantiation of a local class, merge this local
2063 // instantiation scope with the enclosing scope. Otherwise, every
2064 // instantiation of a class has its own local instantiation scope.
2065 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00002066 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00002067
Volodymyr Sapsai4fbaa622017-09-21 19:54:12 +00002068 // Some class state isn't processed immediately but delayed till class
2069 // instantiation completes. We may not be ready to handle any delayed state
2070 // already on the stack as it might correspond to a different class, so save
2071 // it now and put it back later.
2072 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
Reid Kleckner5b640342016-02-26 19:51:02 +00002073
John McCall6602bb12010-08-01 02:01:53 +00002074 // Pull attributes from the pattern onto the instantiation.
2075 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2076
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002077 // Start the definition of this instantiation.
2078 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00002079
2080 // The instantiation is visible here, even if it was first declared in an
2081 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002082 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002083
2084 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00002085 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002086
John McCall76d824f2009-08-25 22:02:44 +00002087 // Do substitution on the base class specifiers.
2088 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002089 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002090
Douglas Gregor869853e2010-11-10 19:44:59 +00002091 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002092 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002093 // Delay instantiation of late parsed attributes.
2094 LateInstantiatedAttrVec LateAttrs;
2095 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2096
Richard Smith921f1322019-05-13 23:35:21 +00002097 bool MightHaveConstexprVirtualFunctions = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002098 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002099 // Don't instantiate members not belonging in this semantic context.
2100 // e.g. for:
2101 // @code
2102 // template <int i> class A {
2103 // class B *g;
2104 // };
2105 // @endcode
2106 // 'class B' has the template as lexical context but semantically it is
2107 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002108 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002109 continue;
2110
Erik Pilkingtona3a462e2018-07-23 22:47:37 +00002111 // BlockDecls can appear in a default-member-initializer. They must be the
2112 // child of a BlockExpr, so we only know how to instantiate them from there.
2113 if (isa<BlockDecl>(Member))
2114 continue;
2115
Aaron Ballman629afae2014-03-07 19:56:05 +00002116 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002117 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002118 continue;
2119 }
2120
Aaron Ballman629afae2014-03-07 19:56:05 +00002121 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002122 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002123 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002124 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002125 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2126 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2127 // specialization causes the implicit instantiation of the definitions
2128 // of unscoped member enumerations.
2129 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002130 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2131 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002132 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2133 assert(MSInfo && "no spec info for member enum specialization");
2134 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2135 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2136 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002137 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2138 if (SA->isFailed()) {
2139 // A static_assert failed. Bail out; instantiating this
2140 // class is probably not meaningful.
2141 Instantiation->setInvalidDecl();
2142 break;
2143 }
Richard Smith921f1322019-05-13 23:35:21 +00002144 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
2145 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
2146 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
2147 MightHaveConstexprVirtualFunctions = true;
Richard Smith7d137e32012-03-23 03:33:32 +00002148 }
2149
2150 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002151 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002152 } else {
2153 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002154 // instantiations was a semantic disaster, and we'll want to mark the
2155 // declaration invalid.
2156 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002157 }
2158 }
2159
2160 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002161 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
Erich Keanec480f302018-07-12 21:09:05 +00002162 SourceLocation(), SourceLocation(), ParsedAttributesView());
Douglas Gregor0be31a22010-07-02 17:43:08 +00002163 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002164
Reid Kleckner93f661a2015-03-17 21:51:43 +00002165 // Default arguments are parsed, if not instantiated. We can go instantiate
2166 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002167 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002168
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002169 // Instantiate late parsed attributes, and attach them to their decls.
2170 // See Sema::InstantiateAttrs
2171 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2172 E = LateAttrs.end(); I != E; ++I) {
2173 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2174 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002175
2176 // Allow 'this' within late-parsed attributes.
2177 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2178 CXXRecordDecl *ThisContext =
2179 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002180 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002181 ND && ND->isCXXInstanceMember());
2182
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002183 Attr *NewAttr =
2184 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2185 I->NewDecl->addAttr(NewAttr);
2186 LocalInstantiationScope::deleteScopes(I->Scope,
2187 Instantiator.getStartingScope());
2188 }
2189 Instantiator.disableLateAttributeInstantiation();
2190 LateAttrs.clear();
2191
Richard Smithd3b5c9082012-07-27 04:22:15 +00002192 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002193
Richard Smitha1087602014-03-10 00:04:29 +00002194 // FIXME: We should do something similar for explicit instantiations so they
2195 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002196 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002197 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002198 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002199 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002200 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002201
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002202 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002203 // Perform any dependent diagnostics from the pattern.
2204 PerformDependentDiagnostics(Pattern, TemplateArgs);
2205
Douglas Gregor869853e2010-11-10 19:44:59 +00002206 // Instantiate any out-of-line class template partial
2207 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002208 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002209 P = Instantiator.delayed_partial_spec_begin(),
2210 PEnd = Instantiator.delayed_partial_spec_end();
2211 P != PEnd; ++P) {
2212 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002213 P->first, P->second)) {
2214 Instantiation->setInvalidDecl();
2215 break;
2216 }
2217 }
2218
2219 // Instantiate any out-of-line variable template partial
2220 // specializations now.
2221 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2222 P = Instantiator.delayed_var_partial_spec_begin(),
2223 PEnd = Instantiator.delayed_var_partial_spec_end();
2224 P != PEnd; ++P) {
2225 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2226 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002227 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002228 break;
2229 }
2230 }
2231 }
2232
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002233 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002234 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002235
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002236 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002237 Consumer.HandleTagDeclDefinition(Instantiation);
2238
Douglas Gregor88d292c2010-05-13 16:44:06 +00002239 // Always emit the vtable for an explicit instantiation definition
Richard Smith921f1322019-05-13 23:35:21 +00002240 // of a polymorphic class template specialization. Otherwise, eagerly
2241 // instantiate only constexpr virtual functions in preparation for their use
2242 // in constant evaluation.
Douglas Gregor88d292c2010-05-13 16:44:06 +00002243 if (TSK == TSK_ExplicitInstantiationDefinition)
2244 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
Richard Smith921f1322019-05-13 23:35:21 +00002245 else if (MightHaveConstexprVirtualFunctions)
2246 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
2247 /*ConstexprOnly*/ true);
Douglas Gregor88d292c2010-05-13 16:44:06 +00002248 }
2249
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002250 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002251}
2252
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002253/// Instantiate the definition of an enum from a given pattern.
Richard Smith4b38ded2012-03-14 23:13:10 +00002254///
2255/// \param PointOfInstantiation The point of instantiation within the
2256/// source code.
2257/// \param Instantiation is the declaration whose definition is being
2258/// instantiated. This will be a member enumeration of a class
2259/// temploid specialization, or a local enumeration within a
2260/// function temploid specialization.
2261/// \param Pattern The templated declaration from which the instantiation
2262/// occurs.
2263/// \param TemplateArgs The template arguments to be substituted into
2264/// the pattern.
2265/// \param TSK The kind of implicit or explicit instantiation to perform.
2266///
2267/// \return \c true if an error occurred, \c false otherwise.
2268bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2269 EnumDecl *Instantiation, EnumDecl *Pattern,
2270 const MultiLevelTemplateArgumentList &TemplateArgs,
2271 TemplateSpecializationKind TSK) {
2272 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002273 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002274 Instantiation->getInstantiatedFromMemberEnum(),
2275 Pattern, PatternDef, TSK,/*Complain*/true))
2276 return true;
2277 Pattern = PatternDef;
2278
2279 // Record the point of instantiation.
2280 if (MemberSpecializationInfo *MSInfo
2281 = Instantiation->getMemberSpecializationInfo()) {
2282 MSInfo->setTemplateSpecializationKind(TSK);
2283 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2284 }
2285
2286 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002287 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002288 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002289 if (Inst.isAlreadyInstantiating())
2290 return false;
Jordan Rose1e879d82018-03-23 00:07:18 +00002291 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002292 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002293
Richard Smitha1087602014-03-10 00:04:29 +00002294 // The instantiation is visible here, even if it was first declared in an
2295 // unimported module.
Richard Smith90dc5252017-06-23 01:04:34 +00002296 Instantiation->setVisibleDespiteOwningModule();
Richard Smitha1087602014-03-10 00:04:29 +00002297
Richard Smith4b38ded2012-03-14 23:13:10 +00002298 // Enter the scope of this instantiation. We don't use
2299 // PushDeclContext because we don't have a scope.
2300 ContextRAII SavedContext(*this, Instantiation);
Faisal Valid143a0c2017-04-01 21:30:49 +00002301 EnterExpressionEvaluationContext EvalContext(
2302 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Richard Smith4b38ded2012-03-14 23:13:10 +00002303
2304 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2305
2306 // Pull attributes from the pattern onto the instantiation.
2307 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2308
2309 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2310 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2311
2312 // Exit the scope of this instantiation.
2313 SavedContext.pop();
2314
2315 return Instantiation->isInvalidDecl();
2316}
2317
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002318
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002319/// Instantiate the definition of a field from the given pattern.
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002320///
2321/// \param PointOfInstantiation The point of instantiation within the
2322/// source code.
2323/// \param Instantiation is the declaration whose definition is being
2324/// instantiated. This will be a class of a class temploid
2325/// specialization, or a local enumeration within a function temploid
2326/// specialization.
2327/// \param Pattern The templated declaration from which the instantiation
2328/// occurs.
2329/// \param TemplateArgs The template arguments to be substituted into
2330/// the pattern.
2331///
2332/// \return \c true if an error occurred, \c false otherwise.
2333bool Sema::InstantiateInClassInitializer(
2334 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2335 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2336 // If there is no initializer, we don't need to do anything.
2337 if (!Pattern->hasInClassInitializer())
2338 return false;
2339
2340 assert(Instantiation->getInClassInitStyle() ==
2341 Pattern->getInClassInitStyle() &&
2342 "pattern and instantiation disagree about init style");
2343
2344 // Error out if we haven't parsed the initializer of the pattern yet because
2345 // we are waiting for the closing brace of the outer class.
2346 Expr *OldInit = Pattern->getInClassInitializer();
2347 if (!OldInit) {
2348 RecordDecl *PatternRD = Pattern->getParent();
2349 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002350 Diag(PointOfInstantiation,
2351 diag::err_in_class_initializer_not_yet_parsed)
2352 << OutermostClass << Pattern;
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002353 Diag(Pattern->getEndLoc(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002354 Instantiation->setInvalidDecl();
2355 return true;
2356 }
2357
2358 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2359 if (Inst.isInvalid())
2360 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002361 if (Inst.isAlreadyInstantiating()) {
2362 // Error out if we hit an instantiation cycle for this initializer.
2363 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2364 << Instantiation;
2365 return true;
2366 }
Jordan Rose1e879d82018-03-23 00:07:18 +00002367 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
Richard Smithe19b95d2016-05-26 20:23:13 +00002368 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002369
2370 // Enter the scope of this instantiation. We don't use PushDeclContext because
2371 // we don't have a scope.
2372 ContextRAII SavedContext(*this, Instantiation->getParent());
Faisal Valid143a0c2017-04-01 21:30:49 +00002373 EnterExpressionEvaluationContext EvalContext(
2374 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002375
Serge Pavlov907233f2015-04-28 17:58:47 +00002376 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002377
2378 // Instantiate the initializer.
2379 ActOnStartCXXInClassMemberInitializer();
Mikael Nilsson9d2872d2018-12-13 10:15:27 +00002380 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002381
2382 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2383 /*CXXDirectInit=*/false);
2384 Expr *Init = NewInit.get();
2385 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2386 ActOnFinishCXXInClassMemberInitializer(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002387 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002388
Richard Smith4b054b22016-08-24 21:25:37 +00002389 if (auto *L = getASTMutationListener())
2390 L->DefaultMemberInitializerInstantiated(Instantiation);
2391
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002392 // Return true if the in-class initializer is still missing.
2393 return !Instantiation->getInClassInitializer();
2394}
2395
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002396namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002397 /// A partial specialization whose template arguments have matched
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002398 /// a given template-id.
2399 struct PartialSpecMatchResult {
2400 ClassTemplatePartialSpecializationDecl *Partial;
2401 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002402 };
2403}
2404
Richard Smithe6d4b772017-06-07 02:42:27 +00002405bool Sema::usesPartialOrExplicitSpecialization(
2406 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
2407 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
2408 TSK_ExplicitSpecialization)
2409 return true;
2410
2411 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2412 ClassTemplateSpec->getSpecializedTemplate()
2413 ->getPartialSpecializations(PartialSpecs);
2414 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2415 TemplateDeductionInfo Info(Loc);
2416 if (!DeduceTemplateArguments(PartialSpecs[I],
2417 ClassTemplateSpec->getTemplateArgs(), Info))
2418 return true;
2419 }
2420
2421 return false;
2422}
2423
Richard Smith32b43762017-01-08 22:45:21 +00002424/// Get the instantiation pattern to use to instantiate the definition of a
2425/// given ClassTemplateSpecializationDecl (either the pattern of the primary
2426/// template or of a partial specialization).
2427static CXXRecordDecl *
2428getPatternForClassTemplateSpecialization(
2429 Sema &S, SourceLocation PointOfInstantiation,
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002430 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2431 TemplateSpecializationKind TSK, bool Complain) {
Richard Smith32b43762017-01-08 22:45:21 +00002432 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
2433 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
2434 return nullptr;
2435
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002436 llvm::PointerUnion<ClassTemplateDecl *,
2437 ClassTemplatePartialSpecializationDecl *>
2438 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2439 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
2440 // Find best matching specialization.
2441 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Douglas Gregor2373c592009-05-31 09:31:02 +00002442
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002443 // C++ [temp.class.spec.match]p1:
2444 // When a class template is used in a context that requires an
2445 // instantiation of the class, it is necessary to determine
2446 // whether the instantiation is to be generated using the primary
2447 // template or one of the partial specializations. This is done by
2448 // matching the template arguments of the class template
2449 // specialization with the template argument lists of the partial
2450 // specializations.
2451 typedef PartialSpecMatchResult MatchResult;
2452 SmallVector<MatchResult, 4> Matched;
2453 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2454 Template->getPartialSpecializations(PartialSpecs);
2455 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2456 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2457 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2458 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2459 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
2460 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
2461 // Store the failed-deduction information for use in diagnostics, later.
2462 // TODO: Actually use the failed-deduction info?
2463 FailedCandidates.addCandidate().set(
2464 DeclAccessPair::make(Template, AS_public), Partial,
2465 MakeDeductionFailureInfo(S.Context, Result, Info));
2466 (void)Result;
2467 } else {
2468 Matched.push_back(PartialSpecMatchResult());
2469 Matched.back().Partial = Partial;
2470 Matched.back().Args = Info.take();
2471 }
2472 }
2473
2474 // If we're dealing with a member template where the template parameters
2475 // have been instantiated, this provides the original template parameters
2476 // from which the member template's parameters were instantiated.
2477
2478 if (Matched.size() >= 1) {
2479 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2480 if (Matched.size() == 1) {
2481 // -- If exactly one matching specialization is found, the
2482 // instantiation is generated from that specialization.
2483 // We don't need to do anything for this.
2484 } else {
2485 // -- If more than one matching specialization is found, the
2486 // partial order rules (14.5.4.2) are used to determine
2487 // whether one of the specializations is more specialized
2488 // than the others. If none of the specializations is more
2489 // specialized than all of the other matching
2490 // specializations, then the use of the class template is
2491 // ambiguous and the program is ill-formed.
2492 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2493 PEnd = Matched.end();
2494 P != PEnd; ++P) {
2495 if (S.getMoreSpecializedPartialSpecialization(
2496 P->Partial, Best->Partial, PointOfInstantiation) ==
2497 P->Partial)
2498 Best = P;
2499 }
2500
2501 // Determine if the best partial specialization is more specialized than
2502 // the others.
2503 bool Ambiguous = false;
2504 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2505 PEnd = Matched.end();
2506 P != PEnd; ++P) {
2507 if (P != Best && S.getMoreSpecializedPartialSpecialization(
2508 P->Partial, Best->Partial,
2509 PointOfInstantiation) != Best->Partial) {
2510 Ambiguous = true;
2511 break;
2512 }
2513 }
2514
2515 if (Ambiguous) {
2516 // Partial ordering did not produce a clear winner. Complain.
2517 Inst.Clear();
2518 ClassTemplateSpec->setInvalidDecl();
2519 S.Diag(PointOfInstantiation,
2520 diag::err_partial_spec_ordering_ambiguous)
2521 << ClassTemplateSpec;
2522
2523 // Print the matching partial specializations.
2524 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2525 PEnd = Matched.end();
2526 P != PEnd; ++P)
2527 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2528 << S.getTemplateArgumentBindingsText(
2529 P->Partial->getTemplateParameters(), *P->Args);
2530
2531 return nullptr;
2532 }
2533 }
2534
2535 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002536 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002537 // -- If no matches are found, the instantiation is generated
2538 // from the primary template.
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002539 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002540 }
2541
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002542 CXXRecordDecl *Pattern = nullptr;
2543 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
2544 if (auto *PartialSpec =
2545 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
Douglas Gregorbe999392009-09-15 16:23:51 +00002546 // Instantiate using the best class template partial specialization.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002547 while (PartialSpec->getInstantiatedFromMember()) {
Douglas Gregor21610382009-10-29 00:04:11 +00002548 // If we've found an explicit specialization of this class template,
2549 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002550 if (PartialSpec->isMemberSpecialization())
Douglas Gregor21610382009-10-29 00:04:11 +00002551 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002552
2553 PartialSpec = PartialSpec->getInstantiatedFromMember();
Douglas Gregor21610382009-10-29 00:04:11 +00002554 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002555 Pattern = PartialSpec;
Douglas Gregor170bc422009-06-12 22:31:52 +00002556 } else {
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002557 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2558 while (Template->getInstantiatedFromMemberTemplate()) {
Douglas Gregorcf915552009-10-13 16:30:37 +00002559 // If we've found an explicit specialization of this class template,
2560 // stop here and use that as the pattern.
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002561 if (Template->isMemberSpecialization())
Douglas Gregorcf915552009-10-13 16:30:37 +00002562 break;
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002563
2564 Template = Template->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002565 }
Volodymyr Sapsai9b973482018-05-16 18:28:58 +00002566 Pattern = Template->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002567 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002568
Richard Smith32b43762017-01-08 22:45:21 +00002569 return Pattern;
2570}
Mike Stump11289f42009-09-09 15:08:12 +00002571
Richard Smith32b43762017-01-08 22:45:21 +00002572bool Sema::InstantiateClassTemplateSpecialization(
2573 SourceLocation PointOfInstantiation,
2574 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2575 TemplateSpecializationKind TSK, bool Complain) {
2576 // Perform the actual instantiation on the canonical declaration.
2577 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2578 ClassTemplateSpec->getCanonicalDecl());
2579 if (ClassTemplateSpec->isInvalidDecl())
2580 return true;
2581
2582 CXXRecordDecl *Pattern = getPatternForClassTemplateSpecialization(
2583 *this, PointOfInstantiation, ClassTemplateSpec, TSK, Complain);
2584 if (!Pattern)
2585 return true;
2586
2587 return InstantiateClass(PointOfInstantiation, ClassTemplateSpec, Pattern,
2588 getTemplateInstantiationArgs(ClassTemplateSpec), TSK,
2589 Complain);
Douglas Gregor463421d2009-03-03 04:44:36 +00002590}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002591
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002592/// Instantiates the definitions of all of the member
John McCall76d824f2009-08-25 22:02:44 +00002593/// of the given class, which is an instantiation of a class template
2594/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002595void
2596Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002597 CXXRecordDecl *Instantiation,
2598 const MultiLevelTemplateArgumentList &TemplateArgs,
2599 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002600 // FIXME: We need to notify the ASTMutationListener that we did all of these
2601 // things, in case we have an explicit instantiation definition in a PCM, a
2602 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002603 assert(
2604 (TSK == TSK_ExplicitInstantiationDefinition ||
2605 TSK == TSK_ExplicitInstantiationDeclaration ||
2606 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2607 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002608 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002609 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002610 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Louis Dionned2695792018-10-04 15:49:42 +00002611 if (FunctionDecl *Pattern =
2612 Function->getInstantiatedFromMemberFunction()) {
2613
2614 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2615 continue;
2616
2617 MemberSpecializationInfo *MSInfo =
2618 Function->getMemberSpecializationInfo();
Douglas Gregor1d957a32009-10-27 18:42:08 +00002619 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002620 if (MSInfo->getTemplateSpecializationKind()
2621 == TSK_ExplicitSpecialization)
2622 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002623
2624 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2625 Function,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002626 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002627 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002628 SuppressNew) ||
2629 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002630 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002631
2632 // C++11 [temp.explicit]p8:
2633 // An explicit instantiation definition that names a class template
2634 // specialization explicitly instantiates the class template
2635 // specialization and is only an explicit instantiation definition
2636 // of members whose definition is visible at the point of
2637 // instantiation.
2638 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002639 continue;
2640
Richard Smitheb36ddf2014-04-24 22:45:46 +00002641 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2642
2643 if (Function->isDefined()) {
2644 // Let the ASTConsumer know that this function has been explicitly
2645 // instantiated now, and its linkage might have changed.
2646 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2647 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002648 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002649 } else if (TSK == TSK_ImplicitInstantiation) {
2650 PendingLocalImplicitInstantiations.push_back(
2651 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002652 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002653 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002654 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002655 if (isa<VarTemplateSpecializationDecl>(Var))
2656 continue;
2657
Douglas Gregor86d142a2009-10-08 07:24:58 +00002658 if (Var->isStaticDataMember()) {
Louis Dionned2695792018-10-04 15:49:42 +00002659 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2660 continue;
2661
Douglas Gregor1d957a32009-10-27 18:42:08 +00002662 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2663 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002664 if (MSInfo->getTemplateSpecializationKind()
2665 == TSK_ExplicitSpecialization)
2666 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002667
2668 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2669 Var,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002670 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002671 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002672 SuppressNew) ||
2673 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002674 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002675
Douglas Gregor1d957a32009-10-27 18:42:08 +00002676 if (TSK == TSK_ExplicitInstantiationDefinition) {
2677 // C++0x [temp.explicit]p8:
2678 // An explicit instantiation definition that names a class template
Fangrui Song6907ce22018-07-30 19:24:48 +00002679 // specialization explicitly instantiates the class template
2680 // specialization and is only an explicit instantiation definition
2681 // of members whose definition is visible at the point of
Douglas Gregor1d957a32009-10-27 18:42:08 +00002682 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002683 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002684 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002685
Douglas Gregor1d957a32009-10-27 18:42:08 +00002686 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Richard Smith891fc7f2017-12-05 01:31:47 +00002687 InstantiateVariableDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002688 } else {
2689 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2690 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002691 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002692 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Louis Dionned2695792018-10-04 15:49:42 +00002693 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
2694 continue;
2695
Douglas Gregor1da22252010-04-18 18:11:38 +00002696 // Always skip the injected-class-name, along with any
2697 // redeclarations of nested classes, since both would cause us
2698 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002699 // Skip closure types; they'll get instantiated when we instantiate
2700 // the corresponding lambda-expression.
2701 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2702 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002703 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002704
Douglas Gregor1d957a32009-10-27 18:42:08 +00002705 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2706 assert(MSInfo && "No member specialization information?");
Fangrui Song6907ce22018-07-30 19:24:48 +00002707
Douglas Gregor06aa50412010-04-09 21:02:29 +00002708 if (MSInfo->getTemplateSpecializationKind()
2709 == TSK_ExplicitSpecialization)
2710 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002711
Reid Kleckner5f789ba2019-04-29 21:32:05 +00002712 if (Context.getTargetInfo().getTriple().isOSWindows() &&
Hans Wennborga86a83b2016-05-26 19:42:56 +00002713 TSK == TSK_ExplicitInstantiationDeclaration) {
Reid Kleckner5f789ba2019-04-29 21:32:05 +00002714 // On Windows, explicit instantiation decl of the outer class doesn't
2715 // affect the inner class. Typically extern template declarations are
2716 // used in combination with dll import/export annotations, but those
2717 // are not propagated from the outer class templates to inner classes.
2718 // Therefore, do not instantiate inner classes on this platform, so
2719 // that users don't end up with undefined symbols during linking.
Hans Wennborga86a83b2016-05-26 19:42:56 +00002720 continue;
2721 }
2722
Fangrui Song6907ce22018-07-30 19:24:48 +00002723 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2724 Record,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002725 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002726 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002727 SuppressNew) ||
2728 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002729 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00002730
Douglas Gregor1d957a32009-10-27 18:42:08 +00002731 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2732 assert(Pattern && "Missing instantiated-from-template information");
Fangrui Song6907ce22018-07-30 19:24:48 +00002733
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002734 if (!Record->getDefinition()) {
2735 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002736 // C++0x [temp.explicit]p8:
2737 // An explicit instantiation definition that names a class template
Fangrui Song6907ce22018-07-30 19:24:48 +00002738 // specialization explicitly instantiates the class template
2739 // specialization and is only an explicit instantiation definition
2740 // of members whose definition is visible at the point of
Douglas Gregor1d957a32009-10-27 18:42:08 +00002741 // instantiation.
2742 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2743 MSInfo->setTemplateSpecializationKind(TSK);
2744 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2745 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002746
Douglas Gregor1d957a32009-10-27 18:42:08 +00002747 continue;
2748 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002749
Douglas Gregor1d957a32009-10-27 18:42:08 +00002750 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002751 TemplateArgs,
2752 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002753 } else {
2754 if (TSK == TSK_ExplicitInstantiationDefinition &&
2755 Record->getTemplateSpecializationKind() ==
2756 TSK_ExplicitInstantiationDeclaration) {
2757 Record->setTemplateSpecializationKind(TSK);
2758 MarkVTableUsed(PointOfInstantiation, Record, true);
2759 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002760 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002761
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002762 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002763 if (Pattern)
Fangrui Song6907ce22018-07-30 19:24:48 +00002764 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
Douglas Gregor1d957a32009-10-27 18:42:08 +00002765 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002766 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002767 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2768 assert(MSInfo && "No member specialization information?");
2769
2770 if (MSInfo->getTemplateSpecializationKind()
2771 == TSK_ExplicitSpecialization)
2772 continue;
2773
2774 if (CheckSpecializationInstantiationRedecl(
2775 PointOfInstantiation, TSK, Enum,
2776 MSInfo->getTemplateSpecializationKind(),
2777 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2778 SuppressNew)
2779 continue;
2780
2781 if (Enum->getDefinition())
2782 continue;
2783
Richard Smith6739a102016-05-05 00:56:12 +00002784 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002785 assert(Pattern && "Missing instantiated-from-template information");
2786
2787 if (TSK == TSK_ExplicitInstantiationDefinition) {
2788 if (!Pattern->getDefinition())
2789 continue;
2790
2791 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2792 } else {
2793 MSInfo->setTemplateSpecializationKind(TSK);
2794 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2795 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002796 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2797 // No need to instantiate in-class initializers during explicit
2798 // instantiation.
2799 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2800 CXXRecordDecl *ClassPattern =
2801 Instantiation->getTemplateInstantiationPattern();
2802 DeclContext::lookup_result Lookup =
2803 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002804 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002805 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2806 TemplateArgs);
2807 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002808 }
2809 }
2810}
2811
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002812/// Instantiate the definitions of all of the members of the
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002813/// given class template specialization, which was named as part of an
2814/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002815void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002816Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002817 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002818 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2819 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002820 // C++0x [temp.explicit]p7:
2821 // An explicit instantiation that names a class template
2822 // specialization is an explicit instantion of the same kind
2823 // (declaration or definition) of each of its members (not
2824 // including members inherited from base classes) that has not
2825 // been previously explicitly specialized in the translation unit
2826 // containing the explicit instantiation, except as described
2827 // below.
2828 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002829 getTemplateInstantiationArgs(ClassTemplateSpec),
2830 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002831}
2832
John McCalldadc5752010-08-24 06:29:42 +00002833StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002834Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002835 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002836 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002837
2838 TemplateInstantiator Instantiator(*this, TemplateArgs,
2839 SourceLocation(),
2840 DeclarationName());
2841 return Instantiator.TransformStmt(S);
2842}
2843
John McCalldadc5752010-08-24 06:29:42 +00002844ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002845Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002846 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002847 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002848
Douglas Gregora16548e2009-08-11 05:31:07 +00002849 TemplateInstantiator Instantiator(*this, TemplateArgs,
2850 SourceLocation(),
2851 DeclarationName());
2852 return Instantiator.TransformExpr(E);
2853}
2854
Richard Smithd59b8322012-12-19 01:39:02 +00002855ExprResult Sema::SubstInitializer(Expr *Init,
2856 const MultiLevelTemplateArgumentList &TemplateArgs,
2857 bool CXXDirectInit) {
2858 TemplateInstantiator Instantiator(*this, TemplateArgs,
2859 SourceLocation(),
2860 DeclarationName());
2861 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2862}
2863
Craig Topper99d23532015-12-24 23:58:29 +00002864bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002865 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002866 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002867 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002868 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002869
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002870 TemplateInstantiator Instantiator(*this, TemplateArgs,
2871 SourceLocation(),
2872 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002873 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2874 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002875}
2876
Douglas Gregor14454802011-02-25 02:25:35 +00002877NestedNameSpecifierLoc
2878Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
Fangrui Song6907ce22018-07-30 19:24:48 +00002879 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor14454802011-02-25 02:25:35 +00002880 if (!NNS)
2881 return NestedNameSpecifierLoc();
Fangrui Song6907ce22018-07-30 19:24:48 +00002882
Douglas Gregor14454802011-02-25 02:25:35 +00002883 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2884 DeclarationName());
2885 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2886}
2887
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00002888/// Do template substitution on declaration name info.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002889DeclarationNameInfo
2890Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2891 const MultiLevelTemplateArgumentList &TemplateArgs) {
2892 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2893 NameInfo.getName());
2894 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2895}
2896
Douglas Gregoraa594892009-03-31 18:38:02 +00002897TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002898Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2899 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002900 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002901 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2902 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002903 CXXScopeSpec SS;
2904 SS.Adopt(QualifierLoc);
2905 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002906}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002907
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002908bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2909 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002910 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002911 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2912 DeclarationName());
Fangrui Song6907ce22018-07-30 19:24:48 +00002913
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002914 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002915}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002916
Richard Smith70b13042015-01-09 01:19:56 +00002917static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002918 // When storing ParmVarDecls in the local instantiation scope, we always
2919 // want to use the ParmVarDecl from the canonical function declaration,
2920 // since the map is then valid for any redeclaration or definition of that
2921 // function.
2922 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2923 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2924 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002925 // This parameter might be from a freestanding function type within the
2926 // function and isn't necessarily referring to one of FD's parameters.
Dmitri Gribenko66b6bb12019-04-10 20:25:07 +00002927 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
Richard Smith70b13042015-01-09 01:19:56 +00002928 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002929 }
2930 }
2931 return D;
2932}
2933
2934
Douglas Gregorf3010112011-01-07 16:43:16 +00002935llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2936LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002937 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002938 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002939 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002940
Douglas Gregor14cf7522010-04-30 18:55:50 +00002941 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002942 const Decl *CheckD = D;
2943 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002944 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002945 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002946 return &Found->second;
Fangrui Song6907ce22018-07-30 19:24:48 +00002947
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002948 // If this is a tag declaration, it's possible that we need to look for
2949 // a previous declaration.
2950 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002951 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002952 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002953 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002954 } while (CheckD);
Fangrui Song6907ce22018-07-30 19:24:48 +00002955
2956 // If we aren't combined with our outer scope, we're done.
Douglas Gregor14cf7522010-04-30 18:55:50 +00002957 if (!Current->CombineWithOuterScope)
2958 break;
2959 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002960
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002961 // If we're performing a partial substitution during template argument
2962 // deduction, we may not have values for template parameters yet.
2963 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2964 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002965 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002966
Serge Pavlove7ad8312015-05-15 10:10:28 +00002967 // Local types referenced prior to definition may require instantiation.
2968 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2969 if (RD->isLocalClass())
2970 return nullptr;
2971
2972 // Enumeration types referenced prior to definition may appear as a result of
2973 // error recovery.
2974 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002975 return nullptr;
2976
Chris Lattnercab02a62011-02-17 20:34:02 +00002977 // If we didn't find the decl, then we either have a sema bug, or we have a
2978 // forward reference to a label declaration. Return null to indicate that
2979 // we have an uninstantiated label.
2980 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002981 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002982}
2983
John McCall19c1bfd2010-08-25 05:32:35 +00002984void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002985 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002986 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002987 if (Stored.isNull()) {
2988#ifndef NDEBUG
2989 // It should not be present in any surrounding scope either.
2990 LocalInstantiationScope *Current = this;
2991 while (Current->CombineWithOuterScope && Current->Outer) {
2992 Current = Current->Outer;
2993 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2994 "Instantiated local in inner and outer scopes");
2995 }
2996#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002997 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002998 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
Richard Smithb2997f52019-05-21 20:10:50 +00002999 Pack->push_back(cast<VarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00003000 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003001 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00003002 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00003003}
Douglas Gregorf3010112011-01-07 16:43:16 +00003004
James Y Knight48fefa32015-09-30 14:04:23 +00003005void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
Richard Smithb2997f52019-05-21 20:10:50 +00003006 VarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003007 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003008 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
3009 Pack->push_back(Inst);
3010}
3011
3012void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00003013#ifndef NDEBUG
3014 // This should be the first time we've been told about this decl.
3015 for (LocalInstantiationScope *Current = this;
3016 Current && Current->CombineWithOuterScope; Current = Current->Outer)
3017 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
3018 "Creating local pack after instantiation of local");
3019#endif
3020
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00003021 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00003022 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00003023 DeclArgumentPack *Pack = new DeclArgumentPack;
3024 Stored = Pack;
3025 ArgumentPacks.push_back(Pack);
3026}
3027
Fangrui Song6907ce22018-07-30 19:24:48 +00003028void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003029 const TemplateArgument *ExplicitArgs,
3030 unsigned NumExplicitArgs) {
3031 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
3032 "Already have a partially-substituted pack");
Fangrui Song6907ce22018-07-30 19:24:48 +00003033 assert((!PartiallySubstitutedPack
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003034 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
3035 "Wrong number of arguments in partially-substituted pack");
3036 PartiallySubstitutedPack = Pack;
3037 ArgsInPartiallySubstitutedPack = ExplicitArgs;
3038 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
3039}
3040
3041NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
3042 const TemplateArgument **ExplicitArgs,
3043 unsigned *NumExplicitArgs) const {
3044 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00003045 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003046 if (NumExplicitArgs)
3047 *NumExplicitArgs = 0;
Fangrui Song6907ce22018-07-30 19:24:48 +00003048
3049 for (const LocalInstantiationScope *Current = this; Current;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003050 Current = Current->Outer) {
3051 if (Current->PartiallySubstitutedPack) {
3052 if (ExplicitArgs)
3053 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
3054 if (NumExplicitArgs)
3055 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
Fangrui Song6907ce22018-07-30 19:24:48 +00003056
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003057 return Current->PartiallySubstitutedPack;
3058 }
3059
3060 if (!Current->CombineWithOuterScope)
3061 break;
3062 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003063
3064 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00003065}