blob: 4f2e74740df20f9f4b04718b4d5cc2217ec64099 [file] [log] [blame]
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Richard Smith4b054b22016-08-24 21:25:37 +000018#include "clang/AST/ASTMutationListener.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000022#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000023#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000024#include "clang/Sema/Lookup.h"
Richard Smithe19b95d2016-05-26 20:23:13 +000025#include "clang/Sema/PrettyDeclStackTrace.h"
John McCallde6836a2010-08-24 07:21:54 +000026#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000027#include "clang/Sema/TemplateDeduction.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000028
29using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000030using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000031
Douglas Gregor4ea568f2009-03-10 18:03:33 +000032//===----------------------------------------------------------------------===/
33// Template Instantiation Support
34//===----------------------------------------------------------------------===/
35
Douglas Gregor01afeef2009-08-28 20:31:08 +000036/// \brief Retrieve the template argument list(s) that should be used to
37/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000038///
39/// \param D the declaration for which we are computing template instantiation
40/// arguments.
41///
42/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000043///
44/// \param RelativeToPrimary true if we should get the template
45/// arguments relative to the primary template, even when we're
46/// dealing with a specialization. This is only relevant for function
47/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000048///
49/// \param Pattern If non-NULL, indicates the pattern from which we will be
50/// instantiating the definition of the given declaration, \p D. This is
51/// used to determine the proper set of template instantiation arguments for
52/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000053MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000054Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000055 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000056 bool RelativeToPrimary,
57 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000058 // Accumulate the set of template argument lists in this structure.
59 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000060
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000061 if (Innermost)
62 Result.addOuterTemplateArguments(Innermost);
63
Douglas Gregora654dd82009-08-28 17:37:35 +000064 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000065 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000066 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000067
68 // Add template arguments from a variable template instantiation.
69 if (VarTemplateSpecializationDecl *Spec =
70 dyn_cast<VarTemplateSpecializationDecl>(D)) {
71 // We're done when we hit an explicit specialization.
72 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
73 !isa<VarTemplatePartialSpecializationDecl>(Spec))
74 return Result;
75
76 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
77
78 // If this variable template specialization was instantiated from a
79 // specialized member that is a variable template, we're done.
80 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000081 llvm::PointerUnion<VarTemplateDecl*,
82 VarTemplatePartialSpecializationDecl*> Specialized
83 = Spec->getSpecializedTemplateOrPartial();
84 if (VarTemplatePartialSpecializationDecl *Partial =
85 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
86 if (Partial->isMemberSpecialization())
87 return Result;
88 } else {
89 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
90 if (Tmpl->isMemberSpecialization())
91 return Result;
92 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000093 }
94
Douglas Gregor55462622011-06-15 14:20:42 +000095 // If we have a template template parameter with translation unit context,
96 // then we're performing substitution into a default template argument of
97 // this template template parameter before we've constructed the template
98 // that will own this template template parameter. In this case, we
99 // use empty template parameter lists for all of the outer templates
100 // to avoid performing any substitutions.
101 if (Ctx->isTranslationUnit()) {
102 if (TemplateTemplateParmDecl *TTP
103 = dyn_cast<TemplateTemplateParmDecl>(D)) {
104 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000105 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000106 return Result;
107 }
108 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000109 }
110
John McCall970d5302009-08-29 03:16:09 +0000111 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000112 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000113 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000114 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
115 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000116 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
117 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000118 break;
Mike Stump11289f42009-09-09 15:08:12 +0000119
Douglas Gregora654dd82009-08-28 17:37:35 +0000120 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000121
122 // If this class template specialization was instantiated from a
123 // specialized member that is a class template, we're done.
124 assert(Spec->getSpecializedTemplate() && "No class template?");
125 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
126 break;
Mike Stump11289f42009-09-09 15:08:12 +0000127 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000128 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000129 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000130 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000131 (Function->getTemplateSpecializationKind() ==
132 TSK_ExplicitSpecialization &&
133 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000134 break;
135
Douglas Gregora654dd82009-08-28 17:37:35 +0000136 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000137 = Function->getTemplateSpecializationArgs()) {
138 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000139 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000140
Douglas Gregorcf915552009-10-13 16:30:37 +0000141 // If this function was instantiated from a specialized member that is
142 // a function template, we're done.
143 assert(Function->getPrimaryTemplate() && "No function template?");
144 if (Function->getPrimaryTemplate()->isMemberSpecialization())
145 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000146
147 // If this function is a generic lambda specialization, we are done.
148 if (isGenericLambdaCallOperatorSpecialization(Function))
149 break;
150
Douglas Gregor43669f82011-03-05 17:54:25 +0000151 } else if (FunctionTemplateDecl *FunTmpl
152 = Function->getDescribedFunctionTemplate()) {
153 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000154 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000155 }
156
John McCall970d5302009-08-29 03:16:09 +0000157 // If this is a friend declaration and it declares an entity at
158 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000159 // instead of its semantic parent, unless of course the pattern we're
160 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000161 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000162 Function->getDeclContext()->isFileContext() &&
163 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000164 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000165 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000166 continue;
167 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000168 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
169 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
170 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000171 const TemplateSpecializationType *TST =
172 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
173 Result.addOuterTemplateArguments(
174 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000175 if (ClassTemplate->isMemberSpecialization())
176 break;
177 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000178 }
John McCall970d5302009-08-29 03:16:09 +0000179
180 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000181 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000182 }
Mike Stump11289f42009-09-09 15:08:12 +0000183
Douglas Gregora654dd82009-08-28 17:37:35 +0000184 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000185}
186
Douglas Gregor84d49a22009-11-11 21:54:23 +0000187bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
188 switch (Kind) {
189 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000190 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000191 case DefaultTemplateArgumentInstantiation:
192 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000193 case ExplicitTemplateArgumentSubstitution:
194 case DeducedTemplateArgumentSubstitution:
195 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000196 return true;
197
Douglas Gregor84d49a22009-11-11 21:54:23 +0000198 case DefaultTemplateArgumentChecking:
199 return false;
200 }
David Blaikie8a40f702012-01-17 06:56:22 +0000201
202 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000203}
204
Benjamin Kramer7761a042015-03-06 16:36:50 +0000205Sema::InstantiatingTemplate::InstantiatingTemplate(
206 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000207 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
208 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000209 sema::TemplateDeductionInfo *DeductionInfo)
210 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
211 SemaRef.InNonInstantiationSFINAEContext) {
Akira Hatanaka43556c12016-11-03 15:04:58 +0000212 // Don't allow further instantiation if a fatal error and an uncompilable
Akira Hatanaka40c15ab2016-11-03 17:11:28 +0000213 // error have occurred. Any diagnostics we might have raised will not be
Akira Hatanaka43556c12016-11-03 15:04:58 +0000214 // visible, and we do not need to construct a correct AST.
215 if (SemaRef.Diags.hasFatalErrorOccurred() &&
216 SemaRef.Diags.hasUncompilableErrorOccurred()) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000217 Invalid = true;
218 return;
219 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000220 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
221 if (!Invalid) {
222 ActiveTemplateInstantiation Inst;
223 Inst.Kind = Kind;
224 Inst.PointOfInstantiation = PointOfInstantiation;
225 Inst.Entity = Entity;
226 Inst.Template = Template;
227 Inst.TemplateArgs = TemplateArgs.data();
228 Inst.NumTemplateArgs = TemplateArgs.size();
229 Inst.DeductionInfo = DeductionInfo;
230 Inst.InstantiationRange = InstantiationRange;
Richard Smith54f18e82016-08-31 02:15:21 +0000231 AlreadyInstantiating =
232 !SemaRef.InstantiatingSpecializations
233 .insert(std::make_pair(Inst.Entity->getCanonicalDecl(), Inst.Kind))
234 .second;
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000235 SemaRef.InNonInstantiationSFINAEContext = false;
236 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
237 if (!Inst.isInstantiationRecord())
238 ++SemaRef.NonInstantiationEntries;
239 }
240}
241
Benjamin Kramer7761a042015-03-06 16:36:50 +0000242Sema::InstantiatingTemplate::InstantiatingTemplate(
243 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
244 SourceRange InstantiationRange)
245 : InstantiatingTemplate(SemaRef,
246 ActiveTemplateInstantiation::TemplateInstantiation,
247 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000248
Benjamin Kramer7761a042015-03-06 16:36:50 +0000249Sema::InstantiatingTemplate::InstantiatingTemplate(
250 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
251 ExceptionSpecification, SourceRange InstantiationRange)
252 : InstantiatingTemplate(
253 SemaRef, ActiveTemplateInstantiation::ExceptionSpecInstantiation,
254 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000255
Benjamin Kramer7761a042015-03-06 16:36:50 +0000256Sema::InstantiatingTemplate::InstantiatingTemplate(
Richard Smith54f18e82016-08-31 02:15:21 +0000257 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
258 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
259 SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000260 : InstantiatingTemplate(
261 SemaRef,
262 ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
Richard Smith54f18e82016-08-31 02:15:21 +0000263 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
264 Template, TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000265
Benjamin Kramer7761a042015-03-06 16:36:50 +0000266Sema::InstantiatingTemplate::InstantiatingTemplate(
267 Sema &SemaRef, SourceLocation PointOfInstantiation,
268 FunctionTemplateDecl *FunctionTemplate,
269 ArrayRef<TemplateArgument> TemplateArgs,
270 ActiveTemplateInstantiation::InstantiationKind Kind,
271 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
272 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
273 InstantiationRange, FunctionTemplate, nullptr,
Richard Smith54f18e82016-08-31 02:15:21 +0000274 TemplateArgs, &DeductionInfo) {
275 assert(
276 Kind == ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution ||
277 Kind == ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution);
278}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000279
Benjamin Kramer7761a042015-03-06 16:36:50 +0000280Sema::InstantiatingTemplate::InstantiatingTemplate(
281 Sema &SemaRef, SourceLocation PointOfInstantiation,
282 ClassTemplatePartialSpecializationDecl *PartialSpec,
283 ArrayRef<TemplateArgument> TemplateArgs,
284 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
285 : InstantiatingTemplate(
286 SemaRef,
287 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
288 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
289 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000290
Larisse Voufo39a1e502013-08-06 01:03:05 +0000291Sema::InstantiatingTemplate::InstantiatingTemplate(
292 Sema &SemaRef, SourceLocation PointOfInstantiation,
293 VarTemplatePartialSpecializationDecl *PartialSpec,
294 ArrayRef<TemplateArgument> TemplateArgs,
295 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000296 : InstantiatingTemplate(
297 SemaRef,
298 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
299 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
300 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000301
Benjamin Kramer7761a042015-03-06 16:36:50 +0000302Sema::InstantiatingTemplate::InstantiatingTemplate(
303 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
304 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
305 : InstantiatingTemplate(
306 SemaRef,
307 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
308 PointOfInstantiation, InstantiationRange, Param, nullptr,
309 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000310
Benjamin Kramer7761a042015-03-06 16:36:50 +0000311Sema::InstantiatingTemplate::InstantiatingTemplate(
312 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
313 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
314 SourceRange InstantiationRange)
315 : InstantiatingTemplate(
316 SemaRef,
317 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
318 PointOfInstantiation, InstantiationRange, Param, Template,
319 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000320
Benjamin Kramer7761a042015-03-06 16:36:50 +0000321Sema::InstantiatingTemplate::InstantiatingTemplate(
322 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
323 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
324 SourceRange InstantiationRange)
325 : InstantiatingTemplate(
326 SemaRef,
327 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
328 PointOfInstantiation, InstantiationRange, Param, Template,
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, TemplateDecl *Template,
333 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
334 SourceRange InstantiationRange)
335 : InstantiatingTemplate(
336 SemaRef, ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
337 PointOfInstantiation, InstantiationRange, Param, Template,
338 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000339
Douglas Gregor85673582009-05-18 17:01:57 +0000340void Sema::InstantiatingTemplate::Clear() {
341 if (!Invalid) {
Richard Smith54f18e82016-08-31 02:15:21 +0000342 auto &Active = SemaRef.ActiveTemplateInstantiations.back();
343 if (!Active.isInstantiationRecord()) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000344 assert(SemaRef.NonInstantiationEntries > 0);
345 --SemaRef.NonInstantiationEntries;
346 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000347 SemaRef.InNonInstantiationSFINAEContext
348 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000349
350 // Name lookup no longer looks in this template's defining module.
351 assert(SemaRef.ActiveTemplateInstantiations.size() >=
352 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
353 "forgot to remove a lookup module for a template instantiation");
354 if (SemaRef.ActiveTemplateInstantiations.size() ==
355 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
356 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
357 SemaRef.LookupModulesCache.erase(M);
358 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
359 }
360
Richard Smith54f18e82016-08-31 02:15:21 +0000361 if (!AlreadyInstantiating)
362 SemaRef.InstantiatingSpecializations.erase(
363 std::make_pair(Active.Entity, Active.Kind));
364
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000365 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000366 Invalid = true;
367 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000368}
369
Douglas Gregor79cf6032009-03-10 20:44:00 +0000370bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
371 SourceLocation PointOfInstantiation,
372 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000373 assert(SemaRef.NonInstantiationEntries <=
374 SemaRef.ActiveTemplateInstantiations.size());
375 if ((SemaRef.ActiveTemplateInstantiations.size() -
376 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000377 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000378 return false;
379
Mike Stump11289f42009-09-09 15:08:12 +0000380 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000381 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000382 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000383 << InstantiationRange;
384 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000385 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000386 return true;
387}
388
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000389/// \brief Prints the current instantiation stack through a series of
390/// notes.
391void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000392 // Determine which template instantiations to skip, if any.
393 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
394 unsigned Limit = Diags.getTemplateBacktraceLimit();
395 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
396 SkipStart = Limit / 2 + Limit % 2;
397 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
398 }
399
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000400 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000401 unsigned InstantiationIdx = 0;
Craig Topper2341c0d2013-07-04 03:08:24 +0000402 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000403 Active = ActiveTemplateInstantiations.rbegin(),
404 ActiveEnd = ActiveTemplateInstantiations.rend();
405 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000406 ++Active, ++InstantiationIdx) {
407 // Skip this instantiation?
408 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
409 if (InstantiationIdx == SkipStart) {
410 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000411 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000412 diag::note_instantiation_contexts_suppressed)
413 << unsigned(ActiveTemplateInstantiations.size() - Limit);
414 }
415 continue;
416 }
417
Douglas Gregor79cf6032009-03-10 20:44:00 +0000418 switch (Active->Kind) {
419 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000420 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000421 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
422 unsigned DiagID = diag::note_template_member_class_here;
423 if (isa<ClassTemplateSpecializationDecl>(Record))
424 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000425 Diags.Report(Active->PointOfInstantiation, DiagID)
Richard Smith792c22d2016-12-24 04:09:05 +0000426 << Record << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000427 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000428 unsigned DiagID;
429 if (Function->getPrimaryTemplate())
430 DiagID = diag::note_function_template_spec_here;
431 else
432 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000433 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000434 << Function
435 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000436 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000437 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000438 VD->isStaticDataMember()?
439 diag::note_template_static_data_member_def_here
440 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000441 << VD
442 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000443 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
444 Diags.Report(Active->PointOfInstantiation,
445 diag::note_template_enum_def_here)
446 << ED
447 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000448 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
449 Diags.Report(Active->PointOfInstantiation,
450 diag::note_template_nsdmi_here)
451 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000452 } else {
453 Diags.Report(Active->PointOfInstantiation,
454 diag::note_template_type_alias_instantiation_here)
455 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000456 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000457 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000458 break;
459 }
460
461 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Richard Smith54f18e82016-08-31 02:15:21 +0000462 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000463 SmallVector<char, 128> TemplateArgsStr;
464 llvm::raw_svector_ostream OS(TemplateArgsStr);
465 Template->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000466 TemplateSpecializationType::PrintTemplateArgumentList(
467 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000468 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000469 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000470 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000471 << Active->InstantiationRange;
472 break;
473 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000474
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000475 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000476 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000477 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000478 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000479 << FnTmpl
480 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
481 Active->TemplateArgs,
482 Active->NumTemplateArgs)
483 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000484 break;
485 }
Mike Stump11289f42009-09-09 15:08:12 +0000486
Richard Smithe68a38f2016-12-24 04:20:31 +0000487 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution: {
488 if (FunctionTemplateDecl *FnTmpl =
489 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000490 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000491 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000492 << FnTmpl
493 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
494 Active->TemplateArgs,
495 Active->NumTemplateArgs)
496 << Active->InstantiationRange;
Richard Smithe68a38f2016-12-24 04:20:31 +0000497 } else {
498 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
499 isa<VarTemplateSpecializationDecl>(Active->Entity);
500 TemplateParameterList *Params;
501 if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
502 Active->Entity)) {
503 Params = D->getTemplateParameters();
504 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
505 Active->Entity)) {
506 Params = D->getTemplateParameters();
507 } else {
508 llvm_unreachable("unexpected template kind");
509 }
510
511 //<< Context.getTypeDeclType(PartialSpec)
512 Diags.Report(Active->PointOfInstantiation,
513 diag::note_deduced_template_arg_substitution_here)
514 << IsVar << cast<NamedDecl>(Active->Entity)
515 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
516 Active->NumTemplateArgs)
517 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000518 }
519 break;
Richard Smithe68a38f2016-12-24 04:20:31 +0000520 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000521
Anders Carlsson657bad42009-09-05 05:14:19 +0000522 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000523 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000524 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000525
Benjamin Kramer9170e912013-02-22 15:46:01 +0000526 SmallVector<char, 128> TemplateArgsStr;
527 llvm::raw_svector_ostream OS(TemplateArgsStr);
528 FD->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000529 TemplateSpecializationType::PrintTemplateArgumentList(
530 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000531 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000532 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000533 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000534 << Active->InstantiationRange;
535 break;
536 }
Mike Stump11289f42009-09-09 15:08:12 +0000537
Douglas Gregore62e6a02009-11-11 19:13:48 +0000538 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000539 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000540 std::string Name;
541 if (!Parm->getName().empty())
542 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000543
544 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000545 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
546 TemplateParams = Template->getTemplateParameters();
547 else
548 TemplateParams =
549 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
550 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000551 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000552 diag::note_prior_template_arg_substitution)
553 << isa<TemplateTemplateParmDecl>(Parm)
554 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000555 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000556 Active->TemplateArgs,
557 Active->NumTemplateArgs)
558 << Active->InstantiationRange;
559 break;
560 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000561
562 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000563 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000564 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
565 TemplateParams = Template->getTemplateParameters();
566 else
567 TemplateParams =
568 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
569 ->getTemplateParameters();
570
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000571 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000572 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000573 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000574 Active->TemplateArgs,
575 Active->NumTemplateArgs)
576 << Active->InstantiationRange;
577 break;
578 }
Richard Smithf623c962012-04-17 00:58:00 +0000579
580 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
581 Diags.Report(Active->PointOfInstantiation,
582 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000583 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000584 << Active->InstantiationRange;
585 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000586 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000587 }
588}
589
David Blaikie05785d12013-02-20 22:23:23 +0000590Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000591 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000592 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000593
Craig Topper2341c0d2013-07-04 03:08:24 +0000594 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000595 Active = ActiveTemplateInstantiations.rbegin(),
596 ActiveEnd = ActiveTemplateInstantiations.rend();
597 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000598 ++Active)
599 {
Douglas Gregor33834512009-06-14 07:33:30 +0000600 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000601 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000602 // An instantiation of an alias template may or may not be a SFINAE
603 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000604 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000605 break;
606 // Fall through.
607 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000608 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000609 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000610 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000611
Douglas Gregor33834512009-06-14 07:33:30 +0000612 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000613 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000614 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000615 // A default template argument instantiation and substitution into
616 // template parameters with arguments for prior parameters may or may
617 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000618 break;
Mike Stump11289f42009-09-09 15:08:12 +0000619
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000620 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
621 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
622 // We're either substitution explicitly-specified template arguments
623 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000624 assert(Active->DeductionInfo && "Missing deduction info pointer");
625 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000626 }
627 }
628
David Blaikie7a30dc52013-02-21 01:47:18 +0000629 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000630}
631
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000632/// \brief Retrieve the depth and index of a parameter pack.
633static std::pair<unsigned, unsigned>
634getDepthAndIndex(NamedDecl *ND) {
635 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
636 return std::make_pair(TTP->getDepth(), TTP->getIndex());
637
638 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
639 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
640
641 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
642 return std::make_pair(TTP->getDepth(), TTP->getIndex());
643}
644
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000645//===----------------------------------------------------------------------===/
646// Template Instantiation for Types
647//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000648namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000649 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000650 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000651 SourceLocation Loc;
652 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000653
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000654 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000655 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000656
657 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000658 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000659 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000660 DeclarationName Entity)
661 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000662 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000663
Mike Stump11289f42009-09-09 15:08:12 +0000664 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000665 /// transformed.
666 ///
667 /// For the purposes of template instantiation, a type has already been
668 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000669 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000670
Douglas Gregord6ff3322009-08-04 16:50:30 +0000671 /// \brief Returns the location of the entity being instantiated, if known.
672 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000673
Douglas Gregord6ff3322009-08-04 16:50:30 +0000674 /// \brief Returns the name of the entity being instantiated, if any.
675 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000676
Douglas Gregoref6ab412009-10-27 06:26:26 +0000677 /// \brief Sets the "base" location and entity when that
678 /// information is known based on another transformation.
679 void setBase(SourceLocation Loc, DeclarationName Entity) {
680 this->Loc = Loc;
681 this->Entity = Entity;
682 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000683
684 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
685 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000686 ArrayRef<UnexpandedParameterPack> Unexpanded,
687 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000688 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000689 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
690 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000691 TemplateArgs,
692 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000693 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000694 NumExpansions);
695 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000696
Douglas Gregorf3010112011-01-07 16:43:16 +0000697 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
698 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
699 }
700
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000701 TemplateArgument ForgetPartiallySubstitutedPack() {
702 TemplateArgument Result;
703 if (NamedDecl *PartialPack
704 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
705 MultiLevelTemplateArgumentList &TemplateArgs
706 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
707 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000708 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000709 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
710 Result = TemplateArgs(Depth, Index);
711 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
712 }
713 }
714
715 return Result;
716 }
717
718 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
719 if (Arg.isNull())
720 return;
721
722 if (NamedDecl *PartialPack
723 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
724 MultiLevelTemplateArgumentList &TemplateArgs
725 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
726 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000727 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000728 TemplateArgs.setArgument(Depth, Index, Arg);
729 }
730 }
731
Douglas Gregord6ff3322009-08-04 16:50:30 +0000732 /// \brief Transform the given declaration by instantiating a reference to
733 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000734 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000735
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000736 void transformAttrs(Decl *Old, Decl *New) {
737 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
738 }
739
740 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000741 // If we've instantiated the call operator of a lambda or the call
742 // operator template of a generic lambda, update the "instantiation of"
743 // information.
744 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
745 if (NewMD && isLambdaCallOperator(NewMD)) {
746 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
747 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
748 NewTD->setInstantiatedFromMemberTemplate(
749 OldMD->getDescribedFunctionTemplate());
750 else
751 NewMD->setInstantiationOfMemberFunction(OldMD,
752 TSK_ImplicitInstantiation);
753 }
754
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000755 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000756
757 // We recreated a local declaration, but not by instantiating it. There
758 // may be pending dependent diagnostics to produce.
759 if (auto *DC = dyn_cast<DeclContext>(Old))
760 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000761 }
762
Mike Stump11289f42009-09-09 15:08:12 +0000763 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000764 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000765 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000766
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000767 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000768 /// declaration.
769 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
770
Douglas Gregorebe10102009-08-20 07:17:43 +0000771 /// \brief Rebuild the exception declaration and register the declaration
772 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000773 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000774 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000775 SourceLocation StartLoc,
776 SourceLocation NameLoc,
777 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000778
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000779 /// \brief Rebuild the Objective-C exception declaration and register the
780 /// declaration as an instantiated local.
781 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
782 TypeSourceInfo *TSInfo, QualType T);
783
John McCall7f41d982009-09-11 04:59:25 +0000784 /// \brief Check for tag mismatches when instantiating an
785 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000786 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
787 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000788 NestedNameSpecifierLoc QualifierLoc,
789 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000790
Craig Topperc3ec1492014-05-26 06:22:03 +0000791 TemplateName
792 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
793 SourceLocation NameLoc,
794 QualType ObjectType = QualType(),
795 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000796
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000797 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
798
John McCalldadc5752010-08-24 06:29:42 +0000799 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
800 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
801 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000802
John McCalldadc5752010-08-24 06:29:42 +0000803 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000804 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000805 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
806 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000807
808 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
809 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
810
811 /// \brief Transform a reference to a function parameter pack.
812 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
813 ParmVarDecl *PD);
814
815 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
816 /// expand a function parameter pack reference which refers to an expanded
817 /// pack.
818 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
819
Hans Wennborge113c202014-09-18 16:01:32 +0000820 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000821 FunctionProtoTypeLoc TL) {
822 // Call the base version; it will forward to our overridden version below.
823 return inherited::TransformFunctionProtoType(TLB, TL);
824 }
825
826 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000827 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
828 FunctionProtoTypeLoc TL,
829 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000830 unsigned ThisTypeQuals,
831 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000832
Douglas Gregor715e4612011-01-14 22:40:04 +0000833 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000834 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000835 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000836 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000837
Mike Stump11289f42009-09-09 15:08:12 +0000838 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000839 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000840 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000841 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000842
Douglas Gregorada4b792011-01-14 02:55:32 +0000843 /// \brief Transforms an already-substituted template type parameter pack
844 /// into either itself (if we aren't substituting into its pack expansion)
845 /// or the appropriate substituted argument.
846 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
847 SubstTemplateTypeParmPackTypeLoc TL);
848
Richard Smith2589b9802012-07-25 03:56:55 +0000849 ExprResult TransformLambdaExpr(LambdaExpr *E) {
850 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
851 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
852 }
853
David Majnemerb1004102014-03-02 18:46:05 +0000854 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000855 TemplateParameterList *OrigTPL) {
856 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
857
858 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
859 TemplateDeclInstantiator DeclInstantiator(getSema(),
860 /* DeclContext *Owner */ Owner, TemplateArgs);
861 return DeclInstantiator.SubstTemplateParams(OrigTPL);
862 }
John McCall7c454bb2011-07-15 05:09:51 +0000863 private:
864 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
865 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000866 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000867 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000868}
Douglas Gregor04318252009-07-06 15:59:29 +0000869
Douglas Gregor5597ab42010-05-07 23:12:07 +0000870bool TemplateInstantiator::AlreadyTransformed(QualType T) {
871 if (T.isNull())
872 return true;
873
Douglas Gregor678d76c2011-07-01 01:22:09 +0000874 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000875 return false;
876
877 getSema().MarkDeclarationsReferencedInType(Loc, T);
878 return true;
879}
880
Eli Friedman8917ad52013-07-19 19:40:38 +0000881static TemplateArgument
882getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
883 assert(S.ArgumentPackSubstitutionIndex >= 0);
884 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
885 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
886 if (Arg.isPackExpansion())
887 Arg = Arg.getPackExpansionPattern();
888 return Arg;
889}
890
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000891Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000892 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000893 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000894
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000895 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000896 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000897 // If the corresponding template argument is NULL or non-existent, it's
898 // because we are performing instantiation from explicitly-specified
899 // template arguments in a function template, but there were some
900 // arguments left unspecified.
901 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
902 TTP->getPosition()))
903 return D;
904
Douglas Gregorf5500772011-01-05 15:48:55 +0000905 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
906
907 if (TTP->isParameterPack()) {
908 assert(Arg.getKind() == TemplateArgument::Pack &&
909 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000910 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000911 }
912
913 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000914 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000915 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000916 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000917 }
Mike Stump11289f42009-09-09 15:08:12 +0000918
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000919 // Fall through to find the instantiated declaration for this template
920 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000923 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000924}
925
Douglas Gregor25289362010-03-01 17:25:41 +0000926Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000927 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000928 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000929 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000930
Douglas Gregorebe10102009-08-20 07:17:43 +0000931 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
932 return Inst;
933}
934
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000935NamedDecl *
936TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
937 SourceLocation Loc) {
938 // If the first part of the nested-name-specifier was a template type
939 // parameter, instantiate that type parameter down to a tag type.
940 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
941 const TemplateTypeParmType *TTP
942 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000943
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000944 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000945 // FIXME: This needs testing w/ member access expressions.
946 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
947
948 if (TTP->isParameterPack()) {
949 assert(Arg.getKind() == TemplateArgument::Pack &&
950 "Missing argument pack");
951
Douglas Gregore1d60df2011-01-14 23:41:42 +0000952 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000953 return nullptr;
954
Eli Friedman8917ad52013-07-19 19:40:38 +0000955 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000956 }
957
958 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000959 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000960 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000961
962 if (const TagType *Tag = T->getAs<TagType>())
963 return Tag->getDecl();
964
965 // The resulting type is not a tag; complain.
966 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000967 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000968 }
969 }
970
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000971 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000972}
973
Douglas Gregorebe10102009-08-20 07:17:43 +0000974VarDecl *
975TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000976 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000977 SourceLocation StartLoc,
978 SourceLocation NameLoc,
979 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000980 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000981 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000982 if (Var)
983 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
984 return Var;
985}
986
987VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
988 TypeSourceInfo *TSInfo,
989 QualType T) {
990 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
991 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000992 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
993 return Var;
994}
995
John McCall7f41d982009-09-11 04:59:25 +0000996QualType
John McCall954b5de2010-11-04 19:04:38 +0000997TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
998 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000999 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +00001000 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +00001001 if (const TagType *TT = T->getAs<TagType>()) {
1002 TagDecl* TD = TT->getDecl();
1003
John McCall954b5de2010-11-04 19:04:38 +00001004 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +00001005
John McCall7f41d982009-09-11 04:59:25 +00001006 IdentifierInfo *Id = TD->getIdentifier();
1007
1008 // TODO: should we even warn on struct/class mismatches for this? Seems
1009 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001010 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001011 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001012 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001013 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001014 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1015 << Id
1016 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1017 TD->getKindName());
1018 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1019 }
John McCall7f41d982009-09-11 04:59:25 +00001020 }
1021 }
1022
John McCall954b5de2010-11-04 19:04:38 +00001023 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1024 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001025 QualifierLoc,
1026 T);
John McCall7f41d982009-09-11 04:59:25 +00001027}
1028
Douglas Gregor9db53502011-03-02 18:07:45 +00001029TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1030 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001031 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001032 QualType ObjectType,
1033 NamedDecl *FirstQualifierInScope) {
1034 if (TemplateTemplateParmDecl *TTP
1035 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1036 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1037 // If the corresponding template argument is NULL or non-existent, it's
1038 // because we are performing instantiation from explicitly-specified
1039 // template arguments in a function template, but there were some
1040 // arguments left unspecified.
1041 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1042 TTP->getPosition()))
1043 return Name;
1044
1045 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1046
1047 if (TTP->isParameterPack()) {
1048 assert(Arg.getKind() == TemplateArgument::Pack &&
1049 "Missing argument pack");
1050
1051 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1052 // We have the template argument pack to substitute, but we're not
1053 // actually expanding the enclosing pack expansion yet. So, just
1054 // keep the entire argument pack.
1055 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1056 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001057
1058 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001059 }
1060
1061 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001062 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001063
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001064 // We don't ever want to substitute for a qualified template name, since
1065 // the qualifier is handled separately. So, look through the qualified
1066 // template name to its underlying declaration.
1067 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1068 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001069
1070 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001071 return Template;
1072 }
1073 }
1074
1075 if (SubstTemplateTemplateParmPackStorage *SubstPack
1076 = Name.getAsSubstTemplateTemplateParmPack()) {
1077 if (getSema().ArgumentPackSubstitutionIndex == -1)
1078 return Name;
1079
Eli Friedman8917ad52013-07-19 19:40:38 +00001080 TemplateArgument Arg = SubstPack->getArgumentPack();
1081 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1082 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001083 }
1084
1085 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1086 FirstQualifierInScope);
1087}
1088
John McCalldadc5752010-08-24 06:29:42 +00001089ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001090TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001091 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001092 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001093
Wei Panc354d212013-09-16 13:57:27 +00001094 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001095}
1096
John McCalldadc5752010-08-24 06:29:42 +00001097ExprResult
John McCall13481c52010-02-06 08:42:39 +00001098TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001099 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001100 // If the corresponding template argument is NULL or non-existent, it's
1101 // because we are performing instantiation from explicitly-specified
1102 // template arguments in a function template, but there were some
1103 // arguments left unspecified.
1104 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1105 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001106 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001107
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001108 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1109 if (NTTP->isParameterPack()) {
1110 assert(Arg.getKind() == TemplateArgument::Pack &&
1111 "Missing argument pack");
1112
1113 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001114 // We have an argument pack, but we can't select a particular argument
1115 // out of it yet. Therefore, we'll build an expression to hold on to that
1116 // argument pack.
1117 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1118 E->getLocation(),
1119 NTTP->getDeclName());
1120 if (TargetType.isNull())
1121 return ExprError();
1122
1123 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1124 NTTP,
1125 E->getLocation(),
1126 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001127 }
1128
Eli Friedman8917ad52013-07-19 19:40:38 +00001129 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001130 }
Mike Stump11289f42009-09-09 15:08:12 +00001131
John McCall7c454bb2011-07-15 05:09:51 +00001132 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1133}
1134
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001135const LoopHintAttr *
1136TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1137 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1138
1139 if (TransformedExpr == LH->getValue())
1140 return LH;
1141
1142 // Generate error if there is a problem with the value.
1143 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1144 return LH;
1145
1146 // Create new LoopHintValueAttr with integral expression in place of the
1147 // non-type template parameter.
1148 return LoopHintAttr::CreateImplicit(
1149 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1150 LH->getState(), TransformedExpr, LH->getRange());
1151}
1152
John McCall7c454bb2011-07-15 05:09:51 +00001153ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1154 NonTypeTemplateParmDecl *parm,
1155 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001156 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001157 ExprResult result;
1158 QualType type;
1159
John McCall13481c52010-02-06 08:42:39 +00001160 // The template argument itself might be an expression, in which
1161 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001162 if (arg.getKind() == TemplateArgument::Expression) {
1163 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001164 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001165 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001166
Eli Friedmanb826a002012-09-26 02:36:12 +00001167 } else if (arg.getKind() == TemplateArgument::Declaration ||
1168 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001169 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001170 if (arg.getKind() == TemplateArgument::Declaration) {
1171 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001172
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001173 // Find the instantiation of the template argument. This is
1174 // required for nested templates.
1175 VD = cast_or_null<ValueDecl>(
1176 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1177 if (!VD)
1178 return ExprError();
1179 } else {
1180 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001181 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001182 }
1183
John McCall15dda372010-02-06 10:23:53 +00001184 // Derive the type we want the substituted decl to have. This had
1185 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001186 if (parm->isExpandedParameterPack()) {
1187 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1188 } else if (parm->isParameterPack() &&
1189 isa<PackExpansionType>(parm->getType())) {
1190 type = SemaRef.SubstType(
1191 cast<PackExpansionType>(parm->getType())->getPattern(),
1192 TemplateArgs, loc, parm->getDeclName());
1193 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001194 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1195 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001196 }
1197 assert(!type.isNull() && "type substitution failed for param type");
1198 assert(!type->isDependentType() && "param type still dependent");
1199 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001200
John McCall7c454bb2011-07-15 05:09:51 +00001201 if (!result.isInvalid()) type = result.get()->getType();
1202 } else {
1203 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1204
1205 // Note that this type can be different from the type of 'result',
1206 // e.g. if it's an enum type.
1207 type = arg.getIntegralType();
1208 }
1209 if (result.isInvalid()) return ExprError();
1210
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001211 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001212 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1213 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001214}
1215
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001216ExprResult
1217TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1218 SubstNonTypeTemplateParmPackExpr *E) {
1219 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1220 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001221 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001222 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001223
1224 TemplateArgument Arg = E->getArgumentPack();
1225 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001226 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1227 E->getParameterPackLocation(),
1228 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001229}
John McCall13481c52010-02-06 08:42:39 +00001230
John McCalldadc5752010-08-24 06:29:42 +00001231ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001232TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1233 SourceLocation Loc) {
1234 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1235 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1236}
1237
1238ExprResult
1239TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1240 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1241 // We can expand this parameter pack now.
1242 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1243 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1244 if (!VD)
1245 return ExprError();
1246 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1247 }
1248
1249 QualType T = TransformType(E->getType());
1250 if (T.isNull())
1251 return ExprError();
1252
1253 // Transform each of the parameter expansions into the corresponding
1254 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001255 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001256 Parms.reserve(E->getNumExpansions());
1257 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1258 I != End; ++I) {
1259 ParmVarDecl *D =
1260 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1261 if (!D)
1262 return ExprError();
1263 Parms.push_back(D);
1264 }
1265
1266 return FunctionParmPackExpr::Create(getSema().Context, T,
1267 E->getParameterPack(),
1268 E->getParameterPackLocation(), Parms);
1269}
1270
1271ExprResult
1272TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1273 ParmVarDecl *PD) {
1274 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1275 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1276 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1277 assert(Found && "no instantiation for parameter pack");
1278
1279 Decl *TransformedDecl;
1280 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001281 // If this is a reference to a function parameter pack which we can
1282 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001283 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1284 QualType T = TransformType(E->getType());
1285 if (T.isNull())
1286 return ExprError();
1287 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1288 E->getExprLoc(), *Pack);
1289 }
1290
1291 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1292 } else {
1293 TransformedDecl = Found->get<Decl*>();
1294 }
1295
1296 // We have either an unexpanded pack or a specific expansion.
1297 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1298 E->getExprLoc());
1299}
1300
1301ExprResult
John McCall13481c52010-02-06 08:42:39 +00001302TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1303 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001304
1305 // Handle references to non-type template parameters and non-type template
1306 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001307 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1308 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1309 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001310
1311 // We have a non-type template parameter that isn't fully substituted;
1312 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001313 }
Mike Stump11289f42009-09-09 15:08:12 +00001314
Richard Smithb15fe3a2012-09-12 00:56:43 +00001315 // Handle references to function parameter packs.
1316 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1317 if (PD->isParameterPack())
1318 return TransformFunctionParmPackRefExpr(E, PD);
1319
John McCall47f29ea2009-12-08 09:21:05 +00001320 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001321}
1322
John McCalldadc5752010-08-24 06:29:42 +00001323ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001324 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001325 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1326 getDescribedFunctionTemplate() &&
1327 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001328 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1329 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1330 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001331}
1332
Richard Smith2e321552014-11-12 02:00:47 +00001333template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001334QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1335 FunctionProtoTypeLoc TL,
1336 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001337 unsigned ThisTypeQuals,
1338 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001339 // We need a local instantiation scope for this function prototype.
1340 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001341 return inherited::TransformFunctionProtoType(
1342 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001343}
1344
John McCall58f10c32010-03-11 09:03:00 +00001345ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001346TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001347 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001348 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001349 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001350 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001351 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001352}
1353
Mike Stump11289f42009-09-09 15:08:12 +00001354QualType
John McCall550e0c22009-10-21 00:40:46 +00001355TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001356 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001357 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001358 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001359 // Replace the template type parameter with its corresponding
1360 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001361
1362 // If the corresponding template argument is NULL or doesn't exist, it's
1363 // because we are performing instantiation from explicitly-specified
1364 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001365 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001366 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1367 TemplateTypeParmTypeLoc NewTL
1368 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1369 NewTL.setNameLoc(TL.getNameLoc());
1370 return TL.getType();
1371 }
Mike Stump11289f42009-09-09 15:08:12 +00001372
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001373 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1374
1375 if (T->isParameterPack()) {
1376 assert(Arg.getKind() == TemplateArgument::Pack &&
1377 "Missing argument pack");
1378
1379 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001380 // We have the template argument pack, but we're not expanding the
1381 // enclosing pack expansion yet. Just save the template argument
1382 // pack for later substitution.
1383 QualType Result
1384 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1385 SubstTemplateTypeParmPackTypeLoc NewTL
1386 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1387 NewTL.setNameLoc(TL.getNameLoc());
1388 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001389 }
1390
Eli Friedman8917ad52013-07-19 19:40:38 +00001391 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001392 }
1393
1394 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001395 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001396
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001397 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001398
1399 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001400 QualType Result
1401 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1402 SubstTemplateTypeParmTypeLoc NewTL
1403 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1404 NewTL.setNameLoc(TL.getNameLoc());
1405 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001406 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001407
1408 // The template type parameter comes from an inner template (e.g.,
1409 // the template parameter list of a member template inside the
1410 // template we are instantiating). Create a new template type
1411 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001412 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001413 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1414 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1415 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1416
John McCall550e0c22009-10-21 00:40:46 +00001417 QualType Result
1418 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1419 - TemplateArgs.getNumLevels(),
1420 T->getIndex(),
1421 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001422 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001423 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1424 NewTL.setNameLoc(TL.getNameLoc());
1425 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001426}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001427
Douglas Gregorada4b792011-01-14 02:55:32 +00001428QualType
1429TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1430 TypeLocBuilder &TLB,
1431 SubstTemplateTypeParmPackTypeLoc TL) {
1432 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1433 // We aren't expanding the parameter pack, so just return ourselves.
1434 SubstTemplateTypeParmPackTypeLoc NewTL
1435 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1436 NewTL.setNameLoc(TL.getNameLoc());
1437 return TL.getType();
1438 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001439
1440 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1441 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1442 QualType Result = Arg.getAsType();
1443
Douglas Gregorada4b792011-01-14 02:55:32 +00001444 Result = getSema().Context.getSubstTemplateTypeParmType(
1445 TL.getTypePtr()->getReplacedParameter(),
1446 Result);
1447 SubstTemplateTypeParmTypeLoc NewTL
1448 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1449 NewTL.setNameLoc(TL.getNameLoc());
1450 return Result;
1451}
1452
John McCall76d824f2009-08-25 22:02:44 +00001453/// \brief Perform substitution on the type T with a given set of template
1454/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001455///
1456/// This routine substitutes the given template arguments into the
1457/// type T and produces the instantiated type.
1458///
1459/// \param T the type into which the template arguments will be
1460/// substituted. If this type is not dependent, it will be returned
1461/// immediately.
1462///
James Dennett634962f2012-06-14 21:40:34 +00001463/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001464/// substituted for the top-level template parameters within T.
1465///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001466/// \param Loc the location in the source code where this substitution
1467/// is being performed. It will typically be the location of the
1468/// declarator (if we're instantiating the type of some declaration)
1469/// or the location of the type in the source code (if, e.g., we're
1470/// instantiating the type of a cast expression).
1471///
1472/// \param Entity the name of the entity associated with a declaration
1473/// being instantiated (if any). May be empty to indicate that there
1474/// is no such entity (if, e.g., this is a type that occurs as part of
1475/// a cast expression) or that the entity has no name (e.g., an
1476/// unnamed function parameter).
1477///
1478/// \returns If the instantiation succeeds, the instantiated
1479/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001480TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001481 const MultiLevelTemplateArgumentList &Args,
1482 SourceLocation Loc,
1483 DeclarationName Entity) {
1484 assert(!ActiveTemplateInstantiations.empty() &&
1485 "Cannot perform an instantiation without some context on the "
1486 "instantiation stack");
1487
Douglas Gregor678d76c2011-07-01 01:22:09 +00001488 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001489 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001490 return T;
1491
1492 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1493 return Instantiator.TransformType(T);
1494}
1495
Douglas Gregor5499af42011-01-05 23:12:31 +00001496TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1497 const MultiLevelTemplateArgumentList &Args,
1498 SourceLocation Loc,
1499 DeclarationName Entity) {
1500 assert(!ActiveTemplateInstantiations.empty() &&
1501 "Cannot perform an instantiation without some context on the "
1502 "instantiation stack");
1503
1504 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001505 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001506
Douglas Gregor678d76c2011-07-01 01:22:09 +00001507 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001508 !TL.getType()->isVariablyModifiedType()) {
1509 // FIXME: Make a copy of the TypeLoc data here, so that we can
1510 // return a new TypeSourceInfo. Inefficient!
1511 TypeLocBuilder TLB;
1512 TLB.pushFullCopy(TL);
1513 return TLB.getTypeSourceInfo(Context, TL.getType());
1514 }
1515
1516 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1517 TypeLocBuilder TLB;
1518 TLB.reserve(TL.getFullDataSize());
1519 QualType Result = Instantiator.TransformType(TLB, TL);
1520 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001521 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001522
1523 return TLB.getTypeSourceInfo(Context, Result);
1524}
1525
John McCall609459e2009-10-21 00:58:09 +00001526/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001527QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001528 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001529 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001530 assert(!ActiveTemplateInstantiations.empty() &&
1531 "Cannot perform an instantiation without some context on the "
1532 "instantiation stack");
1533
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001534 // If T is not a dependent type or a variably-modified type, there
1535 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001536 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001537 return T;
1538
Douglas Gregord6ff3322009-08-04 16:50:30 +00001539 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1540 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001541}
Douglas Gregor463421d2009-03-03 04:44:36 +00001542
John McCallb29f78f2010-04-09 17:38:44 +00001543static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001544 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001545 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001546 return true;
1547
Abramo Bagnara6d810632010-12-14 22:11:44 +00001548 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001549 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001550 return false;
1551
David Blaikie6adc78e2013-02-18 22:06:02 +00001552 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001553 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001554 // This must be synthesized from a typedef.
1555 if (!P) continue;
1556
Nico Weberc0973372016-02-01 22:31:51 +00001557 // If there are any parameters, a new TypeSourceInfo that refers to the
1558 // instantiated parameters must be built.
1559 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001560 }
1561
1562 return false;
1563}
1564
1565/// A form of SubstType intended specifically for instantiating the
1566/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001567/// instantiation of default-argument expressions and to avoid
1568/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001569TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1570 const MultiLevelTemplateArgumentList &Args,
1571 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001572 DeclarationName Entity,
1573 CXXRecordDecl *ThisContext,
1574 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001575 assert(!ActiveTemplateInstantiations.empty() &&
1576 "Cannot perform an instantiation without some context on the "
1577 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001578
John McCallb29f78f2010-04-09 17:38:44 +00001579 if (!NeedsInstantiationAsFunctionType(T))
1580 return T;
1581
1582 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1583
1584 TypeLocBuilder TLB;
1585
1586 TypeLoc TL = T->getTypeLoc();
1587 TLB.reserve(TL.getFullDataSize());
1588
Douglas Gregor3024f072012-04-16 07:05:22 +00001589 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001590
Richard Smith2e321552014-11-12 02:00:47 +00001591 if (FunctionProtoTypeLoc Proto =
1592 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1593 // Instantiate the type, other than its exception specification. The
1594 // exception specification is instantiated in InitFunctionInstantiation
1595 // once we've built the FunctionDecl.
1596 // FIXME: Set the exception specification to EST_Uninstantiated here,
1597 // instead of rebuilding the function type again later.
1598 Result = Instantiator.TransformFunctionProtoType(
1599 TLB, Proto, ThisContext, ThisTypeQuals,
1600 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1601 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001602 } else {
1603 Result = Instantiator.TransformType(TLB, TL);
1604 }
John McCallb29f78f2010-04-09 17:38:44 +00001605 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001606 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001607
1608 return TLB.getTypeSourceInfo(Context, Result);
1609}
1610
Richard Smith2e321552014-11-12 02:00:47 +00001611void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1612 const MultiLevelTemplateArgumentList &Args) {
1613 FunctionProtoType::ExceptionSpecInfo ESI =
1614 Proto->getExtProtoInfo().ExceptionSpec;
1615 assert(ESI.Type != EST_Uninstantiated);
1616
1617 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1618 New->getDeclName());
1619
1620 SmallVector<QualType, 4> ExceptionStorage;
1621 bool Changed = false;
1622 if (Instantiator.TransformExceptionSpec(
1623 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1624 ExceptionStorage, Changed))
1625 // On error, recover by dropping the exception specification.
1626 ESI.Type = EST_None;
1627
1628 UpdateExceptionSpec(New, ESI);
1629}
1630
Douglas Gregor940bca72010-04-12 07:48:19 +00001631ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001632 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001633 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001634 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001635 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001636 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001637 TypeSourceInfo *NewDI = nullptr;
1638
Douglas Gregor5499af42011-01-05 23:12:31 +00001639 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001640 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1641
Douglas Gregor5499af42011-01-05 23:12:31 +00001642 // We have a function parameter pack. Substitute into the pattern of the
1643 // expansion.
1644 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1645 OldParm->getLocation(), OldParm->getDeclName());
1646 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001647 return nullptr;
1648
Douglas Gregor5499af42011-01-05 23:12:31 +00001649 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1650 // We still have unexpanded parameter packs, which means that
1651 // our function parameter is still a function parameter pack.
1652 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001653 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001654 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001655 } else if (ExpectParameterPack) {
1656 // We expected to get a parameter pack but didn't (because the type
1657 // itself is not a pack expansion type), so complain. This can occur when
1658 // the substitution goes through an alias template that "loses" the
1659 // pack expansion.
1660 Diag(OldParm->getLocation(),
1661 diag::err_function_parameter_pack_without_parameter_packs)
1662 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001663 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001664 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001665 } else {
1666 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1667 OldParm->getDeclName());
1668 }
1669
Douglas Gregor940bca72010-04-12 07:48:19 +00001670 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001671 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001672
1673 if (NewDI->getType()->isVoidType()) {
1674 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001675 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001676 }
1677
1678 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001679 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001680 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001681 OldParm->getIdentifier(),
1682 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001683 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001684 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001685 return nullptr;
1686
Douglas Gregor940bca72010-04-12 07:48:19 +00001687 // Mark the (new) default argument as uninstantiated (if any).
1688 if (OldParm->hasUninstantiatedDefaultArg()) {
1689 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1690 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001691 } else if (OldParm->hasUnparsedDefaultArg()) {
1692 NewParm->setUnparsedDefaultArg();
1693 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001694 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1695 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001696 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1697 // Instantiate default arguments for methods of local classes (DR1484)
1698 // and non-defining declarations.
1699 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001700 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001701 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001702 if (NewArg.isUsable()) {
1703 // It would be nice if we still had this.
1704 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1705 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1706 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001707 } else {
1708 // FIXME: if we non-lazily instantiated non-dependent default args for
1709 // non-dependent parameter types we could remove a bunch of duplicate
1710 // conversion warnings for such arguments.
1711 NewParm->setUninstantiatedDefaultArg(Arg);
1712 }
1713 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001714
1715 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001716
Douglas Gregorf3010112011-01-07 16:43:16 +00001717 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001718 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001719 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1720 } else {
1721 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001722 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001723 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001724
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001725 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1726 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001727 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001728
1729 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1730 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001731
1732 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1733
Douglas Gregor940bca72010-04-12 07:48:19 +00001734 return NewParm;
1735}
1736
Douglas Gregordd472162011-01-07 00:20:55 +00001737/// \brief Substitute the given template arguments into the given set of
1738/// parameters, producing the set of parameter types that would be generated
1739/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001740bool Sema::SubstParmTypes(
1741 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1742 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1743 const MultiLevelTemplateArgumentList &TemplateArgs,
1744 SmallVectorImpl<QualType> &ParamTypes,
1745 SmallVectorImpl<ParmVarDecl *> *OutParams,
1746 ExtParameterInfoBuilder &ParamInfos) {
Douglas Gregordd472162011-01-07 00:20:55 +00001747 assert(!ActiveTemplateInstantiations.empty() &&
1748 "Cannot perform an instantiation without some context on the "
1749 "instantiation stack");
1750
1751 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1752 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001753 return Instantiator.TransformFunctionTypeParams(
1754 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001755}
1756
John McCall76d824f2009-08-25 22:02:44 +00001757/// \brief Perform substitution on the base class specifiers of the
1758/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001759///
1760/// Produces a diagnostic and returns true on error, returns false and
1761/// attaches the instantiated base classes to the class template
1762/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001763bool
John McCall76d824f2009-08-25 22:02:44 +00001764Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1765 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001766 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001767 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001768 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001769 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001770 if (!Base.getType()->isDependentType()) {
1771 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001772 if (RD->isInvalidDecl())
1773 Instantiation->setInvalidDecl();
1774 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001775 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001776 continue;
1777 }
1778
Douglas Gregor752a5952011-01-03 22:36:02 +00001779 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001780 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001781 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001782 // This is a pack expansion. See whether we should expand it now, or
1783 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001784 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001785 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001786 Unexpanded);
1787 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001788 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001789 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001790 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1791 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001792 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001793 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001794 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001795 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001796 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001797 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001798 }
1799
1800 // If we should expand this pack expansion now, do so.
1801 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001802 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001803 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1804
Aaron Ballman574705e2014-03-13 15:41:46 +00001805 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001806 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001807 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001808 DeclarationName());
1809 if (!BaseTypeLoc) {
1810 Invalid = true;
1811 continue;
1812 }
1813
1814 if (CXXBaseSpecifier *InstantiatedBase
1815 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001816 Base.getSourceRange(),
1817 Base.isVirtual(),
1818 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001819 BaseTypeLoc,
1820 SourceLocation()))
1821 InstantiatedBases.push_back(InstantiatedBase);
1822 else
1823 Invalid = true;
1824 }
1825
1826 continue;
1827 }
1828
1829 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001830 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001831 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001832 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001833 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001834 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001835 DeclarationName());
1836 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001837 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001838 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001839 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001840 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001841 }
1842
Nick Lewycky19b9f952010-07-26 16:56:01 +00001843 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001844 Invalid = true;
1845 continue;
1846 }
1847
1848 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001849 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001850 Base.getSourceRange(),
1851 Base.isVirtual(),
1852 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001853 BaseTypeLoc,
1854 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001855 InstantiatedBases.push_back(InstantiatedBase);
1856 else
1857 Invalid = true;
1858 }
1859
Craig Topperaa700cb2015-12-27 21:55:19 +00001860 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001861 Invalid = true;
1862
1863 return Invalid;
1864}
1865
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001866// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001867namespace clang {
1868 namespace sema {
1869 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1870 const MultiLevelTemplateArgumentList &TemplateArgs);
1871 }
1872}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001873
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001874/// \brief Instantiate the definition of a class from a given pattern.
1875///
1876/// \param PointOfInstantiation The point of instantiation within the
1877/// source code.
1878///
1879/// \param Instantiation is the declaration whose definition is being
1880/// instantiated. This will be either a class template specialization
1881/// or a member class of a class template specialization.
1882///
1883/// \param Pattern is the pattern from which the instantiation
1884/// occurs. This will be either the declaration of a class template or
1885/// the declaration of a member class of a class template.
1886///
1887/// \param TemplateArgs The template arguments to be substituted into
1888/// the pattern.
1889///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001890/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001891///
1892/// \param Complain whether to complain if the class cannot be instantiated due
1893/// to the lack of a definition.
1894///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001895/// \returns true if an error occurred, false otherwise.
1896bool
1897Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1898 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001899 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001900 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001901 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001902 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001903 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00001904 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00001905 Instantiation->getInstantiatedFromMemberClass(),
1906 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001907 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001908 Pattern = PatternDef;
1909
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001910 // \brief Record the point of instantiation.
1911 if (MemberSpecializationInfo *MSInfo
1912 = Instantiation->getMemberSpecializationInfo()) {
1913 MSInfo->setTemplateSpecializationKind(TSK);
1914 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001915 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001916 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001917 Spec->setTemplateSpecializationKind(TSK);
1918 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001919 }
Richard Smitha1087602014-03-10 00:04:29 +00001920
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001921 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001922 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001923 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00001924 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Richard Smithe19b95d2016-05-26 20:23:13 +00001925 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1926 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001927
1928 // Enter the scope of this instantiation. We don't use
1929 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001930 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001931 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001932 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001933
Douglas Gregor51121572010-03-24 01:33:17 +00001934 // If this is an instantiation of a local class, merge this local
1935 // instantiation scope with the enclosing scope. Otherwise, every
1936 // instantiation of a class has its own local instantiation scope.
1937 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001938 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001939
Reid Kleckner5b640342016-02-26 19:51:02 +00001940 // All dllexported classes created during instantiation should be fully
1941 // emitted after instantiation completes. We may not be ready to emit any
1942 // delayed classes already on the stack, so save them away and put them back
1943 // later.
1944 decltype(DelayedDllExportClasses) ExportedClasses;
1945 std::swap(ExportedClasses, DelayedDllExportClasses);
1946
John McCall6602bb12010-08-01 02:01:53 +00001947 // Pull attributes from the pattern onto the instantiation.
1948 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1949
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001950 // Start the definition of this instantiation.
1951 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001952
1953 // The instantiation is visible here, even if it was first declared in an
1954 // unimported module.
1955 Instantiation->setHidden(false);
1956
1957 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001958 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001959
John McCall76d824f2009-08-25 22:02:44 +00001960 // Do substitution on the base class specifiers.
1961 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001962 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001963
Douglas Gregor869853e2010-11-10 19:44:59 +00001964 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001965 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001966 // Delay instantiation of late parsed attributes.
1967 LateInstantiatedAttrVec LateAttrs;
1968 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1969
Aaron Ballman629afae2014-03-07 19:56:05 +00001970 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001971 // Don't instantiate members not belonging in this semantic context.
1972 // e.g. for:
1973 // @code
1974 // template <int i> class A {
1975 // class B *g;
1976 // };
1977 // @endcode
1978 // 'class B' has the template as lexical context but semantically it is
1979 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00001980 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001981 continue;
1982
Aaron Ballman629afae2014-03-07 19:56:05 +00001983 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00001984 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00001985 continue;
1986 }
1987
Aaron Ballman629afae2014-03-07 19:56:05 +00001988 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001989 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00001990 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00001991 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00001992 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
1993 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1994 // specialization causes the implicit instantiation of the definitions
1995 // of unscoped member enumerations.
1996 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00001997 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
1998 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00001999 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2000 assert(MSInfo && "no spec info for member enum specialization");
2001 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2002 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2003 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002004 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2005 if (SA->isFailed()) {
2006 // A static_assert failed. Bail out; instantiating this
2007 // class is probably not meaningful.
2008 Instantiation->setInvalidDecl();
2009 break;
2010 }
Richard Smith7d137e32012-03-23 03:33:32 +00002011 }
2012
2013 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002014 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002015 } else {
2016 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002017 // instantiations was a semantic disaster, and we'll want to mark the
2018 // declaration invalid.
2019 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002020 }
2021 }
2022
2023 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002024 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2025 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002026 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002027
Reid Kleckner93f661a2015-03-17 21:51:43 +00002028 // Default arguments are parsed, if not instantiated. We can go instantiate
2029 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002030 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002031
Reid Kleckner5b640342016-02-26 19:51:02 +00002032 // Put back the delayed exported classes that we moved out of the way.
2033 std::swap(ExportedClasses, DelayedDllExportClasses);
2034
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002035 // Instantiate late parsed attributes, and attach them to their decls.
2036 // See Sema::InstantiateAttrs
2037 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2038 E = LateAttrs.end(); I != E; ++I) {
2039 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2040 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002041
2042 // Allow 'this' within late-parsed attributes.
2043 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2044 CXXRecordDecl *ThisContext =
2045 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2046 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2047 ND && ND->isCXXInstanceMember());
2048
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002049 Attr *NewAttr =
2050 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2051 I->NewDecl->addAttr(NewAttr);
2052 LocalInstantiationScope::deleteScopes(I->Scope,
2053 Instantiator.getStartingScope());
2054 }
2055 Instantiator.disableLateAttributeInstantiation();
2056 LateAttrs.clear();
2057
Richard Smithd3b5c9082012-07-27 04:22:15 +00002058 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002059
Richard Smitha1087602014-03-10 00:04:29 +00002060 // FIXME: We should do something similar for explicit instantiations so they
2061 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002062 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002063 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002064 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002065 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002066 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002067
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002068 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002069 // Perform any dependent diagnostics from the pattern.
2070 PerformDependentDiagnostics(Pattern, TemplateArgs);
2071
Douglas Gregor869853e2010-11-10 19:44:59 +00002072 // Instantiate any out-of-line class template partial
2073 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002074 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002075 P = Instantiator.delayed_partial_spec_begin(),
2076 PEnd = Instantiator.delayed_partial_spec_end();
2077 P != PEnd; ++P) {
2078 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002079 P->first, P->second)) {
2080 Instantiation->setInvalidDecl();
2081 break;
2082 }
2083 }
2084
2085 // Instantiate any out-of-line variable template partial
2086 // specializations now.
2087 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2088 P = Instantiator.delayed_var_partial_spec_begin(),
2089 PEnd = Instantiator.delayed_var_partial_spec_end();
2090 P != PEnd; ++P) {
2091 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2092 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002093 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002094 break;
2095 }
2096 }
2097 }
2098
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002099 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002100 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002101
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002102 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002103 Consumer.HandleTagDeclDefinition(Instantiation);
2104
Douglas Gregor88d292c2010-05-13 16:44:06 +00002105 // Always emit the vtable for an explicit instantiation definition
2106 // of a polymorphic class template specialization.
2107 if (TSK == TSK_ExplicitInstantiationDefinition)
2108 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2109 }
2110
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002111 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002112}
2113
Richard Smith4b38ded2012-03-14 23:13:10 +00002114/// \brief Instantiate the definition of an enum from a given pattern.
2115///
2116/// \param PointOfInstantiation The point of instantiation within the
2117/// source code.
2118/// \param Instantiation is the declaration whose definition is being
2119/// instantiated. This will be a member enumeration of a class
2120/// temploid specialization, or a local enumeration within a
2121/// function temploid specialization.
2122/// \param Pattern The templated declaration from which the instantiation
2123/// occurs.
2124/// \param TemplateArgs The template arguments to be substituted into
2125/// the pattern.
2126/// \param TSK The kind of implicit or explicit instantiation to perform.
2127///
2128/// \return \c true if an error occurred, \c false otherwise.
2129bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2130 EnumDecl *Instantiation, EnumDecl *Pattern,
2131 const MultiLevelTemplateArgumentList &TemplateArgs,
2132 TemplateSpecializationKind TSK) {
2133 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002134 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002135 Instantiation->getInstantiatedFromMemberEnum(),
2136 Pattern, PatternDef, TSK,/*Complain*/true))
2137 return true;
2138 Pattern = PatternDef;
2139
2140 // Record the point of instantiation.
2141 if (MemberSpecializationInfo *MSInfo
2142 = Instantiation->getMemberSpecializationInfo()) {
2143 MSInfo->setTemplateSpecializationKind(TSK);
2144 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2145 }
2146
2147 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002148 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002149 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002150 if (Inst.isAlreadyInstantiating())
2151 return false;
Richard Smithe19b95d2016-05-26 20:23:13 +00002152 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2153 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002154
Richard Smitha1087602014-03-10 00:04:29 +00002155 // The instantiation is visible here, even if it was first declared in an
2156 // unimported module.
2157 Instantiation->setHidden(false);
2158
Richard Smith4b38ded2012-03-14 23:13:10 +00002159 // Enter the scope of this instantiation. We don't use
2160 // PushDeclContext because we don't have a scope.
2161 ContextRAII SavedContext(*this, Instantiation);
2162 EnterExpressionEvaluationContext EvalContext(*this,
2163 Sema::PotentiallyEvaluated);
2164
2165 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2166
2167 // Pull attributes from the pattern onto the instantiation.
2168 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2169
2170 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2171 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2172
2173 // Exit the scope of this instantiation.
2174 SavedContext.pop();
2175
2176 return Instantiation->isInvalidDecl();
2177}
2178
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002179
2180/// \brief Instantiate the definition of a field from the given pattern.
2181///
2182/// \param PointOfInstantiation The point of instantiation within the
2183/// source code.
2184/// \param Instantiation is the declaration whose definition is being
2185/// instantiated. This will be a class of a class temploid
2186/// specialization, or a local enumeration within a function temploid
2187/// specialization.
2188/// \param Pattern The templated declaration from which the instantiation
2189/// occurs.
2190/// \param TemplateArgs The template arguments to be substituted into
2191/// the pattern.
2192///
2193/// \return \c true if an error occurred, \c false otherwise.
2194bool Sema::InstantiateInClassInitializer(
2195 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2196 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2197 // If there is no initializer, we don't need to do anything.
2198 if (!Pattern->hasInClassInitializer())
2199 return false;
2200
2201 assert(Instantiation->getInClassInitStyle() ==
2202 Pattern->getInClassInitStyle() &&
2203 "pattern and instantiation disagree about init style");
2204
2205 // Error out if we haven't parsed the initializer of the pattern yet because
2206 // we are waiting for the closing brace of the outer class.
2207 Expr *OldInit = Pattern->getInClassInitializer();
2208 if (!OldInit) {
2209 RecordDecl *PatternRD = Pattern->getParent();
2210 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002211 Diag(PointOfInstantiation,
2212 diag::err_in_class_initializer_not_yet_parsed)
2213 << OutermostClass << Pattern;
2214 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002215 Instantiation->setInvalidDecl();
2216 return true;
2217 }
2218
2219 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2220 if (Inst.isInvalid())
2221 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002222 if (Inst.isAlreadyInstantiating()) {
2223 // Error out if we hit an instantiation cycle for this initializer.
2224 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2225 << Instantiation;
2226 return true;
2227 }
Richard Smithe19b95d2016-05-26 20:23:13 +00002228 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2229 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002230
2231 // Enter the scope of this instantiation. We don't use PushDeclContext because
2232 // we don't have a scope.
2233 ContextRAII SavedContext(*this, Instantiation->getParent());
2234 EnterExpressionEvaluationContext EvalContext(*this,
2235 Sema::PotentiallyEvaluated);
2236
Serge Pavlov907233f2015-04-28 17:58:47 +00002237 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002238
2239 // Instantiate the initializer.
2240 ActOnStartCXXInClassMemberInitializer();
2241 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2242
2243 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2244 /*CXXDirectInit=*/false);
2245 Expr *Init = NewInit.get();
2246 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2247 ActOnFinishCXXInClassMemberInitializer(
2248 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2249
Richard Smith4b054b22016-08-24 21:25:37 +00002250 if (auto *L = getASTMutationListener())
2251 L->DefaultMemberInitializerInstantiated(Instantiation);
2252
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002253 // Exit the scope of this instantiation.
2254 SavedContext.pop();
2255
2256 // Return true if the in-class initializer is still missing.
2257 return !Instantiation->getInClassInitializer();
2258}
2259
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002260namespace {
2261 /// \brief A partial specialization whose template arguments have matched
2262 /// a given template-id.
2263 struct PartialSpecMatchResult {
2264 ClassTemplatePartialSpecializationDecl *Partial;
2265 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002266 };
2267}
2268
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002269bool Sema::InstantiateClassTemplateSpecialization(
2270 SourceLocation PointOfInstantiation,
2271 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2272 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002273 // Perform the actual instantiation on the canonical declaration.
2274 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002275 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor00a511f2009-09-15 16:51:42 +00002276 if (ClassTemplateSpec->isInvalidDecl())
2277 return true;
2278
Douglas Gregor463421d2009-03-03 04:44:36 +00002279 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002280 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002281
Douglas Gregor170bc422009-06-12 22:31:52 +00002282 // C++ [temp.class.spec.match]p1:
2283 // When a class template is used in a context that requires an
2284 // instantiation of the class, it is necessary to determine
2285 // whether the instantiation is to be generated using the primary
2286 // template or one of the partial specializations. This is done by
2287 // matching the template arguments of the class template
2288 // specialization with the template argument lists of the partial
2289 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002290 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002291 SmallVector<MatchResult, 4> Matched;
2292 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002293 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002294 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002295 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2296 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002297 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002298 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002299 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002300 ClassTemplateSpec->getTemplateArgs(),
2301 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002302 // Store the failed-deduction information for use in diagnostics, later.
2303 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002304 FailedCandidates.addCandidate().set(
2305 DeclAccessPair::make(Template, AS_public), Partial,
2306 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002307 (void)Result;
2308 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002309 Matched.push_back(PartialSpecMatchResult());
2310 Matched.back().Partial = Partial;
2311 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002312 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002313 }
2314
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002315 // If we're dealing with a member template where the template parameters
2316 // have been instantiated, this provides the original template parameters
2317 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002318
Douglas Gregor21610382009-10-29 00:04:11 +00002319 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002320 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002321 if (Matched.size() == 1) {
2322 // -- If exactly one matching specialization is found, the
2323 // instantiation is generated from that specialization.
2324 // We don't need to do anything for this.
2325 } else {
2326 // -- If more than one matching specialization is found, the
2327 // partial order rules (14.5.4.2) are used to determine
2328 // whether one of the specializations is more specialized
2329 // than the others. If none of the specializations is more
2330 // specialized than all of the other matching
2331 // specializations, then the use of the class template is
2332 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002333 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2334 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002335 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002336 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002337 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002338 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002339 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002340 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002341
Douglas Gregor21610382009-10-29 00:04:11 +00002342 // Determine if the best partial specialization is more specialized than
2343 // the others.
2344 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002345 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2346 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002347 P != PEnd; ++P) {
2348 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002349 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002350 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002351 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002352 Ambiguous = true;
2353 break;
2354 }
2355 }
2356
2357 if (Ambiguous) {
2358 // Partial ordering did not produce a clear winner. Complain.
2359 ClassTemplateSpec->setInvalidDecl();
2360 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2361 << ClassTemplateSpec;
2362
2363 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002364 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2365 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002366 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002367 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2368 << getTemplateArgumentBindingsText(
2369 P->Partial->getTemplateParameters(),
2370 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002371
Douglas Gregor21610382009-10-29 00:04:11 +00002372 return true;
2373 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002374 }
2375
2376 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002377 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002378 while (OrigPartialSpec->getInstantiatedFromMember()) {
2379 // If we've found an explicit specialization of this class template,
2380 // stop here and use that as the pattern.
2381 if (OrigPartialSpec->isMemberSpecialization())
2382 break;
2383
2384 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2385 }
2386
2387 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002388 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002389 } else {
2390 // -- If no matches are found, the instantiation is generated
2391 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002392 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002393 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2394 // If we've found an explicit specialization of this class template,
2395 // stop here and use that as the pattern.
2396 if (OrigTemplate->isMemberSpecialization())
2397 break;
2398
Douglas Gregor01afeef2009-08-28 20:31:08 +00002399 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002400 }
2401
Douglas Gregor01afeef2009-08-28 20:31:08 +00002402 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002403 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002404
Douglas Gregoref6ab412009-10-27 06:26:26 +00002405 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2406 Pattern,
2407 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002408 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002409 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002410
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002411 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002412}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002413
John McCall76d824f2009-08-25 22:02:44 +00002414/// \brief Instantiates the definitions of all of the member
2415/// of the given class, which is an instantiation of a class template
2416/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002417void
2418Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002419 CXXRecordDecl *Instantiation,
2420 const MultiLevelTemplateArgumentList &TemplateArgs,
2421 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002422 // FIXME: We need to notify the ASTMutationListener that we did all of these
2423 // things, in case we have an explicit instantiation definition in a PCM, a
2424 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002425 assert(
2426 (TSK == TSK_ExplicitInstantiationDefinition ||
2427 TSK == TSK_ExplicitInstantiationDeclaration ||
2428 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2429 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002430 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002431 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002432 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002433 if (FunctionDecl *Pattern
2434 = Function->getInstantiatedFromMemberFunction()) {
2435 MemberSpecializationInfo *MSInfo
2436 = Function->getMemberSpecializationInfo();
2437 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002438 if (MSInfo->getTemplateSpecializationKind()
2439 == TSK_ExplicitSpecialization)
2440 continue;
2441
Douglas Gregor1d957a32009-10-27 18:42:08 +00002442 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2443 Function,
2444 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002445 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002446 SuppressNew) ||
2447 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002448 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002449
2450 // C++11 [temp.explicit]p8:
2451 // An explicit instantiation definition that names a class template
2452 // specialization explicitly instantiates the class template
2453 // specialization and is only an explicit instantiation definition
2454 // of members whose definition is visible at the point of
2455 // instantiation.
2456 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002457 continue;
2458
Richard Smitheb36ddf2014-04-24 22:45:46 +00002459 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2460
2461 if (Function->isDefined()) {
2462 // Let the ASTConsumer know that this function has been explicitly
2463 // instantiated now, and its linkage might have changed.
2464 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2465 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002466 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002467 } else if (TSK == TSK_ImplicitInstantiation) {
2468 PendingLocalImplicitInstantiations.push_back(
2469 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002470 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002471 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002472 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002473 if (isa<VarTemplateSpecializationDecl>(Var))
2474 continue;
2475
Douglas Gregor86d142a2009-10-08 07:24:58 +00002476 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002477 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2478 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002479 if (MSInfo->getTemplateSpecializationKind()
2480 == TSK_ExplicitSpecialization)
2481 continue;
2482
Douglas Gregor1d957a32009-10-27 18:42:08 +00002483 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2484 Var,
2485 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002486 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002487 SuppressNew) ||
2488 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002489 continue;
2490
Douglas Gregor1d957a32009-10-27 18:42:08 +00002491 if (TSK == TSK_ExplicitInstantiationDefinition) {
2492 // C++0x [temp.explicit]p8:
2493 // An explicit instantiation definition that names a class template
2494 // specialization explicitly instantiates the class template
2495 // specialization and is only an explicit instantiation definition
2496 // of members whose definition is visible at the point of
2497 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002498 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002499 continue;
2500
2501 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002502 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002503 } else {
2504 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2505 }
2506 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002507 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002508 // Always skip the injected-class-name, along with any
2509 // redeclarations of nested classes, since both would cause us
2510 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002511 // Skip closure types; they'll get instantiated when we instantiate
2512 // the corresponding lambda-expression.
2513 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2514 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002515 continue;
2516
Douglas Gregor1d957a32009-10-27 18:42:08 +00002517 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2518 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002519
2520 if (MSInfo->getTemplateSpecializationKind()
2521 == TSK_ExplicitSpecialization)
2522 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002523
Hans Wennborga86a83b2016-05-26 19:42:56 +00002524 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2525 TSK == TSK_ExplicitInstantiationDeclaration) {
2526 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2527 // affect the inner class.
2528 continue;
2529 }
2530
Douglas Gregor1d957a32009-10-27 18:42:08 +00002531 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2532 Record,
2533 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002534 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002535 SuppressNew) ||
2536 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002537 continue;
2538
Douglas Gregor1d957a32009-10-27 18:42:08 +00002539 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2540 assert(Pattern && "Missing instantiated-from-template information");
2541
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002542 if (!Record->getDefinition()) {
2543 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002544 // C++0x [temp.explicit]p8:
2545 // An explicit instantiation definition that names a class template
2546 // specialization explicitly instantiates the class template
2547 // specialization and is only an explicit instantiation definition
2548 // of members whose definition is visible at the point of
2549 // instantiation.
2550 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2551 MSInfo->setTemplateSpecializationKind(TSK);
2552 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2553 }
2554
2555 continue;
2556 }
2557
2558 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002559 TemplateArgs,
2560 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002561 } else {
2562 if (TSK == TSK_ExplicitInstantiationDefinition &&
2563 Record->getTemplateSpecializationKind() ==
2564 TSK_ExplicitInstantiationDeclaration) {
2565 Record->setTemplateSpecializationKind(TSK);
2566 MarkVTableUsed(PointOfInstantiation, Record, true);
2567 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002568 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002569
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002570 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002571 if (Pattern)
2572 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2573 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002574 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002575 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2576 assert(MSInfo && "No member specialization information?");
2577
2578 if (MSInfo->getTemplateSpecializationKind()
2579 == TSK_ExplicitSpecialization)
2580 continue;
2581
2582 if (CheckSpecializationInstantiationRedecl(
2583 PointOfInstantiation, TSK, Enum,
2584 MSInfo->getTemplateSpecializationKind(),
2585 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2586 SuppressNew)
2587 continue;
2588
2589 if (Enum->getDefinition())
2590 continue;
2591
Richard Smith6739a102016-05-05 00:56:12 +00002592 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002593 assert(Pattern && "Missing instantiated-from-template information");
2594
2595 if (TSK == TSK_ExplicitInstantiationDefinition) {
2596 if (!Pattern->getDefinition())
2597 continue;
2598
2599 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2600 } else {
2601 MSInfo->setTemplateSpecializationKind(TSK);
2602 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2603 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002604 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2605 // No need to instantiate in-class initializers during explicit
2606 // instantiation.
2607 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2608 CXXRecordDecl *ClassPattern =
2609 Instantiation->getTemplateInstantiationPattern();
2610 DeclContext::lookup_result Lookup =
2611 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002612 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002613 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2614 TemplateArgs);
2615 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002616 }
2617 }
2618}
2619
2620/// \brief Instantiate the definitions of all of the members of the
2621/// given class template specialization, which was named as part of an
2622/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002623void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002624Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002625 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002626 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2627 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002628 // C++0x [temp.explicit]p7:
2629 // An explicit instantiation that names a class template
2630 // specialization is an explicit instantion of the same kind
2631 // (declaration or definition) of each of its members (not
2632 // including members inherited from base classes) that has not
2633 // been previously explicitly specialized in the translation unit
2634 // containing the explicit instantiation, except as described
2635 // below.
2636 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002637 getTemplateInstantiationArgs(ClassTemplateSpec),
2638 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002639}
2640
John McCalldadc5752010-08-24 06:29:42 +00002641StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002642Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002643 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002644 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002645
2646 TemplateInstantiator Instantiator(*this, TemplateArgs,
2647 SourceLocation(),
2648 DeclarationName());
2649 return Instantiator.TransformStmt(S);
2650}
2651
John McCalldadc5752010-08-24 06:29:42 +00002652ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002653Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002654 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002655 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002656
Douglas Gregora16548e2009-08-11 05:31:07 +00002657 TemplateInstantiator Instantiator(*this, TemplateArgs,
2658 SourceLocation(),
2659 DeclarationName());
2660 return Instantiator.TransformExpr(E);
2661}
2662
Richard Smithd59b8322012-12-19 01:39:02 +00002663ExprResult Sema::SubstInitializer(Expr *Init,
2664 const MultiLevelTemplateArgumentList &TemplateArgs,
2665 bool CXXDirectInit) {
2666 TemplateInstantiator Instantiator(*this, TemplateArgs,
2667 SourceLocation(),
2668 DeclarationName());
2669 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2670}
2671
Craig Topper99d23532015-12-24 23:58:29 +00002672bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002673 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002674 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002675 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002676 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002677
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002678 TemplateInstantiator Instantiator(*this, TemplateArgs,
2679 SourceLocation(),
2680 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002681 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2682 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002683}
2684
Douglas Gregor14454802011-02-25 02:25:35 +00002685NestedNameSpecifierLoc
2686Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2687 const MultiLevelTemplateArgumentList &TemplateArgs) {
2688 if (!NNS)
2689 return NestedNameSpecifierLoc();
2690
2691 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2692 DeclarationName());
2693 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2694}
2695
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002696/// \brief Do template substitution on declaration name info.
2697DeclarationNameInfo
2698Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2699 const MultiLevelTemplateArgumentList &TemplateArgs) {
2700 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2701 NameInfo.getName());
2702 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2703}
2704
Douglas Gregoraa594892009-03-31 18:38:02 +00002705TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002706Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2707 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002708 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002709 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2710 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002711 CXXScopeSpec SS;
2712 SS.Adopt(QualifierLoc);
2713 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002714}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002715
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002716bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2717 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002718 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002719 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2720 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002721
2722 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002723}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002724
Richard Smith70b13042015-01-09 01:19:56 +00002725static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002726 // When storing ParmVarDecls in the local instantiation scope, we always
2727 // want to use the ParmVarDecl from the canonical function declaration,
2728 // since the map is then valid for any redeclaration or definition of that
2729 // function.
2730 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2731 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2732 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002733 // This parameter might be from a freestanding function type within the
2734 // function and isn't necessarily referring to one of FD's parameters.
2735 if (FD->getParamDecl(i) == PV)
2736 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002737 }
2738 }
2739 return D;
2740}
2741
2742
Douglas Gregorf3010112011-01-07 16:43:16 +00002743llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2744LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002745 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002746 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002747 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002748
Douglas Gregor14cf7522010-04-30 18:55:50 +00002749 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002750 const Decl *CheckD = D;
2751 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002752 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002753 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002754 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002755
2756 // If this is a tag declaration, it's possible that we need to look for
2757 // a previous declaration.
2758 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002759 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002760 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002761 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002762 } while (CheckD);
2763
Douglas Gregor14cf7522010-04-30 18:55:50 +00002764 // If we aren't combined with our outer scope, we're done.
2765 if (!Current->CombineWithOuterScope)
2766 break;
2767 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002768
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002769 // If we're performing a partial substitution during template argument
2770 // deduction, we may not have values for template parameters yet.
2771 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2772 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002773 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002774
Serge Pavlove7ad8312015-05-15 10:10:28 +00002775 // Local types referenced prior to definition may require instantiation.
2776 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2777 if (RD->isLocalClass())
2778 return nullptr;
2779
2780 // Enumeration types referenced prior to definition may appear as a result of
2781 // error recovery.
2782 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002783 return nullptr;
2784
Chris Lattnercab02a62011-02-17 20:34:02 +00002785 // If we didn't find the decl, then we either have a sema bug, or we have a
2786 // forward reference to a label declaration. Return null to indicate that
2787 // we have an uninstantiated label.
2788 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002789 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002790}
2791
John McCall19c1bfd2010-08-25 05:32:35 +00002792void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002793 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002794 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002795 if (Stored.isNull()) {
2796#ifndef NDEBUG
2797 // It should not be present in any surrounding scope either.
2798 LocalInstantiationScope *Current = this;
2799 while (Current->CombineWithOuterScope && Current->Outer) {
2800 Current = Current->Outer;
2801 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2802 "Instantiated local in inner and outer scopes");
2803 }
2804#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002805 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002806 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002807 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002808 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002809 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002810 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002811}
Douglas Gregorf3010112011-01-07 16:43:16 +00002812
James Y Knight48fefa32015-09-30 14:04:23 +00002813void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2814 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002815 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002816 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2817 Pack->push_back(Inst);
2818}
2819
2820void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002821#ifndef NDEBUG
2822 // This should be the first time we've been told about this decl.
2823 for (LocalInstantiationScope *Current = this;
2824 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2825 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2826 "Creating local pack after instantiation of local");
2827#endif
2828
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002829 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002830 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002831 DeclArgumentPack *Pack = new DeclArgumentPack;
2832 Stored = Pack;
2833 ArgumentPacks.push_back(Pack);
2834}
2835
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002836void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2837 const TemplateArgument *ExplicitArgs,
2838 unsigned NumExplicitArgs) {
2839 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2840 "Already have a partially-substituted pack");
2841 assert((!PartiallySubstitutedPack
2842 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2843 "Wrong number of arguments in partially-substituted pack");
2844 PartiallySubstitutedPack = Pack;
2845 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2846 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2847}
2848
2849NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2850 const TemplateArgument **ExplicitArgs,
2851 unsigned *NumExplicitArgs) const {
2852 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002853 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002854 if (NumExplicitArgs)
2855 *NumExplicitArgs = 0;
2856
2857 for (const LocalInstantiationScope *Current = this; Current;
2858 Current = Current->Outer) {
2859 if (Current->PartiallySubstitutedPack) {
2860 if (ExplicitArgs)
2861 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2862 if (NumExplicitArgs)
2863 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2864
2865 return Current->PartiallySubstitutedPack;
2866 }
2867
2868 if (!Current->CombineWithOuterScope)
2869 break;
2870 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002871
2872 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002873}