blob: ba12fcf540bdb19b65b6693efb29051a07e34e41 [file] [log] [blame]
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//===----------------------------------------------------------------------===/
8//
9// This file implements C++ template instantiation.
10//
11//===----------------------------------------------------------------------===/
12
John McCall83024632010-08-25 22:03:47 +000013#include "clang/Sema/SemaInternal.h"
Douglas Gregord6ff3322009-08-04 16:50:30 +000014#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
Faisal Vali2cba1332013-10-23 06:44:28 +000017#include "clang/AST/ASTLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/Expr.h"
20#include "clang/Basic/LangOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000021#include "clang/Sema/DeclSpec.h"
Richard Smith938f40b2011-06-11 17:19:42 +000022#include "clang/Sema/Initialization.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000023#include "clang/Sema/Lookup.h"
Richard Smithe19b95d2016-05-26 20:23:13 +000024#include "clang/Sema/PrettyDeclStackTrace.h"
John McCallde6836a2010-08-24 07:21:54 +000025#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000026#include "clang/Sema/TemplateDeduction.h"
Douglas Gregorfe1e1102009-02-27 19:31:52 +000027
28using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000029using namespace sema;
Douglas Gregorfe1e1102009-02-27 19:31:52 +000030
Douglas Gregor4ea568f2009-03-10 18:03:33 +000031//===----------------------------------------------------------------------===/
32// Template Instantiation Support
33//===----------------------------------------------------------------------===/
34
Douglas Gregor01afeef2009-08-28 20:31:08 +000035/// \brief Retrieve the template argument list(s) that should be used to
36/// instantiate the definition of the given declaration.
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000037///
38/// \param D the declaration for which we are computing template instantiation
39/// arguments.
40///
41/// \param Innermost if non-NULL, the innermost template argument list.
Douglas Gregor8c702532010-02-05 07:33:43 +000042///
43/// \param RelativeToPrimary true if we should get the template
44/// arguments relative to the primary template, even when we're
45/// dealing with a specialization. This is only relevant for function
46/// template specializations.
Douglas Gregor1bd7a942010-05-03 23:29:10 +000047///
48/// \param Pattern If non-NULL, indicates the pattern from which we will be
49/// instantiating the definition of the given declaration, \p D. This is
50/// used to determine the proper set of template instantiation arguments for
51/// friend function template specializations.
Douglas Gregora654dd82009-08-28 17:37:35 +000052MultiLevelTemplateArgumentList
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000053Sema::getTemplateInstantiationArgs(NamedDecl *D,
Douglas Gregor8c702532010-02-05 07:33:43 +000054 const TemplateArgumentList *Innermost,
Douglas Gregor1bd7a942010-05-03 23:29:10 +000055 bool RelativeToPrimary,
56 const FunctionDecl *Pattern) {
Douglas Gregora654dd82009-08-28 17:37:35 +000057 // Accumulate the set of template argument lists in this structure.
58 MultiLevelTemplateArgumentList Result;
Mike Stump11289f42009-09-09 15:08:12 +000059
Douglas Gregor36d7c5f2009-11-09 19:17:50 +000060 if (Innermost)
61 Result.addOuterTemplateArguments(Innermost);
62
Douglas Gregora654dd82009-08-28 17:37:35 +000063 DeclContext *Ctx = dyn_cast<DeclContext>(D);
Douglas Gregora51c9cc2011-05-22 00:21:10 +000064 if (!Ctx) {
Douglas Gregora654dd82009-08-28 17:37:35 +000065 Ctx = D->getDeclContext();
Larisse Voufo39a1e502013-08-06 01:03:05 +000066
67 // Add template arguments from a variable template instantiation.
68 if (VarTemplateSpecializationDecl *Spec =
69 dyn_cast<VarTemplateSpecializationDecl>(D)) {
70 // We're done when we hit an explicit specialization.
71 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
72 !isa<VarTemplatePartialSpecializationDecl>(Spec))
73 return Result;
74
75 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
76
77 // If this variable template specialization was instantiated from a
78 // specialized member that is a variable template, we're done.
79 assert(Spec->getSpecializedTemplate() && "No variable template?");
Richard Smithbeef3452014-01-16 23:39:20 +000080 llvm::PointerUnion<VarTemplateDecl*,
81 VarTemplatePartialSpecializationDecl*> Specialized
82 = Spec->getSpecializedTemplateOrPartial();
83 if (VarTemplatePartialSpecializationDecl *Partial =
84 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
85 if (Partial->isMemberSpecialization())
86 return Result;
87 } else {
88 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
89 if (Tmpl->isMemberSpecialization())
90 return Result;
91 }
Larisse Voufo39a1e502013-08-06 01:03:05 +000092 }
93
Douglas Gregor55462622011-06-15 14:20:42 +000094 // If we have a template template parameter with translation unit context,
95 // then we're performing substitution into a default template argument of
96 // this template template parameter before we've constructed the template
97 // that will own this template template parameter. In this case, we
98 // use empty template parameter lists for all of the outer templates
99 // to avoid performing any substitutions.
100 if (Ctx->isTranslationUnit()) {
101 if (TemplateTemplateParmDecl *TTP
102 = dyn_cast<TemplateTemplateParmDecl>(D)) {
103 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
Richard Smith841d8b22013-05-17 03:04:50 +0000104 Result.addOuterTemplateArguments(None);
Douglas Gregor55462622011-06-15 14:20:42 +0000105 return Result;
106 }
107 }
Douglas Gregora51c9cc2011-05-22 00:21:10 +0000108 }
109
John McCall970d5302009-08-29 03:16:09 +0000110 while (!Ctx->isFileContext()) {
Douglas Gregora654dd82009-08-28 17:37:35 +0000111 // Add template arguments from a class template instantiation.
Mike Stump11289f42009-09-09 15:08:12 +0000112 if (ClassTemplateSpecializationDecl *Spec
Douglas Gregora654dd82009-08-28 17:37:35 +0000113 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
114 // We're done when we hit an explicit specialization.
Douglas Gregor9961ce92010-07-08 18:37:38 +0000115 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
116 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
Douglas Gregora654dd82009-08-28 17:37:35 +0000117 break;
Mike Stump11289f42009-09-09 15:08:12 +0000118
Douglas Gregora654dd82009-08-28 17:37:35 +0000119 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000120
121 // If this class template specialization was instantiated from a
122 // specialized member that is a class template, we're done.
123 assert(Spec->getSpecializedTemplate() && "No class template?");
124 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
125 break;
Mike Stump11289f42009-09-09 15:08:12 +0000126 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000127 // Add template arguments from a function template specialization.
John McCall970d5302009-08-29 03:16:09 +0000128 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
Douglas Gregor8c702532010-02-05 07:33:43 +0000129 if (!RelativeToPrimary &&
Francois Pichet00c7e6c2011-08-14 03:52:19 +0000130 (Function->getTemplateSpecializationKind() ==
131 TSK_ExplicitSpecialization &&
132 !Function->getClassScopeSpecializationPattern()))
Douglas Gregorcf915552009-10-13 16:30:37 +0000133 break;
134
Douglas Gregora654dd82009-08-28 17:37:35 +0000135 if (const TemplateArgumentList *TemplateArgs
Douglas Gregorcf915552009-10-13 16:30:37 +0000136 = Function->getTemplateSpecializationArgs()) {
137 // Add the template arguments for this specialization.
Douglas Gregora654dd82009-08-28 17:37:35 +0000138 Result.addOuterTemplateArguments(TemplateArgs);
John McCall970d5302009-08-29 03:16:09 +0000139
Douglas Gregorcf915552009-10-13 16:30:37 +0000140 // If this function was instantiated from a specialized member that is
141 // a function template, we're done.
142 assert(Function->getPrimaryTemplate() && "No function template?");
143 if (Function->getPrimaryTemplate()->isMemberSpecialization())
144 break;
Faisal Vali2cba1332013-10-23 06:44:28 +0000145
146 // If this function is a generic lambda specialization, we are done.
147 if (isGenericLambdaCallOperatorSpecialization(Function))
148 break;
149
Douglas Gregor43669f82011-03-05 17:54:25 +0000150 } else if (FunctionTemplateDecl *FunTmpl
151 = Function->getDescribedFunctionTemplate()) {
152 // Add the "injected" template arguments.
Richard Smith841d8b22013-05-17 03:04:50 +0000153 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
Douglas Gregorcf915552009-10-13 16:30:37 +0000154 }
155
John McCall970d5302009-08-29 03:16:09 +0000156 // If this is a friend declaration and it declares an entity at
157 // namespace scope, take arguments from its lexical parent
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000158 // instead of its semantic parent, unless of course the pattern we're
159 // instantiating actually comes from the file's context!
John McCall970d5302009-08-29 03:16:09 +0000160 if (Function->getFriendObjectKind() &&
Douglas Gregor1bd7a942010-05-03 23:29:10 +0000161 Function->getDeclContext()->isFileContext() &&
162 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
John McCall970d5302009-08-29 03:16:09 +0000163 Ctx = Function->getLexicalDeclContext();
Douglas Gregor8c702532010-02-05 07:33:43 +0000164 RelativeToPrimary = false;
John McCall970d5302009-08-29 03:16:09 +0000165 continue;
166 }
Douglas Gregor9961ce92010-07-08 18:37:38 +0000167 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
168 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
169 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
Richard Smith841d8b22013-05-17 03:04:50 +0000170 const TemplateSpecializationType *TST =
171 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
172 Result.addOuterTemplateArguments(
173 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
Douglas Gregor9961ce92010-07-08 18:37:38 +0000174 if (ClassTemplate->isMemberSpecialization())
175 break;
176 }
Douglas Gregora654dd82009-08-28 17:37:35 +0000177 }
John McCall970d5302009-08-29 03:16:09 +0000178
179 Ctx = Ctx->getParent();
Douglas Gregor8c702532010-02-05 07:33:43 +0000180 RelativeToPrimary = false;
Douglas Gregorb4850462009-05-14 23:26:13 +0000181 }
Mike Stump11289f42009-09-09 15:08:12 +0000182
Douglas Gregora654dd82009-08-28 17:37:35 +0000183 return Result;
Douglas Gregorb4850462009-05-14 23:26:13 +0000184}
185
Douglas Gregor84d49a22009-11-11 21:54:23 +0000186bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
187 switch (Kind) {
188 case TemplateInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000189 case ExceptionSpecInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000190 case DefaultTemplateArgumentInstantiation:
191 case DefaultFunctionArgumentInstantiation:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000192 case ExplicitTemplateArgumentSubstitution:
193 case DeducedTemplateArgumentSubstitution:
194 case PriorTemplateArgumentSubstitution:
Richard Smith8a874c92012-07-08 02:38:24 +0000195 return true;
196
Douglas Gregor84d49a22009-11-11 21:54:23 +0000197 case DefaultTemplateArgumentChecking:
198 return false;
199 }
David Blaikie8a40f702012-01-17 06:56:22 +0000200
201 llvm_unreachable("Invalid InstantiationKind!");
Douglas Gregor84d49a22009-11-11 21:54:23 +0000202}
203
Benjamin Kramer7761a042015-03-06 16:36:50 +0000204Sema::InstantiatingTemplate::InstantiatingTemplate(
205 Sema &SemaRef, ActiveTemplateInstantiation::InstantiationKind Kind,
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000206 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
207 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
Benjamin Kramer7761a042015-03-06 16:36:50 +0000208 sema::TemplateDeductionInfo *DeductionInfo)
209 : SemaRef(SemaRef), SavedInNonInstantiationSFINAEContext(
210 SemaRef.InNonInstantiationSFINAEContext) {
David Majnemer8c969ea2015-01-30 05:01:23 +0000211 // Don't allow further instantiation if a fatal error has occcured. Any
212 // diagnostics we might have raised will not be visible.
213 if (SemaRef.Diags.hasFatalErrorOccurred()) {
214 Invalid = true;
215 return;
216 }
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000217 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
218 if (!Invalid) {
219 ActiveTemplateInstantiation Inst;
220 Inst.Kind = Kind;
221 Inst.PointOfInstantiation = PointOfInstantiation;
222 Inst.Entity = Entity;
223 Inst.Template = Template;
224 Inst.TemplateArgs = TemplateArgs.data();
225 Inst.NumTemplateArgs = TemplateArgs.size();
226 Inst.DeductionInfo = DeductionInfo;
227 Inst.InstantiationRange = InstantiationRange;
228 SemaRef.InNonInstantiationSFINAEContext = false;
229 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
230 if (!Inst.isInstantiationRecord())
231 ++SemaRef.NonInstantiationEntries;
232 }
233}
234
Benjamin Kramer7761a042015-03-06 16:36:50 +0000235Sema::InstantiatingTemplate::InstantiatingTemplate(
236 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
237 SourceRange InstantiationRange)
238 : InstantiatingTemplate(SemaRef,
239 ActiveTemplateInstantiation::TemplateInstantiation,
240 PointOfInstantiation, InstantiationRange, Entity) {}
Douglas Gregor79cf6032009-03-10 20:44:00 +0000241
Benjamin Kramer7761a042015-03-06 16:36:50 +0000242Sema::InstantiatingTemplate::InstantiatingTemplate(
243 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
244 ExceptionSpecification, SourceRange InstantiationRange)
245 : InstantiatingTemplate(
246 SemaRef, ActiveTemplateInstantiation::ExceptionSpecInstantiation,
247 PointOfInstantiation, InstantiationRange, Entity) {}
Richard Smithf623c962012-04-17 00:58:00 +0000248
Benjamin Kramer7761a042015-03-06 16:36:50 +0000249Sema::InstantiatingTemplate::InstantiatingTemplate(
250 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
251 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
252 : InstantiatingTemplate(
253 SemaRef,
254 ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
255 PointOfInstantiation, InstantiationRange, Template, nullptr,
256 TemplateArgs) {}
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000257
Benjamin Kramer7761a042015-03-06 16:36:50 +0000258Sema::InstantiatingTemplate::InstantiatingTemplate(
259 Sema &SemaRef, SourceLocation PointOfInstantiation,
260 FunctionTemplateDecl *FunctionTemplate,
261 ArrayRef<TemplateArgument> TemplateArgs,
262 ActiveTemplateInstantiation::InstantiationKind Kind,
263 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
264 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
265 InstantiationRange, FunctionTemplate, nullptr,
266 TemplateArgs, &DeductionInfo) {}
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000267
Benjamin Kramer7761a042015-03-06 16:36:50 +0000268Sema::InstantiatingTemplate::InstantiatingTemplate(
269 Sema &SemaRef, SourceLocation PointOfInstantiation,
270 ClassTemplatePartialSpecializationDecl *PartialSpec,
271 ArrayRef<TemplateArgument> TemplateArgs,
272 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
273 : InstantiatingTemplate(
274 SemaRef,
275 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
276 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
277 TemplateArgs, &DeductionInfo) {}
Douglas Gregor637d9982009-06-10 23:47:09 +0000278
Larisse Voufo39a1e502013-08-06 01:03:05 +0000279Sema::InstantiatingTemplate::InstantiatingTemplate(
280 Sema &SemaRef, SourceLocation PointOfInstantiation,
281 VarTemplatePartialSpecializationDecl *PartialSpec,
282 ArrayRef<TemplateArgument> TemplateArgs,
283 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
Benjamin Kramer7761a042015-03-06 16:36:50 +0000284 : InstantiatingTemplate(
285 SemaRef,
286 ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
287 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
288 TemplateArgs, &DeductionInfo) {}
Larisse Voufo39a1e502013-08-06 01:03:05 +0000289
Benjamin Kramer7761a042015-03-06 16:36:50 +0000290Sema::InstantiatingTemplate::InstantiatingTemplate(
291 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
292 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
293 : InstantiatingTemplate(
294 SemaRef,
295 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
296 PointOfInstantiation, InstantiationRange, Param, nullptr,
297 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000298
Benjamin Kramer7761a042015-03-06 16:36:50 +0000299Sema::InstantiatingTemplate::InstantiatingTemplate(
300 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
301 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
302 SourceRange InstantiationRange)
303 : InstantiatingTemplate(
304 SemaRef,
305 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
306 PointOfInstantiation, InstantiationRange, Param, Template,
307 TemplateArgs) {}
Stephan Tolksdorf232670f2014-03-13 20:34:22 +0000308
Benjamin Kramer7761a042015-03-06 16:36:50 +0000309Sema::InstantiatingTemplate::InstantiatingTemplate(
310 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
311 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
312 SourceRange InstantiationRange)
313 : InstantiatingTemplate(
314 SemaRef,
315 ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
316 PointOfInstantiation, InstantiationRange, Param, Template,
317 TemplateArgs) {}
Douglas Gregore62e6a02009-11-11 19:13:48 +0000318
Benjamin Kramer7761a042015-03-06 16:36:50 +0000319Sema::InstantiatingTemplate::InstantiatingTemplate(
320 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
321 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
322 SourceRange InstantiationRange)
323 : InstantiatingTemplate(
324 SemaRef, ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
325 PointOfInstantiation, InstantiationRange, Param, Template,
326 TemplateArgs) {}
Anders Carlsson657bad42009-09-05 05:14:19 +0000327
Douglas Gregor85673582009-05-18 17:01:57 +0000328void Sema::InstantiatingTemplate::Clear() {
329 if (!Invalid) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000330 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
331 assert(SemaRef.NonInstantiationEntries > 0);
332 --SemaRef.NonInstantiationEntries;
333 }
Douglas Gregoredb76852011-01-27 22:31:44 +0000334 SemaRef.InNonInstantiationSFINAEContext
335 = SavedInNonInstantiationSFINAEContext;
Richard Smith0e5d7b82013-07-25 23:08:39 +0000336
337 // Name lookup no longer looks in this template's defining module.
338 assert(SemaRef.ActiveTemplateInstantiations.size() >=
339 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
340 "forgot to remove a lookup module for a template instantiation");
341 if (SemaRef.ActiveTemplateInstantiations.size() ==
342 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
343 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
344 SemaRef.LookupModulesCache.erase(M);
345 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
346 }
347
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000348 SemaRef.ActiveTemplateInstantiations.pop_back();
Douglas Gregor85673582009-05-18 17:01:57 +0000349 Invalid = true;
350 }
Douglas Gregorfcd5db32009-03-10 00:06:19 +0000351}
352
Douglas Gregor79cf6032009-03-10 20:44:00 +0000353bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
354 SourceLocation PointOfInstantiation,
355 SourceRange InstantiationRange) {
Douglas Gregor84d49a22009-11-11 21:54:23 +0000356 assert(SemaRef.NonInstantiationEntries <=
357 SemaRef.ActiveTemplateInstantiations.size());
358 if ((SemaRef.ActiveTemplateInstantiations.size() -
359 SemaRef.NonInstantiationEntries)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000360 <= SemaRef.getLangOpts().InstantiationDepth)
Douglas Gregor79cf6032009-03-10 20:44:00 +0000361 return false;
362
Mike Stump11289f42009-09-09 15:08:12 +0000363 SemaRef.Diag(PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000364 diag::err_template_recursion_depth_exceeded)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000365 << SemaRef.getLangOpts().InstantiationDepth
Douglas Gregor79cf6032009-03-10 20:44:00 +0000366 << InstantiationRange;
367 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000368 << SemaRef.getLangOpts().InstantiationDepth;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000369 return true;
370}
371
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000372/// \brief Prints the current instantiation stack through a series of
373/// notes.
374void Sema::PrintInstantiationStack() {
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000375 // Determine which template instantiations to skip, if any.
376 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
377 unsigned Limit = Diags.getTemplateBacktraceLimit();
378 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
379 SkipStart = Limit / 2 + Limit % 2;
380 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
381 }
382
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000383 // FIXME: In all of these cases, we need to show the template arguments
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000384 unsigned InstantiationIdx = 0;
Craig Topper2341c0d2013-07-04 03:08:24 +0000385 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000386 Active = ActiveTemplateInstantiations.rbegin(),
387 ActiveEnd = ActiveTemplateInstantiations.rend();
388 Active != ActiveEnd;
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000389 ++Active, ++InstantiationIdx) {
390 // Skip this instantiation?
391 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
392 if (InstantiationIdx == SkipStart) {
393 // Note that we're skipping instantiations.
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000394 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorffed1cb2010-04-20 07:18:24 +0000395 diag::note_instantiation_contexts_suppressed)
396 << unsigned(ActiveTemplateInstantiations.size() - Limit);
397 }
398 continue;
399 }
400
Douglas Gregor79cf6032009-03-10 20:44:00 +0000401 switch (Active->Kind) {
402 case ActiveTemplateInstantiation::TemplateInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000403 Decl *D = Active->Entity;
Douglas Gregor85673582009-05-18 17:01:57 +0000404 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
405 unsigned DiagID = diag::note_template_member_class_here;
406 if (isa<ClassTemplateSpecializationDecl>(Record))
407 DiagID = diag::note_template_class_instantiation_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000408 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000409 << Context.getTypeDeclType(Record)
410 << Active->InstantiationRange;
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000411 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor4adbc6d2009-06-26 00:10:03 +0000412 unsigned DiagID;
413 if (Function->getPrimaryTemplate())
414 DiagID = diag::note_function_template_spec_here;
415 else
416 DiagID = diag::note_template_member_function_here;
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000417 Diags.Report(Active->PointOfInstantiation, DiagID)
Douglas Gregor85673582009-05-18 17:01:57 +0000418 << Function
419 << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000420 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000421 Diags.Report(Active->PointOfInstantiation,
Larisse Voufodbd65772013-08-14 20:15:02 +0000422 VD->isStaticDataMember()?
423 diag::note_template_static_data_member_def_here
424 : diag::note_template_variable_def_here)
Richard Smith3f1b5d02011-05-05 21:57:07 +0000425 << VD
426 << Active->InstantiationRange;
Richard Smith4b38ded2012-03-14 23:13:10 +0000427 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
428 Diags.Report(Active->PointOfInstantiation,
429 diag::note_template_enum_def_here)
430 << ED
431 << Active->InstantiationRange;
Reid Klecknerd60b82f2014-11-17 23:36:45 +0000432 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
433 Diags.Report(Active->PointOfInstantiation,
434 diag::note_template_nsdmi_here)
435 << FD << Active->InstantiationRange;
Richard Smith3f1b5d02011-05-05 21:57:07 +0000436 } else {
437 Diags.Report(Active->PointOfInstantiation,
438 diag::note_template_type_alias_instantiation_here)
439 << cast<TypeAliasTemplateDecl>(D)
Douglas Gregora6ef8f02009-07-24 20:34:43 +0000440 << Active->InstantiationRange;
Douglas Gregor85673582009-05-18 17:01:57 +0000441 }
Douglas Gregor79cf6032009-03-10 20:44:00 +0000442 break;
443 }
444
445 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000446 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
Benjamin Kramer9170e912013-02-22 15:46:01 +0000447 SmallVector<char, 128> TemplateArgsStr;
448 llvm::raw_svector_ostream OS(TemplateArgsStr);
449 Template->printName(OS);
450 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000451 Active->TemplateArgs,
Douglas Gregor7de59662009-05-29 20:38:28 +0000452 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000453 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000454 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor79cf6032009-03-10 20:44:00 +0000455 diag::note_default_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000456 << OS.str()
Douglas Gregor79cf6032009-03-10 20:44:00 +0000457 << Active->InstantiationRange;
458 break;
459 }
Douglas Gregor637d9982009-06-10 23:47:09 +0000460
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000461 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000462 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000463 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000464 diag::note_explicit_template_arg_substitution_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000465 << FnTmpl
466 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
467 Active->TemplateArgs,
468 Active->NumTemplateArgs)
469 << Active->InstantiationRange;
Douglas Gregor637d9982009-06-10 23:47:09 +0000470 break;
471 }
Mike Stump11289f42009-09-09 15:08:12 +0000472
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000473 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000474 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
475 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000476 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000477 diag::note_partial_spec_deduct_instantiation_here)
478 << Context.getTypeDeclType(PartialSpec)
Douglas Gregor607f1412010-03-30 20:35:20 +0000479 << getTemplateArgumentBindingsText(
480 PartialSpec->getTemplateParameters(),
481 Active->TemplateArgs,
482 Active->NumTemplateArgs)
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000483 << Active->InstantiationRange;
484 } else {
485 FunctionTemplateDecl *FnTmpl
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000486 = cast<FunctionTemplateDecl>(Active->Entity);
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000487 Diags.Report(Active->PointOfInstantiation,
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000488 diag::note_function_template_deduction_instantiation_here)
Douglas Gregor607f1412010-03-30 20:35:20 +0000489 << FnTmpl
490 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
491 Active->TemplateArgs,
492 Active->NumTemplateArgs)
493 << Active->InstantiationRange;
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000494 }
495 break;
Douglas Gregor637d9982009-06-10 23:47:09 +0000496
Anders Carlsson657bad42009-09-05 05:14:19 +0000497 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000498 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
Anders Carlsson657bad42009-09-05 05:14:19 +0000499 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
Mike Stump11289f42009-09-09 15:08:12 +0000500
Benjamin Kramer9170e912013-02-22 15:46:01 +0000501 SmallVector<char, 128> TemplateArgsStr;
502 llvm::raw_svector_ostream OS(TemplateArgsStr);
503 FD->printName(OS);
504 TemplateSpecializationType::PrintTemplateArgumentList(OS,
Mike Stump11289f42009-09-09 15:08:12 +0000505 Active->TemplateArgs,
Anders Carlsson657bad42009-09-05 05:14:19 +0000506 Active->NumTemplateArgs,
Douglas Gregor75acd922011-09-27 23:30:47 +0000507 getPrintingPolicy());
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000508 Diags.Report(Active->PointOfInstantiation,
Anders Carlsson657bad42009-09-05 05:14:19 +0000509 diag::note_default_function_arg_instantiation_here)
Benjamin Kramer9170e912013-02-22 15:46:01 +0000510 << OS.str()
Anders Carlsson657bad42009-09-05 05:14:19 +0000511 << Active->InstantiationRange;
512 break;
513 }
Mike Stump11289f42009-09-09 15:08:12 +0000514
Douglas Gregore62e6a02009-11-11 19:13:48 +0000515 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000516 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
Douglas Gregore62e6a02009-11-11 19:13:48 +0000517 std::string Name;
518 if (!Parm->getName().empty())
519 Name = std::string(" '") + Parm->getName().str() + "'";
Craig Topperc3ec1492014-05-26 06:22:03 +0000520
521 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000522 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
523 TemplateParams = Template->getTemplateParameters();
524 else
525 TemplateParams =
526 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
527 ->getTemplateParameters();
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000528 Diags.Report(Active->PointOfInstantiation,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000529 diag::note_prior_template_arg_substitution)
530 << isa<TemplateTemplateParmDecl>(Parm)
531 << Name
Douglas Gregorca4686d2011-01-04 23:35:54 +0000532 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregore62e6a02009-11-11 19:13:48 +0000533 Active->TemplateArgs,
534 Active->NumTemplateArgs)
535 << Active->InstantiationRange;
536 break;
537 }
Douglas Gregor84d49a22009-11-11 21:54:23 +0000538
539 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
Craig Topperc3ec1492014-05-26 06:22:03 +0000540 TemplateParameterList *TemplateParams = nullptr;
Douglas Gregorca4686d2011-01-04 23:35:54 +0000541 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
542 TemplateParams = Template->getTemplateParameters();
543 else
544 TemplateParams =
545 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
546 ->getTemplateParameters();
547
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000548 Diags.Report(Active->PointOfInstantiation,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000549 diag::note_template_default_arg_checking)
Douglas Gregorca4686d2011-01-04 23:35:54 +0000550 << getTemplateArgumentBindingsText(TemplateParams,
Douglas Gregor84d49a22009-11-11 21:54:23 +0000551 Active->TemplateArgs,
552 Active->NumTemplateArgs)
553 << Active->InstantiationRange;
554 break;
555 }
Richard Smithf623c962012-04-17 00:58:00 +0000556
557 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
558 Diags.Report(Active->PointOfInstantiation,
559 diag::note_template_exception_spec_instantiation_here)
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000560 << cast<FunctionDecl>(Active->Entity)
Richard Smithf623c962012-04-17 00:58:00 +0000561 << Active->InstantiationRange;
562 break;
Douglas Gregor79cf6032009-03-10 20:44:00 +0000563 }
Douglas Gregor4ea568f2009-03-10 18:03:33 +0000564 }
565}
566
David Blaikie05785d12013-02-20 22:23:23 +0000567Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
Douglas Gregoredb76852011-01-27 22:31:44 +0000568 if (InNonInstantiationSFINAEContext)
Craig Topperc3ec1492014-05-26 06:22:03 +0000569 return Optional<TemplateDeductionInfo *>(nullptr);
Douglas Gregoredb76852011-01-27 22:31:44 +0000570
Craig Topper2341c0d2013-07-04 03:08:24 +0000571 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
Douglas Gregor33834512009-06-14 07:33:30 +0000572 Active = ActiveTemplateInstantiations.rbegin(),
573 ActiveEnd = ActiveTemplateInstantiations.rend();
574 Active != ActiveEnd;
Douglas Gregor84d49a22009-11-11 21:54:23 +0000575 ++Active)
576 {
Douglas Gregor33834512009-06-14 07:33:30 +0000577 switch(Active->Kind) {
Douglas Gregoredb76852011-01-27 22:31:44 +0000578 case ActiveTemplateInstantiation::TemplateInstantiation:
Richard Smith72249ba2012-04-26 07:24:08 +0000579 // An instantiation of an alias template may or may not be a SFINAE
580 // context, depending on what else is on the stack.
Nick Lewyckycc8990f2012-11-16 08:40:59 +0000581 if (isa<TypeAliasTemplateDecl>(Active->Entity))
Richard Smith72249ba2012-04-26 07:24:08 +0000582 break;
583 // Fall through.
584 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
Richard Smithf623c962012-04-17 00:58:00 +0000585 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000586 // This is a template instantiation, so there is no SFINAE.
David Blaikie7a30dc52013-02-21 01:47:18 +0000587 return None;
Mike Stump11289f42009-09-09 15:08:12 +0000588
Douglas Gregor33834512009-06-14 07:33:30 +0000589 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000590 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
Douglas Gregor84d49a22009-11-11 21:54:23 +0000591 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
Douglas Gregore62e6a02009-11-11 19:13:48 +0000592 // A default template argument instantiation and substitution into
593 // template parameters with arguments for prior parameters may or may
594 // not be a SFINAE context; look further up the stack.
Douglas Gregor33834512009-06-14 07:33:30 +0000595 break;
Mike Stump11289f42009-09-09 15:08:12 +0000596
Douglas Gregorff6cbdf2009-07-01 22:01:06 +0000597 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
598 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
599 // We're either substitution explicitly-specified template arguments
600 // or deduced template arguments, so SFINAE applies.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000601 assert(Active->DeductionInfo && "Missing deduction info pointer");
602 return Active->DeductionInfo;
Douglas Gregor33834512009-06-14 07:33:30 +0000603 }
604 }
605
David Blaikie7a30dc52013-02-21 01:47:18 +0000606 return None;
Douglas Gregor33834512009-06-14 07:33:30 +0000607}
608
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000609/// \brief Retrieve the depth and index of a parameter pack.
610static std::pair<unsigned, unsigned>
611getDepthAndIndex(NamedDecl *ND) {
612 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
613 return std::make_pair(TTP->getDepth(), TTP->getIndex());
614
615 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
616 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
617
618 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
619 return std::make_pair(TTP->getDepth(), TTP->getIndex());
620}
621
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000622//===----------------------------------------------------------------------===/
623// Template Instantiation for Types
624//===----------------------------------------------------------------------===/
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000625namespace {
Douglas Gregor14cf7522010-04-30 18:55:50 +0000626 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000627 const MultiLevelTemplateArgumentList &TemplateArgs;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000628 SourceLocation Loc;
629 DeclarationName Entity;
Douglas Gregorfe1e1102009-02-27 19:31:52 +0000630
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000631 public:
Douglas Gregorebe10102009-08-20 07:17:43 +0000632 typedef TreeTransform<TemplateInstantiator> inherited;
Mike Stump11289f42009-09-09 15:08:12 +0000633
634 TemplateInstantiator(Sema &SemaRef,
Douglas Gregor01afeef2009-08-28 20:31:08 +0000635 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregord6ff3322009-08-04 16:50:30 +0000636 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +0000637 DeclarationName Entity)
638 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
Douglas Gregorebe10102009-08-20 07:17:43 +0000639 Entity(Entity) { }
Douglas Gregor17c0d7b2009-02-28 00:25:32 +0000640
Mike Stump11289f42009-09-09 15:08:12 +0000641 /// \brief Determine whether the given type \p T has already been
Douglas Gregord6ff3322009-08-04 16:50:30 +0000642 /// transformed.
643 ///
644 /// For the purposes of template instantiation, a type has already been
645 /// transformed if it is NULL or if it is not dependent.
Douglas Gregor5597ab42010-05-07 23:12:07 +0000646 bool AlreadyTransformed(QualType T);
Mike Stump11289f42009-09-09 15:08:12 +0000647
Douglas Gregord6ff3322009-08-04 16:50:30 +0000648 /// \brief Returns the location of the entity being instantiated, if known.
649 SourceLocation getBaseLocation() { return Loc; }
Mike Stump11289f42009-09-09 15:08:12 +0000650
Douglas Gregord6ff3322009-08-04 16:50:30 +0000651 /// \brief Returns the name of the entity being instantiated, if any.
652 DeclarationName getBaseEntity() { return Entity; }
Mike Stump11289f42009-09-09 15:08:12 +0000653
Douglas Gregoref6ab412009-10-27 06:26:26 +0000654 /// \brief Sets the "base" location and entity when that
655 /// information is known based on another transformation.
656 void setBase(SourceLocation Loc, DeclarationName Entity) {
657 this->Loc = Loc;
658 this->Entity = Entity;
659 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000660
661 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
662 SourceRange PatternRange,
Robert Wilhelm16e94b92013-08-09 18:02:13 +0000663 ArrayRef<UnexpandedParameterPack> Unexpanded,
664 bool &ShouldExpand, bool &RetainExpansion,
David Blaikie05785d12013-02-20 22:23:23 +0000665 Optional<unsigned> &NumExpansions) {
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000666 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
667 PatternRange, Unexpanded,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000668 TemplateArgs,
669 ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000670 RetainExpansion,
Douglas Gregor76aca7b2010-12-21 00:52:54 +0000671 NumExpansions);
672 }
Douglas Gregor840bd6c2010-12-20 22:05:00 +0000673
Douglas Gregorf3010112011-01-07 16:43:16 +0000674 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
675 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
676 }
677
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000678 TemplateArgument ForgetPartiallySubstitutedPack() {
679 TemplateArgument Result;
680 if (NamedDecl *PartialPack
681 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
682 MultiLevelTemplateArgumentList &TemplateArgs
683 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
684 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000685 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000686 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
687 Result = TemplateArgs(Depth, Index);
688 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
689 }
690 }
691
692 return Result;
693 }
694
695 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
696 if (Arg.isNull())
697 return;
698
699 if (NamedDecl *PartialPack
700 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
701 MultiLevelTemplateArgumentList &TemplateArgs
702 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
703 unsigned Depth, Index;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000704 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
Douglas Gregora8bac7f2011-01-10 07:32:04 +0000705 TemplateArgs.setArgument(Depth, Index, Arg);
706 }
707 }
708
Douglas Gregord6ff3322009-08-04 16:50:30 +0000709 /// \brief Transform the given declaration by instantiating a reference to
710 /// this declaration.
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000711 Decl *TransformDecl(SourceLocation Loc, Decl *D);
Douglas Gregora16548e2009-08-11 05:31:07 +0000712
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000713 void transformAttrs(Decl *Old, Decl *New) {
714 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
715 }
716
717 void transformedLocalDecl(Decl *Old, Decl *New) {
Richard Smithc38498f2015-04-27 21:27:54 +0000718 // If we've instantiated the call operator of a lambda or the call
719 // operator template of a generic lambda, update the "instantiation of"
720 // information.
721 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
722 if (NewMD && isLambdaCallOperator(NewMD)) {
723 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
724 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
725 NewTD->setInstantiatedFromMemberTemplate(
726 OldMD->getDescribedFunctionTemplate());
727 else
728 NewMD->setInstantiationOfMemberFunction(OldMD,
729 TSK_ImplicitInstantiation);
730 }
731
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000732 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
Richard Smithc7649dc2016-03-23 20:07:07 +0000733
734 // We recreated a local declaration, but not by instantiating it. There
735 // may be pending dependent diagnostics to produce.
736 if (auto *DC = dyn_cast<DeclContext>(Old))
737 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000738 }
739
Mike Stump11289f42009-09-09 15:08:12 +0000740 /// \brief Transform the definition of the given declaration by
Douglas Gregorebe10102009-08-20 07:17:43 +0000741 /// instantiating it.
Douglas Gregor25289362010-03-01 17:25:41 +0000742 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
Mike Stump11289f42009-09-09 15:08:12 +0000743
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000744 /// \brief Transform the first qualifier within a scope by instantiating the
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000745 /// declaration.
746 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
747
Douglas Gregorebe10102009-08-20 07:17:43 +0000748 /// \brief Rebuild the exception declaration and register the declaration
749 /// as an instantiated local.
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000750 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000751 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000752 SourceLocation StartLoc,
753 SourceLocation NameLoc,
754 IdentifierInfo *Name);
Mike Stump11289f42009-09-09 15:08:12 +0000755
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000756 /// \brief Rebuild the Objective-C exception declaration and register the
757 /// declaration as an instantiated local.
758 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
759 TypeSourceInfo *TSInfo, QualType T);
760
John McCall7f41d982009-09-11 04:59:25 +0000761 /// \brief Check for tag mismatches when instantiating an
762 /// elaborated type.
John McCall954b5de2010-11-04 19:04:38 +0000763 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
764 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000765 NestedNameSpecifierLoc QualifierLoc,
766 QualType T);
John McCall7f41d982009-09-11 04:59:25 +0000767
Craig Topperc3ec1492014-05-26 06:22:03 +0000768 TemplateName
769 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
770 SourceLocation NameLoc,
771 QualType ObjectType = QualType(),
772 NamedDecl *FirstQualifierInScope = nullptr);
Douglas Gregor9db53502011-03-02 18:07:45 +0000773
Tyler Nowickic724a83e2014-10-12 20:46:07 +0000774 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
775
John McCalldadc5752010-08-24 06:29:42 +0000776 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
777 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
778 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000779
John McCalldadc5752010-08-24 06:29:42 +0000780 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregoreb5a39d2010-12-24 00:15:10 +0000781 NonTypeTemplateParmDecl *D);
Douglas Gregorcdbc5392011-01-15 01:15:58 +0000782 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
783 SubstNonTypeTemplateParmPackExpr *E);
Richard Smithb15fe3a2012-09-12 00:56:43 +0000784
785 /// \brief Rebuild a DeclRefExpr for a ParmVarDecl reference.
786 ExprResult RebuildParmVarDeclRefExpr(ParmVarDecl *PD, SourceLocation Loc);
787
788 /// \brief Transform a reference to a function parameter pack.
789 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E,
790 ParmVarDecl *PD);
791
792 /// \brief Transform a FunctionParmPackExpr which was built when we couldn't
793 /// expand a function parameter pack reference which refers to an expanded
794 /// pack.
795 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
796
Hans Wennborge113c202014-09-18 16:01:32 +0000797 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
Richard Smith2e321552014-11-12 02:00:47 +0000798 FunctionProtoTypeLoc TL) {
799 // Call the base version; it will forward to our overridden version below.
800 return inherited::TransformFunctionProtoType(TLB, TL);
801 }
802
803 template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +0000804 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
805 FunctionProtoTypeLoc TL,
806 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +0000807 unsigned ThisTypeQuals,
808 Fn TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +0000809
Douglas Gregor715e4612011-01-14 22:40:04 +0000810 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +0000811 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +0000812 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +0000813 bool ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +0000814
Mike Stump11289f42009-09-09 15:08:12 +0000815 /// \brief Transforms a template type parameter type by performing
Douglas Gregord6ff3322009-08-04 16:50:30 +0000816 /// substitution of the corresponding template type argument.
John McCall550e0c22009-10-21 00:40:46 +0000817 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +0000818 TemplateTypeParmTypeLoc TL);
Nick Lewyckyc96c37f2010-07-06 19:51:49 +0000819
Douglas Gregorada4b792011-01-14 02:55:32 +0000820 /// \brief Transforms an already-substituted template type parameter pack
821 /// into either itself (if we aren't substituting into its pack expansion)
822 /// or the appropriate substituted argument.
823 QualType TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
824 SubstTemplateTypeParmPackTypeLoc TL);
825
Richard Smith2589b9802012-07-25 03:56:55 +0000826 ExprResult TransformLambdaExpr(LambdaExpr *E) {
827 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
828 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
829 }
830
David Majnemerb1004102014-03-02 18:46:05 +0000831 TemplateParameterList *TransformTemplateParameterList(
Faisal Vali2cba1332013-10-23 06:44:28 +0000832 TemplateParameterList *OrigTPL) {
833 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
834
835 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
836 TemplateDeclInstantiator DeclInstantiator(getSema(),
837 /* DeclContext *Owner */ Owner, TemplateArgs);
838 return DeclInstantiator.SubstTemplateParams(OrigTPL);
839 }
John McCall7c454bb2011-07-15 05:09:51 +0000840 private:
841 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
842 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +0000843 TemplateArgument arg);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000844 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000845}
Douglas Gregor04318252009-07-06 15:59:29 +0000846
Douglas Gregor5597ab42010-05-07 23:12:07 +0000847bool TemplateInstantiator::AlreadyTransformed(QualType T) {
848 if (T.isNull())
849 return true;
850
Douglas Gregor678d76c2011-07-01 01:22:09 +0000851 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
Douglas Gregor5597ab42010-05-07 23:12:07 +0000852 return false;
853
854 getSema().MarkDeclarationsReferencedInType(Loc, T);
855 return true;
856}
857
Eli Friedman8917ad52013-07-19 19:40:38 +0000858static TemplateArgument
859getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
860 assert(S.ArgumentPackSubstitutionIndex >= 0);
861 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
862 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
863 if (Arg.isPackExpansion())
864 Arg = Arg.getPackExpansionPattern();
865 return Arg;
866}
867
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000868Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000869 if (!D)
Craig Topperc3ec1492014-05-26 06:22:03 +0000870 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000871
Douglas Gregor2b6ca462009-09-03 21:38:09 +0000872 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
Douglas Gregor01afeef2009-08-28 20:31:08 +0000873 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorb93971082010-02-05 19:54:12 +0000874 // If the corresponding template argument is NULL or non-existent, it's
875 // because we are performing instantiation from explicitly-specified
876 // template arguments in a function template, but there were some
877 // arguments left unspecified.
878 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
879 TTP->getPosition()))
880 return D;
881
Douglas Gregorf5500772011-01-05 15:48:55 +0000882 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
883
884 if (TTP->isParameterPack()) {
885 assert(Arg.getKind() == TemplateArgument::Pack &&
886 "Missing argument pack");
Eli Friedman8917ad52013-07-19 19:40:38 +0000887 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregorf5500772011-01-05 15:48:55 +0000888 }
889
890 TemplateName Template = Arg.getAsTemplate();
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000891 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
Douglas Gregor01afeef2009-08-28 20:31:08 +0000892 "Wrong kind of template template argument");
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000893 return Template.getAsTemplateDecl();
Douglas Gregor01afeef2009-08-28 20:31:08 +0000894 }
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregor9167f8b2009-11-11 01:00:40 +0000896 // Fall through to find the instantiated declaration for this template
897 // template parameter.
Douglas Gregor71dc5092009-08-06 06:41:21 +0000898 }
Mike Stump11289f42009-09-09 15:08:12 +0000899
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000900 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
Douglas Gregord6ff3322009-08-04 16:50:30 +0000901}
902
Douglas Gregor25289362010-03-01 17:25:41 +0000903Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
John McCall76d824f2009-08-25 22:02:44 +0000904 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
Douglas Gregorebe10102009-08-20 07:17:43 +0000905 if (!Inst)
Craig Topperc3ec1492014-05-26 06:22:03 +0000906 return nullptr;
Mike Stump11289f42009-09-09 15:08:12 +0000907
Douglas Gregorebe10102009-08-20 07:17:43 +0000908 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
909 return Inst;
910}
911
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000912NamedDecl *
913TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
914 SourceLocation Loc) {
915 // If the first part of the nested-name-specifier was a template type
916 // parameter, instantiate that type parameter down to a tag type.
917 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
918 const TemplateTypeParmType *TTP
919 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000920
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000921 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000922 // FIXME: This needs testing w/ member access expressions.
923 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
924
925 if (TTP->isParameterPack()) {
926 assert(Arg.getKind() == TemplateArgument::Pack &&
927 "Missing argument pack");
928
Douglas Gregore1d60df2011-01-14 23:41:42 +0000929 if (getSema().ArgumentPackSubstitutionIndex == -1)
Craig Topperc3ec1492014-05-26 06:22:03 +0000930 return nullptr;
931
Eli Friedman8917ad52013-07-19 19:40:38 +0000932 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor53c3f4e2010-12-20 22:48:17 +0000933 }
934
935 QualType T = Arg.getAsType();
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000936 if (T.isNull())
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000937 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000938
939 if (const TagType *Tag = T->getAs<TagType>())
940 return Tag->getDecl();
941
942 // The resulting type is not a tag; complain.
943 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
Craig Topperc3ec1492014-05-26 06:22:03 +0000944 return nullptr;
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000945 }
946 }
947
Douglas Gregora04f2ca2010-03-01 15:56:25 +0000948 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
Douglas Gregora5cb6da2009-10-20 05:58:46 +0000949}
950
Douglas Gregorebe10102009-08-20 07:17:43 +0000951VarDecl *
952TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
John McCallbcd03502009-12-07 02:54:59 +0000953 TypeSourceInfo *Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000954 SourceLocation StartLoc,
955 SourceLocation NameLoc,
956 IdentifierInfo *Name) {
Douglas Gregor9f0e1aa2010-09-09 17:09:21 +0000957 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
Abramo Bagnaradff19302011-03-08 08:55:46 +0000958 StartLoc, NameLoc, Name);
Douglas Gregorf4e837f2010-04-26 17:57:08 +0000959 if (Var)
960 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
961 return Var;
962}
963
964VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
965 TypeSourceInfo *TSInfo,
966 QualType T) {
967 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
968 if (Var)
Douglas Gregorebe10102009-08-20 07:17:43 +0000969 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
970 return Var;
971}
972
John McCall7f41d982009-09-11 04:59:25 +0000973QualType
John McCall954b5de2010-11-04 19:04:38 +0000974TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
975 ElaboratedTypeKeyword Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +0000976 NestedNameSpecifierLoc QualifierLoc,
Abramo Bagnara6150c882010-05-11 21:36:43 +0000977 QualType T) {
John McCall7f41d982009-09-11 04:59:25 +0000978 if (const TagType *TT = T->getAs<TagType>()) {
979 TagDecl* TD = TT->getDecl();
980
John McCall954b5de2010-11-04 19:04:38 +0000981 SourceLocation TagLocation = KeywordLoc;
John McCall7f41d982009-09-11 04:59:25 +0000982
John McCall7f41d982009-09-11 04:59:25 +0000983 IdentifierInfo *Id = TD->getIdentifier();
984
985 // TODO: should we even warn on struct/class mismatches for this? Seems
986 // like it's likely to produce a lot of spurious errors.
Richard Smith80b3c5a2012-08-17 00:12:27 +0000987 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000988 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
Richard Trieucaa33d32011-06-10 03:11:26 +0000989 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
Justin Bognerc6ecb7c2015-07-10 23:05:47 +0000990 TagLocation, Id)) {
Abramo Bagnara6150c882010-05-11 21:36:43 +0000991 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
992 << Id
993 << FixItHint::CreateReplacement(SourceRange(TagLocation),
994 TD->getKindName());
995 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
996 }
John McCall7f41d982009-09-11 04:59:25 +0000997 }
998 }
999
John McCall954b5de2010-11-04 19:04:38 +00001000 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1001 Keyword,
Douglas Gregor844cb502011-03-01 18:12:44 +00001002 QualifierLoc,
1003 T);
John McCall7f41d982009-09-11 04:59:25 +00001004}
1005
Douglas Gregor9db53502011-03-02 18:07:45 +00001006TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1007 TemplateName Name,
Nico Weberc153d242014-07-28 00:02:09 +00001008 SourceLocation NameLoc,
Douglas Gregor9db53502011-03-02 18:07:45 +00001009 QualType ObjectType,
1010 NamedDecl *FirstQualifierInScope) {
1011 if (TemplateTemplateParmDecl *TTP
1012 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1013 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1014 // If the corresponding template argument is NULL or non-existent, it's
1015 // because we are performing instantiation from explicitly-specified
1016 // template arguments in a function template, but there were some
1017 // arguments left unspecified.
1018 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1019 TTP->getPosition()))
1020 return Name;
1021
1022 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1023
1024 if (TTP->isParameterPack()) {
1025 assert(Arg.getKind() == TemplateArgument::Pack &&
1026 "Missing argument pack");
1027
1028 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1029 // We have the template argument pack to substitute, but we're not
1030 // actually expanding the enclosing pack expansion yet. So, just
1031 // keep the entire argument pack.
1032 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1033 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001034
1035 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor9db53502011-03-02 18:07:45 +00001036 }
1037
1038 TemplateName Template = Arg.getAsTemplate();
Richard Smith3f1b5d02011-05-05 21:57:07 +00001039 assert(!Template.isNull() && "Null template template argument");
John McCalld9dfe3a2011-06-30 08:33:18 +00001040
Douglas Gregor9d9f8db2011-03-05 20:06:51 +00001041 // We don't ever want to substitute for a qualified template name, since
1042 // the qualifier is handled separately. So, look through the qualified
1043 // template name to its underlying declaration.
1044 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1045 Template = TemplateName(QTN->getTemplateDecl());
John McCalld9dfe3a2011-06-30 08:33:18 +00001046
1047 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
Douglas Gregor9db53502011-03-02 18:07:45 +00001048 return Template;
1049 }
1050 }
1051
1052 if (SubstTemplateTemplateParmPackStorage *SubstPack
1053 = Name.getAsSubstTemplateTemplateParmPack()) {
1054 if (getSema().ArgumentPackSubstitutionIndex == -1)
1055 return Name;
1056
Eli Friedman8917ad52013-07-19 19:40:38 +00001057 TemplateArgument Arg = SubstPack->getArgumentPack();
1058 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1059 return Arg.getAsTemplate();
Douglas Gregor9db53502011-03-02 18:07:45 +00001060 }
1061
1062 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1063 FirstQualifierInScope);
1064}
1065
John McCalldadc5752010-08-24 06:29:42 +00001066ExprResult
John McCall47f29ea2009-12-08 09:21:05 +00001067TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
Anders Carlsson0b209a82009-09-11 01:22:35 +00001068 if (!E->isTypeDependent())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001069 return E;
Anders Carlsson0b209a82009-09-11 01:22:35 +00001070
Wei Panc354d212013-09-16 13:57:27 +00001071 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
Anders Carlsson0b209a82009-09-11 01:22:35 +00001072}
1073
John McCalldadc5752010-08-24 06:29:42 +00001074ExprResult
John McCall13481c52010-02-06 08:42:39 +00001075TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
Douglas Gregor6c379e22010-02-08 23:41:45 +00001076 NonTypeTemplateParmDecl *NTTP) {
John McCall13481c52010-02-06 08:42:39 +00001077 // If the corresponding template argument is NULL or non-existent, it's
1078 // because we are performing instantiation from explicitly-specified
1079 // template arguments in a function template, but there were some
1080 // arguments left unspecified.
1081 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1082 NTTP->getPosition()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001083 return E;
Mike Stump11289f42009-09-09 15:08:12 +00001084
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001085 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1086 if (NTTP->isParameterPack()) {
1087 assert(Arg.getKind() == TemplateArgument::Pack &&
1088 "Missing argument pack");
1089
1090 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001091 // We have an argument pack, but we can't select a particular argument
1092 // out of it yet. Therefore, we'll build an expression to hold on to that
1093 // argument pack.
1094 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1095 E->getLocation(),
1096 NTTP->getDeclName());
1097 if (TargetType.isNull())
1098 return ExprError();
1099
1100 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1101 NTTP,
1102 E->getLocation(),
1103 Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001104 }
1105
Eli Friedman8917ad52013-07-19 19:40:38 +00001106 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregoreb5a39d2010-12-24 00:15:10 +00001107 }
Mike Stump11289f42009-09-09 15:08:12 +00001108
John McCall7c454bb2011-07-15 05:09:51 +00001109 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1110}
1111
Tyler Nowickic724a83e2014-10-12 20:46:07 +00001112const LoopHintAttr *
1113TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1114 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1115
1116 if (TransformedExpr == LH->getValue())
1117 return LH;
1118
1119 // Generate error if there is a problem with the value.
1120 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1121 return LH;
1122
1123 // Create new LoopHintValueAttr with integral expression in place of the
1124 // non-type template parameter.
1125 return LoopHintAttr::CreateImplicit(
1126 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1127 LH->getState(), TransformedExpr, LH->getRange());
1128}
1129
John McCall7c454bb2011-07-15 05:09:51 +00001130ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1131 NonTypeTemplateParmDecl *parm,
1132 SourceLocation loc,
Richard Smith34349002012-07-09 03:07:20 +00001133 TemplateArgument arg) {
John McCall7c454bb2011-07-15 05:09:51 +00001134 ExprResult result;
1135 QualType type;
1136
John McCall13481c52010-02-06 08:42:39 +00001137 // The template argument itself might be an expression, in which
1138 // case we just return that expression.
John McCall7c454bb2011-07-15 05:09:51 +00001139 if (arg.getKind() == TemplateArgument::Expression) {
1140 Expr *argExpr = arg.getAsExpr();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001141 result = argExpr;
John McCall7c454bb2011-07-15 05:09:51 +00001142 type = argExpr->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001143
Eli Friedmanb826a002012-09-26 02:36:12 +00001144 } else if (arg.getKind() == TemplateArgument::Declaration ||
1145 arg.getKind() == TemplateArgument::NullPtr) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001146 ValueDecl *VD;
Eli Friedmanb826a002012-09-26 02:36:12 +00001147 if (arg.getKind() == TemplateArgument::Declaration) {
1148 VD = cast<ValueDecl>(arg.getAsDecl());
Mike Stump11289f42009-09-09 15:08:12 +00001149
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001150 // Find the instantiation of the template argument. This is
1151 // required for nested templates.
1152 VD = cast_or_null<ValueDecl>(
1153 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1154 if (!VD)
1155 return ExprError();
1156 } else {
1157 // Propagate NULL template argument.
Craig Topperc3ec1492014-05-26 06:22:03 +00001158 VD = nullptr;
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001159 }
1160
John McCall15dda372010-02-06 10:23:53 +00001161 // Derive the type we want the substituted decl to have. This had
1162 // better be non-dependent, or these checks will have serious problems.
John McCall7c454bb2011-07-15 05:09:51 +00001163 if (parm->isExpandedParameterPack()) {
1164 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1165 } else if (parm->isParameterPack() &&
1166 isa<PackExpansionType>(parm->getType())) {
1167 type = SemaRef.SubstType(
1168 cast<PackExpansionType>(parm->getType())->getPattern(),
1169 TemplateArgs, loc, parm->getDeclName());
1170 } else {
1171 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1172 loc, parm->getDeclName());
1173 }
1174 assert(!type.isNull() && "type substitution failed for param type");
1175 assert(!type->isDependentType() && "param type still dependent");
1176 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
John McCall13481c52010-02-06 08:42:39 +00001177
John McCall7c454bb2011-07-15 05:09:51 +00001178 if (!result.isInvalid()) type = result.get()->getType();
1179 } else {
1180 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1181
1182 // Note that this type can be different from the type of 'result',
1183 // e.g. if it's an enum type.
1184 type = arg.getIntegralType();
1185 }
1186 if (result.isInvalid()) return ExprError();
1187
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001188 Expr *resultExpr = result.get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001189 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1190 type, resultExpr->getValueKind(), loc, parm, resultExpr);
John McCall13481c52010-02-06 08:42:39 +00001191}
1192
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001193ExprResult
1194TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1195 SubstNonTypeTemplateParmPackExpr *E) {
1196 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1197 // We aren't expanding the parameter pack, so just return ourselves.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001198 return E;
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001199 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001200
1201 TemplateArgument Arg = E->getArgumentPack();
1202 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
John McCall7c454bb2011-07-15 05:09:51 +00001203 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1204 E->getParameterPackLocation(),
1205 Arg);
Douglas Gregorcdbc5392011-01-15 01:15:58 +00001206}
John McCall13481c52010-02-06 08:42:39 +00001207
John McCalldadc5752010-08-24 06:29:42 +00001208ExprResult
Richard Smithb15fe3a2012-09-12 00:56:43 +00001209TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1210 SourceLocation Loc) {
1211 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1212 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1213}
1214
1215ExprResult
1216TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1217 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1218 // We can expand this parameter pack now.
1219 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1220 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1221 if (!VD)
1222 return ExprError();
1223 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1224 }
1225
1226 QualType T = TransformType(E->getType());
1227 if (T.isNull())
1228 return ExprError();
1229
1230 // Transform each of the parameter expansions into the corresponding
1231 // parameters in the instantiation of the function decl.
James Y Knight48fefa32015-09-30 14:04:23 +00001232 SmallVector<ParmVarDecl *, 8> Parms;
Richard Smithb15fe3a2012-09-12 00:56:43 +00001233 Parms.reserve(E->getNumExpansions());
1234 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1235 I != End; ++I) {
1236 ParmVarDecl *D =
1237 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1238 if (!D)
1239 return ExprError();
1240 Parms.push_back(D);
1241 }
1242
1243 return FunctionParmPackExpr::Create(getSema().Context, T,
1244 E->getParameterPack(),
1245 E->getParameterPackLocation(), Parms);
1246}
1247
1248ExprResult
1249TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1250 ParmVarDecl *PD) {
1251 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1252 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1253 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1254 assert(Found && "no instantiation for parameter pack");
1255
1256 Decl *TransformedDecl;
1257 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
Nico Weberc153d242014-07-28 00:02:09 +00001258 // If this is a reference to a function parameter pack which we can
1259 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
Richard Smithb15fe3a2012-09-12 00:56:43 +00001260 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1261 QualType T = TransformType(E->getType());
1262 if (T.isNull())
1263 return ExprError();
1264 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1265 E->getExprLoc(), *Pack);
1266 }
1267
1268 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1269 } else {
1270 TransformedDecl = Found->get<Decl*>();
1271 }
1272
1273 // We have either an unexpanded pack or a specific expansion.
1274 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1275 E->getExprLoc());
1276}
1277
1278ExprResult
John McCall13481c52010-02-06 08:42:39 +00001279TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1280 NamedDecl *D = E->getDecl();
Richard Smithb15fe3a2012-09-12 00:56:43 +00001281
1282 // Handle references to non-type template parameters and non-type template
1283 // parameter packs.
John McCall13481c52010-02-06 08:42:39 +00001284 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1285 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1286 return TransformTemplateParmRefExpr(E, NTTP);
Douglas Gregor954de172009-10-31 17:21:17 +00001287
1288 // We have a non-type template parameter that isn't fully substituted;
1289 // FindInstantiatedDecl will find it in the local instantiation scope.
Douglas Gregora16548e2009-08-11 05:31:07 +00001290 }
Mike Stump11289f42009-09-09 15:08:12 +00001291
Richard Smithb15fe3a2012-09-12 00:56:43 +00001292 // Handle references to function parameter packs.
1293 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1294 if (PD->isParameterPack())
1295 return TransformFunctionParmPackRefExpr(E, PD);
1296
John McCall47f29ea2009-12-08 09:21:05 +00001297 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
Douglas Gregora16548e2009-08-11 05:31:07 +00001298}
1299
John McCalldadc5752010-08-24 06:29:42 +00001300ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
John McCall47f29ea2009-12-08 09:21:05 +00001301 CXXDefaultArgExpr *E) {
Sebastian Redl14236c82009-11-08 13:56:19 +00001302 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1303 getDescribedFunctionTemplate() &&
1304 "Default arg expressions are never formed in dependent cases.");
Douglas Gregor033f6752009-12-23 23:03:06 +00001305 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1306 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1307 E->getParam());
Sebastian Redl14236c82009-11-08 13:56:19 +00001308}
1309
Richard Smith2e321552014-11-12 02:00:47 +00001310template<typename Fn>
Douglas Gregor3024f072012-04-16 07:05:22 +00001311QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1312 FunctionProtoTypeLoc TL,
1313 CXXRecordDecl *ThisContext,
Richard Smith2e321552014-11-12 02:00:47 +00001314 unsigned ThisTypeQuals,
1315 Fn TransformExceptionSpec) {
Douglas Gregor3024f072012-04-16 07:05:22 +00001316 // We need a local instantiation scope for this function prototype.
1317 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
Richard Smith2e321552014-11-12 02:00:47 +00001318 return inherited::TransformFunctionProtoType(
1319 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
Douglas Gregor3024f072012-04-16 07:05:22 +00001320}
1321
John McCall58f10c32010-03-11 09:03:00 +00001322ParmVarDecl *
Douglas Gregor715e4612011-01-14 22:40:04 +00001323TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
John McCall8fb0d9d2011-05-01 22:35:37 +00001324 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001325 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001326 bool ExpectParameterPack) {
John McCall8fb0d9d2011-05-01 22:35:37 +00001327 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001328 NumExpansions, ExpectParameterPack);
John McCall58f10c32010-03-11 09:03:00 +00001329}
1330
Mike Stump11289f42009-09-09 15:08:12 +00001331QualType
John McCall550e0c22009-10-21 00:40:46 +00001332TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
John McCall31f82722010-11-12 08:19:04 +00001333 TemplateTypeParmTypeLoc TL) {
John McCall424cec92011-01-19 06:33:43 +00001334 const TemplateTypeParmType *T = TL.getTypePtr();
Douglas Gregor01afeef2009-08-28 20:31:08 +00001335 if (T->getDepth() < TemplateArgs.getNumLevels()) {
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001336 // Replace the template type parameter with its corresponding
1337 // template argument.
Mike Stump11289f42009-09-09 15:08:12 +00001338
1339 // If the corresponding template argument is NULL or doesn't exist, it's
1340 // because we are performing instantiation from explicitly-specified
1341 // template arguments in a function template class, but there were some
Douglas Gregore3f1f352009-07-01 00:28:38 +00001342 // arguments left unspecified.
John McCall550e0c22009-10-21 00:40:46 +00001343 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1344 TemplateTypeParmTypeLoc NewTL
1345 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1346 NewTL.setNameLoc(TL.getNameLoc());
1347 return TL.getType();
1348 }
Mike Stump11289f42009-09-09 15:08:12 +00001349
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001350 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1351
1352 if (T->isParameterPack()) {
1353 assert(Arg.getKind() == TemplateArgument::Pack &&
1354 "Missing argument pack");
1355
1356 if (getSema().ArgumentPackSubstitutionIndex == -1) {
Douglas Gregorada4b792011-01-14 02:55:32 +00001357 // We have the template argument pack, but we're not expanding the
1358 // enclosing pack expansion yet. Just save the template argument
1359 // pack for later substitution.
1360 QualType Result
1361 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1362 SubstTemplateTypeParmPackTypeLoc NewTL
1363 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1364 NewTL.setNameLoc(TL.getNameLoc());
1365 return Result;
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001366 }
1367
Eli Friedman8917ad52013-07-19 19:40:38 +00001368 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001369 }
1370
1371 assert(Arg.getKind() == TemplateArgument::Type &&
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001372 "Template argument kind mismatch");
Douglas Gregor01afeef2009-08-28 20:31:08 +00001373
Douglas Gregor840bd6c2010-12-20 22:05:00 +00001374 QualType Replacement = Arg.getAsType();
John McCallcebee162009-10-18 09:09:24 +00001375
1376 // TODO: only do this uniquing once, at the start of instantiation.
John McCall550e0c22009-10-21 00:40:46 +00001377 QualType Result
1378 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1379 SubstTemplateTypeParmTypeLoc NewTL
1380 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1381 NewTL.setNameLoc(TL.getNameLoc());
1382 return Result;
Mike Stump11289f42009-09-09 15:08:12 +00001383 }
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001384
1385 // The template type parameter comes from an inner template (e.g.,
1386 // the template parameter list of a member template inside the
1387 // template we are instantiating). Create a new template type
1388 // parameter with the template "level" reduced by one.
Craig Topperc3ec1492014-05-26 06:22:03 +00001389 TemplateTypeParmDecl *NewTTPDecl = nullptr;
Chandler Carruth08836322011-05-01 00:51:33 +00001390 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1391 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1392 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1393
John McCall550e0c22009-10-21 00:40:46 +00001394 QualType Result
1395 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1396 - TemplateArgs.getNumLevels(),
1397 T->getIndex(),
1398 T->isParameterPack(),
Chandler Carruth08836322011-05-01 00:51:33 +00001399 NewTTPDecl);
John McCall550e0c22009-10-21 00:40:46 +00001400 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1401 NewTL.setNameLoc(TL.getNameLoc());
1402 return Result;
Douglas Gregor17c0d7b2009-02-28 00:25:32 +00001403}
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001404
Douglas Gregorada4b792011-01-14 02:55:32 +00001405QualType
1406TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1407 TypeLocBuilder &TLB,
1408 SubstTemplateTypeParmPackTypeLoc TL) {
1409 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1410 // We aren't expanding the parameter pack, so just return ourselves.
1411 SubstTemplateTypeParmPackTypeLoc NewTL
1412 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1413 NewTL.setNameLoc(TL.getNameLoc());
1414 return TL.getType();
1415 }
Eli Friedman8917ad52013-07-19 19:40:38 +00001416
1417 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1418 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1419 QualType Result = Arg.getAsType();
1420
Douglas Gregorada4b792011-01-14 02:55:32 +00001421 Result = getSema().Context.getSubstTemplateTypeParmType(
1422 TL.getTypePtr()->getReplacedParameter(),
1423 Result);
1424 SubstTemplateTypeParmTypeLoc NewTL
1425 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1426 NewTL.setNameLoc(TL.getNameLoc());
1427 return Result;
1428}
1429
John McCall76d824f2009-08-25 22:02:44 +00001430/// \brief Perform substitution on the type T with a given set of template
1431/// arguments.
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001432///
1433/// This routine substitutes the given template arguments into the
1434/// type T and produces the instantiated type.
1435///
1436/// \param T the type into which the template arguments will be
1437/// substituted. If this type is not dependent, it will be returned
1438/// immediately.
1439///
James Dennett634962f2012-06-14 21:40:34 +00001440/// \param Args the template arguments that will be
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001441/// substituted for the top-level template parameters within T.
1442///
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001443/// \param Loc the location in the source code where this substitution
1444/// is being performed. It will typically be the location of the
1445/// declarator (if we're instantiating the type of some declaration)
1446/// or the location of the type in the source code (if, e.g., we're
1447/// instantiating the type of a cast expression).
1448///
1449/// \param Entity the name of the entity associated with a declaration
1450/// being instantiated (if any). May be empty to indicate that there
1451/// is no such entity (if, e.g., this is a type that occurs as part of
1452/// a cast expression) or that the entity has no name (e.g., an
1453/// unnamed function parameter).
1454///
1455/// \returns If the instantiation succeeds, the instantiated
1456/// type. Otherwise, produces diagnostics and returns a NULL type.
John McCallbcd03502009-12-07 02:54:59 +00001457TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
John McCall609459e2009-10-21 00:58:09 +00001458 const MultiLevelTemplateArgumentList &Args,
1459 SourceLocation Loc,
1460 DeclarationName Entity) {
1461 assert(!ActiveTemplateInstantiations.empty() &&
1462 "Cannot perform an instantiation without some context on the "
1463 "instantiation stack");
1464
Douglas Gregor678d76c2011-07-01 01:22:09 +00001465 if (!T->getType()->isInstantiationDependentType() &&
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001466 !T->getType()->isVariablyModifiedType())
John McCall609459e2009-10-21 00:58:09 +00001467 return T;
1468
1469 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1470 return Instantiator.TransformType(T);
1471}
1472
Douglas Gregor5499af42011-01-05 23:12:31 +00001473TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1474 const MultiLevelTemplateArgumentList &Args,
1475 SourceLocation Loc,
1476 DeclarationName Entity) {
1477 assert(!ActiveTemplateInstantiations.empty() &&
1478 "Cannot perform an instantiation without some context on the "
1479 "instantiation stack");
1480
1481 if (TL.getType().isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001482 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001483
Douglas Gregor678d76c2011-07-01 01:22:09 +00001484 if (!TL.getType()->isInstantiationDependentType() &&
Douglas Gregor5499af42011-01-05 23:12:31 +00001485 !TL.getType()->isVariablyModifiedType()) {
1486 // FIXME: Make a copy of the TypeLoc data here, so that we can
1487 // return a new TypeSourceInfo. Inefficient!
1488 TypeLocBuilder TLB;
1489 TLB.pushFullCopy(TL);
1490 return TLB.getTypeSourceInfo(Context, TL.getType());
1491 }
1492
1493 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1494 TypeLocBuilder TLB;
1495 TLB.reserve(TL.getFullDataSize());
1496 QualType Result = Instantiator.TransformType(TLB, TL);
1497 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001498 return nullptr;
Douglas Gregor5499af42011-01-05 23:12:31 +00001499
1500 return TLB.getTypeSourceInfo(Context, Result);
1501}
1502
John McCall609459e2009-10-21 00:58:09 +00001503/// Deprecated form of the above.
Mike Stump11289f42009-09-09 15:08:12 +00001504QualType Sema::SubstType(QualType T,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001505 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall76d824f2009-08-25 22:02:44 +00001506 SourceLocation Loc, DeclarationName Entity) {
Douglas Gregor79cf6032009-03-10 20:44:00 +00001507 assert(!ActiveTemplateInstantiations.empty() &&
1508 "Cannot perform an instantiation without some context on the "
1509 "instantiation stack");
1510
Douglas Gregor5a5073e2010-05-24 17:22:01 +00001511 // If T is not a dependent type or a variably-modified type, there
1512 // is nothing to do.
Douglas Gregor678d76c2011-07-01 01:22:09 +00001513 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001514 return T;
1515
Douglas Gregord6ff3322009-08-04 16:50:30 +00001516 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1517 return Instantiator.TransformType(T);
Douglas Gregorfe1e1102009-02-27 19:31:52 +00001518}
Douglas Gregor463421d2009-03-03 04:44:36 +00001519
John McCallb29f78f2010-04-09 17:38:44 +00001520static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
Nico Weberc0973372016-02-01 22:31:51 +00001521 if (T->getType()->isInstantiationDependentType() ||
Douglas Gregor678d76c2011-07-01 01:22:09 +00001522 T->getType()->isVariablyModifiedType())
John McCallb29f78f2010-04-09 17:38:44 +00001523 return true;
1524
Abramo Bagnara6d810632010-12-14 22:11:44 +00001525 TypeLoc TL = T->getTypeLoc().IgnoreParens();
David Blaikie6adc78e2013-02-18 22:06:02 +00001526 if (!TL.getAs<FunctionProtoTypeLoc>())
John McCallb29f78f2010-04-09 17:38:44 +00001527 return false;
1528
David Blaikie6adc78e2013-02-18 22:06:02 +00001529 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
Nico Weberc0973372016-02-01 22:31:51 +00001530 for (ParmVarDecl *P : FP.getParams()) {
Reid Klecknera09e44c2013-07-31 21:00:18 +00001531 // This must be synthesized from a typedef.
1532 if (!P) continue;
1533
Nico Weberc0973372016-02-01 22:31:51 +00001534 // If there are any parameters, a new TypeSourceInfo that refers to the
1535 // instantiated parameters must be built.
1536 return true;
John McCallb29f78f2010-04-09 17:38:44 +00001537 }
1538
1539 return false;
1540}
1541
1542/// A form of SubstType intended specifically for instantiating the
1543/// type of a FunctionDecl. Its purpose is solely to force the
Richard Smith2e321552014-11-12 02:00:47 +00001544/// instantiation of default-argument expressions and to avoid
1545/// instantiating an exception-specification.
John McCallb29f78f2010-04-09 17:38:44 +00001546TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1547 const MultiLevelTemplateArgumentList &Args,
1548 SourceLocation Loc,
Douglas Gregor3024f072012-04-16 07:05:22 +00001549 DeclarationName Entity,
1550 CXXRecordDecl *ThisContext,
1551 unsigned ThisTypeQuals) {
John McCallb29f78f2010-04-09 17:38:44 +00001552 assert(!ActiveTemplateInstantiations.empty() &&
1553 "Cannot perform an instantiation without some context on the "
1554 "instantiation stack");
Nico Weberc0973372016-02-01 22:31:51 +00001555
John McCallb29f78f2010-04-09 17:38:44 +00001556 if (!NeedsInstantiationAsFunctionType(T))
1557 return T;
1558
1559 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1560
1561 TypeLocBuilder TLB;
1562
1563 TypeLoc TL = T->getTypeLoc();
1564 TLB.reserve(TL.getFullDataSize());
1565
Douglas Gregor3024f072012-04-16 07:05:22 +00001566 QualType Result;
David Blaikie6adc78e2013-02-18 22:06:02 +00001567
Richard Smith2e321552014-11-12 02:00:47 +00001568 if (FunctionProtoTypeLoc Proto =
1569 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1570 // Instantiate the type, other than its exception specification. The
1571 // exception specification is instantiated in InitFunctionInstantiation
1572 // once we've built the FunctionDecl.
1573 // FIXME: Set the exception specification to EST_Uninstantiated here,
1574 // instead of rebuilding the function type again later.
1575 Result = Instantiator.TransformFunctionProtoType(
1576 TLB, Proto, ThisContext, ThisTypeQuals,
1577 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1578 bool &Changed) { return false; });
Douglas Gregor3024f072012-04-16 07:05:22 +00001579 } else {
1580 Result = Instantiator.TransformType(TLB, TL);
1581 }
John McCallb29f78f2010-04-09 17:38:44 +00001582 if (Result.isNull())
Craig Topperc3ec1492014-05-26 06:22:03 +00001583 return nullptr;
John McCallb29f78f2010-04-09 17:38:44 +00001584
1585 return TLB.getTypeSourceInfo(Context, Result);
1586}
1587
Richard Smith2e321552014-11-12 02:00:47 +00001588void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1589 const MultiLevelTemplateArgumentList &Args) {
1590 FunctionProtoType::ExceptionSpecInfo ESI =
1591 Proto->getExtProtoInfo().ExceptionSpec;
1592 assert(ESI.Type != EST_Uninstantiated);
1593
1594 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1595 New->getDeclName());
1596
1597 SmallVector<QualType, 4> ExceptionStorage;
1598 bool Changed = false;
1599 if (Instantiator.TransformExceptionSpec(
1600 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1601 ExceptionStorage, Changed))
1602 // On error, recover by dropping the exception specification.
1603 ESI.Type = EST_None;
1604
1605 UpdateExceptionSpec(New, ESI);
1606}
1607
Douglas Gregor940bca72010-04-12 07:48:19 +00001608ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
Douglas Gregor715e4612011-01-14 22:40:04 +00001609 const MultiLevelTemplateArgumentList &TemplateArgs,
John McCall8fb0d9d2011-05-01 22:35:37 +00001610 int indexAdjustment,
David Blaikie05785d12013-02-20 22:23:23 +00001611 Optional<unsigned> NumExpansions,
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001612 bool ExpectParameterPack) {
Douglas Gregor940bca72010-04-12 07:48:19 +00001613 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
Craig Topperc3ec1492014-05-26 06:22:03 +00001614 TypeSourceInfo *NewDI = nullptr;
1615
Douglas Gregor5499af42011-01-05 23:12:31 +00001616 TypeLoc OldTL = OldDI->getTypeLoc();
David Blaikie6adc78e2013-02-18 22:06:02 +00001617 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1618
Douglas Gregor5499af42011-01-05 23:12:31 +00001619 // We have a function parameter pack. Substitute into the pattern of the
1620 // expansion.
1621 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1622 OldParm->getLocation(), OldParm->getDeclName());
1623 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001624 return nullptr;
1625
Douglas Gregor5499af42011-01-05 23:12:31 +00001626 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1627 // We still have unexpanded parameter packs, which means that
1628 // our function parameter is still a function parameter pack.
1629 // Therefore, make its type a pack expansion type.
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001630 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
Douglas Gregor715e4612011-01-14 22:40:04 +00001631 NumExpansions);
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001632 } else if (ExpectParameterPack) {
1633 // We expected to get a parameter pack but didn't (because the type
1634 // itself is not a pack expansion type), so complain. This can occur when
1635 // the substitution goes through an alias template that "loses" the
1636 // pack expansion.
1637 Diag(OldParm->getLocation(),
1638 diag::err_function_parameter_pack_without_parameter_packs)
1639 << NewDI->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001640 return nullptr;
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001641 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001642 } else {
1643 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1644 OldParm->getDeclName());
1645 }
1646
Douglas Gregor940bca72010-04-12 07:48:19 +00001647 if (!NewDI)
Craig Topperc3ec1492014-05-26 06:22:03 +00001648 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001649
1650 if (NewDI->getType()->isVoidType()) {
1651 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
Craig Topperc3ec1492014-05-26 06:22:03 +00001652 return nullptr;
Douglas Gregor940bca72010-04-12 07:48:19 +00001653 }
1654
1655 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001656 OldParm->getInnerLocStart(),
Douglas Gregor940bca72010-04-12 07:48:19 +00001657 OldParm->getLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001658 OldParm->getIdentifier(),
1659 NewDI->getType(), NewDI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001660 OldParm->getStorageClass());
Douglas Gregor940bca72010-04-12 07:48:19 +00001661 if (!NewParm)
Craig Topperc3ec1492014-05-26 06:22:03 +00001662 return nullptr;
1663
Douglas Gregor940bca72010-04-12 07:48:19 +00001664 // Mark the (new) default argument as uninstantiated (if any).
1665 if (OldParm->hasUninstantiatedDefaultArg()) {
1666 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1667 NewParm->setUninstantiatedDefaultArg(Arg);
Douglas Gregor758cb672010-10-12 18:23:32 +00001668 } else if (OldParm->hasUnparsedDefaultArg()) {
1669 NewParm->setUnparsedDefaultArg();
1670 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001671 } else if (Expr *Arg = OldParm->getDefaultArg()) {
1672 FunctionDecl *OwningFunc = cast<FunctionDecl>(OldParm->getDeclContext());
Serge Pavlov73c6a242015-08-23 10:22:28 +00001673 if (OwningFunc->isLexicallyWithinFunctionOrMethod()) {
1674 // Instantiate default arguments for methods of local classes (DR1484)
1675 // and non-defining declarations.
1676 Sema::ContextRAII SavedContext(*this, OwningFunc);
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001677 LocalInstantiationScope Local(*this);
1678 ExprResult NewArg = SubstExpr(Arg, TemplateArgs);
John McCalldc40b612015-12-11 01:56:36 +00001679 if (NewArg.isUsable()) {
1680 // It would be nice if we still had this.
1681 SourceLocation EqualLoc = NewArg.get()->getLocStart();
1682 SetParamDefaultArgument(NewParm, NewArg.get(), EqualLoc);
1683 }
Serge Pavlov3739f5e72015-06-29 17:50:19 +00001684 } else {
1685 // FIXME: if we non-lazily instantiated non-dependent default args for
1686 // non-dependent parameter types we could remove a bunch of duplicate
1687 // conversion warnings for such arguments.
1688 NewParm->setUninstantiatedDefaultArg(Arg);
1689 }
1690 }
Douglas Gregor940bca72010-04-12 07:48:19 +00001691
1692 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
Douglas Gregor0dd22bc2012-01-25 16:15:54 +00001693
Douglas Gregorf3010112011-01-07 16:43:16 +00001694 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
Richard Smith928be492012-01-25 02:14:59 +00001695 // Add the new parameter to the instantiated parameter pack.
Douglas Gregorf3010112011-01-07 16:43:16 +00001696 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1697 } else {
1698 // Introduce an Old -> New mapping
Douglas Gregor5499af42011-01-05 23:12:31 +00001699 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
Douglas Gregorf3010112011-01-07 16:43:16 +00001700 }
Douglas Gregor5499af42011-01-05 23:12:31 +00001701
Argyrios Kyrtzidis3816ed42010-07-19 10:14:41 +00001702 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1703 // can be anything, is this right ?
Fariborz Jahanian714447b2010-07-13 21:05:02 +00001704 NewParm->setDeclContext(CurContext);
John McCall8fb0d9d2011-05-01 22:35:37 +00001705
1706 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1707 OldParm->getFunctionScopeIndex() + indexAdjustment);
Jordan Rosea0a86be2013-03-08 22:25:36 +00001708
1709 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1710
Douglas Gregor940bca72010-04-12 07:48:19 +00001711 return NewParm;
1712}
1713
Douglas Gregordd472162011-01-07 00:20:55 +00001714/// \brief Substitute the given template arguments into the given set of
1715/// parameters, producing the set of parameter types that would be generated
1716/// from such a substitution.
David Majnemer59f77922016-06-24 04:05:48 +00001717bool Sema::SubstParmTypes(
1718 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
1719 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
1720 const MultiLevelTemplateArgumentList &TemplateArgs,
1721 SmallVectorImpl<QualType> &ParamTypes,
1722 SmallVectorImpl<ParmVarDecl *> *OutParams,
1723 ExtParameterInfoBuilder &ParamInfos) {
Douglas Gregordd472162011-01-07 00:20:55 +00001724 assert(!ActiveTemplateInstantiations.empty() &&
1725 "Cannot perform an instantiation without some context on the "
1726 "instantiation stack");
1727
1728 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1729 DeclarationName());
David Majnemer59f77922016-06-24 04:05:48 +00001730 return Instantiator.TransformFunctionTypeParams(
1731 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
Douglas Gregordd472162011-01-07 00:20:55 +00001732}
1733
John McCall76d824f2009-08-25 22:02:44 +00001734/// \brief Perform substitution on the base class specifiers of the
1735/// given class template specialization.
Douglas Gregor463421d2009-03-03 04:44:36 +00001736///
1737/// Produces a diagnostic and returns true on error, returns false and
1738/// attaches the instantiated base classes to the class template
1739/// specialization if successful.
Mike Stump11289f42009-09-09 15:08:12 +00001740bool
John McCall76d824f2009-08-25 22:02:44 +00001741Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1742 CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001743 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001744 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001745 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
Richard Trieub5841332015-04-15 01:21:42 +00001746 for (const auto &Base : Pattern->bases()) {
Aaron Ballman574705e2014-03-13 15:41:46 +00001747 if (!Base.getType()->isDependentType()) {
1748 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
Matt Beaumont-Gay76d0b462013-06-21 18:58:32 +00001749 if (RD->isInvalidDecl())
1750 Instantiation->setInvalidDecl();
1751 }
Aaron Ballman574705e2014-03-13 15:41:46 +00001752 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
Douglas Gregor463421d2009-03-03 04:44:36 +00001753 continue;
1754 }
1755
Douglas Gregor752a5952011-01-03 22:36:02 +00001756 SourceLocation EllipsisLoc;
Douglas Gregorc52264e2011-03-02 02:04:06 +00001757 TypeSourceInfo *BaseTypeLoc;
Aaron Ballman574705e2014-03-13 15:41:46 +00001758 if (Base.isPackExpansion()) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001759 // This is a pack expansion. See whether we should expand it now, or
1760 // wait until later.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001761 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
Aaron Ballman574705e2014-03-13 15:41:46 +00001762 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001763 Unexpanded);
1764 bool ShouldExpand = false;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001765 bool RetainExpansion = false;
David Blaikie05785d12013-02-20 22:23:23 +00001766 Optional<unsigned> NumExpansions;
Aaron Ballman574705e2014-03-13 15:41:46 +00001767 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1768 Base.getSourceRange(),
David Blaikieb9c168a2011-09-22 02:34:54 +00001769 Unexpanded,
Douglas Gregor752a5952011-01-03 22:36:02 +00001770 TemplateArgs, ShouldExpand,
Douglas Gregora8bac7f2011-01-10 07:32:04 +00001771 RetainExpansion,
Douglas Gregor752a5952011-01-03 22:36:02 +00001772 NumExpansions)) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001773 Invalid = true;
Douglas Gregor44e7df62011-01-04 00:32:56 +00001774 continue;
Douglas Gregor752a5952011-01-03 22:36:02 +00001775 }
1776
1777 // If we should expand this pack expansion now, do so.
1778 if (ShouldExpand) {
Douglas Gregor0dca5fd2011-01-14 17:04:44 +00001779 for (unsigned I = 0; I != *NumExpansions; ++I) {
Douglas Gregor752a5952011-01-03 22:36:02 +00001780 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1781
Aaron Ballman574705e2014-03-13 15:41:46 +00001782 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001783 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001784 Base.getSourceRange().getBegin(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001785 DeclarationName());
1786 if (!BaseTypeLoc) {
1787 Invalid = true;
1788 continue;
1789 }
1790
1791 if (CXXBaseSpecifier *InstantiatedBase
1792 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001793 Base.getSourceRange(),
1794 Base.isVirtual(),
1795 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001796 BaseTypeLoc,
1797 SourceLocation()))
1798 InstantiatedBases.push_back(InstantiatedBase);
1799 else
1800 Invalid = true;
1801 }
1802
1803 continue;
1804 }
1805
1806 // The resulting base specifier will (still) be a pack expansion.
Aaron Ballman574705e2014-03-13 15:41:46 +00001807 EllipsisLoc = Base.getEllipsisLoc();
Douglas Gregorc52264e2011-03-02 02:04:06 +00001808 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
Aaron Ballman574705e2014-03-13 15:41:46 +00001809 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001810 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001811 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001812 DeclarationName());
1813 } else {
Aaron Ballman574705e2014-03-13 15:41:46 +00001814 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001815 TemplateArgs,
Aaron Ballman574705e2014-03-13 15:41:46 +00001816 Base.getSourceRange().getBegin(),
Douglas Gregorc52264e2011-03-02 02:04:06 +00001817 DeclarationName());
Douglas Gregor752a5952011-01-03 22:36:02 +00001818 }
1819
Nick Lewycky19b9f952010-07-26 16:56:01 +00001820 if (!BaseTypeLoc) {
Douglas Gregor463421d2009-03-03 04:44:36 +00001821 Invalid = true;
1822 continue;
1823 }
1824
1825 if (CXXBaseSpecifier *InstantiatedBase
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001826 = CheckBaseSpecifier(Instantiation,
Aaron Ballman574705e2014-03-13 15:41:46 +00001827 Base.getSourceRange(),
1828 Base.isVirtual(),
1829 Base.getAccessSpecifierAsWritten(),
Douglas Gregor752a5952011-01-03 22:36:02 +00001830 BaseTypeLoc,
1831 EllipsisLoc))
Douglas Gregor463421d2009-03-03 04:44:36 +00001832 InstantiatedBases.push_back(InstantiatedBase);
1833 else
1834 Invalid = true;
1835 }
1836
Craig Topperaa700cb2015-12-27 21:55:19 +00001837 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
Douglas Gregor463421d2009-03-03 04:44:36 +00001838 Invalid = true;
1839
1840 return Invalid;
1841}
1842
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001843// Defined via #include from SemaTemplateInstantiateDecl.cpp
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00001844namespace clang {
1845 namespace sema {
1846 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1847 const MultiLevelTemplateArgumentList &TemplateArgs);
1848 }
1849}
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001850
Richard Smith4b38ded2012-03-14 23:13:10 +00001851/// Determine whether we would be unable to instantiate this template (because
1852/// it either has no definition, or is in the process of being instantiated).
1853static bool DiagnoseUninstantiableTemplate(Sema &S,
1854 SourceLocation PointOfInstantiation,
1855 TagDecl *Instantiation,
1856 bool InstantiatedFromMember,
1857 TagDecl *Pattern,
1858 TagDecl *PatternDef,
1859 TemplateSpecializationKind TSK,
1860 bool Complain = true) {
Richard Smith6739a102016-05-05 00:56:12 +00001861 if (PatternDef && !PatternDef->isBeingDefined()) {
1862 NamedDecl *SuggestedDef = nullptr;
1863 if (!S.hasVisibleDefinition(PatternDef, &SuggestedDef,
1864 /*OnlyNeedComplete*/false)) {
1865 // If we're allowed to diagnose this and recover, do so.
1866 bool Recover = Complain && !S.isSFINAEContext();
1867 if (Complain)
1868 S.diagnoseMissingImport(PointOfInstantiation, SuggestedDef,
1869 Sema::MissingImportKind::Definition, Recover);
1870 return !Recover;
1871 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001872 return false;
Richard Smith6739a102016-05-05 00:56:12 +00001873 }
Richard Smith4b38ded2012-03-14 23:13:10 +00001874
1875 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1876 // Say nothing
1877 } else if (PatternDef) {
1878 assert(PatternDef->isBeingDefined());
1879 S.Diag(PointOfInstantiation,
1880 diag::err_template_instantiate_within_definition)
1881 << (TSK != TSK_ImplicitInstantiation)
1882 << S.Context.getTypeDeclType(Instantiation);
1883 // Not much point in noting the template declaration here, since
1884 // we're lexically inside it.
1885 Instantiation->setInvalidDecl();
1886 } else if (InstantiatedFromMember) {
1887 S.Diag(PointOfInstantiation,
1888 diag::err_implicit_instantiate_member_undefined)
1889 << S.Context.getTypeDeclType(Instantiation);
Alp Toker2afa8782014-05-28 12:20:14 +00001890 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
Richard Smith4b38ded2012-03-14 23:13:10 +00001891 } else {
1892 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1893 << (TSK != TSK_ImplicitInstantiation)
1894 << S.Context.getTypeDeclType(Instantiation);
1895 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1896 }
1897
1898 // In general, Instantiation isn't marked invalid to get more than one
1899 // error for multiple undefined instantiations. But the code that does
1900 // explicit declaration -> explicit definition conversion can't handle
1901 // invalid declarations, so mark as invalid in that case.
1902 if (TSK == TSK_ExplicitInstantiationDeclaration)
1903 Instantiation->setInvalidDecl();
1904 return true;
1905}
1906
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001907/// \brief Instantiate the definition of a class from a given pattern.
1908///
1909/// \param PointOfInstantiation The point of instantiation within the
1910/// source code.
1911///
1912/// \param Instantiation is the declaration whose definition is being
1913/// instantiated. This will be either a class template specialization
1914/// or a member class of a class template specialization.
1915///
1916/// \param Pattern is the pattern from which the instantiation
1917/// occurs. This will be either the declaration of a class template or
1918/// the declaration of a member class of a class template.
1919///
1920/// \param TemplateArgs The template arguments to be substituted into
1921/// the pattern.
1922///
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001923/// \param TSK the kind of implicit or explicit instantiation to perform.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001924///
1925/// \param Complain whether to complain if the class cannot be instantiated due
1926/// to the lack of a definition.
1927///
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001928/// \returns true if an error occurred, false otherwise.
1929bool
1930Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1931 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
Douglas Gregor01afeef2009-08-28 20:31:08 +00001932 const MultiLevelTemplateArgumentList &TemplateArgs,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00001933 TemplateSpecializationKind TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001934 bool Complain) {
Mike Stump11289f42009-09-09 15:08:12 +00001935 CXXRecordDecl *PatternDef
Douglas Gregor0a5a2212010-02-11 01:04:33 +00001936 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
Richard Smith4b38ded2012-03-14 23:13:10 +00001937 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1938 Instantiation->getInstantiatedFromMemberClass(),
1939 Pattern, PatternDef, TSK, Complain))
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001940 return true;
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001941 Pattern = PatternDef;
1942
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001943 // \brief Record the point of instantiation.
1944 if (MemberSpecializationInfo *MSInfo
1945 = Instantiation->getMemberSpecializationInfo()) {
1946 MSInfo->setTemplateSpecializationKind(TSK);
1947 MSInfo->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregoref6ab412009-10-27 06:26:26 +00001948 } else if (ClassTemplateSpecializationDecl *Spec
Nico Weber3ffc4c92011-12-20 20:32:49 +00001949 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
Douglas Gregoref6ab412009-10-27 06:26:26 +00001950 Spec->setTemplateSpecializationKind(TSK);
1951 Spec->setPointOfInstantiation(PointOfInstantiation);
Douglas Gregord6ba93d2009-10-15 15:54:05 +00001952 }
Richard Smitha1087602014-03-10 00:04:29 +00001953
Douglas Gregorf3430ae2009-03-25 21:23:52 +00001954 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00001955 if (Inst.isInvalid())
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001956 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00001957 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
1958 "instantiating class definition");
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001959
1960 // Enter the scope of this instantiation. We don't use
1961 // PushDeclContext because we don't have a scope.
John McCall80e58cd2010-04-29 00:35:03 +00001962 ContextRAII SavedContext(*this, Instantiation);
Douglas Gregor17158422010-05-12 17:27:19 +00001963 EnterExpressionEvaluationContext EvalContext(*this,
John McCallfaf5fb42010-08-26 23:41:50 +00001964 Sema::PotentiallyEvaluated);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001965
Douglas Gregor51121572010-03-24 01:33:17 +00001966 // If this is an instantiation of a local class, merge this local
1967 // instantiation scope with the enclosing scope. Otherwise, every
1968 // instantiation of a class has its own local instantiation scope.
1969 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
John McCall19c1bfd2010-08-25 05:32:35 +00001970 LocalInstantiationScope Scope(*this, MergeWithParentScope);
Douglas Gregor51121572010-03-24 01:33:17 +00001971
Reid Kleckner5b640342016-02-26 19:51:02 +00001972 // All dllexported classes created during instantiation should be fully
1973 // emitted after instantiation completes. We may not be ready to emit any
1974 // delayed classes already on the stack, so save them away and put them back
1975 // later.
1976 decltype(DelayedDllExportClasses) ExportedClasses;
1977 std::swap(ExportedClasses, DelayedDllExportClasses);
1978
John McCall6602bb12010-08-01 02:01:53 +00001979 // Pull attributes from the pattern onto the instantiation.
1980 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1981
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001982 // Start the definition of this instantiation.
1983 Instantiation->startDefinition();
Richard Smitha1087602014-03-10 00:04:29 +00001984
1985 // The instantiation is visible here, even if it was first declared in an
1986 // unimported module.
1987 Instantiation->setHidden(false);
1988
1989 // FIXME: This loses the as-written tag kind for an explicit instantiation.
Douglas Gregore9029562010-05-06 00:28:52 +00001990 Instantiation->setTagKind(Pattern->getTagKind());
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001991
John McCall76d824f2009-08-25 22:02:44 +00001992 // Do substitution on the base class specifiers.
1993 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
Douglas Gregorb9b8b812012-07-02 21:00:41 +00001994 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00001995
Douglas Gregor869853e2010-11-10 19:44:59 +00001996 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001997 SmallVector<Decl*, 4> Fields;
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00001998 // Delay instantiation of late parsed attributes.
1999 LateInstantiatedAttrVec LateAttrs;
2000 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2001
Aaron Ballman629afae2014-03-07 19:56:05 +00002002 for (auto *Member : Pattern->decls()) {
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002003 // Don't instantiate members not belonging in this semantic context.
2004 // e.g. for:
2005 // @code
2006 // template <int i> class A {
2007 // class B *g;
2008 // };
2009 // @endcode
2010 // 'class B' has the template as lexical context but semantically it is
2011 // introduced in namespace scope.
Aaron Ballman629afae2014-03-07 19:56:05 +00002012 if (Member->getDeclContext() != Pattern)
Argyrios Kyrtzidis9a94d9b2010-11-04 03:18:57 +00002013 continue;
2014
Aaron Ballman629afae2014-03-07 19:56:05 +00002015 if (Member->isInvalidDecl()) {
Richard Smithded9c2e2012-07-11 22:37:56 +00002016 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002017 continue;
2018 }
2019
Aaron Ballman629afae2014-03-07 19:56:05 +00002020 Decl *NewMember = Instantiator.Visit(Member);
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002021 if (NewMember) {
Richard Smith938f40b2011-06-11 17:19:42 +00002022 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
John McCall48871652010-08-21 09:40:31 +00002023 Fields.push_back(Field);
Richard Smith7d137e32012-03-23 03:33:32 +00002024 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2025 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2026 // specialization causes the implicit instantiation of the definitions
2027 // of unscoped member enumerations.
2028 // Record a point of instantiation for this implicit instantiation.
Richard Smithb66d7772012-03-23 23:09:08 +00002029 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2030 Enum->isCompleteDefinition()) {
Richard Smith7d137e32012-03-23 03:33:32 +00002031 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2032 assert(MSInfo && "no spec info for member enum specialization");
2033 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2034 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2035 }
Richard Smithded9c2e2012-07-11 22:37:56 +00002036 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2037 if (SA->isFailed()) {
2038 // A static_assert failed. Bail out; instantiating this
2039 // class is probably not meaningful.
2040 Instantiation->setInvalidDecl();
2041 break;
2042 }
Richard Smith7d137e32012-03-23 03:33:32 +00002043 }
2044
2045 if (NewMember->isInvalidDecl())
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002046 Instantiation->setInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002047 } else {
2048 // FIXME: Eventually, a NULL return will mean that one of the
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002049 // instantiations was a semantic disaster, and we'll want to mark the
2050 // declaration invalid.
2051 // For now, we expect to skip some members that we can't yet handle.
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002052 }
2053 }
2054
2055 // Finish checking fields.
Craig Topperc3ec1492014-05-26 06:22:03 +00002056 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2057 SourceLocation(), SourceLocation(), nullptr);
Douglas Gregor0be31a22010-07-02 17:43:08 +00002058 CheckCompletedCXXClass(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002059
Reid Kleckner93f661a2015-03-17 21:51:43 +00002060 // Default arguments are parsed, if not instantiated. We can go instantiate
2061 // default arg exprs for default constructors if necessary now.
Hans Wennborg99000c22015-08-15 01:18:16 +00002062 ActOnFinishCXXNonNestedClass(Instantiation);
Reid Kleckner93f661a2015-03-17 21:51:43 +00002063
Reid Kleckner5b640342016-02-26 19:51:02 +00002064 // Put back the delayed exported classes that we moved out of the way.
2065 std::swap(ExportedClasses, DelayedDllExportClasses);
2066
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002067 // Instantiate late parsed attributes, and attach them to their decls.
2068 // See Sema::InstantiateAttrs
2069 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2070 E = LateAttrs.end(); I != E; ++I) {
2071 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2072 CurrentInstantiationScope = I->Scope;
Richard Smithc3d2ebb2013-06-07 02:33:37 +00002073
2074 // Allow 'this' within late-parsed attributes.
2075 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2076 CXXRecordDecl *ThisContext =
2077 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2078 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2079 ND && ND->isCXXInstanceMember());
2080
DeLesley Hutchins30398dd2012-01-20 22:50:54 +00002081 Attr *NewAttr =
2082 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2083 I->NewDecl->addAttr(NewAttr);
2084 LocalInstantiationScope::deleteScopes(I->Scope,
2085 Instantiator.getStartingScope());
2086 }
2087 Instantiator.disableLateAttributeInstantiation();
2088 LateAttrs.clear();
2089
Richard Smithd3b5c9082012-07-27 04:22:15 +00002090 ActOnFinishDelayedMemberInitializers(Instantiation);
Richard Smith938f40b2011-06-11 17:19:42 +00002091
Richard Smitha1087602014-03-10 00:04:29 +00002092 // FIXME: We should do something similar for explicit instantiations so they
2093 // end up in the right module.
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002094 if (TSK == TSK_ImplicitInstantiation) {
Argyrios Kyrtzidise3789482012-02-11 01:59:57 +00002095 Instantiation->setLocation(Pattern->getLocation());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002096 Instantiation->setLocStart(Pattern->getInnerLocStart());
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002097 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
Abramo Bagnara12dcbf32011-11-18 08:08:52 +00002098 }
Abramo Bagnarafd3a4552011-10-03 20:34:03 +00002099
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002100 if (!Instantiation->isInvalidDecl()) {
John McCalla0a96892012-08-10 03:15:35 +00002101 // Perform any dependent diagnostics from the pattern.
2102 PerformDependentDiagnostics(Pattern, TemplateArgs);
2103
Douglas Gregor869853e2010-11-10 19:44:59 +00002104 // Instantiate any out-of-line class template partial
2105 // specializations now.
Richard Smith10b55fc2013-09-26 03:49:48 +00002106 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
Douglas Gregor869853e2010-11-10 19:44:59 +00002107 P = Instantiator.delayed_partial_spec_begin(),
2108 PEnd = Instantiator.delayed_partial_spec_end();
2109 P != PEnd; ++P) {
2110 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
Richard Smith10b55fc2013-09-26 03:49:48 +00002111 P->first, P->second)) {
2112 Instantiation->setInvalidDecl();
2113 break;
2114 }
2115 }
2116
2117 // Instantiate any out-of-line variable template partial
2118 // specializations now.
2119 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2120 P = Instantiator.delayed_var_partial_spec_begin(),
2121 PEnd = Instantiator.delayed_var_partial_spec_end();
2122 P != PEnd; ++P) {
2123 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2124 P->first, P->second)) {
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002125 Instantiation->setInvalidDecl();
Douglas Gregor869853e2010-11-10 19:44:59 +00002126 break;
2127 }
2128 }
2129 }
2130
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002131 // Exit the scope of this instantiation.
John McCall80e58cd2010-04-29 00:35:03 +00002132 SavedContext.pop();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002133
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002134 if (!Instantiation->isInvalidDecl()) {
Douglas Gregor28ad4b52009-05-26 20:50:29 +00002135 Consumer.HandleTagDeclDefinition(Instantiation);
2136
Douglas Gregor88d292c2010-05-13 16:44:06 +00002137 // Always emit the vtable for an explicit instantiation definition
2138 // of a polymorphic class template specialization.
2139 if (TSK == TSK_ExplicitInstantiationDefinition)
2140 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2141 }
2142
Douglas Gregorb9b8b812012-07-02 21:00:41 +00002143 return Instantiation->isInvalidDecl();
Douglas Gregor8ea8fd42009-03-25 21:17:03 +00002144}
2145
Richard Smith4b38ded2012-03-14 23:13:10 +00002146/// \brief Instantiate the definition of an enum from a given pattern.
2147///
2148/// \param PointOfInstantiation The point of instantiation within the
2149/// source code.
2150/// \param Instantiation is the declaration whose definition is being
2151/// instantiated. This will be a member enumeration of a class
2152/// temploid specialization, or a local enumeration within a
2153/// function temploid specialization.
2154/// \param Pattern The templated declaration from which the instantiation
2155/// occurs.
2156/// \param TemplateArgs The template arguments to be substituted into
2157/// the pattern.
2158/// \param TSK The kind of implicit or explicit instantiation to perform.
2159///
2160/// \return \c true if an error occurred, \c false otherwise.
2161bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2162 EnumDecl *Instantiation, EnumDecl *Pattern,
2163 const MultiLevelTemplateArgumentList &TemplateArgs,
2164 TemplateSpecializationKind TSK) {
2165 EnumDecl *PatternDef = Pattern->getDefinition();
2166 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2167 Instantiation->getInstantiatedFromMemberEnum(),
2168 Pattern, PatternDef, TSK,/*Complain*/true))
2169 return true;
2170 Pattern = PatternDef;
2171
2172 // Record the point of instantiation.
2173 if (MemberSpecializationInfo *MSInfo
2174 = Instantiation->getMemberSpecializationInfo()) {
2175 MSInfo->setTemplateSpecializationKind(TSK);
2176 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2177 }
2178
2179 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
Alp Tokerd4a72d52013-10-08 08:09:04 +00002180 if (Inst.isInvalid())
Richard Smith4b38ded2012-03-14 23:13:10 +00002181 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00002182 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2183 "instantiating enum definition");
Richard Smith4b38ded2012-03-14 23:13:10 +00002184
Richard Smitha1087602014-03-10 00:04:29 +00002185 // The instantiation is visible here, even if it was first declared in an
2186 // unimported module.
2187 Instantiation->setHidden(false);
2188
Richard Smith4b38ded2012-03-14 23:13:10 +00002189 // Enter the scope of this instantiation. We don't use
2190 // PushDeclContext because we don't have a scope.
2191 ContextRAII SavedContext(*this, Instantiation);
2192 EnterExpressionEvaluationContext EvalContext(*this,
2193 Sema::PotentiallyEvaluated);
2194
2195 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2196
2197 // Pull attributes from the pattern onto the instantiation.
2198 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2199
2200 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2201 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2202
2203 // Exit the scope of this instantiation.
2204 SavedContext.pop();
2205
2206 return Instantiation->isInvalidDecl();
2207}
2208
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002209
2210/// \brief Instantiate the definition of a field from the given pattern.
2211///
2212/// \param PointOfInstantiation The point of instantiation within the
2213/// source code.
2214/// \param Instantiation is the declaration whose definition is being
2215/// instantiated. This will be a class of a class temploid
2216/// specialization, or a local enumeration within a function temploid
2217/// specialization.
2218/// \param Pattern The templated declaration from which the instantiation
2219/// occurs.
2220/// \param TemplateArgs The template arguments to be substituted into
2221/// the pattern.
2222///
2223/// \return \c true if an error occurred, \c false otherwise.
2224bool Sema::InstantiateInClassInitializer(
2225 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2226 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2227 // If there is no initializer, we don't need to do anything.
2228 if (!Pattern->hasInClassInitializer())
2229 return false;
2230
2231 assert(Instantiation->getInClassInitStyle() ==
2232 Pattern->getInClassInitStyle() &&
2233 "pattern and instantiation disagree about init style");
2234
2235 // Error out if we haven't parsed the initializer of the pattern yet because
2236 // we are waiting for the closing brace of the outer class.
2237 Expr *OldInit = Pattern->getInClassInitializer();
2238 if (!OldInit) {
2239 RecordDecl *PatternRD = Pattern->getParent();
2240 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2241 if (OutermostClass == PatternRD) {
2242 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2243 << PatternRD << Pattern;
2244 } else {
2245 Diag(Pattern->getLocEnd(),
2246 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2247 << PatternRD << OutermostClass << Pattern;
2248 }
2249 Instantiation->setInvalidDecl();
2250 return true;
2251 }
2252
2253 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2254 if (Inst.isInvalid())
2255 return true;
Richard Smithe19b95d2016-05-26 20:23:13 +00002256 PrettyDeclStackTraceEntry CrashInfo(*this, Instantiation, SourceLocation(),
2257 "instantiating default member init");
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002258
2259 // Enter the scope of this instantiation. We don't use PushDeclContext because
2260 // we don't have a scope.
2261 ContextRAII SavedContext(*this, Instantiation->getParent());
2262 EnterExpressionEvaluationContext EvalContext(*this,
2263 Sema::PotentiallyEvaluated);
2264
Serge Pavlov907233f2015-04-28 17:58:47 +00002265 LocalInstantiationScope Scope(*this, true);
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002266
2267 // Instantiate the initializer.
2268 ActOnStartCXXInClassMemberInitializer();
2269 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2270
2271 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2272 /*CXXDirectInit=*/false);
2273 Expr *Init = NewInit.get();
2274 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2275 ActOnFinishCXXInClassMemberInitializer(
2276 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2277
2278 // Exit the scope of this instantiation.
2279 SavedContext.pop();
2280
2281 // Return true if the in-class initializer is still missing.
2282 return !Instantiation->getInClassInitializer();
2283}
2284
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002285namespace {
2286 /// \brief A partial specialization whose template arguments have matched
2287 /// a given template-id.
2288 struct PartialSpecMatchResult {
2289 ClassTemplatePartialSpecializationDecl *Partial;
2290 TemplateArgumentList *Args;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002291 };
2292}
2293
Larisse Voufo72caf2b2013-08-22 00:59:14 +00002294bool Sema::InstantiateClassTemplateSpecialization(
2295 SourceLocation PointOfInstantiation,
2296 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2297 TemplateSpecializationKind TSK, bool Complain) {
Douglas Gregor463421d2009-03-03 04:44:36 +00002298 // Perform the actual instantiation on the canonical declaration.
2299 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00002300 ClassTemplateSpec->getCanonicalDecl());
Douglas Gregor00a511f2009-09-15 16:51:42 +00002301 if (ClassTemplateSpec->isInvalidDecl())
2302 return true;
2303
Douglas Gregor463421d2009-03-03 04:44:36 +00002304 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
Craig Topperc3ec1492014-05-26 06:22:03 +00002305 CXXRecordDecl *Pattern = nullptr;
Douglas Gregor2373c592009-05-31 09:31:02 +00002306
Douglas Gregor170bc422009-06-12 22:31:52 +00002307 // C++ [temp.class.spec.match]p1:
2308 // When a class template is used in a context that requires an
2309 // instantiation of the class, it is necessary to determine
2310 // whether the instantiation is to be generated using the primary
2311 // template or one of the partial specializations. This is done by
2312 // matching the template arguments of the class template
2313 // specialization with the template argument lists of the partial
2314 // specializations.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002315 typedef PartialSpecMatchResult MatchResult;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002316 SmallVector<MatchResult, 4> Matched;
2317 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
Douglas Gregor407e9612010-04-30 05:56:50 +00002318 Template->getPartialSpecializations(PartialSpecs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00002319 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
Douglas Gregor407e9612010-04-30 05:56:50 +00002320 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2321 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
Larisse Voufo98b20f12013-07-19 23:00:19 +00002322 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002323 if (TemplateDeductionResult Result
Douglas Gregor407e9612010-04-30 05:56:50 +00002324 = DeduceTemplateArguments(Partial,
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002325 ClassTemplateSpec->getTemplateArgs(),
2326 Info)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00002327 // Store the failed-deduction information for use in diagnostics, later.
2328 // TODO: Actually use the failed-deduction info?
Richard Smithc2bebe92016-05-11 20:37:46 +00002329 FailedCandidates.addCandidate().set(
2330 DeclAccessPair::make(Template, AS_public), Partial,
2331 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002332 (void)Result;
2333 } else {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002334 Matched.push_back(PartialSpecMatchResult());
2335 Matched.back().Partial = Partial;
2336 Matched.back().Args = Info.take();
Douglas Gregor181aa4a2009-06-12 18:26:56 +00002337 }
Douglas Gregor2373c592009-05-31 09:31:02 +00002338 }
2339
Douglas Gregor0231d8d2011-01-19 20:10:05 +00002340 // If we're dealing with a member template where the template parameters
2341 // have been instantiated, this provides the original template parameters
2342 // from which the member template's parameters were instantiated.
Alp Toker965f8822013-11-27 05:22:15 +00002343
Douglas Gregor21610382009-10-29 00:04:11 +00002344 if (Matched.size() >= 1) {
Craig Topper2341c0d2013-07-04 03:08:24 +00002345 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
Douglas Gregor21610382009-10-29 00:04:11 +00002346 if (Matched.size() == 1) {
2347 // -- If exactly one matching specialization is found, the
2348 // instantiation is generated from that specialization.
2349 // We don't need to do anything for this.
2350 } else {
2351 // -- If more than one matching specialization is found, the
2352 // partial order rules (14.5.4.2) are used to determine
2353 // whether one of the specializations is more specialized
2354 // than the others. If none of the specializations is more
2355 // specialized than all of the other matching
2356 // specializations, then the use of the class template is
2357 // ambiguous and the program is ill-formed.
Craig Topper2341c0d2013-07-04 03:08:24 +00002358 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2359 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002360 P != PEnd; ++P) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002361 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002362 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002363 == P->Partial)
Douglas Gregor21610382009-10-29 00:04:11 +00002364 Best = P;
Douglas Gregorbe999392009-09-15 16:23:51 +00002365 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002366
Douglas Gregor21610382009-10-29 00:04:11 +00002367 // Determine if the best partial specialization is more specialized than
2368 // the others.
2369 bool Ambiguous = false;
Craig Topper2341c0d2013-07-04 03:08:24 +00002370 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2371 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002372 P != PEnd; ++P) {
2373 if (P != Best &&
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002374 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
John McCallbc077cf2010-02-08 23:07:23 +00002375 PointOfInstantiation)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002376 != Best->Partial) {
Douglas Gregor21610382009-10-29 00:04:11 +00002377 Ambiguous = true;
2378 break;
2379 }
2380 }
2381
2382 if (Ambiguous) {
2383 // Partial ordering did not produce a clear winner. Complain.
2384 ClassTemplateSpec->setInvalidDecl();
2385 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2386 << ClassTemplateSpec;
2387
2388 // Print the matching partial specializations.
Craig Topper2341c0d2013-07-04 03:08:24 +00002389 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2390 PEnd = Matched.end();
Douglas Gregor21610382009-10-29 00:04:11 +00002391 P != PEnd; ++P)
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002392 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2393 << getTemplateArgumentBindingsText(
2394 P->Partial->getTemplateParameters(),
2395 *P->Args);
Douglas Gregor01afeef2009-08-28 20:31:08 +00002396
Douglas Gregor21610382009-10-29 00:04:11 +00002397 return true;
2398 }
Douglas Gregorbe999392009-09-15 16:23:51 +00002399 }
2400
2401 // Instantiate using the best class template partial specialization.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002402 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
Douglas Gregor21610382009-10-29 00:04:11 +00002403 while (OrigPartialSpec->getInstantiatedFromMember()) {
2404 // If we've found an explicit specialization of this class template,
2405 // stop here and use that as the pattern.
2406 if (OrigPartialSpec->isMemberSpecialization())
2407 break;
2408
2409 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2410 }
2411
2412 Pattern = OrigPartialSpec;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002413 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
Douglas Gregor170bc422009-06-12 22:31:52 +00002414 } else {
2415 // -- If no matches are found, the instantiation is generated
2416 // from the primary template.
Douglas Gregor01afeef2009-08-28 20:31:08 +00002417 ClassTemplateDecl *OrigTemplate = Template;
Douglas Gregorcf915552009-10-13 16:30:37 +00002418 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2419 // If we've found an explicit specialization of this class template,
2420 // stop here and use that as the pattern.
2421 if (OrigTemplate->isMemberSpecialization())
2422 break;
2423
Douglas Gregor01afeef2009-08-28 20:31:08 +00002424 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
Douglas Gregorcf915552009-10-13 16:30:37 +00002425 }
2426
Douglas Gregor01afeef2009-08-28 20:31:08 +00002427 Pattern = OrigTemplate->getTemplatedDecl();
Douglas Gregor2373c592009-05-31 09:31:02 +00002428 }
Douglas Gregor463421d2009-03-03 04:44:36 +00002429
Douglas Gregoref6ab412009-10-27 06:26:26 +00002430 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2431 Pattern,
2432 getTemplateInstantiationArgs(ClassTemplateSpec),
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002433 TSK,
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002434 Complain);
Mike Stump11289f42009-09-09 15:08:12 +00002435
Douglas Gregorb7ae10f2009-06-05 00:53:49 +00002436 return Result;
Douglas Gregor463421d2009-03-03 04:44:36 +00002437}
Douglas Gregor90a1a652009-03-19 17:26:29 +00002438
John McCall76d824f2009-08-25 22:02:44 +00002439/// \brief Instantiates the definitions of all of the member
2440/// of the given class, which is an instantiation of a class template
2441/// or a member class of a template.
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002442void
2443Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002444 CXXRecordDecl *Instantiation,
2445 const MultiLevelTemplateArgumentList &TemplateArgs,
2446 TemplateSpecializationKind TSK) {
Richard Smitheb36ddf2014-04-24 22:45:46 +00002447 // FIXME: We need to notify the ASTMutationListener that we did all of these
2448 // things, in case we have an explicit instantiation definition in a PCM, a
2449 // module, or preamble, and the declaration is in an imported AST.
David Majnemer192d1792013-11-27 08:20:38 +00002450 assert(
2451 (TSK == TSK_ExplicitInstantiationDefinition ||
2452 TSK == TSK_ExplicitInstantiationDeclaration ||
2453 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2454 "Unexpected template specialization kind!");
Aaron Ballman629afae2014-03-07 19:56:05 +00002455 for (auto *D : Instantiation->decls()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002456 bool SuppressNew = false;
Aaron Ballman629afae2014-03-07 19:56:05 +00002457 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002458 if (FunctionDecl *Pattern
2459 = Function->getInstantiatedFromMemberFunction()) {
2460 MemberSpecializationInfo *MSInfo
2461 = Function->getMemberSpecializationInfo();
2462 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002463 if (MSInfo->getTemplateSpecializationKind()
2464 == TSK_ExplicitSpecialization)
2465 continue;
2466
Douglas Gregor1d957a32009-10-27 18:42:08 +00002467 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2468 Function,
2469 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002470 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002471 SuppressNew) ||
2472 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002473 continue;
Richard Smitheb36ddf2014-04-24 22:45:46 +00002474
2475 // C++11 [temp.explicit]p8:
2476 // An explicit instantiation definition that names a class template
2477 // specialization explicitly instantiates the class template
2478 // specialization and is only an explicit instantiation definition
2479 // of members whose definition is visible at the point of
2480 // instantiation.
2481 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002482 continue;
2483
Richard Smitheb36ddf2014-04-24 22:45:46 +00002484 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2485
2486 if (Function->isDefined()) {
2487 // Let the ASTConsumer know that this function has been explicitly
2488 // instantiated now, and its linkage might have changed.
2489 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2490 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002491 InstantiateFunctionDefinition(PointOfInstantiation, Function);
Richard Smitheb36ddf2014-04-24 22:45:46 +00002492 } else if (TSK == TSK_ImplicitInstantiation) {
2493 PendingLocalImplicitInstantiations.push_back(
2494 std::make_pair(Function, PointOfInstantiation));
Douglas Gregor1d957a32009-10-27 18:42:08 +00002495 }
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002496 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002497 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
Richard Smith8809a0c2013-09-27 20:14:12 +00002498 if (isa<VarTemplateSpecializationDecl>(Var))
2499 continue;
2500
Douglas Gregor86d142a2009-10-08 07:24:58 +00002501 if (Var->isStaticDataMember()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002502 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2503 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002504 if (MSInfo->getTemplateSpecializationKind()
2505 == TSK_ExplicitSpecialization)
2506 continue;
2507
Douglas Gregor1d957a32009-10-27 18:42:08 +00002508 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2509 Var,
2510 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002511 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002512 SuppressNew) ||
2513 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002514 continue;
2515
Douglas Gregor1d957a32009-10-27 18:42:08 +00002516 if (TSK == TSK_ExplicitInstantiationDefinition) {
2517 // C++0x [temp.explicit]p8:
2518 // An explicit instantiation definition that names a class template
2519 // specialization explicitly instantiates the class template
2520 // specialization and is only an explicit instantiation definition
2521 // of members whose definition is visible at the point of
2522 // instantiation.
Richard Smith62f19e72016-06-25 00:15:56 +00002523 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
Douglas Gregor1d957a32009-10-27 18:42:08 +00002524 continue;
2525
2526 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
Douglas Gregor86d142a2009-10-08 07:24:58 +00002527 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
Douglas Gregor1d957a32009-10-27 18:42:08 +00002528 } else {
2529 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2530 }
2531 }
Aaron Ballman629afae2014-03-07 19:56:05 +00002532 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
Douglas Gregor1da22252010-04-18 18:11:38 +00002533 // Always skip the injected-class-name, along with any
2534 // redeclarations of nested classes, since both would cause us
2535 // to try to instantiate the members of a class twice.
Richard Smith069ecf62014-11-20 22:56:34 +00002536 // Skip closure types; they'll get instantiated when we instantiate
2537 // the corresponding lambda-expression.
2538 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2539 Record->isLambda())
Douglas Gregord801b062009-10-07 23:56:10 +00002540 continue;
2541
Douglas Gregor1d957a32009-10-27 18:42:08 +00002542 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2543 assert(MSInfo && "No member specialization information?");
Douglas Gregor06aa50412010-04-09 21:02:29 +00002544
2545 if (MSInfo->getTemplateSpecializationKind()
2546 == TSK_ExplicitSpecialization)
2547 continue;
Nico Weberd75488d2010-09-27 21:02:09 +00002548
Hans Wennborga86a83b2016-05-26 19:42:56 +00002549 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2550 TSK == TSK_ExplicitInstantiationDeclaration) {
2551 // In MSVC mode, explicit instantiation decl of the outer class doesn't
2552 // affect the inner class.
2553 continue;
2554 }
2555
Douglas Gregor1d957a32009-10-27 18:42:08 +00002556 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2557 Record,
2558 MSInfo->getTemplateSpecializationKind(),
Nico Weberd75488d2010-09-27 21:02:09 +00002559 MSInfo->getPointOfInstantiation(),
Douglas Gregor1d957a32009-10-27 18:42:08 +00002560 SuppressNew) ||
2561 SuppressNew)
Douglas Gregorbbe8f462009-10-08 15:14:33 +00002562 continue;
2563
Douglas Gregor1d957a32009-10-27 18:42:08 +00002564 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2565 assert(Pattern && "Missing instantiated-from-template information");
2566
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002567 if (!Record->getDefinition()) {
2568 if (!Pattern->getDefinition()) {
Douglas Gregor1d957a32009-10-27 18:42:08 +00002569 // C++0x [temp.explicit]p8:
2570 // An explicit instantiation definition that names a class template
2571 // specialization explicitly instantiates the class template
2572 // specialization and is only an explicit instantiation definition
2573 // of members whose definition is visible at the point of
2574 // instantiation.
2575 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2576 MSInfo->setTemplateSpecializationKind(TSK);
2577 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2578 }
2579
2580 continue;
2581 }
2582
2583 InstantiateClass(PointOfInstantiation, Record, Pattern,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002584 TemplateArgs,
2585 TSK);
Nico Weberd75488d2010-09-27 21:02:09 +00002586 } else {
2587 if (TSK == TSK_ExplicitInstantiationDefinition &&
2588 Record->getTemplateSpecializationKind() ==
2589 TSK_ExplicitInstantiationDeclaration) {
2590 Record->setTemplateSpecializationKind(TSK);
2591 MarkVTableUsed(PointOfInstantiation, Record, true);
2592 }
Douglas Gregor1d957a32009-10-27 18:42:08 +00002593 }
Douglas Gregorc093c1d2009-10-08 01:19:17 +00002594
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002595 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
Douglas Gregor1d957a32009-10-27 18:42:08 +00002596 if (Pattern)
2597 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2598 TSK);
Aaron Ballman629afae2014-03-07 19:56:05 +00002599 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
Richard Smith4b38ded2012-03-14 23:13:10 +00002600 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2601 assert(MSInfo && "No member specialization information?");
2602
2603 if (MSInfo->getTemplateSpecializationKind()
2604 == TSK_ExplicitSpecialization)
2605 continue;
2606
2607 if (CheckSpecializationInstantiationRedecl(
2608 PointOfInstantiation, TSK, Enum,
2609 MSInfo->getTemplateSpecializationKind(),
2610 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2611 SuppressNew)
2612 continue;
2613
2614 if (Enum->getDefinition())
2615 continue;
2616
Richard Smith6739a102016-05-05 00:56:12 +00002617 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
Richard Smith4b38ded2012-03-14 23:13:10 +00002618 assert(Pattern && "Missing instantiated-from-template information");
2619
2620 if (TSK == TSK_ExplicitInstantiationDefinition) {
2621 if (!Pattern->getDefinition())
2622 continue;
2623
2624 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2625 } else {
2626 MSInfo->setTemplateSpecializationKind(TSK);
2627 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2628 }
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002629 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2630 // No need to instantiate in-class initializers during explicit
2631 // instantiation.
2632 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2633 CXXRecordDecl *ClassPattern =
2634 Instantiation->getTemplateInstantiationPattern();
2635 DeclContext::lookup_result Lookup =
2636 ClassPattern->lookup(Field->getDeclName());
David Majnemer76a25622016-06-09 05:26:56 +00002637 FieldDecl *Pattern = cast<FieldDecl>(Lookup.front());
Reid Klecknerd60b82f2014-11-17 23:36:45 +00002638 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2639 TemplateArgs);
2640 }
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002641 }
2642 }
2643}
2644
2645/// \brief Instantiate the definitions of all of the members of the
2646/// given class template specialization, which was named as part of an
2647/// explicit instantiation.
Mike Stump11289f42009-09-09 15:08:12 +00002648void
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002649Sema::InstantiateClassTemplateSpecializationMembers(
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002650 SourceLocation PointOfInstantiation,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002651 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2652 TemplateSpecializationKind TSK) {
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002653 // C++0x [temp.explicit]p7:
2654 // An explicit instantiation that names a class template
2655 // specialization is an explicit instantion of the same kind
2656 // (declaration or definition) of each of its members (not
2657 // including members inherited from base classes) that has not
2658 // been previously explicitly specialized in the translation unit
2659 // containing the explicit instantiation, except as described
2660 // below.
2661 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
Douglas Gregor34ec2ef2009-09-04 22:48:11 +00002662 getTemplateInstantiationArgs(ClassTemplateSpec),
2663 TSK);
Douglas Gregorbbbb02d2009-05-13 20:28:22 +00002664}
2665
John McCalldadc5752010-08-24 06:29:42 +00002666StmtResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002667Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregorebe10102009-08-20 07:17:43 +00002668 if (!S)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002669 return S;
Douglas Gregorebe10102009-08-20 07:17:43 +00002670
2671 TemplateInstantiator Instantiator(*this, TemplateArgs,
2672 SourceLocation(),
2673 DeclarationName());
2674 return Instantiator.TransformStmt(S);
2675}
2676
John McCalldadc5752010-08-24 06:29:42 +00002677ExprResult
Douglas Gregor01afeef2009-08-28 20:31:08 +00002678Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregora16548e2009-08-11 05:31:07 +00002679 if (!E)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002680 return E;
Mike Stump11289f42009-09-09 15:08:12 +00002681
Douglas Gregora16548e2009-08-11 05:31:07 +00002682 TemplateInstantiator Instantiator(*this, TemplateArgs,
2683 SourceLocation(),
2684 DeclarationName());
2685 return Instantiator.TransformExpr(E);
2686}
2687
Richard Smithd59b8322012-12-19 01:39:02 +00002688ExprResult Sema::SubstInitializer(Expr *Init,
2689 const MultiLevelTemplateArgumentList &TemplateArgs,
2690 bool CXXDirectInit) {
2691 TemplateInstantiator Instantiator(*this, TemplateArgs,
2692 SourceLocation(),
2693 DeclarationName());
2694 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2695}
2696
Craig Topper99d23532015-12-24 23:58:29 +00002697bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002698 const MultiLevelTemplateArgumentList &TemplateArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002699 SmallVectorImpl<Expr *> &Outputs) {
Craig Topper99d23532015-12-24 23:58:29 +00002700 if (Exprs.empty())
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002701 return false;
Richard Smithd59b8322012-12-19 01:39:02 +00002702
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002703 TemplateInstantiator Instantiator(*this, TemplateArgs,
2704 SourceLocation(),
2705 DeclarationName());
Craig Topper99d23532015-12-24 23:58:29 +00002706 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
2707 IsCall, Outputs);
Douglas Gregor2cd32a02011-01-07 19:35:17 +00002708}
2709
Douglas Gregor14454802011-02-25 02:25:35 +00002710NestedNameSpecifierLoc
2711Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2712 const MultiLevelTemplateArgumentList &TemplateArgs) {
2713 if (!NNS)
2714 return NestedNameSpecifierLoc();
2715
2716 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2717 DeclarationName());
2718 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2719}
2720
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002721/// \brief Do template substitution on declaration name info.
2722DeclarationNameInfo
2723Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2724 const MultiLevelTemplateArgumentList &TemplateArgs) {
2725 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2726 NameInfo.getName());
2727 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2728}
2729
Douglas Gregoraa594892009-03-31 18:38:02 +00002730TemplateName
Douglas Gregordf846d12011-03-02 18:46:51 +00002731Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2732 TemplateName Name, SourceLocation Loc,
Douglas Gregor01afeef2009-08-28 20:31:08 +00002733 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregor71dc5092009-08-06 06:41:21 +00002734 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2735 DeclarationName());
Douglas Gregordf846d12011-03-02 18:46:51 +00002736 CXXScopeSpec SS;
2737 SS.Adopt(QualifierLoc);
2738 return Instantiator.TransformTemplateName(SS, Name, Loc);
Douglas Gregoraa594892009-03-31 18:38:02 +00002739}
Douglas Gregorc43620d2009-06-11 00:06:24 +00002740
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002741bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2742 TemplateArgumentListInfo &Result,
John McCall0ad16662009-10-29 08:12:44 +00002743 const MultiLevelTemplateArgumentList &TemplateArgs) {
Douglas Gregore922c772009-08-04 22:27:00 +00002744 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2745 DeclarationName());
Douglas Gregor0f3feb42010-12-22 21:19:48 +00002746
2747 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
Douglas Gregorc43620d2009-06-11 00:06:24 +00002748}
Douglas Gregor14cf7522010-04-30 18:55:50 +00002749
Richard Smith70b13042015-01-09 01:19:56 +00002750static const Decl *getCanonicalParmVarDecl(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002751 // When storing ParmVarDecls in the local instantiation scope, we always
2752 // want to use the ParmVarDecl from the canonical function declaration,
2753 // since the map is then valid for any redeclaration or definition of that
2754 // function.
2755 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2756 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2757 unsigned i = PV->getFunctionScopeIndex();
Richard Smith70b13042015-01-09 01:19:56 +00002758 // This parameter might be from a freestanding function type within the
2759 // function and isn't necessarily referring to one of FD's parameters.
2760 if (FD->getParamDecl(i) == PV)
2761 return FD->getCanonicalDecl()->getParamDecl(i);
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002762 }
2763 }
2764 return D;
2765}
2766
2767
Douglas Gregorf3010112011-01-07 16:43:16 +00002768llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
2769LocalInstantiationScope::findInstantiationOf(const Decl *D) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002770 D = getCanonicalParmVarDecl(D);
Chris Lattnercab02a62011-02-17 20:34:02 +00002771 for (LocalInstantiationScope *Current = this; Current;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002772 Current = Current->Outer) {
Chris Lattnercab02a62011-02-17 20:34:02 +00002773
Douglas Gregor14cf7522010-04-30 18:55:50 +00002774 // Check if we found something within this scope.
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002775 const Decl *CheckD = D;
2776 do {
Douglas Gregorf3010112011-01-07 16:43:16 +00002777 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002778 if (Found != Current->LocalDecls.end())
Douglas Gregorf3010112011-01-07 16:43:16 +00002779 return &Found->second;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002780
2781 // If this is a tag declaration, it's possible that we need to look for
2782 // a previous declaration.
2783 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
Douglas Gregorec9fd132012-01-14 16:38:05 +00002784 CheckD = Tag->getPreviousDecl();
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002785 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002786 CheckD = nullptr;
Douglas Gregore9fc8dc2010-12-21 21:22:51 +00002787 } while (CheckD);
2788
Douglas Gregor14cf7522010-04-30 18:55:50 +00002789 // If we aren't combined with our outer scope, we're done.
2790 if (!Current->CombineWithOuterScope)
2791 break;
2792 }
Chris Lattnercab02a62011-02-17 20:34:02 +00002793
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002794 // If we're performing a partial substitution during template argument
2795 // deduction, we may not have values for template parameters yet.
2796 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2797 isa<TemplateTemplateParmDecl>(D))
Craig Topperc3ec1492014-05-26 06:22:03 +00002798 return nullptr;
Serge Pavlov7cd8f602013-07-15 06:14:07 +00002799
Serge Pavlove7ad8312015-05-15 10:10:28 +00002800 // Local types referenced prior to definition may require instantiation.
2801 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
2802 if (RD->isLocalClass())
2803 return nullptr;
2804
2805 // Enumeration types referenced prior to definition may appear as a result of
2806 // error recovery.
2807 if (isa<EnumDecl>(D))
Serge Pavlov4c511742015-05-04 16:44:39 +00002808 return nullptr;
2809
Chris Lattnercab02a62011-02-17 20:34:02 +00002810 // If we didn't find the decl, then we either have a sema bug, or we have a
2811 // forward reference to a label declaration. Return null to indicate that
2812 // we have an uninstantiated label.
2813 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
Craig Topperc3ec1492014-05-26 06:22:03 +00002814 return nullptr;
Douglas Gregor14cf7522010-04-30 18:55:50 +00002815}
2816
John McCall19c1bfd2010-08-25 05:32:35 +00002817void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002818 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002819 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Richard Smith70b13042015-01-09 01:19:56 +00002820 if (Stored.isNull()) {
2821#ifndef NDEBUG
2822 // It should not be present in any surrounding scope either.
2823 LocalInstantiationScope *Current = this;
2824 while (Current->CombineWithOuterScope && Current->Outer) {
2825 Current = Current->Outer;
2826 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2827 "Instantiated local in inner and outer scopes");
2828 }
2829#endif
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002830 Stored = Inst;
Richard Smith70b13042015-01-09 01:19:56 +00002831 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
James Y Knight48fefa32015-09-30 14:04:23 +00002832 Pack->push_back(cast<ParmVarDecl>(Inst));
Richard Smith70b13042015-01-09 01:19:56 +00002833 } else {
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002834 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
Richard Smith70b13042015-01-09 01:19:56 +00002835 }
Douglas Gregor14cf7522010-04-30 18:55:50 +00002836}
Douglas Gregorf3010112011-01-07 16:43:16 +00002837
James Y Knight48fefa32015-09-30 14:04:23 +00002838void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2839 ParmVarDecl *Inst) {
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002840 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002841 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2842 Pack->push_back(Inst);
2843}
2844
2845void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
Richard Smith70b13042015-01-09 01:19:56 +00002846#ifndef NDEBUG
2847 // This should be the first time we've been told about this decl.
2848 for (LocalInstantiationScope *Current = this;
2849 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2850 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2851 "Creating local pack after instantiation of local");
2852#endif
2853
DeLesley Hutchinsf39c0c22012-09-26 17:57:31 +00002854 D = getCanonicalParmVarDecl(D);
Douglas Gregorf3010112011-01-07 16:43:16 +00002855 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
Douglas Gregorf3010112011-01-07 16:43:16 +00002856 DeclArgumentPack *Pack = new DeclArgumentPack;
2857 Stored = Pack;
2858 ArgumentPacks.push_back(Pack);
2859}
2860
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002861void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2862 const TemplateArgument *ExplicitArgs,
2863 unsigned NumExplicitArgs) {
2864 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2865 "Already have a partially-substituted pack");
2866 assert((!PartiallySubstitutedPack
2867 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2868 "Wrong number of arguments in partially-substituted pack");
2869 PartiallySubstitutedPack = Pack;
2870 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2871 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2872}
2873
2874NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2875 const TemplateArgument **ExplicitArgs,
2876 unsigned *NumExplicitArgs) const {
2877 if (ExplicitArgs)
Craig Topperc3ec1492014-05-26 06:22:03 +00002878 *ExplicitArgs = nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002879 if (NumExplicitArgs)
2880 *NumExplicitArgs = 0;
2881
2882 for (const LocalInstantiationScope *Current = this; Current;
2883 Current = Current->Outer) {
2884 if (Current->PartiallySubstitutedPack) {
2885 if (ExplicitArgs)
2886 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2887 if (NumExplicitArgs)
2888 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2889
2890 return Current->PartiallySubstitutedPack;
2891 }
2892
2893 if (!Current->CombineWithOuterScope)
2894 break;
2895 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002896
2897 return nullptr;
Douglas Gregora8bac7f2011-01-10 07:32:04 +00002898}