blob: 4e3862a14d65bed44c2bfbd59db7ba163e917c34 [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)
Douglas Gregor85673582009-05-18 17:01:57 +0000426 << Context.getTypeDeclType(Record)
427 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000428 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000429 unsigned DiagID;
430 if (Function->getPrimaryTemplate())
431 DiagID = diag::note_function_template_spec_here;
432 else
433 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000434 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000435 << Function
436 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000437 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000438 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000439 VD->isStaticDataMember()?
440 diag::note_template_static_data_member_def_here
441 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000442 << VD
443 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000444 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
445 Diags.Report(Active->PointOfInstantiation,
446 diag::note_template_enum_def_here)
447 << ED
448 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000449 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
450 Diags.Report(Active->PointOfInstantiation,
451 diag::note_template_nsdmi_here)
452 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000453 } else {
454 Diags.Report(Active->PointOfInstantiation,
455 diag::note_template_type_alias_instantiation_here)
456 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000457 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000458 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000459 break;
460 }
461
462 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Richard Smith54f18e82016-08-31 02:15:21 +0000463 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000464 SmallVector<char, 128> TemplateArgsStr;
465 llvm::raw_svector_ostream OS(TemplateArgsStr);
466 Template->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000467 TemplateSpecializationType::PrintTemplateArgumentList(
468 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000469 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000470 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000471 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000472 << Active->InstantiationRange;
473 break;
474 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000475
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000476 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000477 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000478 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000479 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000480 << FnTmpl
481 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
482 Active->TemplateArgs,
483 Active->NumTemplateArgs)
484 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000485 break;
486 }
Mike Stump11289f42009-09-09 15:08:12 +0000487
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000488 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000489 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
490 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000491 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000492 diag::note_partial_spec_deduct_instantiation_here)
493 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000494 << getTemplateArgumentBindingsText(
495 PartialSpec->getTemplateParameters(),
496 Active->TemplateArgs,
497 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000498 << Active->InstantiationRange;
499 } else {
500 FunctionTemplateDecl *FnTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000501 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000502 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000503 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000504 << FnTmpl
505 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
506 Active->TemplateArgs,
507 Active->NumTemplateArgs)
508 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000509 }
510 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000511
Anders Carlsson657bad42009-09-05 05:14:19 +0000512 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000513 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000514 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000515
Benjamin Kramer9170e912013-02-22 15:46:01 +0000516 SmallVector<char, 128> TemplateArgsStr;
517 llvm::raw_svector_ostream OS(TemplateArgsStr);
518 FD->printName(OS);
David Majnemer6fbeee32016-07-07 04:43:07 +0000519 TemplateSpecializationType::PrintTemplateArgumentList(
520 OS, Active->template_arguments(), getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000521 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000522 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000523 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000524 << Active->InstantiationRange;
525 break;
526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Douglas Gregore62e6a02009-11-11 19:13:48 +0000528 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000529 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000530 std::string Name;
531 if (!Parm->getName().empty())
532 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000533
534 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000535 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
536 TemplateParams = Template->getTemplateParameters();
537 else
538 TemplateParams =
539 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
540 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000541 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000542 diag::note_prior_template_arg_substitution)
543 << isa<TemplateTemplateParmDecl>(Parm)
544 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000545 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000546 Active->TemplateArgs,
547 Active->NumTemplateArgs)
548 << Active->InstantiationRange;
549 break;
550 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000551
552 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000553 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000554 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
555 TemplateParams = Template->getTemplateParameters();
556 else
557 TemplateParams =
558 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
559 ->getTemplateParameters();
560
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000561 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000562 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000563 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000564 Active->TemplateArgs,
565 Active->NumTemplateArgs)
566 << Active->InstantiationRange;
567 break;
568 }
Richard Smithf623c962012-04-17 00:58:00 +0000569
570 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
571 Diags.Report(Active->PointOfInstantiation,
572 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000573 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000574 << Active->InstantiationRange;
575 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000576 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000577 }
578}
579
David Blaikie05785d12013-02-20 22:23:23 +0000580Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000581 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000582 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000583
Craig Topper2341c0d2013-07-04 03:08:24 +0000584 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000585 Active = ActiveTemplateInstantiations.rbegin(),
586 ActiveEnd = ActiveTemplateInstantiations.rend();
587 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000588 ++Active)
589 {
Douglas Gregor33834512009-06-14 07:33:30 +0000590 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000591 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000592 // An instantiation of an alias template may or may not be a SFINAE
593 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000594 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000595 break;
596 // Fall through.
597 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000598 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000599 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000600 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000601
Douglas Gregor33834512009-06-14 07:33:30 +0000602 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000603 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000604 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000605 // A default template argument instantiation and substitution into
606 // template parameters with arguments for prior parameters may or may
607 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000608 break;
Mike Stump11289f42009-09-09 15:08:12 +0000609
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000610 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
611 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
612 // We're either substitution explicitly-specified template arguments
613 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000614 assert(Active->DeductionInfo && "Missing deduction info pointer");
615 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000616 }
617 }
618
David Blaikie7a30dc52013-02-21 01:47:18 +0000619 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000620}
621
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000622/// \brief Retrieve the depth and index of a parameter pack.
623static std::pair<unsigned, unsigned>
624getDepthAndIndex(NamedDecl *ND) {
625 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
626 return std::make_pair(TTP->getDepth(), TTP->getIndex());
627
628 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
629 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
630
631 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
632 return std::make_pair(TTP->getDepth(), TTP->getIndex());
633}
634
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000635//===----------------------------------------------------------------------===/
636// Template Instantiation for Types
637//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000638namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000639 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000640 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000641 SourceLocation Loc;
642 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000643
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000644 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000645 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000646
647 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000648 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000649 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000650 DeclarationName Entity)
651 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000652 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000653
Mike Stump11289f42009-09-09 15:08:12 +0000654 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000655 /// transformed.
656 ///
657 /// For the purposes of template instantiation, a type has already been
658 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000659 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000660
Douglas Gregord6ff3322009-08-04 16:50:30 +0000661 /// \brief Returns the location of the entity being instantiated, if known.
662 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000663
Douglas Gregord6ff3322009-08-04 16:50:30 +0000664 /// \brief Returns the name of the entity being instantiated, if any.
665 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000666
Douglas Gregoref6ab412009-10-27 06:26:26 +0000667 /// \brief Sets the "base" location and entity when that
668 /// information is known based on another transformation.
669 void setBase(SourceLocation Loc, DeclarationName Entity) {
670 this->Loc = Loc;
671 this->Entity = Entity;
672 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000673
674 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
675 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000676 ArrayRef<UnexpandedParameterPack> Unexpanded,
677 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000678 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000679 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
680 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000681 TemplateArgs,
682 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000683 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000684 NumExpansions);
685 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000686
Douglas Gregorf3010112011-01-07 16:43:16 +0000687 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
688 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
689 }
690
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000691 TemplateArgument ForgetPartiallySubstitutedPack() {
692 TemplateArgument Result;
693 if (NamedDecl *PartialPack
694 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
695 MultiLevelTemplateArgumentList &TemplateArgs
696 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
697 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000698 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000699 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
700 Result = TemplateArgs(Depth, Index);
701 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
702 }
703 }
704
705 return Result;
706 }
707
708 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
709 if (Arg.isNull())
710 return;
711
712 if (NamedDecl *PartialPack
713 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
714 MultiLevelTemplateArgumentList &TemplateArgs
715 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
716 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000717 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000718 TemplateArgs.setArgument(Depth, Index, Arg);
719 }
720 }
721
Douglas Gregord6ff3322009-08-04 16:50:30 +0000722 /// \brief Transform the given declaration by instantiating a reference to
723 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000724 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000725
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000726 void transformAttrs(Decl *Old, Decl *New) {
727 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
728 }
729
730 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000731 // If we've instantiated the call operator of a lambda or the call
732 // operator template of a generic lambda, update the "instantiation of"
733 // information.
734 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
735 if (NewMD && isLambdaCallOperator(NewMD)) {
736 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
737 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
738 NewTD->setInstantiatedFromMemberTemplate(
739 OldMD->getDescribedFunctionTemplate());
740 else
741 NewMD->setInstantiationOfMemberFunction(OldMD,
742 TSK_ImplicitInstantiation);
743 }
744
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000745 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000746
747 // We recreated a local declaration, but not by instantiating it. There
748 // may be pending dependent diagnostics to produce.
749 if (auto *DC = dyn_cast<DeclContext>(Old))
750 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000751 }
752
Mike Stump11289f42009-09-09 15:08:12 +0000753 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000754 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000755 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000756
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000757 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000758 /// declaration.
759 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
760
Douglas Gregorebe10102009-08-20 07:17:43 +0000761 /// \brief Rebuild the exception declaration and register the declaration
762 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000763 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000764 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000765 SourceLocation StartLoc,
766 SourceLocation NameLoc,
767 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000768
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000769 /// \brief Rebuild the Objective-C exception declaration and register the
770 /// declaration as an instantiated local.
771 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
772 TypeSourceInfo *TSInfo, QualType T);
773
John McCall7f41d982009-09-11 04:59:25 +0000774 /// \brief Check for tag mismatches when instantiating an
775 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000776 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
777 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000778 NestedNameSpecifierLoc QualifierLoc,
779 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000780
Craig Topperc3ec1492014-05-26 06:22:03 +0000781 TemplateName
782 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
783 SourceLocation NameLoc,
784 QualType ObjectType = QualType(),
785 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000786
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000787 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
788
John McCalldadc5752010-08-24 06:29:42 +0000789 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
790 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
791 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000792
John McCalldadc5752010-08-24 06:29:42 +0000793 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000794 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000795 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
796 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000797
798 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
799 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
800
801 /// \brief Transform a reference to a function parameter pack.
802 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
803 ParmVarDecl *PD);
804
805 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
806 /// expand a function parameter pack reference which refers to an expanded
807 /// pack.
808 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
809
Hans Wennborge113c202014-09-18 16:01:32 +0000810 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000811 FunctionProtoTypeLoc TL) {
812 // Call the base version; it will forward to our overridden version below.
813 return inherited::TransformFunctionProtoType(TLB, TL);
814 }
815
816 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000817 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
818 FunctionProtoTypeLoc TL,
819 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000820 unsigned ThisTypeQuals,
821 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000822
Douglas Gregor715e4612011-01-14 22:40:04 +0000823 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000824 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000825 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000826 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000827
Mike Stump11289f42009-09-09 15:08:12 +0000828 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000829 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000830 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000831 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000832
Douglas Gregorada4b792011-01-14 02:55:32 +0000833 /// \brief Transforms an already-substituted template type parameter pack
834 /// into either itself (if we aren't substituting into its pack expansion)
835 /// or the appropriate substituted argument.
836 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
837 SubstTemplateTypeParmPackTypeLoc TL);
838
Richard Smith2589b9802012-07-25 03:56:55 +0000839 ExprResult TransformLambdaExpr(LambdaExpr *E) {
840 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
841 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
842 }
843
David Majnemerb1004102014-03-02 18:46:05 +0000844 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000845 TemplateParameterList *OrigTPL) {
846 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
847
848 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
849 TemplateDeclInstantiator DeclInstantiator(getSema(),
850 /* DeclContext *Owner */ Owner, TemplateArgs);
851 return DeclInstantiator.SubstTemplateParams(OrigTPL);
852 }
John McCall7c454bb2011-07-15 05:09:51 +0000853 private:
854 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
855 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000856 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000857 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000858}
Douglas Gregor04318252009-07-06 15:59:29 +0000859
Douglas Gregor5597ab42010-05-07 23:12:07 +0000860bool TemplateInstantiator::AlreadyTransformed(QualType T) {
861 if (T.isNull())
862 return true;
863
Douglas Gregor678d76c2011-07-01 01:22:09 +0000864 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000865 return false;
866
867 getSema().MarkDeclarationsReferencedInType(Loc, T);
868 return true;
869}
870
Eli Friedman8917ad52013-07-19 19:40:38 +0000871static TemplateArgument
872getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
873 assert(S.ArgumentPackSubstitutionIndex >= 0);
874 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
875 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
876 if (Arg.isPackExpansion())
877 Arg = Arg.getPackExpansionPattern();
878 return Arg;
879}
880
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000881Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000882 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000883 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000884
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000885 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000886 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000887 // If the corresponding template argument is NULL or non-existent, it's
888 // because we are performing instantiation from explicitly-specified
889 // template arguments in a function template, but there were some
890 // arguments left unspecified.
891 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
892 TTP->getPosition()))
893 return D;
894
Douglas Gregorf5500772011-01-05 15:48:55 +0000895 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
896
897 if (TTP->isParameterPack()) {
898 assert(Arg.getKind() == TemplateArgument::Pack &&
899 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000900 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000901 }
902
903 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000904 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000905 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000906 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000907 }
Mike Stump11289f42009-09-09 15:08:12 +0000908
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000909 // Fall through to find the instantiated declaration for this template
910 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000911 }
Mike Stump11289f42009-09-09 15:08:12 +0000912
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000913 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000914}
915
Douglas Gregor25289362010-03-01 17:25:41 +0000916Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000917 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000918 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000919 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000920
Douglas Gregorebe10102009-08-20 07:17:43 +0000921 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
922 return Inst;
923}
924
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000925NamedDecl *
926TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
927 SourceLocation Loc) {
928 // If the first part of the nested-name-specifier was a template type
929 // parameter, instantiate that type parameter down to a tag type.
930 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
931 const TemplateTypeParmType *TTP
932 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000933
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000934 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000935 // FIXME: This needs testing w/ member access expressions.
936 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
937
938 if (TTP->isParameterPack()) {
939 assert(Arg.getKind() == TemplateArgument::Pack &&
940 "Missing argument pack");
941
Douglas Gregore1d60df2011-01-14 23:41:42 +0000942 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000943 return nullptr;
944
Eli Friedman8917ad52013-07-19 19:40:38 +0000945 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000946 }
947
948 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000949 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000950 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000951
952 if (const TagType *Tag = T->getAs<TagType>())
953 return Tag->getDecl();
954
955 // The resulting type is not a tag; complain.
956 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000957 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000958 }
959 }
960
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000961 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000962}
963
Douglas Gregorebe10102009-08-20 07:17:43 +0000964VarDecl *
965TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000966 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000967 SourceLocation StartLoc,
968 SourceLocation NameLoc,
969 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000970 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000971 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000972 if (Var)
973 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
974 return Var;
975}
976
977VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
978 TypeSourceInfo *TSInfo,
979 QualType T) {
980 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
981 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000982 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
983 return Var;
984}
985
John McCall7f41d982009-09-11 04:59:25 +0000986QualType
John McCall954b5de2010-11-04 19:04:38 +0000987TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
988 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000989 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000990 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000991 if (const TagType *TT = T->getAs<TagType>()) {
992 TagDecl* TD = TT->getDecl();
993
John McCall954b5de2010-11-04 19:04:38 +0000994 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000995
John McCall7f41d982009-09-11 04:59:25 +0000996 IdentifierInfo *Id = TD->getIdentifier();
997
998 // TODO: should we even warn on struct/class mismatches for this? Seems
999 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +00001000 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001001 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +00001002 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +00001003 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +00001004 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1005 << Id
1006 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1007 TD->getKindName());
1008 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1009 }
John McCall7f41d982009-09-11 04:59:25 +00001010 }
1011 }
1012
John McCall954b5de2010-11-04 19:04:38 +00001013 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1014 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001015 QualifierLoc,
1016 T);
John McCall7f41d982009-09-11 04:59:25 +00001017}
1018
Douglas Gregor9db53502011-03-02 18:07:45 +00001019TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1020 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001021 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001022 QualType ObjectType,
1023 NamedDecl *FirstQualifierInScope) {
1024 if (TemplateTemplateParmDecl *TTP
1025 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1026 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1027 // If the corresponding template argument is NULL or non-existent, it's
1028 // because we are performing instantiation from explicitly-specified
1029 // template arguments in a function template, but there were some
1030 // arguments left unspecified.
1031 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1032 TTP->getPosition()))
1033 return Name;
1034
1035 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1036
1037 if (TTP->isParameterPack()) {
1038 assert(Arg.getKind() == TemplateArgument::Pack &&
1039 "Missing argument pack");
1040
1041 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1042 // We have the template argument pack to substitute, but we're not
1043 // actually expanding the enclosing pack expansion yet. So, just
1044 // keep the entire argument pack.
1045 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1046 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001047
1048 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001049 }
1050
1051 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001052 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001053
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001054 // We don't ever want to substitute for a qualified template name, since
1055 // the qualifier is handled separately. So, look through the qualified
1056 // template name to its underlying declaration.
1057 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1058 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001059
1060 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001061 return Template;
1062 }
1063 }
1064
1065 if (SubstTemplateTemplateParmPackStorage *SubstPack
1066 = Name.getAsSubstTemplateTemplateParmPack()) {
1067 if (getSema().ArgumentPackSubstitutionIndex == -1)
1068 return Name;
1069
Eli Friedman8917ad52013-07-19 19:40:38 +00001070 TemplateArgument Arg = SubstPack->getArgumentPack();
1071 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1072 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001073 }
1074
1075 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1076 FirstQualifierInScope);
1077}
1078
John McCalldadc5752010-08-24 06:29:42 +00001079ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001080TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001081 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001082 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001083
Wei Panc354d212013-09-16 13:57:27 +00001084 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001085}
1086
John McCalldadc5752010-08-24 06:29:42 +00001087ExprResult
John McCall13481c52010-02-06 08:42:39 +00001088TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001089 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001090 // If the corresponding template argument is NULL or non-existent, it's
1091 // because we are performing instantiation from explicitly-specified
1092 // template arguments in a function template, but there were some
1093 // arguments left unspecified.
1094 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1095 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001096 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001097
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001098 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1099 if (NTTP->isParameterPack()) {
1100 assert(Arg.getKind() == TemplateArgument::Pack &&
1101 "Missing argument pack");
1102
1103 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001104 // We have an argument pack, but we can't select a particular argument
1105 // out of it yet. Therefore, we'll build an expression to hold on to that
1106 // argument pack.
1107 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1108 E->getLocation(),
1109 NTTP->getDeclName());
1110 if (TargetType.isNull())
1111 return ExprError();
1112
1113 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1114 NTTP,
1115 E->getLocation(),
1116 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001117 }
1118
Eli Friedman8917ad52013-07-19 19:40:38 +00001119 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001120 }
Mike Stump11289f42009-09-09 15:08:12 +00001121
John McCall7c454bb2011-07-15 05:09:51 +00001122 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1123}
1124
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001125const LoopHintAttr *
1126TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1127 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1128
1129 if (TransformedExpr == LH->getValue())
1130 return LH;
1131
1132 // Generate error if there is a problem with the value.
1133 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1134 return LH;
1135
1136 // Create new LoopHintValueAttr with integral expression in place of the
1137 // non-type template parameter.
1138 return LoopHintAttr::CreateImplicit(
1139 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1140 LH->getState(), TransformedExpr, LH->getRange());
1141}
1142
John McCall7c454bb2011-07-15 05:09:51 +00001143ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1144 NonTypeTemplateParmDecl *parm,
1145 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001146 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001147 ExprResult result;
1148 QualType type;
1149
John McCall13481c52010-02-06 08:42:39 +00001150 // The template argument itself might be an expression, in which
1151 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001152 if (arg.getKind() == TemplateArgument::Expression) {
1153 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001154 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001155 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001156
Eli Friedmanb826a002012-09-26 02:36:12 +00001157 } else if (arg.getKind() == TemplateArgument::Declaration ||
1158 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001159 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001160 if (arg.getKind() == TemplateArgument::Declaration) {
1161 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001162
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001163 // Find the instantiation of the template argument. This is
1164 // required for nested templates.
1165 VD = cast_or_null<ValueDecl>(
1166 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1167 if (!VD)
1168 return ExprError();
1169 } else {
1170 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001171 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001172 }
1173
John McCall15dda372010-02-06 10:23:53 +00001174 // Derive the type we want the substituted decl to have. This had
1175 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001176 if (parm->isExpandedParameterPack()) {
1177 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1178 } else if (parm->isParameterPack() &&
1179 isa<PackExpansionType>(parm->getType())) {
1180 type = SemaRef.SubstType(
1181 cast<PackExpansionType>(parm->getType())->getPattern(),
1182 TemplateArgs, loc, parm->getDeclName());
1183 } else {
Richard Smith5f274382016-09-28 23:55:27 +00001184 type = SemaRef.SubstType(VD ? arg.getParamTypeForDecl() : arg.getNullPtrType(),
1185 TemplateArgs, loc, parm->getDeclName());
John McCall7c454bb2011-07-15 05:09:51 +00001186 }
1187 assert(!type.isNull() && "type substitution failed for param type");
1188 assert(!type->isDependentType() && "param type still dependent");
1189 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001190
John McCall7c454bb2011-07-15 05:09:51 +00001191 if (!result.isInvalid()) type = result.get()->getType();
1192 } else {
1193 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1194
1195 // Note that this type can be different from the type of 'result',
1196 // e.g. if it's an enum type.
1197 type = arg.getIntegralType();
1198 }
1199 if (result.isInvalid()) return ExprError();
1200
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001201 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001202 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1203 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001204}
1205
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001206ExprResult
1207TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1208 SubstNonTypeTemplateParmPackExpr *E) {
1209 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1210 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001211 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001212 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001213
1214 TemplateArgument Arg = E->getArgumentPack();
1215 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001216 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1217 E->getParameterPackLocation(),
1218 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001219}
John McCall13481c52010-02-06 08:42:39 +00001220
John McCalldadc5752010-08-24 06:29:42 +00001221ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001222TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1223 SourceLocation Loc) {
1224 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1225 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1226}
1227
1228ExprResult
1229TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1230 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1231 // We can expand this parameter pack now.
1232 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1233 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1234 if (!VD)
1235 return ExprError();
1236 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1237 }
1238
1239 QualType T = TransformType(E->getType());
1240 if (T.isNull())
1241 return ExprError();
1242
1243 // Transform each of the parameter expansions into the corresponding
1244 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001245 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001246 Parms.reserve(E->getNumExpansions());
1247 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1248 I != End; ++I) {
1249 ParmVarDecl *D =
1250 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1251 if (!D)
1252 return ExprError();
1253 Parms.push_back(D);
1254 }
1255
1256 return FunctionParmPackExpr::Create(getSema().Context, T,
1257 E->getParameterPack(),
1258 E->getParameterPackLocation(), Parms);
1259}
1260
1261ExprResult
1262TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1263 ParmVarDecl *PD) {
1264 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1265 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1266 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1267 assert(Found && "no instantiation for parameter pack");
1268
1269 Decl *TransformedDecl;
1270 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001271 // If this is a reference to a function parameter pack which we can
1272 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001273 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1274 QualType T = TransformType(E->getType());
1275 if (T.isNull())
1276 return ExprError();
1277 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1278 E->getExprLoc(), *Pack);
1279 }
1280
1281 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1282 } else {
1283 TransformedDecl = Found->get<Decl*>();
1284 }
1285
1286 // We have either an unexpanded pack or a specific expansion.
1287 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1288 E->getExprLoc());
1289}
1290
1291ExprResult
John McCall13481c52010-02-06 08:42:39 +00001292TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1293 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001294
1295 // Handle references to non-type template parameters and non-type template
1296 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001297 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1298 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1299 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001300
1301 // We have a non-type template parameter that isn't fully substituted;
1302 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
Richard Smithb15fe3a2012-09-12 00:56:43 +00001305 // Handle references to function parameter packs.
1306 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1307 if (PD->isParameterPack())
1308 return TransformFunctionParmPackRefExpr(E, PD);
1309
John McCall47f29ea2009-12-08 09:21:05 +00001310 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001311}
1312
John McCalldadc5752010-08-24 06:29:42 +00001313ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001314 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001315 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1316 getDescribedFunctionTemplate() &&
1317 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001318 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1319 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1320 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001321}
1322
Richard Smith2e321552014-11-12 02:00:47 +00001323template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001324QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1325 FunctionProtoTypeLoc TL,
1326 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001327 unsigned ThisTypeQuals,
1328 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001329 // We need a local instantiation scope for this function prototype.
1330 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001331 return inherited::TransformFunctionProtoType(
1332 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001333}
1334
John McCall58f10c32010-03-11 09:03:00 +00001335ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001336TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001337 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001338 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001339 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001340 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001341 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001342}
1343
Mike Stump11289f42009-09-09 15:08:12 +00001344QualType
John McCall550e0c22009-10-21 00:40:46 +00001345TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001346 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001347 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001348 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001349 // Replace the template type parameter with its corresponding
1350 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001351
1352 // If the corresponding template argument is NULL or doesn't exist, it's
1353 // because we are performing instantiation from explicitly-specified
1354 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001355 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001356 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1357 TemplateTypeParmTypeLoc NewTL
1358 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1359 NewTL.setNameLoc(TL.getNameLoc());
1360 return TL.getType();
1361 }
Mike Stump11289f42009-09-09 15:08:12 +00001362
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001363 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1364
1365 if (T->isParameterPack()) {
1366 assert(Arg.getKind() == TemplateArgument::Pack &&
1367 "Missing argument pack");
1368
1369 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001370 // We have the template argument pack, but we're not expanding the
1371 // enclosing pack expansion yet. Just save the template argument
1372 // pack for later substitution.
1373 QualType Result
1374 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1375 SubstTemplateTypeParmPackTypeLoc NewTL
1376 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1377 NewTL.setNameLoc(TL.getNameLoc());
1378 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001379 }
1380
Eli Friedman8917ad52013-07-19 19:40:38 +00001381 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001382 }
1383
1384 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001385 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001386
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001387 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001388
1389 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001390 QualType Result
1391 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1392 SubstTemplateTypeParmTypeLoc NewTL
1393 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1394 NewTL.setNameLoc(TL.getNameLoc());
1395 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001396 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001397
1398 // The template type parameter comes from an inner template (e.g.,
1399 // the template parameter list of a member template inside the
1400 // template we are instantiating). Create a new template type
1401 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001402 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001403 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1404 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1405 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1406
John McCall550e0c22009-10-21 00:40:46 +00001407 QualType Result
1408 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1409 - TemplateArgs.getNumLevels(),
1410 T->getIndex(),
1411 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001412 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001413 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1414 NewTL.setNameLoc(TL.getNameLoc());
1415 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001416}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001417
Douglas Gregorada4b792011-01-14 02:55:32 +00001418QualType
1419TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1420 TypeLocBuilder &TLB,
1421 SubstTemplateTypeParmPackTypeLoc TL) {
1422 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1423 // We aren't expanding the parameter pack, so just return ourselves.
1424 SubstTemplateTypeParmPackTypeLoc NewTL
1425 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1426 NewTL.setNameLoc(TL.getNameLoc());
1427 return TL.getType();
1428 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001429
1430 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1431 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1432 QualType Result = Arg.getAsType();
1433
Douglas Gregorada4b792011-01-14 02:55:32 +00001434 Result = getSema().Context.getSubstTemplateTypeParmType(
1435 TL.getTypePtr()->getReplacedParameter(),
1436 Result);
1437 SubstTemplateTypeParmTypeLoc NewTL
1438 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1439 NewTL.setNameLoc(TL.getNameLoc());
1440 return Result;
1441}
1442
John McCall76d824f2009-08-25 22:02:44 +00001443/// \brief Perform substitution on the type T with a given set of template
1444/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001445///
1446/// This routine substitutes the given template arguments into the
1447/// type T and produces the instantiated type.
1448///
1449/// \param T the type into which the template arguments will be
1450/// substituted. If this type is not dependent, it will be returned
1451/// immediately.
1452///
James Dennett634962f2012-06-14 21:40:34 +00001453/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001454/// substituted for the top-level template parameters within T.
1455///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001456/// \param Loc the location in the source code where this substitution
1457/// is being performed. It will typically be the location of the
1458/// declarator (if we're instantiating the type of some declaration)
1459/// or the location of the type in the source code (if, e.g., we're
1460/// instantiating the type of a cast expression).
1461///
1462/// \param Entity the name of the entity associated with a declaration
1463/// being instantiated (if any). May be empty to indicate that there
1464/// is no such entity (if, e.g., this is a type that occurs as part of
1465/// a cast expression) or that the entity has no name (e.g., an
1466/// unnamed function parameter).
1467///
1468/// \returns If the instantiation succeeds, the instantiated
1469/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001470TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001471 const MultiLevelTemplateArgumentList &Args,
1472 SourceLocation Loc,
1473 DeclarationName Entity) {
1474 assert(!ActiveTemplateInstantiations.empty() &&
1475 "Cannot perform an instantiation without some context on the "
1476 "instantiation stack");
1477
Douglas Gregor678d76c2011-07-01 01:22:09 +00001478 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001479 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001480 return T;
1481
1482 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1483 return Instantiator.TransformType(T);
1484}
1485
Douglas Gregor5499af42011-01-05 23:12:31 +00001486TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1487 const MultiLevelTemplateArgumentList &Args,
1488 SourceLocation Loc,
1489 DeclarationName Entity) {
1490 assert(!ActiveTemplateInstantiations.empty() &&
1491 "Cannot perform an instantiation without some context on the "
1492 "instantiation stack");
1493
1494 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001495 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001496
Douglas Gregor678d76c2011-07-01 01:22:09 +00001497 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001498 !TL.getType()->isVariablyModifiedType()) {
1499 // FIXME: Make a copy of the TypeLoc data here, so that we can
1500 // return a new TypeSourceInfo. Inefficient!
1501 TypeLocBuilder TLB;
1502 TLB.pushFullCopy(TL);
1503 return TLB.getTypeSourceInfo(Context, TL.getType());
1504 }
1505
1506 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1507 TypeLocBuilder TLB;
1508 TLB.reserve(TL.getFullDataSize());
1509 QualType Result = Instantiator.TransformType(TLB, TL);
1510 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001511 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001512
1513 return TLB.getTypeSourceInfo(Context, Result);
1514}
1515
John McCall609459e2009-10-21 00:58:09 +00001516/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001517QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001518 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001519 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001520 assert(!ActiveTemplateInstantiations.empty() &&
1521 "Cannot perform an instantiation without some context on the "
1522 "instantiation stack");
1523
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001524 // If T is not a dependent type or a variably-modified type, there
1525 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001526 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001527 return T;
1528
Douglas Gregord6ff3322009-08-04 16:50:30 +00001529 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1530 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001531}
Douglas Gregor463421d2009-03-03 04:44:36 +00001532
John McCallb29f78f2010-04-09 17:38:44 +00001533static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001534 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001535 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001536 return true;
1537
Abramo Bagnara6d810632010-12-14 22:11:44 +00001538 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001539 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001540 return false;
1541
David Blaikie6adc78e2013-02-18 22:06:02 +00001542 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001543 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001544 // This must be synthesized from a typedef.
1545 if (!P) continue;
1546
Nico Weberc0973372016-02-01 22:31:51 +00001547 // If there are any parameters, a new TypeSourceInfo that refers to the
1548 // instantiated parameters must be built.
1549 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001550 }
1551
1552 return false;
1553}
1554
1555/// A form of SubstType intended specifically for instantiating the
1556/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001557/// instantiation of default-argument expressions and to avoid
1558/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001559TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1560 const MultiLevelTemplateArgumentList &Args,
1561 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001562 DeclarationName Entity,
1563 CXXRecordDecl *ThisContext,
1564 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001565 assert(!ActiveTemplateInstantiations.empty() &&
1566 "Cannot perform an instantiation without some context on the "
1567 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001568
John McCallb29f78f2010-04-09 17:38:44 +00001569 if (!NeedsInstantiationAsFunctionType(T))
1570 return T;
1571
1572 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1573
1574 TypeLocBuilder TLB;
1575
1576 TypeLoc TL = T->getTypeLoc();
1577 TLB.reserve(TL.getFullDataSize());
1578
Douglas Gregor3024f072012-04-16 07:05:22 +00001579 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001580
Richard Smith2e321552014-11-12 02:00:47 +00001581 if (FunctionProtoTypeLoc Proto =
1582 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1583 // Instantiate the type, other than its exception specification. The
1584 // exception specification is instantiated in InitFunctionInstantiation
1585 // once we've built the FunctionDecl.
1586 // FIXME: Set the exception specification to EST_Uninstantiated here,
1587 // instead of rebuilding the function type again later.
1588 Result = Instantiator.TransformFunctionProtoType(
1589 TLB, Proto, ThisContext, ThisTypeQuals,
1590 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1591 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001592 } else {
1593 Result = Instantiator.TransformType(TLB, TL);
1594 }
John McCallb29f78f2010-04-09 17:38:44 +00001595 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001596 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001597
1598 return TLB.getTypeSourceInfo(Context, Result);
1599}
1600
Richard Smith2e321552014-11-12 02:00:47 +00001601void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1602 const MultiLevelTemplateArgumentList &Args) {
1603 FunctionProtoType::ExceptionSpecInfo ESI =
1604 Proto->getExtProtoInfo().ExceptionSpec;
1605 assert(ESI.Type != EST_Uninstantiated);
1606
1607 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1608 New->getDeclName());
1609
1610 SmallVector<QualType, 4> ExceptionStorage;
1611 bool Changed = false;
1612 if (Instantiator.TransformExceptionSpec(
1613 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1614 ExceptionStorage, Changed))
1615 // On error, recover by dropping the exception specification.
1616 ESI.Type = EST_None;
1617
1618 UpdateExceptionSpec(New, ESI);
1619}
1620
Douglas Gregor940bca72010-04-12 07:48:19 +00001621ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001622 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001623 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001624 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001625 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001626 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001627 TypeSourceInfo *NewDI = nullptr;
1628
Douglas Gregor5499af42011-01-05 23:12:31 +00001629 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001630 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1631
Douglas Gregor5499af42011-01-05 23:12:31 +00001632 // We have a function parameter pack. Substitute into the pattern of the
1633 // expansion.
1634 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1635 OldParm->getLocation(), OldParm->getDeclName());
1636 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001637 return nullptr;
1638
Douglas Gregor5499af42011-01-05 23:12:31 +00001639 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1640 // We still have unexpanded parameter packs, which means that
1641 // our function parameter is still a function parameter pack.
1642 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001643 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001644 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001645 } else if (ExpectParameterPack) {
1646 // We expected to get a parameter pack but didn't (because the type
1647 // itself is not a pack expansion type), so complain. This can occur when
1648 // the substitution goes through an alias template that "loses" the
1649 // pack expansion.
1650 Diag(OldParm->getLocation(),
1651 diag::err_function_parameter_pack_without_parameter_packs)
1652 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001653 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001654 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001655 } else {
1656 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1657 OldParm->getDeclName());
1658 }
1659
Douglas Gregor940bca72010-04-12 07:48:19 +00001660 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001661 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001662
1663 if (NewDI->getType()->isVoidType()) {
1664 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001665 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001666 }
1667
1668 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001669 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001670 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001671 OldParm->getIdentifier(),
1672 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001673 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001674 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001675 return nullptr;
1676
Douglas Gregor940bca72010-04-12 07:48:19 +00001677 // Mark the (new) default argument as uninstantiated (if any).
1678 if (OldParm->hasUninstantiatedDefaultArg()) {
1679 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1680 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001681 } else if (OldParm->hasUnparsedDefaultArg()) {
1682 NewParm->setUnparsedDefaultArg();
1683 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001684 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1685 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001686 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1687 // Instantiate default arguments for methods of local classes (DR1484)
1688 // and non-defining declarations.
1689 Sema::ContextRAII SavedContext(*this, OwningFunc);
Akira Hatanakad644e022016-12-16 03:19:41 +00001690 LocalInstantiationScope Local(*this, true);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001691 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001692 if (NewArg.isUsable()) {
1693 // It would be nice if we still had this.
1694 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1695 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1696 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001697 } else {
1698 // FIXME: if we non-lazily instantiated non-dependent default args for
1699 // non-dependent parameter types we could remove a bunch of duplicate
1700 // conversion warnings for such arguments.
1701 NewParm->setUninstantiatedDefaultArg(Arg);
1702 }
1703 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001704
1705 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001706
Douglas Gregorf3010112011-01-07 16:43:16 +00001707 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001708 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001709 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1710 } else {
1711 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001712 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001713 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001714
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001715 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1716 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001717 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001718
1719 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1720 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001721
1722 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1723
Douglas Gregor940bca72010-04-12 07:48:19 +00001724 return NewParm;
1725}
1726
Douglas Gregordd472162011-01-07 00:20:55 +00001727/// \brief Substitute the given template arguments into the given set of
1728/// parameters, producing the set of parameter types that would be generated
1729/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001730bool Sema::SubstParmTypes(
1731 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1732 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1733 const MultiLevelTemplateArgumentList &TemplateArgs,
1734 SmallVectorImpl<QualType> &ParamTypes,
1735 SmallVectorImpl<ParmVarDecl *> *OutParams,
1736 ExtParameterInfoBuilder &ParamInfos) {
Douglas Gregordd472162011-01-07 00:20:55 +00001737 assert(!ActiveTemplateInstantiations.empty() &&
1738 "Cannot perform an instantiation without some context on the "
1739 "instantiation stack");
1740
1741 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1742 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001743 return Instantiator.TransformFunctionTypeParams(
1744 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001745}
1746
John McCall76d824f2009-08-25 22:02:44 +00001747/// \brief Perform substitution on the base class specifiers of the
1748/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001749///
1750/// Produces a diagnostic and returns true on error, returns false and
1751/// attaches the instantiated base classes to the class template
1752/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001753bool
John McCall76d824f2009-08-25 22:02:44 +00001754Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1755 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001756 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001757 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001758 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001759 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001760 if (!Base.getType()->isDependentType()) {
1761 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001762 if (RD->isInvalidDecl())
1763 Instantiation->setInvalidDecl();
1764 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001765 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001766 continue;
1767 }
1768
Douglas Gregor752a5952011-01-03 22:36:02 +00001769 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001770 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001771 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001772 // This is a pack expansion. See whether we should expand it now, or
1773 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001774 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001775 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001776 Unexpanded);
1777 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001778 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001779 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001780 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1781 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001782 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001783 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001784 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001785 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001786 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001787 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001788 }
1789
1790 // If we should expand this pack expansion now, do so.
1791 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001792 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001793 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1794
Aaron Ballman574705e2014-03-13 15:41:46 +00001795 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001796 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001797 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001798 DeclarationName());
1799 if (!BaseTypeLoc) {
1800 Invalid = true;
1801 continue;
1802 }
1803
1804 if (CXXBaseSpecifier *InstantiatedBase
1805 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001806 Base.getSourceRange(),
1807 Base.isVirtual(),
1808 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001809 BaseTypeLoc,
1810 SourceLocation()))
1811 InstantiatedBases.push_back(InstantiatedBase);
1812 else
1813 Invalid = true;
1814 }
1815
1816 continue;
1817 }
1818
1819 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001820 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001821 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001822 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001823 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001824 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001825 DeclarationName());
1826 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001827 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001828 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001829 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001830 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001831 }
1832
Nick Lewycky19b9f952010-07-26 16:56:01 +00001833 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001834 Invalid = true;
1835 continue;
1836 }
1837
1838 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001839 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001840 Base.getSourceRange(),
1841 Base.isVirtual(),
1842 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001843 BaseTypeLoc,
1844 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001845 InstantiatedBases.push_back(InstantiatedBase);
1846 else
1847 Invalid = true;
1848 }
1849
Craig Topperaa700cb2015-12-27 21:55:19 +00001850 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001851 Invalid = true;
1852
1853 return Invalid;
1854}
1855
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001856// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001857namespace clang {
1858 namespace sema {
1859 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1860 const MultiLevelTemplateArgumentList &TemplateArgs);
1861 }
1862}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001863
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001864/// \brief Instantiate the definition of a class from a given pattern.
1865///
1866/// \param PointOfInstantiation The point of instantiation within the
1867/// source code.
1868///
1869/// \param Instantiation is the declaration whose definition is being
1870/// instantiated. This will be either a class template specialization
1871/// or a member class of a class template specialization.
1872///
1873/// \param Pattern is the pattern from which the instantiation
1874/// occurs. This will be either the declaration of a class template or
1875/// the declaration of a member class of a class template.
1876///
1877/// \param TemplateArgs The template arguments to be substituted into
1878/// the pattern.
1879///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001880/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001881///
1882/// \param Complain whether to complain if the class cannot be instantiated due
1883/// to the lack of a definition.
1884///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001885/// \returns true if an error occurred, false otherwise.
1886bool
1887Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1888 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001889 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001890 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001891 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001892 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001893 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Vassil Vassilevb21ee082016-08-18 22:01:25 +00001894 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00001895 Instantiation->getInstantiatedFromMemberClass(),
1896 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001897 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001898 Pattern = PatternDef;
1899
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001900 // \brief Record the point of instantiation.
1901 if (MemberSpecializationInfo *MSInfo
1902 = Instantiation->getMemberSpecializationInfo()) {
1903 MSInfo->setTemplateSpecializationKind(TSK);
1904 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001905 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001906 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001907 Spec->setTemplateSpecializationKind(TSK);
1908 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001909 }
Richard Smitha1087602014-03-10 00:04:29 +00001910
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001911 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001912 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001913 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00001914 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
Richard Smithe19b95d2016-05-26 20:23:13 +00001915 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1916 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001917
1918 // Enter the scope of this instantiation. We don't use
1919 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001920 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001921 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001922 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001923
Douglas Gregor51121572010-03-24 01:33:17 +00001924 // If this is an instantiation of a local class, merge this local
1925 // instantiation scope with the enclosing scope. Otherwise, every
1926 // instantiation of a class has its own local instantiation scope.
1927 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001928 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001929
Reid Kleckner5b640342016-02-26 19:51:02 +00001930 // All dllexported classes created during instantiation should be fully
1931 // emitted after instantiation completes. We may not be ready to emit any
1932 // delayed classes already on the stack, so save them away and put them back
1933 // later.
1934 decltype(DelayedDllExportClasses) ExportedClasses;
1935 std::swap(ExportedClasses, DelayedDllExportClasses);
1936
John McCall6602bb12010-08-01 02:01:53 +00001937 // Pull attributes from the pattern onto the instantiation.
1938 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1939
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001940 // Start the definition of this instantiation.
1941 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001942
1943 // The instantiation is visible here, even if it was first declared in an
1944 // unimported module.
1945 Instantiation->setHidden(false);
1946
1947 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001948 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001949
John McCall76d824f2009-08-25 22:02:44 +00001950 // Do substitution on the base class specifiers.
1951 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001952 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001953
Douglas Gregor869853e2010-11-10 19:44:59 +00001954 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001955 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001956 // Delay instantiation of late parsed attributes.
1957 LateInstantiatedAttrVec LateAttrs;
1958 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
1959
Aaron Ballman629afae2014-03-07 19:56:05 +00001960 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001961 // Don't instantiate members not belonging in this semantic context.
1962 // e.g. for:
1963 // @code
1964 // template <int i> class A {
1965 // class B *g;
1966 // };
1967 // @endcode
1968 // 'class B' has the template as lexical context but semantically it is
1969 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00001970 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00001971 continue;
1972
Aaron Ballman629afae2014-03-07 19:56:05 +00001973 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00001974 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00001975 continue;
1976 }
1977
Aaron Ballman629afae2014-03-07 19:56:05 +00001978 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001979 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00001980 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00001981 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00001982 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
1983 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1984 // specialization causes the implicit instantiation of the definitions
1985 // of unscoped member enumerations.
1986 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00001987 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
1988 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00001989 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
1990 assert(MSInfo && "no spec info for member enum specialization");
1991 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
1992 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1993 }
Richard Smithded9c2e2012-07-11 22:37:56 +00001994 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
1995 if (SA->isFailed()) {
1996 // A static_assert failed. Bail out; instantiating this
1997 // class is probably not meaningful.
1998 Instantiation->setInvalidDecl();
1999 break;
2000 }
Richard Smith7d137e32012-03-23 03:33:32 +00002001 }
2002
2003 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002004 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002005 } else {
2006 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002007 // instantiations was a semantic disaster, and we'll want to mark the
2008 // declaration invalid.
2009 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002010 }
2011 }
2012
2013 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002014 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2015 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002016 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002017
Reid Kleckner93f661a2015-03-17 21:51:43 +00002018 // Default arguments are parsed, if not instantiated. We can go instantiate
2019 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002020 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002021
Reid Kleckner5b640342016-02-26 19:51:02 +00002022 // Put back the delayed exported classes that we moved out of the way.
2023 std::swap(ExportedClasses, DelayedDllExportClasses);
2024
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002025 // Instantiate late parsed attributes, and attach them to their decls.
2026 // See Sema::InstantiateAttrs
2027 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2028 E = LateAttrs.end(); I != E; ++I) {
2029 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2030 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002031
2032 // Allow 'this' within late-parsed attributes.
2033 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2034 CXXRecordDecl *ThisContext =
2035 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2036 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2037 ND && ND->isCXXInstanceMember());
2038
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002039 Attr *NewAttr =
2040 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2041 I->NewDecl->addAttr(NewAttr);
2042 LocalInstantiationScope::deleteScopes(I->Scope,
2043 Instantiator.getStartingScope());
2044 }
2045 Instantiator.disableLateAttributeInstantiation();
2046 LateAttrs.clear();
2047
Richard Smithd3b5c9082012-07-27 04:22:15 +00002048 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002049
Richard Smitha1087602014-03-10 00:04:29 +00002050 // FIXME: We should do something similar for explicit instantiations so they
2051 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002052 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002053 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002054 Instantiation->setLocStart(Pattern->getInnerLocStart());
Argyrios Kyrtzidisd798c052016-07-15 18:11:33 +00002055 Instantiation->setBraceRange(Pattern->getBraceRange());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002056 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002057
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002058 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002059 // Perform any dependent diagnostics from the pattern.
2060 PerformDependentDiagnostics(Pattern, TemplateArgs);
2061
Douglas Gregor869853e2010-11-10 19:44:59 +00002062 // Instantiate any out-of-line class template partial
2063 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002064 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002065 P = Instantiator.delayed_partial_spec_begin(),
2066 PEnd = Instantiator.delayed_partial_spec_end();
2067 P != PEnd; ++P) {
2068 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002069 P->first, P->second)) {
2070 Instantiation->setInvalidDecl();
2071 break;
2072 }
2073 }
2074
2075 // Instantiate any out-of-line variable template partial
2076 // specializations now.
2077 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2078 P = Instantiator.delayed_var_partial_spec_begin(),
2079 PEnd = Instantiator.delayed_var_partial_spec_end();
2080 P != PEnd; ++P) {
2081 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2082 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002083 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002084 break;
2085 }
2086 }
2087 }
2088
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002089 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002090 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002091
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002092 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002093 Consumer.HandleTagDeclDefinition(Instantiation);
2094
Douglas Gregor88d292c2010-05-13 16:44:06 +00002095 // Always emit the vtable for an explicit instantiation definition
2096 // of a polymorphic class template specialization.
2097 if (TSK == TSK_ExplicitInstantiationDefinition)
2098 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2099 }
2100
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002101 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002102}
2103
Richard Smith4b38ded2012-03-14 23:13:10 +00002104/// \brief Instantiate the definition of an enum from a given pattern.
2105///
2106/// \param PointOfInstantiation The point of instantiation within the
2107/// source code.
2108/// \param Instantiation is the declaration whose definition is being
2109/// instantiated. This will be a member enumeration of a class
2110/// temploid specialization, or a local enumeration within a
2111/// function temploid specialization.
2112/// \param Pattern The templated declaration from which the instantiation
2113/// occurs.
2114/// \param TemplateArgs The template arguments to be substituted into
2115/// the pattern.
2116/// \param TSK The kind of implicit or explicit instantiation to perform.
2117///
2118/// \return \c true if an error occurred, \c false otherwise.
2119bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2120 EnumDecl *Instantiation, EnumDecl *Pattern,
2121 const MultiLevelTemplateArgumentList &TemplateArgs,
2122 TemplateSpecializationKind TSK) {
2123 EnumDecl *PatternDef = Pattern->getDefinition();
Vassil Vassilevb21ee082016-08-18 22:01:25 +00002124 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
Richard Smith4b38ded2012-03-14 23:13:10 +00002125 Instantiation->getInstantiatedFromMemberEnum(),
2126 Pattern, PatternDef, TSK,/*Complain*/true))
2127 return true;
2128 Pattern = PatternDef;
2129
2130 // Record the point of instantiation.
2131 if (MemberSpecializationInfo *MSInfo
2132 = Instantiation->getMemberSpecializationInfo()) {
2133 MSInfo->setTemplateSpecializationKind(TSK);
2134 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2135 }
2136
2137 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002138 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002139 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002140 if (Inst.isAlreadyInstantiating())
2141 return false;
Richard Smithe19b95d2016-05-26 20:23:13 +00002142 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2143 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002144
Richard Smitha1087602014-03-10 00:04:29 +00002145 // The instantiation is visible here, even if it was first declared in an
2146 // unimported module.
2147 Instantiation->setHidden(false);
2148
Richard Smith4b38ded2012-03-14 23:13:10 +00002149 // Enter the scope of this instantiation. We don't use
2150 // PushDeclContext because we don't have a scope.
2151 ContextRAII SavedContext(*this, Instantiation);
2152 EnterExpressionEvaluationContext EvalContext(*this,
2153 Sema::PotentiallyEvaluated);
2154
2155 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2156
2157 // Pull attributes from the pattern onto the instantiation.
2158 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2159
2160 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2161 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2162
2163 // Exit the scope of this instantiation.
2164 SavedContext.pop();
2165
2166 return Instantiation->isInvalidDecl();
2167}
2168
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002169
2170/// \brief Instantiate the definition of a field from the given pattern.
2171///
2172/// \param PointOfInstantiation The point of instantiation within the
2173/// source code.
2174/// \param Instantiation is the declaration whose definition is being
2175/// instantiated. This will be a class of a class temploid
2176/// specialization, or a local enumeration within a function temploid
2177/// specialization.
2178/// \param Pattern The templated declaration from which the instantiation
2179/// occurs.
2180/// \param TemplateArgs The template arguments to be substituted into
2181/// the pattern.
2182///
2183/// \return \c true if an error occurred, \c false otherwise.
2184bool Sema::InstantiateInClassInitializer(
2185 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2186 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2187 // If there is no initializer, we don't need to do anything.
2188 if (!Pattern->hasInClassInitializer())
2189 return false;
2190
2191 assert(Instantiation->getInClassInitStyle() ==
2192 Pattern->getInClassInitStyle() &&
2193 "pattern and instantiation disagree about init style");
2194
2195 // Error out if we haven't parsed the initializer of the pattern yet because
2196 // we are waiting for the closing brace of the outer class.
2197 Expr *OldInit = Pattern->getInClassInitializer();
2198 if (!OldInit) {
2199 RecordDecl *PatternRD = Pattern->getParent();
2200 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
Richard Smith8dbc6b22016-11-22 22:55:12 +00002201 Diag(PointOfInstantiation,
2202 diag::err_in_class_initializer_not_yet_parsed)
2203 << OutermostClass << Pattern;
2204 Diag(Pattern->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002205 Instantiation->setInvalidDecl();
2206 return true;
2207 }
2208
2209 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2210 if (Inst.isInvalid())
2211 return true;
Richard Smith54f18e82016-08-31 02:15:21 +00002212 if (Inst.isAlreadyInstantiating()) {
2213 // Error out if we hit an instantiation cycle for this initializer.
2214 Diag(PointOfInstantiation, diag::err_in_class_initializer_cycle)
2215 << Instantiation;
2216 return true;
2217 }
Richard Smithe19b95d2016-05-26 20:23:13 +00002218 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2219 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002220
2221 // Enter the scope of this instantiation. We don't use PushDeclContext because
2222 // we don't have a scope.
2223 ContextRAII SavedContext(*this, Instantiation->getParent());
2224 EnterExpressionEvaluationContext EvalContext(*this,
2225 Sema::PotentiallyEvaluated);
2226
Serge Pavlov907233f2015-04-28 17:58:47 +00002227 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002228
2229 // Instantiate the initializer.
2230 ActOnStartCXXInClassMemberInitializer();
2231 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2232
2233 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2234 /*CXXDirectInit=*/false);
2235 Expr *Init = NewInit.get();
2236 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2237 ActOnFinishCXXInClassMemberInitializer(
2238 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2239
Richard Smith4b054b22016-08-24 21:25:37 +00002240 if (auto *L = getASTMutationListener())
2241 L->DefaultMemberInitializerInstantiated(Instantiation);
2242
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002243 // Exit the scope of this instantiation.
2244 SavedContext.pop();
2245
2246 // Return true if the in-class initializer is still missing.
2247 return !Instantiation->getInClassInitializer();
2248}
2249
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002250namespace {
2251 /// \brief A partial specialization whose template arguments have matched
2252 /// a given template-id.
2253 struct PartialSpecMatchResult {
2254 ClassTemplatePartialSpecializationDecl *Partial;
2255 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002256 };
2257}
2258
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002259bool Sema::InstantiateClassTemplateSpecialization(
2260 SourceLocation PointOfInstantiation,
2261 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2262 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002263 // Perform the actual instantiation on the canonical declaration.
2264 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002265 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor00a511f2009-09-15 16:51:42 +00002266 if (ClassTemplateSpec->isInvalidDecl())
2267 return true;
2268
Douglas Gregor463421d2009-03-03 04:44:36 +00002269 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002270 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002271
Douglas Gregor170bc422009-06-12 22:31:52 +00002272 // C++ [temp.class.spec.match]p1:
2273 // When a class template is used in a context that requires an
2274 // instantiation of the class, it is necessary to determine
2275 // whether the instantiation is to be generated using the primary
2276 // template or one of the partial specializations. This is done by
2277 // matching the template arguments of the class template
2278 // specialization with the template argument lists of the partial
2279 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002280 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002281 SmallVector<MatchResult, 4> Matched;
2282 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002283 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002284 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002285 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2286 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002287 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002288 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002289 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002290 ClassTemplateSpec->getTemplateArgs(),
2291 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002292 // Store the failed-deduction information for use in diagnostics, later.
2293 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002294 FailedCandidates.addCandidate().set(
2295 DeclAccessPair::make(Template, AS_public), Partial,
2296 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002297 (void)Result;
2298 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002299 Matched.push_back(PartialSpecMatchResult());
2300 Matched.back().Partial = Partial;
2301 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002302 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002303 }
2304
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002305 // If we're dealing with a member template where the template parameters
2306 // have been instantiated, this provides the original template parameters
2307 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002308
Douglas Gregor21610382009-10-29 00:04:11 +00002309 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002310 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002311 if (Matched.size() == 1) {
2312 // -- If exactly one matching specialization is found, the
2313 // instantiation is generated from that specialization.
2314 // We don't need to do anything for this.
2315 } else {
2316 // -- If more than one matching specialization is found, the
2317 // partial order rules (14.5.4.2) are used to determine
2318 // whether one of the specializations is more specialized
2319 // than the others. If none of the specializations is more
2320 // specialized than all of the other matching
2321 // specializations, then the use of the class template is
2322 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002323 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2324 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002325 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002326 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002327 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002328 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002329 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002330 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002331
Douglas Gregor21610382009-10-29 00:04:11 +00002332 // Determine if the best partial specialization is more specialized than
2333 // the others.
2334 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002335 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2336 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002337 P != PEnd; ++P) {
2338 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002339 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002340 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002341 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002342 Ambiguous = true;
2343 break;
2344 }
2345 }
2346
2347 if (Ambiguous) {
2348 // Partial ordering did not produce a clear winner. Complain.
2349 ClassTemplateSpec->setInvalidDecl();
2350 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2351 << ClassTemplateSpec;
2352
2353 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002354 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2355 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002356 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002357 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2358 << getTemplateArgumentBindingsText(
2359 P->Partial->getTemplateParameters(),
2360 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002361
Douglas Gregor21610382009-10-29 00:04:11 +00002362 return true;
2363 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002364 }
2365
2366 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002367 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002368 while (OrigPartialSpec->getInstantiatedFromMember()) {
2369 // If we've found an explicit specialization of this class template,
2370 // stop here and use that as the pattern.
2371 if (OrigPartialSpec->isMemberSpecialization())
2372 break;
2373
2374 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2375 }
2376
2377 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002378 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002379 } else {
2380 // -- If no matches are found, the instantiation is generated
2381 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002382 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002383 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2384 // If we've found an explicit specialization of this class template,
2385 // stop here and use that as the pattern.
2386 if (OrigTemplate->isMemberSpecialization())
2387 break;
2388
Douglas Gregor01afeef2009-08-28 20:31:08 +00002389 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002390 }
2391
Douglas Gregor01afeef2009-08-28 20:31:08 +00002392 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002393 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002394
Douglas Gregoref6ab412009-10-27 06:26:26 +00002395 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2396 Pattern,
2397 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002398 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002399 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002400
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002401 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002402}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002403
John McCall76d824f2009-08-25 22:02:44 +00002404/// \brief Instantiates the definitions of all of the member
2405/// of the given class, which is an instantiation of a class template
2406/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002407void
2408Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002409 CXXRecordDecl *Instantiation,
2410 const MultiLevelTemplateArgumentList &TemplateArgs,
2411 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002412 // FIXME: We need to notify the ASTMutationListener that we did all of these
2413 // things, in case we have an explicit instantiation definition in a PCM, a
2414 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002415 assert(
2416 (TSK == TSK_ExplicitInstantiationDefinition ||
2417 TSK == TSK_ExplicitInstantiationDeclaration ||
2418 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2419 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002420 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002421 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002422 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002423 if (FunctionDecl *Pattern
2424 = Function->getInstantiatedFromMemberFunction()) {
2425 MemberSpecializationInfo *MSInfo
2426 = Function->getMemberSpecializationInfo();
2427 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002428 if (MSInfo->getTemplateSpecializationKind()
2429 == TSK_ExplicitSpecialization)
2430 continue;
2431
Douglas Gregor1d957a32009-10-27 18:42:08 +00002432 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2433 Function,
2434 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002435 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002436 SuppressNew) ||
2437 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002438 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002439
2440 // C++11 [temp.explicit]p8:
2441 // An explicit instantiation definition that names a class template
2442 // specialization explicitly instantiates the class template
2443 // specialization and is only an explicit instantiation definition
2444 // of members whose definition is visible at the point of
2445 // instantiation.
2446 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002447 continue;
2448
Richard Smitheb36ddf2014-04-24 22:45:46 +00002449 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2450
2451 if (Function->isDefined()) {
2452 // Let the ASTConsumer know that this function has been explicitly
2453 // instantiated now, and its linkage might have changed.
2454 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2455 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002456 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002457 } else if (TSK == TSK_ImplicitInstantiation) {
2458 PendingLocalImplicitInstantiations.push_back(
2459 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002460 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002461 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002462 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002463 if (isa<VarTemplateSpecializationDecl>(Var))
2464 continue;
2465
Douglas Gregor86d142a2009-10-08 07:24:58 +00002466 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002467 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2468 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002469 if (MSInfo->getTemplateSpecializationKind()
2470 == TSK_ExplicitSpecialization)
2471 continue;
2472
Douglas Gregor1d957a32009-10-27 18:42:08 +00002473 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2474 Var,
2475 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002476 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002477 SuppressNew) ||
2478 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002479 continue;
2480
Douglas Gregor1d957a32009-10-27 18:42:08 +00002481 if (TSK == TSK_ExplicitInstantiationDefinition) {
2482 // C++0x [temp.explicit]p8:
2483 // An explicit instantiation definition that names a class template
2484 // specialization explicitly instantiates the class template
2485 // specialization and is only an explicit instantiation definition
2486 // of members whose definition is visible at the point of
2487 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002488 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002489 continue;
2490
2491 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002492 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002493 } else {
2494 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2495 }
2496 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002497 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002498 // Always skip the injected-class-name, along with any
2499 // redeclarations of nested classes, since both would cause us
2500 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002501 // Skip closure types; they'll get instantiated when we instantiate
2502 // the corresponding lambda-expression.
2503 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2504 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002505 continue;
2506
Douglas Gregor1d957a32009-10-27 18:42:08 +00002507 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2508 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002509
2510 if (MSInfo->getTemplateSpecializationKind()
2511 == TSK_ExplicitSpecialization)
2512 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002513
Hans Wennborga86a83b2016-05-26 19:42:56 +00002514 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2515 TSK == TSK_ExplicitInstantiationDeclaration) {
2516 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2517 // affect the inner class.
2518 continue;
2519 }
2520
Douglas Gregor1d957a32009-10-27 18:42:08 +00002521 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2522 Record,
2523 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002524 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002525 SuppressNew) ||
2526 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002527 continue;
2528
Douglas Gregor1d957a32009-10-27 18:42:08 +00002529 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2530 assert(Pattern && "Missing instantiated-from-template information");
2531
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002532 if (!Record->getDefinition()) {
2533 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002534 // C++0x [temp.explicit]p8:
2535 // An explicit instantiation definition that names a class template
2536 // specialization explicitly instantiates the class template
2537 // specialization and is only an explicit instantiation definition
2538 // of members whose definition is visible at the point of
2539 // instantiation.
2540 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2541 MSInfo->setTemplateSpecializationKind(TSK);
2542 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2543 }
2544
2545 continue;
2546 }
2547
2548 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002549 TemplateArgs,
2550 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002551 } else {
2552 if (TSK == TSK_ExplicitInstantiationDefinition &&
2553 Record->getTemplateSpecializationKind() ==
2554 TSK_ExplicitInstantiationDeclaration) {
2555 Record->setTemplateSpecializationKind(TSK);
2556 MarkVTableUsed(PointOfInstantiation, Record, true);
2557 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002558 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002559
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002560 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002561 if (Pattern)
2562 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2563 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002564 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002565 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2566 assert(MSInfo && "No member specialization information?");
2567
2568 if (MSInfo->getTemplateSpecializationKind()
2569 == TSK_ExplicitSpecialization)
2570 continue;
2571
2572 if (CheckSpecializationInstantiationRedecl(
2573 PointOfInstantiation, TSK, Enum,
2574 MSInfo->getTemplateSpecializationKind(),
2575 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2576 SuppressNew)
2577 continue;
2578
2579 if (Enum->getDefinition())
2580 continue;
2581
Richard Smith6739a102016-05-05 00:56:12 +00002582 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002583 assert(Pattern && "Missing instantiated-from-template information");
2584
2585 if (TSK == TSK_ExplicitInstantiationDefinition) {
2586 if (!Pattern->getDefinition())
2587 continue;
2588
2589 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2590 } else {
2591 MSInfo->setTemplateSpecializationKind(TSK);
2592 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2593 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002594 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2595 // No need to instantiate in-class initializers during explicit
2596 // instantiation.
2597 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2598 CXXRecordDecl *ClassPattern =
2599 Instantiation->getTemplateInstantiationPattern();
2600 DeclContext::lookup_result Lookup =
2601 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002602 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002603 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2604 TemplateArgs);
2605 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002606 }
2607 }
2608}
2609
2610/// \brief Instantiate the definitions of all of the members of the
2611/// given class template specialization, which was named as part of an
2612/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002613void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002614Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002615 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002616 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2617 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002618 // C++0x [temp.explicit]p7:
2619 // An explicit instantiation that names a class template
2620 // specialization is an explicit instantion of the same kind
2621 // (declaration or definition) of each of its members (not
2622 // including members inherited from base classes) that has not
2623 // been previously explicitly specialized in the translation unit
2624 // containing the explicit instantiation, except as described
2625 // below.
2626 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002627 getTemplateInstantiationArgs(ClassTemplateSpec),
2628 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002629}
2630
John McCalldadc5752010-08-24 06:29:42 +00002631StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002632Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002633 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002634 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002635
2636 TemplateInstantiator Instantiator(*this, TemplateArgs,
2637 SourceLocation(),
2638 DeclarationName());
2639 return Instantiator.TransformStmt(S);
2640}
2641
John McCalldadc5752010-08-24 06:29:42 +00002642ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002643Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002644 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002645 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002646
Douglas Gregora16548e2009-08-11 05:31:07 +00002647 TemplateInstantiator Instantiator(*this, TemplateArgs,
2648 SourceLocation(),
2649 DeclarationName());
2650 return Instantiator.TransformExpr(E);
2651}
2652
Richard Smithd59b8322012-12-19 01:39:02 +00002653ExprResult Sema::SubstInitializer(Expr *Init,
2654 const MultiLevelTemplateArgumentList &TemplateArgs,
2655 bool CXXDirectInit) {
2656 TemplateInstantiator Instantiator(*this, TemplateArgs,
2657 SourceLocation(),
2658 DeclarationName());
2659 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2660}
2661
Craig Topper99d23532015-12-24 23:58:29 +00002662bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002663 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002664 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002665 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002666 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002667
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002668 TemplateInstantiator Instantiator(*this, TemplateArgs,
2669 SourceLocation(),
2670 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002671 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2672 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002673}
2674
Douglas Gregor14454802011-02-25 02:25:35 +00002675NestedNameSpecifierLoc
2676Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2677 const MultiLevelTemplateArgumentList &TemplateArgs) {
2678 if (!NNS)
2679 return NestedNameSpecifierLoc();
2680
2681 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2682 DeclarationName());
2683 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2684}
2685
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002686/// \brief Do template substitution on declaration name info.
2687DeclarationNameInfo
2688Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2689 const MultiLevelTemplateArgumentList &TemplateArgs) {
2690 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2691 NameInfo.getName());
2692 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2693}
2694
Douglas Gregoraa594892009-03-31 18:38:02 +00002695TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002696Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2697 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002698 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002699 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2700 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002701 CXXScopeSpec SS;
2702 SS.Adopt(QualifierLoc);
2703 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002704}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002705
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002706bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2707 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002708 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002709 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2710 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002711
2712 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002713}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002714
Richard Smith70b13042015-01-09 01:19:56 +00002715static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002716 // When storing ParmVarDecls in the local instantiation scope, we always
2717 // want to use the ParmVarDecl from the canonical function declaration,
2718 // since the map is then valid for any redeclaration or definition of that
2719 // function.
2720 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2721 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2722 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002723 // This parameter might be from a freestanding function type within the
2724 // function and isn't necessarily referring to one of FD's parameters.
2725 if (FD->getParamDecl(i) == PV)
2726 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002727 }
2728 }
2729 return D;
2730}
2731
2732
Douglas Gregorf3010112011-01-07 16:43:16 +00002733llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2734LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002735 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002736 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002737 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002738
Douglas Gregor14cf7522010-04-30 18:55:50 +00002739 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002740 const Decl *CheckD = D;
2741 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002742 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002743 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002744 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002745
2746 // If this is a tag declaration, it's possible that we need to look for
2747 // a previous declaration.
2748 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002749 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002750 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002751 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002752 } while (CheckD);
2753
Douglas Gregor14cf7522010-04-30 18:55:50 +00002754 // If we aren't combined with our outer scope, we're done.
2755 if (!Current->CombineWithOuterScope)
2756 break;
2757 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002758
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002759 // If we're performing a partial substitution during template argument
2760 // deduction, we may not have values for template parameters yet.
2761 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2762 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002763 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002764
Serge Pavlove7ad8312015-05-15 10:10:28 +00002765 // Local types referenced prior to definition may require instantiation.
2766 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2767 if (RD->isLocalClass())
2768 return nullptr;
2769
2770 // Enumeration types referenced prior to definition may appear as a result of
2771 // error recovery.
2772 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002773 return nullptr;
2774
Chris Lattnercab02a62011-02-17 20:34:02 +00002775 // If we didn't find the decl, then we either have a sema bug, or we have a
2776 // forward reference to a label declaration. Return null to indicate that
2777 // we have an uninstantiated label.
2778 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002779 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002780}
2781
John McCall19c1bfd2010-08-25 05:32:35 +00002782void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002783 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002784 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002785 if (Stored.isNull()) {
2786#ifndef NDEBUG
2787 // It should not be present in any surrounding scope either.
2788 LocalInstantiationScope *Current = this;
2789 while (Current->CombineWithOuterScope && Current->Outer) {
2790 Current = Current->Outer;
2791 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2792 "Instantiated local in inner and outer scopes");
2793 }
2794#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002795 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002796 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002797 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002798 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002799 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002800 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002801}
Douglas Gregorf3010112011-01-07 16:43:16 +00002802
James Y Knight48fefa32015-09-30 14:04:23 +00002803void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2804 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002805 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002806 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2807 Pack->push_back(Inst);
2808}
2809
2810void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002811#ifndef NDEBUG
2812 // This should be the first time we've been told about this decl.
2813 for (LocalInstantiationScope *Current = this;
2814 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2815 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2816 "Creating local pack after instantiation of local");
2817#endif
2818
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002819 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002820 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002821 DeclArgumentPack *Pack = new DeclArgumentPack;
2822 Stored = Pack;
2823 ArgumentPacks.push_back(Pack);
2824}
2825
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002826void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2827 const TemplateArgument *ExplicitArgs,
2828 unsigned NumExplicitArgs) {
2829 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2830 "Already have a partially-substituted pack");
2831 assert((!PartiallySubstitutedPack
2832 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2833 "Wrong number of arguments in partially-substituted pack");
2834 PartiallySubstitutedPack = Pack;
2835 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2836 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2837}
2838
2839NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2840 const TemplateArgument **ExplicitArgs,
2841 unsigned *NumExplicitArgs) const {
2842 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002843 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002844 if (NumExplicitArgs)
2845 *NumExplicitArgs = 0;
2846
2847 for (const LocalInstantiationScope *Current = this; Current;
2848 Current = Current->Outer) {
2849 if (Current->PartiallySubstitutedPack) {
2850 if (ExplicitArgs)
2851 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2852 if (NumExplicitArgs)
2853 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2854
2855 return Current->PartiallySubstitutedPack;
2856 }
2857
2858 if (!Current->CombineWithOuterScope)
2859 break;
2860 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002861
2862 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002863}