1 //===------- 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
13 #include "clang/Sema/SemaInternal.h"
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Sema/DeclSpec.h"
22 #include "clang/Sema/Initialization.h"
23 #include "clang/Sema/Lookup.h"
24 #include "clang/Sema/Template.h"
25 #include "clang/Sema/TemplateDeduction.h"
26
27 using namespace clang;
28 using namespace sema;
29
30 //===----------------------------------------------------------------------===/
31 // Template Instantiation Support
32 //===----------------------------------------------------------------------===/
33
34 /// \brief Retrieve the template argument list(s) that should be used to
35 /// instantiate the definition of the given declaration.
36 ///
37 /// \param D the declaration for which we are computing template instantiation
38 /// arguments.
39 ///
40 /// \param Innermost if non-NULL, the innermost template argument list.
41 ///
42 /// \param RelativeToPrimary true if we should get the template
43 /// arguments relative to the primary template, even when we're
44 /// dealing with a specialization. This is only relevant for function
45 /// template specializations.
46 ///
47 /// \param Pattern If non-NULL, indicates the pattern from which we will be
48 /// instantiating the definition of the given declaration, \p D. This is
49 /// used to determine the proper set of template instantiation arguments for
50 /// friend function template specializations.
51 MultiLevelTemplateArgumentList
getTemplateInstantiationArgs(NamedDecl * D,const TemplateArgumentList * Innermost,bool RelativeToPrimary,const FunctionDecl * Pattern)52 Sema::getTemplateInstantiationArgs(NamedDecl *D,
53 const TemplateArgumentList *Innermost,
54 bool RelativeToPrimary,
55 const FunctionDecl *Pattern) {
56 // Accumulate the set of template argument lists in this structure.
57 MultiLevelTemplateArgumentList Result;
58
59 if (Innermost)
60 Result.addOuterTemplateArguments(Innermost);
61
62 DeclContext *Ctx = dyn_cast<DeclContext>(D);
63 if (!Ctx) {
64 Ctx = D->getDeclContext();
65
66 // Add template arguments from a variable template instantiation.
67 if (VarTemplateSpecializationDecl *Spec =
68 dyn_cast<VarTemplateSpecializationDecl>(D)) {
69 // We're done when we hit an explicit specialization.
70 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
71 !isa<VarTemplatePartialSpecializationDecl>(Spec))
72 return Result;
73
74 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
75
76 // If this variable template specialization was instantiated from a
77 // specialized member that is a variable template, we're done.
78 assert(Spec->getSpecializedTemplate() && "No variable template?");
79 llvm::PointerUnion<VarTemplateDecl*,
80 VarTemplatePartialSpecializationDecl*> Specialized
81 = Spec->getSpecializedTemplateOrPartial();
82 if (VarTemplatePartialSpecializationDecl *Partial =
83 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
84 if (Partial->isMemberSpecialization())
85 return Result;
86 } else {
87 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
88 if (Tmpl->isMemberSpecialization())
89 return Result;
90 }
91 }
92
93 // If we have a template template parameter with translation unit context,
94 // then we're performing substitution into a default template argument of
95 // this template template parameter before we've constructed the template
96 // that will own this template template parameter. In this case, we
97 // use empty template parameter lists for all of the outer templates
98 // to avoid performing any substitutions.
99 if (Ctx->isTranslationUnit()) {
100 if (TemplateTemplateParmDecl *TTP
101 = dyn_cast<TemplateTemplateParmDecl>(D)) {
102 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
103 Result.addOuterTemplateArguments(None);
104 return Result;
105 }
106 }
107 }
108
109 while (!Ctx->isFileContext()) {
110 // Add template arguments from a class template instantiation.
111 if (ClassTemplateSpecializationDecl *Spec
112 = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
113 // We're done when we hit an explicit specialization.
114 if (Spec->getSpecializationKind() == TSK_ExplicitSpecialization &&
115 !isa<ClassTemplatePartialSpecializationDecl>(Spec))
116 break;
117
118 Result.addOuterTemplateArguments(&Spec->getTemplateInstantiationArgs());
119
120 // If this class template specialization was instantiated from a
121 // specialized member that is a class template, we're done.
122 assert(Spec->getSpecializedTemplate() && "No class template?");
123 if (Spec->getSpecializedTemplate()->isMemberSpecialization())
124 break;
125 }
126 // Add template arguments from a function template specialization.
127 else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Ctx)) {
128 if (!RelativeToPrimary &&
129 (Function->getTemplateSpecializationKind() ==
130 TSK_ExplicitSpecialization &&
131 !Function->getClassScopeSpecializationPattern()))
132 break;
133
134 if (const TemplateArgumentList *TemplateArgs
135 = Function->getTemplateSpecializationArgs()) {
136 // Add the template arguments for this specialization.
137 Result.addOuterTemplateArguments(TemplateArgs);
138
139 // If this function was instantiated from a specialized member that is
140 // a function template, we're done.
141 assert(Function->getPrimaryTemplate() && "No function template?");
142 if (Function->getPrimaryTemplate()->isMemberSpecialization())
143 break;
144
145 // If this function is a generic lambda specialization, we are done.
146 if (isGenericLambdaCallOperatorSpecialization(Function))
147 break;
148
149 } else if (FunctionTemplateDecl *FunTmpl
150 = Function->getDescribedFunctionTemplate()) {
151 // Add the "injected" template arguments.
152 Result.addOuterTemplateArguments(FunTmpl->getInjectedTemplateArgs());
153 }
154
155 // If this is a friend declaration and it declares an entity at
156 // namespace scope, take arguments from its lexical parent
157 // instead of its semantic parent, unless of course the pattern we're
158 // instantiating actually comes from the file's context!
159 if (Function->getFriendObjectKind() &&
160 Function->getDeclContext()->isFileContext() &&
161 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
162 Ctx = Function->getLexicalDeclContext();
163 RelativeToPrimary = false;
164 continue;
165 }
166 } else if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Ctx)) {
167 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
168 QualType T = ClassTemplate->getInjectedClassNameSpecialization();
169 const TemplateSpecializationType *TST =
170 cast<TemplateSpecializationType>(Context.getCanonicalType(T));
171 Result.addOuterTemplateArguments(
172 llvm::makeArrayRef(TST->getArgs(), TST->getNumArgs()));
173 if (ClassTemplate->isMemberSpecialization())
174 break;
175 }
176 }
177
178 Ctx = Ctx->getParent();
179 RelativeToPrimary = false;
180 }
181
182 return Result;
183 }
184
isInstantiationRecord() const185 bool Sema::ActiveTemplateInstantiation::isInstantiationRecord() const {
186 switch (Kind) {
187 case TemplateInstantiation:
188 case ExceptionSpecInstantiation:
189 case DefaultTemplateArgumentInstantiation:
190 case DefaultFunctionArgumentInstantiation:
191 case ExplicitTemplateArgumentSubstitution:
192 case DeducedTemplateArgumentSubstitution:
193 case PriorTemplateArgumentSubstitution:
194 return true;
195
196 case DefaultTemplateArgumentChecking:
197 return false;
198 }
199
200 llvm_unreachable("Invalid InstantiationKind!");
201 }
202
Initialize(ActiveTemplateInstantiation::InstantiationKind Kind,SourceLocation PointOfInstantiation,SourceRange InstantiationRange,Decl * Entity,NamedDecl * Template,ArrayRef<TemplateArgument> TemplateArgs,sema::TemplateDeductionInfo * DeductionInfo)203 void Sema::InstantiatingTemplate::Initialize(
204 ActiveTemplateInstantiation::InstantiationKind Kind,
205 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
206 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
207 sema::TemplateDeductionInfo *DeductionInfo) {
208 SavedInNonInstantiationSFINAEContext =
209 SemaRef.InNonInstantiationSFINAEContext;
210 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
211 if (!Invalid) {
212 ActiveTemplateInstantiation Inst;
213 Inst.Kind = Kind;
214 Inst.PointOfInstantiation = PointOfInstantiation;
215 Inst.Entity = Entity;
216 Inst.Template = Template;
217 Inst.TemplateArgs = TemplateArgs.data();
218 Inst.NumTemplateArgs = TemplateArgs.size();
219 Inst.DeductionInfo = DeductionInfo;
220 Inst.InstantiationRange = InstantiationRange;
221 SemaRef.InNonInstantiationSFINAEContext = false;
222 SemaRef.ActiveTemplateInstantiations.push_back(Inst);
223 if (!Inst.isInstantiationRecord())
224 ++SemaRef.NonInstantiationEntries;
225 }
226 }
227
228 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,Decl * Entity,SourceRange InstantiationRange)229 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
230 Decl *Entity,
231 SourceRange InstantiationRange)
232 : SemaRef(SemaRef)
233 {
234 Initialize(ActiveTemplateInstantiation::TemplateInstantiation,
235 PointOfInstantiation, InstantiationRange, Entity);
236 }
237
238 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,FunctionDecl * Entity,ExceptionSpecification,SourceRange InstantiationRange)239 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
240 FunctionDecl *Entity, ExceptionSpecification,
241 SourceRange InstantiationRange)
242 : SemaRef(SemaRef)
243 {
244 Initialize(ActiveTemplateInstantiation::ExceptionSpecInstantiation,
245 PointOfInstantiation, InstantiationRange, Entity);
246 }
247
248 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,TemplateDecl * Template,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)249 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
250 TemplateDecl *Template,
251 ArrayRef<TemplateArgument> TemplateArgs,
252 SourceRange InstantiationRange)
253 : SemaRef(SemaRef)
254 {
255 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation,
256 PointOfInstantiation, InstantiationRange,
257 Template, nullptr, TemplateArgs);
258 }
259
260 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,FunctionTemplateDecl * FunctionTemplate,ArrayRef<TemplateArgument> TemplateArgs,ActiveTemplateInstantiation::InstantiationKind Kind,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)261 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
262 FunctionTemplateDecl *FunctionTemplate,
263 ArrayRef<TemplateArgument> TemplateArgs,
264 ActiveTemplateInstantiation::InstantiationKind Kind,
265 sema::TemplateDeductionInfo &DeductionInfo,
266 SourceRange InstantiationRange)
267 : SemaRef(SemaRef)
268 {
269 Initialize(Kind, PointOfInstantiation, InstantiationRange,
270 FunctionTemplate, nullptr, TemplateArgs, &DeductionInfo);
271 }
272
273 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,ClassTemplatePartialSpecializationDecl * PartialSpec,ArrayRef<TemplateArgument> TemplateArgs,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)274 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
275 ClassTemplatePartialSpecializationDecl *PartialSpec,
276 ArrayRef<TemplateArgument> TemplateArgs,
277 sema::TemplateDeductionInfo &DeductionInfo,
278 SourceRange InstantiationRange)
279 : SemaRef(SemaRef)
280 {
281 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
282 PointOfInstantiation, InstantiationRange,
283 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
284 }
285
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,VarTemplatePartialSpecializationDecl * PartialSpec,ArrayRef<TemplateArgument> TemplateArgs,sema::TemplateDeductionInfo & DeductionInfo,SourceRange InstantiationRange)286 Sema::InstantiatingTemplate::InstantiatingTemplate(
287 Sema &SemaRef, SourceLocation PointOfInstantiation,
288 VarTemplatePartialSpecializationDecl *PartialSpec,
289 ArrayRef<TemplateArgument> TemplateArgs,
290 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
291 : SemaRef(SemaRef)
292 {
293 Initialize(ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution,
294 PointOfInstantiation, InstantiationRange,
295 PartialSpec, nullptr, TemplateArgs, &DeductionInfo);
296 }
297
298 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,ParmVarDecl * Param,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)299 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
300 ParmVarDecl *Param,
301 ArrayRef<TemplateArgument> TemplateArgs,
302 SourceRange InstantiationRange)
303 : SemaRef(SemaRef)
304 {
305 Initialize(ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation,
306 PointOfInstantiation, InstantiationRange,
307 Param, nullptr, TemplateArgs);
308 }
309
310
311 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,NamedDecl * Template,NonTypeTemplateParmDecl * Param,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)312 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
313 NamedDecl *Template, NonTypeTemplateParmDecl *Param,
314 ArrayRef<TemplateArgument> TemplateArgs,
315 SourceRange InstantiationRange)
316 : SemaRef(SemaRef)
317 {
318 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
319 PointOfInstantiation, InstantiationRange,
320 Param, Template, TemplateArgs);
321 }
322
323 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,NamedDecl * Template,TemplateTemplateParmDecl * Param,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)324 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
325 NamedDecl *Template, TemplateTemplateParmDecl *Param,
326 ArrayRef<TemplateArgument> TemplateArgs,
327 SourceRange InstantiationRange)
328 : SemaRef(SemaRef)
329 {
330 Initialize(ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution,
331 PointOfInstantiation, InstantiationRange,
332 Param, Template, TemplateArgs);
333 }
334
335 Sema::InstantiatingTemplate::
InstantiatingTemplate(Sema & SemaRef,SourceLocation PointOfInstantiation,TemplateDecl * Template,NamedDecl * Param,ArrayRef<TemplateArgument> TemplateArgs,SourceRange InstantiationRange)336 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
337 TemplateDecl *Template, NamedDecl *Param,
338 ArrayRef<TemplateArgument> TemplateArgs,
339 SourceRange InstantiationRange)
340 : SemaRef(SemaRef)
341 {
342 Initialize(ActiveTemplateInstantiation::DefaultTemplateArgumentChecking,
343 PointOfInstantiation, InstantiationRange,
344 Param, Template, TemplateArgs);
345 }
346
Clear()347 void Sema::InstantiatingTemplate::Clear() {
348 if (!Invalid) {
349 if (!SemaRef.ActiveTemplateInstantiations.back().isInstantiationRecord()) {
350 assert(SemaRef.NonInstantiationEntries > 0);
351 --SemaRef.NonInstantiationEntries;
352 }
353 SemaRef.InNonInstantiationSFINAEContext
354 = SavedInNonInstantiationSFINAEContext;
355
356 // Name lookup no longer looks in this template's defining module.
357 assert(SemaRef.ActiveTemplateInstantiations.size() >=
358 SemaRef.ActiveTemplateInstantiationLookupModules.size() &&
359 "forgot to remove a lookup module for a template instantiation");
360 if (SemaRef.ActiveTemplateInstantiations.size() ==
361 SemaRef.ActiveTemplateInstantiationLookupModules.size()) {
362 if (Module *M = SemaRef.ActiveTemplateInstantiationLookupModules.back())
363 SemaRef.LookupModulesCache.erase(M);
364 SemaRef.ActiveTemplateInstantiationLookupModules.pop_back();
365 }
366
367 SemaRef.ActiveTemplateInstantiations.pop_back();
368 Invalid = true;
369 }
370 }
371
CheckInstantiationDepth(SourceLocation PointOfInstantiation,SourceRange InstantiationRange)372 bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
373 SourceLocation PointOfInstantiation,
374 SourceRange InstantiationRange) {
375 assert(SemaRef.NonInstantiationEntries <=
376 SemaRef.ActiveTemplateInstantiations.size());
377 if ((SemaRef.ActiveTemplateInstantiations.size() -
378 SemaRef.NonInstantiationEntries)
379 <= SemaRef.getLangOpts().InstantiationDepth)
380 return false;
381
382 SemaRef.Diag(PointOfInstantiation,
383 diag::err_template_recursion_depth_exceeded)
384 << SemaRef.getLangOpts().InstantiationDepth
385 << InstantiationRange;
386 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
387 << SemaRef.getLangOpts().InstantiationDepth;
388 return true;
389 }
390
391 /// \brief Prints the current instantiation stack through a series of
392 /// notes.
PrintInstantiationStack()393 void Sema::PrintInstantiationStack() {
394 // Determine which template instantiations to skip, if any.
395 unsigned SkipStart = ActiveTemplateInstantiations.size(), SkipEnd = SkipStart;
396 unsigned Limit = Diags.getTemplateBacktraceLimit();
397 if (Limit && Limit < ActiveTemplateInstantiations.size()) {
398 SkipStart = Limit / 2 + Limit % 2;
399 SkipEnd = ActiveTemplateInstantiations.size() - Limit / 2;
400 }
401
402 // FIXME: In all of these cases, we need to show the template arguments
403 unsigned InstantiationIdx = 0;
404 for (SmallVectorImpl<ActiveTemplateInstantiation>::reverse_iterator
405 Active = ActiveTemplateInstantiations.rbegin(),
406 ActiveEnd = ActiveTemplateInstantiations.rend();
407 Active != ActiveEnd;
408 ++Active, ++InstantiationIdx) {
409 // Skip this instantiation?
410 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
411 if (InstantiationIdx == SkipStart) {
412 // Note that we're skipping instantiations.
413 Diags.Report(Active->PointOfInstantiation,
414 diag::note_instantiation_contexts_suppressed)
415 << unsigned(ActiveTemplateInstantiations.size() - Limit);
416 }
417 continue;
418 }
419
420 switch (Active->Kind) {
421 case ActiveTemplateInstantiation::TemplateInstantiation: {
422 Decl *D = Active->Entity;
423 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
424 unsigned DiagID = diag::note_template_member_class_here;
425 if (isa<ClassTemplateSpecializationDecl>(Record))
426 DiagID = diag::note_template_class_instantiation_here;
427 Diags.Report(Active->PointOfInstantiation, DiagID)
428 << Context.getTypeDeclType(Record)
429 << Active->InstantiationRange;
430 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
431 unsigned DiagID;
432 if (Function->getPrimaryTemplate())
433 DiagID = diag::note_function_template_spec_here;
434 else
435 DiagID = diag::note_template_member_function_here;
436 Diags.Report(Active->PointOfInstantiation, DiagID)
437 << Function
438 << Active->InstantiationRange;
439 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
440 Diags.Report(Active->PointOfInstantiation,
441 VD->isStaticDataMember()?
442 diag::note_template_static_data_member_def_here
443 : diag::note_template_variable_def_here)
444 << VD
445 << Active->InstantiationRange;
446 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
447 Diags.Report(Active->PointOfInstantiation,
448 diag::note_template_enum_def_here)
449 << ED
450 << Active->InstantiationRange;
451 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
452 Diags.Report(Active->PointOfInstantiation,
453 diag::note_template_nsdmi_here)
454 << FD << Active->InstantiationRange;
455 } else {
456 Diags.Report(Active->PointOfInstantiation,
457 diag::note_template_type_alias_instantiation_here)
458 << cast<TypeAliasTemplateDecl>(D)
459 << Active->InstantiationRange;
460 }
461 break;
462 }
463
464 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation: {
465 TemplateDecl *Template = cast<TemplateDecl>(Active->Entity);
466 SmallVector<char, 128> TemplateArgsStr;
467 llvm::raw_svector_ostream OS(TemplateArgsStr);
468 Template->printName(OS);
469 TemplateSpecializationType::PrintTemplateArgumentList(OS,
470 Active->TemplateArgs,
471 Active->NumTemplateArgs,
472 getPrintingPolicy());
473 Diags.Report(Active->PointOfInstantiation,
474 diag::note_default_arg_instantiation_here)
475 << OS.str()
476 << Active->InstantiationRange;
477 break;
478 }
479
480 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution: {
481 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
482 Diags.Report(Active->PointOfInstantiation,
483 diag::note_explicit_template_arg_substitution_here)
484 << FnTmpl
485 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
486 Active->TemplateArgs,
487 Active->NumTemplateArgs)
488 << Active->InstantiationRange;
489 break;
490 }
491
492 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
493 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
494 dyn_cast<ClassTemplatePartialSpecializationDecl>(Active->Entity)) {
495 Diags.Report(Active->PointOfInstantiation,
496 diag::note_partial_spec_deduct_instantiation_here)
497 << Context.getTypeDeclType(PartialSpec)
498 << getTemplateArgumentBindingsText(
499 PartialSpec->getTemplateParameters(),
500 Active->TemplateArgs,
501 Active->NumTemplateArgs)
502 << Active->InstantiationRange;
503 } else {
504 FunctionTemplateDecl *FnTmpl
505 = cast<FunctionTemplateDecl>(Active->Entity);
506 Diags.Report(Active->PointOfInstantiation,
507 diag::note_function_template_deduction_instantiation_here)
508 << FnTmpl
509 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
510 Active->TemplateArgs,
511 Active->NumTemplateArgs)
512 << Active->InstantiationRange;
513 }
514 break;
515
516 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation: {
517 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
518 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
519
520 SmallVector<char, 128> TemplateArgsStr;
521 llvm::raw_svector_ostream OS(TemplateArgsStr);
522 FD->printName(OS);
523 TemplateSpecializationType::PrintTemplateArgumentList(OS,
524 Active->TemplateArgs,
525 Active->NumTemplateArgs,
526 getPrintingPolicy());
527 Diags.Report(Active->PointOfInstantiation,
528 diag::note_default_function_arg_instantiation_here)
529 << OS.str()
530 << Active->InstantiationRange;
531 break;
532 }
533
534 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution: {
535 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
536 std::string Name;
537 if (!Parm->getName().empty())
538 Name = std::string(" '") + Parm->getName().str() + "'";
539
540 TemplateParameterList *TemplateParams = nullptr;
541 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
542 TemplateParams = Template->getTemplateParameters();
543 else
544 TemplateParams =
545 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
546 ->getTemplateParameters();
547 Diags.Report(Active->PointOfInstantiation,
548 diag::note_prior_template_arg_substitution)
549 << isa<TemplateTemplateParmDecl>(Parm)
550 << Name
551 << getTemplateArgumentBindingsText(TemplateParams,
552 Active->TemplateArgs,
553 Active->NumTemplateArgs)
554 << Active->InstantiationRange;
555 break;
556 }
557
558 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking: {
559 TemplateParameterList *TemplateParams = nullptr;
560 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
561 TemplateParams = Template->getTemplateParameters();
562 else
563 TemplateParams =
564 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
565 ->getTemplateParameters();
566
567 Diags.Report(Active->PointOfInstantiation,
568 diag::note_template_default_arg_checking)
569 << getTemplateArgumentBindingsText(TemplateParams,
570 Active->TemplateArgs,
571 Active->NumTemplateArgs)
572 << Active->InstantiationRange;
573 break;
574 }
575
576 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
577 Diags.Report(Active->PointOfInstantiation,
578 diag::note_template_exception_spec_instantiation_here)
579 << cast<FunctionDecl>(Active->Entity)
580 << Active->InstantiationRange;
581 break;
582 }
583 }
584 }
585
isSFINAEContext() const586 Optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
587 if (InNonInstantiationSFINAEContext)
588 return Optional<TemplateDeductionInfo *>(nullptr);
589
590 for (SmallVectorImpl<ActiveTemplateInstantiation>::const_reverse_iterator
591 Active = ActiveTemplateInstantiations.rbegin(),
592 ActiveEnd = ActiveTemplateInstantiations.rend();
593 Active != ActiveEnd;
594 ++Active)
595 {
596 switch(Active->Kind) {
597 case ActiveTemplateInstantiation::TemplateInstantiation:
598 // An instantiation of an alias template may or may not be a SFINAE
599 // context, depending on what else is on the stack.
600 if (isa<TypeAliasTemplateDecl>(Active->Entity))
601 break;
602 // Fall through.
603 case ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation:
604 case ActiveTemplateInstantiation::ExceptionSpecInstantiation:
605 // This is a template instantiation, so there is no SFINAE.
606 return None;
607
608 case ActiveTemplateInstantiation::DefaultTemplateArgumentInstantiation:
609 case ActiveTemplateInstantiation::PriorTemplateArgumentSubstitution:
610 case ActiveTemplateInstantiation::DefaultTemplateArgumentChecking:
611 // A default template argument instantiation and substitution into
612 // template parameters with arguments for prior parameters may or may
613 // not be a SFINAE context; look further up the stack.
614 break;
615
616 case ActiveTemplateInstantiation::ExplicitTemplateArgumentSubstitution:
617 case ActiveTemplateInstantiation::DeducedTemplateArgumentSubstitution:
618 // We're either substitution explicitly-specified template arguments
619 // or deduced template arguments, so SFINAE applies.
620 assert(Active->DeductionInfo && "Missing deduction info pointer");
621 return Active->DeductionInfo;
622 }
623 }
624
625 return None;
626 }
627
628 /// \brief Retrieve the depth and index of a parameter pack.
629 static std::pair<unsigned, unsigned>
getDepthAndIndex(NamedDecl * ND)630 getDepthAndIndex(NamedDecl *ND) {
631 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ND))
632 return std::make_pair(TTP->getDepth(), TTP->getIndex());
633
634 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(ND))
635 return std::make_pair(NTTP->getDepth(), NTTP->getIndex());
636
637 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(ND);
638 return std::make_pair(TTP->getDepth(), TTP->getIndex());
639 }
640
641 //===----------------------------------------------------------------------===/
642 // Template Instantiation for Types
643 //===----------------------------------------------------------------------===/
644 namespace {
645 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
646 const MultiLevelTemplateArgumentList &TemplateArgs;
647 SourceLocation Loc;
648 DeclarationName Entity;
649
650 public:
651 typedef TreeTransform<TemplateInstantiator> inherited;
652
TemplateInstantiator(Sema & SemaRef,const MultiLevelTemplateArgumentList & TemplateArgs,SourceLocation Loc,DeclarationName Entity)653 TemplateInstantiator(Sema &SemaRef,
654 const MultiLevelTemplateArgumentList &TemplateArgs,
655 SourceLocation Loc,
656 DeclarationName Entity)
657 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
658 Entity(Entity) { }
659
660 /// \brief Determine whether the given type \p T has already been
661 /// transformed.
662 ///
663 /// For the purposes of template instantiation, a type has already been
664 /// transformed if it is NULL or if it is not dependent.
665 bool AlreadyTransformed(QualType T);
666
667 /// \brief Returns the location of the entity being instantiated, if known.
getBaseLocation()668 SourceLocation getBaseLocation() { return Loc; }
669
670 /// \brief Returns the name of the entity being instantiated, if any.
getBaseEntity()671 DeclarationName getBaseEntity() { return Entity; }
672
673 /// \brief Sets the "base" location and entity when that
674 /// information is known based on another transformation.
setBase(SourceLocation Loc,DeclarationName Entity)675 void setBase(SourceLocation Loc, DeclarationName Entity) {
676 this->Loc = Loc;
677 this->Entity = Entity;
678 }
679
TryExpandParameterPacks(SourceLocation EllipsisLoc,SourceRange PatternRange,ArrayRef<UnexpandedParameterPack> Unexpanded,bool & ShouldExpand,bool & RetainExpansion,Optional<unsigned> & NumExpansions)680 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
681 SourceRange PatternRange,
682 ArrayRef<UnexpandedParameterPack> Unexpanded,
683 bool &ShouldExpand, bool &RetainExpansion,
684 Optional<unsigned> &NumExpansions) {
685 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
686 PatternRange, Unexpanded,
687 TemplateArgs,
688 ShouldExpand,
689 RetainExpansion,
690 NumExpansions);
691 }
692
ExpandingFunctionParameterPack(ParmVarDecl * Pack)693 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
694 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
695 }
696
ForgetPartiallySubstitutedPack()697 TemplateArgument ForgetPartiallySubstitutedPack() {
698 TemplateArgument Result;
699 if (NamedDecl *PartialPack
700 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
701 MultiLevelTemplateArgumentList &TemplateArgs
702 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
703 unsigned Depth, Index;
704 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
705 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
706 Result = TemplateArgs(Depth, Index);
707 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
708 }
709 }
710
711 return Result;
712 }
713
RememberPartiallySubstitutedPack(TemplateArgument Arg)714 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
715 if (Arg.isNull())
716 return;
717
718 if (NamedDecl *PartialPack
719 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
720 MultiLevelTemplateArgumentList &TemplateArgs
721 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
722 unsigned Depth, Index;
723 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
724 TemplateArgs.setArgument(Depth, Index, Arg);
725 }
726 }
727
728 /// \brief Transform the given declaration by instantiating a reference to
729 /// this declaration.
730 Decl *TransformDecl(SourceLocation Loc, Decl *D);
731
transformAttrs(Decl * Old,Decl * New)732 void transformAttrs(Decl *Old, Decl *New) {
733 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
734 }
735
transformedLocalDecl(Decl * Old,Decl * New)736 void transformedLocalDecl(Decl *Old, Decl *New) {
737 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
738 }
739
740 /// \brief Transform the definition of the given declaration by
741 /// instantiating it.
742 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
743
744 /// \brief Transform the first qualifier within a scope by instantiating the
745 /// declaration.
746 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
747
748 /// \brief Rebuild the exception declaration and register the declaration
749 /// as an instantiated local.
750 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
751 TypeSourceInfo *Declarator,
752 SourceLocation StartLoc,
753 SourceLocation NameLoc,
754 IdentifierInfo *Name);
755
756 /// \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
761 /// \brief Check for tag mismatches when instantiating an
762 /// elaborated type.
763 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
764 ElaboratedTypeKeyword Keyword,
765 NestedNameSpecifierLoc QualifierLoc,
766 QualType T);
767
768 TemplateName
769 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
770 SourceLocation NameLoc,
771 QualType ObjectType = QualType(),
772 NamedDecl *FirstQualifierInScope = nullptr);
773
774 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
775
776 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
777 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
778 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
779
780 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
781 NonTypeTemplateParmDecl *D);
782 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
783 SubstNonTypeTemplateParmPackExpr *E);
784
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
TransformFunctionProtoType(TypeLocBuilder & TLB,FunctionProtoTypeLoc TL)797 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
798 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>
804 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
805 FunctionProtoTypeLoc TL,
806 CXXRecordDecl *ThisContext,
807 unsigned ThisTypeQuals,
808 Fn TransformExceptionSpec);
809
810 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
811 int indexAdjustment,
812 Optional<unsigned> NumExpansions,
813 bool ExpectParameterPack);
814
815 /// \brief Transforms a template type parameter type by performing
816 /// substitution of the corresponding template type argument.
817 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
818 TemplateTypeParmTypeLoc TL);
819
820 /// \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
TransformCallExpr(CallExpr * CE)826 ExprResult TransformCallExpr(CallExpr *CE) {
827 getSema().CallsUndergoingInstantiation.push_back(CE);
828 ExprResult Result =
829 TreeTransform<TemplateInstantiator>::TransformCallExpr(CE);
830 getSema().CallsUndergoingInstantiation.pop_back();
831 return Result;
832 }
833
TransformLambdaExpr(LambdaExpr * E)834 ExprResult TransformLambdaExpr(LambdaExpr *E) {
835 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
836 return TreeTransform<TemplateInstantiator>::TransformLambdaExpr(E);
837 }
838
TransformLambdaScope(LambdaExpr * E,CXXMethodDecl * NewCallOperator,ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes)839 ExprResult TransformLambdaScope(LambdaExpr *E,
840 CXXMethodDecl *NewCallOperator,
841 ArrayRef<InitCaptureInfoTy> InitCaptureExprsAndTypes) {
842 CXXMethodDecl *const OldCallOperator = E->getCallOperator();
843 // In the generic lambda case, we set the NewTemplate to be considered
844 // an "instantiation" of the OldTemplate.
845 if (FunctionTemplateDecl *const NewCallOperatorTemplate =
846 NewCallOperator->getDescribedFunctionTemplate()) {
847
848 FunctionTemplateDecl *const OldCallOperatorTemplate =
849 OldCallOperator->getDescribedFunctionTemplate();
850 NewCallOperatorTemplate->setInstantiatedFromMemberTemplate(
851 OldCallOperatorTemplate);
852 } else
853 // For a non-generic lambda we set the NewCallOperator to
854 // be an instantiation of the OldCallOperator.
855 NewCallOperator->setInstantiationOfMemberFunction(OldCallOperator,
856 TSK_ImplicitInstantiation);
857
858 return inherited::TransformLambdaScope(E, NewCallOperator,
859 InitCaptureExprsAndTypes);
860 }
TransformTemplateParameterList(TemplateParameterList * OrigTPL)861 TemplateParameterList *TransformTemplateParameterList(
862 TemplateParameterList *OrigTPL) {
863 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
864
865 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
866 TemplateDeclInstantiator DeclInstantiator(getSema(),
867 /* DeclContext *Owner */ Owner, TemplateArgs);
868 return DeclInstantiator.SubstTemplateParams(OrigTPL);
869 }
870 private:
871 ExprResult transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl *parm,
872 SourceLocation loc,
873 TemplateArgument arg);
874 };
875 }
876
AlreadyTransformed(QualType T)877 bool TemplateInstantiator::AlreadyTransformed(QualType T) {
878 if (T.isNull())
879 return true;
880
881 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
882 return false;
883
884 getSema().MarkDeclarationsReferencedInType(Loc, T);
885 return true;
886 }
887
888 static TemplateArgument
getPackSubstitutedTemplateArgument(Sema & S,TemplateArgument Arg)889 getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
890 assert(S.ArgumentPackSubstitutionIndex >= 0);
891 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
892 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
893 if (Arg.isPackExpansion())
894 Arg = Arg.getPackExpansionPattern();
895 return Arg;
896 }
897
TransformDecl(SourceLocation Loc,Decl * D)898 Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
899 if (!D)
900 return nullptr;
901
902 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
903 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
904 // If the corresponding template argument is NULL or non-existent, it's
905 // because we are performing instantiation from explicitly-specified
906 // template arguments in a function template, but there were some
907 // arguments left unspecified.
908 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
909 TTP->getPosition()))
910 return D;
911
912 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
913
914 if (TTP->isParameterPack()) {
915 assert(Arg.getKind() == TemplateArgument::Pack &&
916 "Missing argument pack");
917 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
918 }
919
920 TemplateName Template = Arg.getAsTemplate();
921 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
922 "Wrong kind of template template argument");
923 return Template.getAsTemplateDecl();
924 }
925
926 // Fall through to find the instantiated declaration for this template
927 // template parameter.
928 }
929
930 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
931 }
932
TransformDefinition(SourceLocation Loc,Decl * D)933 Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
934 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
935 if (!Inst)
936 return nullptr;
937
938 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
939 return Inst;
940 }
941
942 NamedDecl *
TransformFirstQualifierInScope(NamedDecl * D,SourceLocation Loc)943 TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
944 SourceLocation Loc) {
945 // If the first part of the nested-name-specifier was a template type
946 // parameter, instantiate that type parameter down to a tag type.
947 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
948 const TemplateTypeParmType *TTP
949 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
950
951 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
952 // FIXME: This needs testing w/ member access expressions.
953 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
954
955 if (TTP->isParameterPack()) {
956 assert(Arg.getKind() == TemplateArgument::Pack &&
957 "Missing argument pack");
958
959 if (getSema().ArgumentPackSubstitutionIndex == -1)
960 return nullptr;
961
962 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
963 }
964
965 QualType T = Arg.getAsType();
966 if (T.isNull())
967 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
968
969 if (const TagType *Tag = T->getAs<TagType>())
970 return Tag->getDecl();
971
972 // The resulting type is not a tag; complain.
973 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
974 return nullptr;
975 }
976 }
977
978 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
979 }
980
981 VarDecl *
RebuildExceptionDecl(VarDecl * ExceptionDecl,TypeSourceInfo * Declarator,SourceLocation StartLoc,SourceLocation NameLoc,IdentifierInfo * Name)982 TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
983 TypeSourceInfo *Declarator,
984 SourceLocation StartLoc,
985 SourceLocation NameLoc,
986 IdentifierInfo *Name) {
987 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
988 StartLoc, NameLoc, Name);
989 if (Var)
990 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
991 return Var;
992 }
993
RebuildObjCExceptionDecl(VarDecl * ExceptionDecl,TypeSourceInfo * TSInfo,QualType T)994 VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
995 TypeSourceInfo *TSInfo,
996 QualType T) {
997 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
998 if (Var)
999 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1000 return Var;
1001 }
1002
1003 QualType
RebuildElaboratedType(SourceLocation KeywordLoc,ElaboratedTypeKeyword Keyword,NestedNameSpecifierLoc QualifierLoc,QualType T)1004 TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1005 ElaboratedTypeKeyword Keyword,
1006 NestedNameSpecifierLoc QualifierLoc,
1007 QualType T) {
1008 if (const TagType *TT = T->getAs<TagType>()) {
1009 TagDecl* TD = TT->getDecl();
1010
1011 SourceLocation TagLocation = KeywordLoc;
1012
1013 IdentifierInfo *Id = TD->getIdentifier();
1014
1015 // TODO: should we even warn on struct/class mismatches for this? Seems
1016 // like it's likely to produce a lot of spurious errors.
1017 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1018 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1019 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1020 TagLocation, *Id)) {
1021 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1022 << Id
1023 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1024 TD->getKindName());
1025 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1026 }
1027 }
1028 }
1029
1030 return TreeTransform<TemplateInstantiator>::RebuildElaboratedType(KeywordLoc,
1031 Keyword,
1032 QualifierLoc,
1033 T);
1034 }
1035
TransformTemplateName(CXXScopeSpec & SS,TemplateName Name,SourceLocation NameLoc,QualType ObjectType,NamedDecl * FirstQualifierInScope)1036 TemplateName TemplateInstantiator::TransformTemplateName(CXXScopeSpec &SS,
1037 TemplateName Name,
1038 SourceLocation NameLoc,
1039 QualType ObjectType,
1040 NamedDecl *FirstQualifierInScope) {
1041 if (TemplateTemplateParmDecl *TTP
1042 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1043 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1044 // If the corresponding template argument is NULL or non-existent, it's
1045 // because we are performing instantiation from explicitly-specified
1046 // template arguments in a function template, but there were some
1047 // arguments left unspecified.
1048 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1049 TTP->getPosition()))
1050 return Name;
1051
1052 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1053
1054 if (TTP->isParameterPack()) {
1055 assert(Arg.getKind() == TemplateArgument::Pack &&
1056 "Missing argument pack");
1057
1058 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1059 // We have the template argument pack to substitute, but we're not
1060 // actually expanding the enclosing pack expansion yet. So, just
1061 // keep the entire argument pack.
1062 return getSema().Context.getSubstTemplateTemplateParmPack(TTP, Arg);
1063 }
1064
1065 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1066 }
1067
1068 TemplateName Template = Arg.getAsTemplate();
1069 assert(!Template.isNull() && "Null template template argument");
1070
1071 // We don't ever want to substitute for a qualified template name, since
1072 // the qualifier is handled separately. So, look through the qualified
1073 // template name to its underlying declaration.
1074 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
1075 Template = TemplateName(QTN->getTemplateDecl());
1076
1077 Template = getSema().Context.getSubstTemplateTemplateParm(TTP, Template);
1078 return Template;
1079 }
1080 }
1081
1082 if (SubstTemplateTemplateParmPackStorage *SubstPack
1083 = Name.getAsSubstTemplateTemplateParmPack()) {
1084 if (getSema().ArgumentPackSubstitutionIndex == -1)
1085 return Name;
1086
1087 TemplateArgument Arg = SubstPack->getArgumentPack();
1088 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1089 return Arg.getAsTemplate();
1090 }
1091
1092 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1093 FirstQualifierInScope);
1094 }
1095
1096 ExprResult
TransformPredefinedExpr(PredefinedExpr * E)1097 TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1098 if (!E->isTypeDependent())
1099 return E;
1100
1101 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentType());
1102 }
1103
1104 ExprResult
TransformTemplateParmRefExpr(DeclRefExpr * E,NonTypeTemplateParmDecl * NTTP)1105 TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1106 NonTypeTemplateParmDecl *NTTP) {
1107 // If the corresponding template argument is NULL or non-existent, it's
1108 // because we are performing instantiation from explicitly-specified
1109 // template arguments in a function template, but there were some
1110 // arguments left unspecified.
1111 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1112 NTTP->getPosition()))
1113 return E;
1114
1115 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1116 if (NTTP->isParameterPack()) {
1117 assert(Arg.getKind() == TemplateArgument::Pack &&
1118 "Missing argument pack");
1119
1120 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1121 // We have an argument pack, but we can't select a particular argument
1122 // out of it yet. Therefore, we'll build an expression to hold on to that
1123 // argument pack.
1124 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1125 E->getLocation(),
1126 NTTP->getDeclName());
1127 if (TargetType.isNull())
1128 return ExprError();
1129
1130 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(TargetType,
1131 NTTP,
1132 E->getLocation(),
1133 Arg);
1134 }
1135
1136 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1137 }
1138
1139 return transformNonTypeTemplateParmRef(NTTP, E->getLocation(), Arg);
1140 }
1141
1142 const LoopHintAttr *
TransformLoopHintAttr(const LoopHintAttr * LH)1143 TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1144 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1145
1146 if (TransformedExpr == LH->getValue())
1147 return LH;
1148
1149 // Generate error if there is a problem with the value.
1150 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1151 return LH;
1152
1153 // Create new LoopHintValueAttr with integral expression in place of the
1154 // non-type template parameter.
1155 return LoopHintAttr::CreateImplicit(
1156 getSema().Context, LH->getSemanticSpelling(), LH->getOption(),
1157 LH->getState(), TransformedExpr, LH->getRange());
1158 }
1159
transformNonTypeTemplateParmRef(NonTypeTemplateParmDecl * parm,SourceLocation loc,TemplateArgument arg)1160 ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1161 NonTypeTemplateParmDecl *parm,
1162 SourceLocation loc,
1163 TemplateArgument arg) {
1164 ExprResult result;
1165 QualType type;
1166
1167 // The template argument itself might be an expression, in which
1168 // case we just return that expression.
1169 if (arg.getKind() == TemplateArgument::Expression) {
1170 Expr *argExpr = arg.getAsExpr();
1171 result = argExpr;
1172 type = argExpr->getType();
1173
1174 } else if (arg.getKind() == TemplateArgument::Declaration ||
1175 arg.getKind() == TemplateArgument::NullPtr) {
1176 ValueDecl *VD;
1177 if (arg.getKind() == TemplateArgument::Declaration) {
1178 VD = cast<ValueDecl>(arg.getAsDecl());
1179
1180 // Find the instantiation of the template argument. This is
1181 // required for nested templates.
1182 VD = cast_or_null<ValueDecl>(
1183 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1184 if (!VD)
1185 return ExprError();
1186 } else {
1187 // Propagate NULL template argument.
1188 VD = nullptr;
1189 }
1190
1191 // Derive the type we want the substituted decl to have. This had
1192 // better be non-dependent, or these checks will have serious problems.
1193 if (parm->isExpandedParameterPack()) {
1194 type = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1195 } else if (parm->isParameterPack() &&
1196 isa<PackExpansionType>(parm->getType())) {
1197 type = SemaRef.SubstType(
1198 cast<PackExpansionType>(parm->getType())->getPattern(),
1199 TemplateArgs, loc, parm->getDeclName());
1200 } else {
1201 type = SemaRef.SubstType(parm->getType(), TemplateArgs,
1202 loc, parm->getDeclName());
1203 }
1204 assert(!type.isNull() && "type substitution failed for param type");
1205 assert(!type->isDependentType() && "param type still dependent");
1206 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, type, loc);
1207
1208 if (!result.isInvalid()) type = result.get()->getType();
1209 } else {
1210 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1211
1212 // Note that this type can be different from the type of 'result',
1213 // e.g. if it's an enum type.
1214 type = arg.getIntegralType();
1215 }
1216 if (result.isInvalid()) return ExprError();
1217
1218 Expr *resultExpr = result.get();
1219 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1220 type, resultExpr->getValueKind(), loc, parm, resultExpr);
1221 }
1222
1223 ExprResult
TransformSubstNonTypeTemplateParmPackExpr(SubstNonTypeTemplateParmPackExpr * E)1224 TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1225 SubstNonTypeTemplateParmPackExpr *E) {
1226 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1227 // We aren't expanding the parameter pack, so just return ourselves.
1228 return E;
1229 }
1230
1231 TemplateArgument Arg = E->getArgumentPack();
1232 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1233 return transformNonTypeTemplateParmRef(E->getParameterPack(),
1234 E->getParameterPackLocation(),
1235 Arg);
1236 }
1237
1238 ExprResult
RebuildParmVarDeclRefExpr(ParmVarDecl * PD,SourceLocation Loc)1239 TemplateInstantiator::RebuildParmVarDeclRefExpr(ParmVarDecl *PD,
1240 SourceLocation Loc) {
1241 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1242 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1243 }
1244
1245 ExprResult
TransformFunctionParmPackExpr(FunctionParmPackExpr * E)1246 TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1247 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1248 // We can expand this parameter pack now.
1249 ParmVarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1250 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
1251 if (!VD)
1252 return ExprError();
1253 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(VD), E->getExprLoc());
1254 }
1255
1256 QualType T = TransformType(E->getType());
1257 if (T.isNull())
1258 return ExprError();
1259
1260 // Transform each of the parameter expansions into the corresponding
1261 // parameters in the instantiation of the function decl.
1262 SmallVector<Decl *, 8> Parms;
1263 Parms.reserve(E->getNumExpansions());
1264 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1265 I != End; ++I) {
1266 ParmVarDecl *D =
1267 cast_or_null<ParmVarDecl>(TransformDecl(E->getExprLoc(), *I));
1268 if (!D)
1269 return ExprError();
1270 Parms.push_back(D);
1271 }
1272
1273 return FunctionParmPackExpr::Create(getSema().Context, T,
1274 E->getParameterPack(),
1275 E->getParameterPackLocation(), Parms);
1276 }
1277
1278 ExprResult
TransformFunctionParmPackRefExpr(DeclRefExpr * E,ParmVarDecl * PD)1279 TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1280 ParmVarDecl *PD) {
1281 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1282 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1283 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1284 assert(Found && "no instantiation for parameter pack");
1285
1286 Decl *TransformedDecl;
1287 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1288 // If this is a reference to a function parameter pack which we can
1289 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1290 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1291 QualType T = TransformType(E->getType());
1292 if (T.isNull())
1293 return ExprError();
1294 return FunctionParmPackExpr::Create(getSema().Context, T, PD,
1295 E->getExprLoc(), *Pack);
1296 }
1297
1298 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1299 } else {
1300 TransformedDecl = Found->get<Decl*>();
1301 }
1302
1303 // We have either an unexpanded pack or a specific expansion.
1304 return RebuildParmVarDeclRefExpr(cast<ParmVarDecl>(TransformedDecl),
1305 E->getExprLoc());
1306 }
1307
1308 ExprResult
TransformDeclRefExpr(DeclRefExpr * E)1309 TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1310 NamedDecl *D = E->getDecl();
1311
1312 // Handle references to non-type template parameters and non-type template
1313 // parameter packs.
1314 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1315 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1316 return TransformTemplateParmRefExpr(E, NTTP);
1317
1318 // We have a non-type template parameter that isn't fully substituted;
1319 // FindInstantiatedDecl will find it in the local instantiation scope.
1320 }
1321
1322 // Handle references to function parameter packs.
1323 if (ParmVarDecl *PD = dyn_cast<ParmVarDecl>(D))
1324 if (PD->isParameterPack())
1325 return TransformFunctionParmPackRefExpr(E, PD);
1326
1327 return TreeTransform<TemplateInstantiator>::TransformDeclRefExpr(E);
1328 }
1329
TransformCXXDefaultArgExpr(CXXDefaultArgExpr * E)1330 ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
1331 CXXDefaultArgExpr *E) {
1332 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
1333 getDescribedFunctionTemplate() &&
1334 "Default arg expressions are never formed in dependent cases.");
1335 return SemaRef.BuildCXXDefaultArgExpr(E->getUsedLocation(),
1336 cast<FunctionDecl>(E->getParam()->getDeclContext()),
1337 E->getParam());
1338 }
1339
1340 template<typename Fn>
TransformFunctionProtoType(TypeLocBuilder & TLB,FunctionProtoTypeLoc TL,CXXRecordDecl * ThisContext,unsigned ThisTypeQuals,Fn TransformExceptionSpec)1341 QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
1342 FunctionProtoTypeLoc TL,
1343 CXXRecordDecl *ThisContext,
1344 unsigned ThisTypeQuals,
1345 Fn TransformExceptionSpec) {
1346 // We need a local instantiation scope for this function prototype.
1347 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1348 return inherited::TransformFunctionProtoType(
1349 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
1350 }
1351
1352 ParmVarDecl *
TransformFunctionTypeParam(ParmVarDecl * OldParm,int indexAdjustment,Optional<unsigned> NumExpansions,bool ExpectParameterPack)1353 TemplateInstantiator::TransformFunctionTypeParam(ParmVarDecl *OldParm,
1354 int indexAdjustment,
1355 Optional<unsigned> NumExpansions,
1356 bool ExpectParameterPack) {
1357 return SemaRef.SubstParmVarDecl(OldParm, TemplateArgs, indexAdjustment,
1358 NumExpansions, ExpectParameterPack);
1359 }
1360
1361 QualType
TransformTemplateTypeParmType(TypeLocBuilder & TLB,TemplateTypeParmTypeLoc TL)1362 TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1363 TemplateTypeParmTypeLoc TL) {
1364 const TemplateTypeParmType *T = TL.getTypePtr();
1365 if (T->getDepth() < TemplateArgs.getNumLevels()) {
1366 // Replace the template type parameter with its corresponding
1367 // template argument.
1368
1369 // If the corresponding template argument is NULL or doesn't exist, it's
1370 // because we are performing instantiation from explicitly-specified
1371 // template arguments in a function template class, but there were some
1372 // arguments left unspecified.
1373 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
1374 TemplateTypeParmTypeLoc NewTL
1375 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
1376 NewTL.setNameLoc(TL.getNameLoc());
1377 return TL.getType();
1378 }
1379
1380 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
1381
1382 if (T->isParameterPack()) {
1383 assert(Arg.getKind() == TemplateArgument::Pack &&
1384 "Missing argument pack");
1385
1386 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1387 // We have the template argument pack, but we're not expanding the
1388 // enclosing pack expansion yet. Just save the template argument
1389 // pack for later substitution.
1390 QualType Result
1391 = getSema().Context.getSubstTemplateTypeParmPackType(T, Arg);
1392 SubstTemplateTypeParmPackTypeLoc NewTL
1393 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
1394 NewTL.setNameLoc(TL.getNameLoc());
1395 return Result;
1396 }
1397
1398 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1399 }
1400
1401 assert(Arg.getKind() == TemplateArgument::Type &&
1402 "Template argument kind mismatch");
1403
1404 QualType Replacement = Arg.getAsType();
1405
1406 // TODO: only do this uniquing once, at the start of instantiation.
1407 QualType Result
1408 = getSema().Context.getSubstTemplateTypeParmType(T, Replacement);
1409 SubstTemplateTypeParmTypeLoc NewTL
1410 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1411 NewTL.setNameLoc(TL.getNameLoc());
1412 return Result;
1413 }
1414
1415 // The template type parameter comes from an inner template (e.g.,
1416 // the template parameter list of a member template inside the
1417 // template we are instantiating). Create a new template type
1418 // parameter with the template "level" reduced by one.
1419 TemplateTypeParmDecl *NewTTPDecl = nullptr;
1420 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
1421 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
1422 TransformDecl(TL.getNameLoc(), OldTTPDecl));
1423
1424 QualType Result
1425 = getSema().Context.getTemplateTypeParmType(T->getDepth()
1426 - TemplateArgs.getNumLevels(),
1427 T->getIndex(),
1428 T->isParameterPack(),
1429 NewTTPDecl);
1430 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
1431 NewTL.setNameLoc(TL.getNameLoc());
1432 return Result;
1433 }
1434
1435 QualType
TransformSubstTemplateTypeParmPackType(TypeLocBuilder & TLB,SubstTemplateTypeParmPackTypeLoc TL)1436 TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
1437 TypeLocBuilder &TLB,
1438 SubstTemplateTypeParmPackTypeLoc TL) {
1439 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1440 // We aren't expanding the parameter pack, so just return ourselves.
1441 SubstTemplateTypeParmPackTypeLoc NewTL
1442 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(TL.getType());
1443 NewTL.setNameLoc(TL.getNameLoc());
1444 return TL.getType();
1445 }
1446
1447 TemplateArgument Arg = TL.getTypePtr()->getArgumentPack();
1448 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1449 QualType Result = Arg.getAsType();
1450
1451 Result = getSema().Context.getSubstTemplateTypeParmType(
1452 TL.getTypePtr()->getReplacedParameter(),
1453 Result);
1454 SubstTemplateTypeParmTypeLoc NewTL
1455 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
1456 NewTL.setNameLoc(TL.getNameLoc());
1457 return Result;
1458 }
1459
1460 /// \brief Perform substitution on the type T with a given set of template
1461 /// arguments.
1462 ///
1463 /// This routine substitutes the given template arguments into the
1464 /// type T and produces the instantiated type.
1465 ///
1466 /// \param T the type into which the template arguments will be
1467 /// substituted. If this type is not dependent, it will be returned
1468 /// immediately.
1469 ///
1470 /// \param Args the template arguments that will be
1471 /// substituted for the top-level template parameters within T.
1472 ///
1473 /// \param Loc the location in the source code where this substitution
1474 /// is being performed. It will typically be the location of the
1475 /// declarator (if we're instantiating the type of some declaration)
1476 /// or the location of the type in the source code (if, e.g., we're
1477 /// instantiating the type of a cast expression).
1478 ///
1479 /// \param Entity the name of the entity associated with a declaration
1480 /// being instantiated (if any). May be empty to indicate that there
1481 /// is no such entity (if, e.g., this is a type that occurs as part of
1482 /// a cast expression) or that the entity has no name (e.g., an
1483 /// unnamed function parameter).
1484 ///
1485 /// \returns If the instantiation succeeds, the instantiated
1486 /// type. Otherwise, produces diagnostics and returns a NULL type.
SubstType(TypeSourceInfo * T,const MultiLevelTemplateArgumentList & Args,SourceLocation Loc,DeclarationName Entity)1487 TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
1488 const MultiLevelTemplateArgumentList &Args,
1489 SourceLocation Loc,
1490 DeclarationName Entity) {
1491 assert(!ActiveTemplateInstantiations.empty() &&
1492 "Cannot perform an instantiation without some context on the "
1493 "instantiation stack");
1494
1495 if (!T->getType()->isInstantiationDependentType() &&
1496 !T->getType()->isVariablyModifiedType())
1497 return T;
1498
1499 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1500 return Instantiator.TransformType(T);
1501 }
1502
SubstType(TypeLoc TL,const MultiLevelTemplateArgumentList & Args,SourceLocation Loc,DeclarationName Entity)1503 TypeSourceInfo *Sema::SubstType(TypeLoc TL,
1504 const MultiLevelTemplateArgumentList &Args,
1505 SourceLocation Loc,
1506 DeclarationName Entity) {
1507 assert(!ActiveTemplateInstantiations.empty() &&
1508 "Cannot perform an instantiation without some context on the "
1509 "instantiation stack");
1510
1511 if (TL.getType().isNull())
1512 return nullptr;
1513
1514 if (!TL.getType()->isInstantiationDependentType() &&
1515 !TL.getType()->isVariablyModifiedType()) {
1516 // FIXME: Make a copy of the TypeLoc data here, so that we can
1517 // return a new TypeSourceInfo. Inefficient!
1518 TypeLocBuilder TLB;
1519 TLB.pushFullCopy(TL);
1520 return TLB.getTypeSourceInfo(Context, TL.getType());
1521 }
1522
1523 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1524 TypeLocBuilder TLB;
1525 TLB.reserve(TL.getFullDataSize());
1526 QualType Result = Instantiator.TransformType(TLB, TL);
1527 if (Result.isNull())
1528 return nullptr;
1529
1530 return TLB.getTypeSourceInfo(Context, Result);
1531 }
1532
1533 /// Deprecated form of the above.
SubstType(QualType T,const MultiLevelTemplateArgumentList & TemplateArgs,SourceLocation Loc,DeclarationName Entity)1534 QualType Sema::SubstType(QualType T,
1535 const MultiLevelTemplateArgumentList &TemplateArgs,
1536 SourceLocation Loc, DeclarationName Entity) {
1537 assert(!ActiveTemplateInstantiations.empty() &&
1538 "Cannot perform an instantiation without some context on the "
1539 "instantiation stack");
1540
1541 // If T is not a dependent type or a variably-modified type, there
1542 // is nothing to do.
1543 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
1544 return T;
1545
1546 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
1547 return Instantiator.TransformType(T);
1548 }
1549
NeedsInstantiationAsFunctionType(TypeSourceInfo * T)1550 static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
1551 if (T->getType()->isInstantiationDependentType() ||
1552 T->getType()->isVariablyModifiedType())
1553 return true;
1554
1555 TypeLoc TL = T->getTypeLoc().IgnoreParens();
1556 if (!TL.getAs<FunctionProtoTypeLoc>())
1557 return false;
1558
1559 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
1560 for (unsigned I = 0, E = FP.getNumParams(); I != E; ++I) {
1561 ParmVarDecl *P = FP.getParam(I);
1562
1563 // This must be synthesized from a typedef.
1564 if (!P) continue;
1565
1566 // The parameter's type as written might be dependent even if the
1567 // decayed type was not dependent.
1568 if (TypeSourceInfo *TSInfo = P->getTypeSourceInfo())
1569 if (TSInfo->getType()->isInstantiationDependentType())
1570 return true;
1571
1572 // TODO: currently we always rebuild expressions. When we
1573 // properly get lazier about this, we should use the same
1574 // logic to avoid rebuilding prototypes here.
1575 if (P->hasDefaultArg())
1576 return true;
1577 }
1578
1579 return false;
1580 }
1581
1582 /// A form of SubstType intended specifically for instantiating the
1583 /// type of a FunctionDecl. Its purpose is solely to force the
1584 /// instantiation of default-argument expressions and to avoid
1585 /// instantiating an exception-specification.
SubstFunctionDeclType(TypeSourceInfo * T,const MultiLevelTemplateArgumentList & Args,SourceLocation Loc,DeclarationName Entity,CXXRecordDecl * ThisContext,unsigned ThisTypeQuals)1586 TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
1587 const MultiLevelTemplateArgumentList &Args,
1588 SourceLocation Loc,
1589 DeclarationName Entity,
1590 CXXRecordDecl *ThisContext,
1591 unsigned ThisTypeQuals) {
1592 assert(!ActiveTemplateInstantiations.empty() &&
1593 "Cannot perform an instantiation without some context on the "
1594 "instantiation stack");
1595
1596 if (!NeedsInstantiationAsFunctionType(T))
1597 return T;
1598
1599 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
1600
1601 TypeLocBuilder TLB;
1602
1603 TypeLoc TL = T->getTypeLoc();
1604 TLB.reserve(TL.getFullDataSize());
1605
1606 QualType Result;
1607
1608 if (FunctionProtoTypeLoc Proto =
1609 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
1610 // Instantiate the type, other than its exception specification. The
1611 // exception specification is instantiated in InitFunctionInstantiation
1612 // once we've built the FunctionDecl.
1613 // FIXME: Set the exception specification to EST_Uninstantiated here,
1614 // instead of rebuilding the function type again later.
1615 Result = Instantiator.TransformFunctionProtoType(
1616 TLB, Proto, ThisContext, ThisTypeQuals,
1617 [](FunctionProtoType::ExceptionSpecInfo &ESI,
1618 bool &Changed) { return false; });
1619 } else {
1620 Result = Instantiator.TransformType(TLB, TL);
1621 }
1622 if (Result.isNull())
1623 return nullptr;
1624
1625 return TLB.getTypeSourceInfo(Context, Result);
1626 }
1627
SubstExceptionSpec(FunctionDecl * New,const FunctionProtoType * Proto,const MultiLevelTemplateArgumentList & Args)1628 void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
1629 const MultiLevelTemplateArgumentList &Args) {
1630 FunctionProtoType::ExceptionSpecInfo ESI =
1631 Proto->getExtProtoInfo().ExceptionSpec;
1632 assert(ESI.Type != EST_Uninstantiated);
1633
1634 TemplateInstantiator Instantiator(*this, Args, New->getLocation(),
1635 New->getDeclName());
1636
1637 SmallVector<QualType, 4> ExceptionStorage;
1638 bool Changed = false;
1639 if (Instantiator.TransformExceptionSpec(
1640 New->getTypeSourceInfo()->getTypeLoc().getLocEnd(), ESI,
1641 ExceptionStorage, Changed))
1642 // On error, recover by dropping the exception specification.
1643 ESI.Type = EST_None;
1644
1645 UpdateExceptionSpec(New, ESI);
1646 }
1647
SubstParmVarDecl(ParmVarDecl * OldParm,const MultiLevelTemplateArgumentList & TemplateArgs,int indexAdjustment,Optional<unsigned> NumExpansions,bool ExpectParameterPack)1648 ParmVarDecl *Sema::SubstParmVarDecl(ParmVarDecl *OldParm,
1649 const MultiLevelTemplateArgumentList &TemplateArgs,
1650 int indexAdjustment,
1651 Optional<unsigned> NumExpansions,
1652 bool ExpectParameterPack) {
1653 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
1654 TypeSourceInfo *NewDI = nullptr;
1655
1656 TypeLoc OldTL = OldDI->getTypeLoc();
1657 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
1658
1659 // We have a function parameter pack. Substitute into the pattern of the
1660 // expansion.
1661 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
1662 OldParm->getLocation(), OldParm->getDeclName());
1663 if (!NewDI)
1664 return nullptr;
1665
1666 if (NewDI->getType()->containsUnexpandedParameterPack()) {
1667 // We still have unexpanded parameter packs, which means that
1668 // our function parameter is still a function parameter pack.
1669 // Therefore, make its type a pack expansion type.
1670 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
1671 NumExpansions);
1672 } else if (ExpectParameterPack) {
1673 // We expected to get a parameter pack but didn't (because the type
1674 // itself is not a pack expansion type), so complain. This can occur when
1675 // the substitution goes through an alias template that "loses" the
1676 // pack expansion.
1677 Diag(OldParm->getLocation(),
1678 diag::err_function_parameter_pack_without_parameter_packs)
1679 << NewDI->getType();
1680 return nullptr;
1681 }
1682 } else {
1683 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
1684 OldParm->getDeclName());
1685 }
1686
1687 if (!NewDI)
1688 return nullptr;
1689
1690 if (NewDI->getType()->isVoidType()) {
1691 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
1692 return nullptr;
1693 }
1694
1695 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
1696 OldParm->getInnerLocStart(),
1697 OldParm->getLocation(),
1698 OldParm->getIdentifier(),
1699 NewDI->getType(), NewDI,
1700 OldParm->getStorageClass());
1701 if (!NewParm)
1702 return nullptr;
1703
1704 // Mark the (new) default argument as uninstantiated (if any).
1705 if (OldParm->hasUninstantiatedDefaultArg()) {
1706 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
1707 NewParm->setUninstantiatedDefaultArg(Arg);
1708 } else if (OldParm->hasUnparsedDefaultArg()) {
1709 NewParm->setUnparsedDefaultArg();
1710 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
1711 } else if (Expr *Arg = OldParm->getDefaultArg())
1712 // FIXME: if we non-lazily instantiated non-dependent default args for
1713 // non-dependent parameter types we could remove a bunch of duplicate
1714 // conversion warnings for such arguments.
1715 NewParm->setUninstantiatedDefaultArg(Arg);
1716
1717 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
1718
1719 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
1720 // Add the new parameter to the instantiated parameter pack.
1721 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
1722 } else {
1723 // Introduce an Old -> New mapping
1724 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
1725 }
1726
1727 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
1728 // can be anything, is this right ?
1729 NewParm->setDeclContext(CurContext);
1730
1731 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
1732 OldParm->getFunctionScopeIndex() + indexAdjustment);
1733
1734 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
1735
1736 return NewParm;
1737 }
1738
1739 /// \brief Substitute the given template arguments into the given set of
1740 /// parameters, producing the set of parameter types that would be generated
1741 /// from such a substitution.
SubstParmTypes(SourceLocation Loc,ParmVarDecl ** Params,unsigned NumParams,const MultiLevelTemplateArgumentList & TemplateArgs,SmallVectorImpl<QualType> & ParamTypes,SmallVectorImpl<ParmVarDecl * > * OutParams)1742 bool Sema::SubstParmTypes(SourceLocation Loc,
1743 ParmVarDecl **Params, unsigned NumParams,
1744 const MultiLevelTemplateArgumentList &TemplateArgs,
1745 SmallVectorImpl<QualType> &ParamTypes,
1746 SmallVectorImpl<ParmVarDecl *> *OutParams) {
1747 assert(!ActiveTemplateInstantiations.empty() &&
1748 "Cannot perform an instantiation without some context on the "
1749 "instantiation stack");
1750
1751 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
1752 DeclarationName());
1753 return Instantiator.TransformFunctionTypeParams(Loc, Params, NumParams,
1754 nullptr, ParamTypes,
1755 OutParams);
1756 }
1757
1758 /// \brief Perform substitution on the base class specifiers of the
1759 /// given class template specialization.
1760 ///
1761 /// Produces a diagnostic and returns true on error, returns false and
1762 /// attaches the instantiated base classes to the class template
1763 /// specialization if successful.
1764 bool
SubstBaseSpecifiers(CXXRecordDecl * Instantiation,CXXRecordDecl * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs)1765 Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
1766 CXXRecordDecl *Pattern,
1767 const MultiLevelTemplateArgumentList &TemplateArgs) {
1768 bool Invalid = false;
1769 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
1770 for (const auto Base : Pattern->bases()) {
1771 if (!Base.getType()->isDependentType()) {
1772 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
1773 if (RD->isInvalidDecl())
1774 Instantiation->setInvalidDecl();
1775 }
1776 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
1777 continue;
1778 }
1779
1780 SourceLocation EllipsisLoc;
1781 TypeSourceInfo *BaseTypeLoc;
1782 if (Base.isPackExpansion()) {
1783 // This is a pack expansion. See whether we should expand it now, or
1784 // wait until later.
1785 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1786 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
1787 Unexpanded);
1788 bool ShouldExpand = false;
1789 bool RetainExpansion = false;
1790 Optional<unsigned> NumExpansions;
1791 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
1792 Base.getSourceRange(),
1793 Unexpanded,
1794 TemplateArgs, ShouldExpand,
1795 RetainExpansion,
1796 NumExpansions)) {
1797 Invalid = true;
1798 continue;
1799 }
1800
1801 // If we should expand this pack expansion now, do so.
1802 if (ShouldExpand) {
1803 for (unsigned I = 0; I != *NumExpansions; ++I) {
1804 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
1805
1806 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1807 TemplateArgs,
1808 Base.getSourceRange().getBegin(),
1809 DeclarationName());
1810 if (!BaseTypeLoc) {
1811 Invalid = true;
1812 continue;
1813 }
1814
1815 if (CXXBaseSpecifier *InstantiatedBase
1816 = CheckBaseSpecifier(Instantiation,
1817 Base.getSourceRange(),
1818 Base.isVirtual(),
1819 Base.getAccessSpecifierAsWritten(),
1820 BaseTypeLoc,
1821 SourceLocation()))
1822 InstantiatedBases.push_back(InstantiatedBase);
1823 else
1824 Invalid = true;
1825 }
1826
1827 continue;
1828 }
1829
1830 // The resulting base specifier will (still) be a pack expansion.
1831 EllipsisLoc = Base.getEllipsisLoc();
1832 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
1833 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1834 TemplateArgs,
1835 Base.getSourceRange().getBegin(),
1836 DeclarationName());
1837 } else {
1838 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
1839 TemplateArgs,
1840 Base.getSourceRange().getBegin(),
1841 DeclarationName());
1842 }
1843
1844 if (!BaseTypeLoc) {
1845 Invalid = true;
1846 continue;
1847 }
1848
1849 if (CXXBaseSpecifier *InstantiatedBase
1850 = CheckBaseSpecifier(Instantiation,
1851 Base.getSourceRange(),
1852 Base.isVirtual(),
1853 Base.getAccessSpecifierAsWritten(),
1854 BaseTypeLoc,
1855 EllipsisLoc))
1856 InstantiatedBases.push_back(InstantiatedBase);
1857 else
1858 Invalid = true;
1859 }
1860
1861 if (!Invalid &&
1862 AttachBaseSpecifiers(Instantiation, InstantiatedBases.data(),
1863 InstantiatedBases.size()))
1864 Invalid = true;
1865
1866 return Invalid;
1867 }
1868
1869 // Defined via #include from SemaTemplateInstantiateDecl.cpp
1870 namespace clang {
1871 namespace sema {
1872 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
1873 const MultiLevelTemplateArgumentList &TemplateArgs);
1874 }
1875 }
1876
1877 /// Determine whether we would be unable to instantiate this template (because
1878 /// it either has no definition, or is in the process of being instantiated).
DiagnoseUninstantiableTemplate(Sema & S,SourceLocation PointOfInstantiation,TagDecl * Instantiation,bool InstantiatedFromMember,TagDecl * Pattern,TagDecl * PatternDef,TemplateSpecializationKind TSK,bool Complain=true)1879 static bool DiagnoseUninstantiableTemplate(Sema &S,
1880 SourceLocation PointOfInstantiation,
1881 TagDecl *Instantiation,
1882 bool InstantiatedFromMember,
1883 TagDecl *Pattern,
1884 TagDecl *PatternDef,
1885 TemplateSpecializationKind TSK,
1886 bool Complain = true) {
1887 if (PatternDef && !PatternDef->isBeingDefined())
1888 return false;
1889
1890 if (!Complain || (PatternDef && PatternDef->isInvalidDecl())) {
1891 // Say nothing
1892 } else if (PatternDef) {
1893 assert(PatternDef->isBeingDefined());
1894 S.Diag(PointOfInstantiation,
1895 diag::err_template_instantiate_within_definition)
1896 << (TSK != TSK_ImplicitInstantiation)
1897 << S.Context.getTypeDeclType(Instantiation);
1898 // Not much point in noting the template declaration here, since
1899 // we're lexically inside it.
1900 Instantiation->setInvalidDecl();
1901 } else if (InstantiatedFromMember) {
1902 S.Diag(PointOfInstantiation,
1903 diag::err_implicit_instantiate_member_undefined)
1904 << S.Context.getTypeDeclType(Instantiation);
1905 S.Diag(Pattern->getLocation(), diag::note_member_declared_at);
1906 } else {
1907 S.Diag(PointOfInstantiation, diag::err_template_instantiate_undefined)
1908 << (TSK != TSK_ImplicitInstantiation)
1909 << S.Context.getTypeDeclType(Instantiation);
1910 S.Diag(Pattern->getLocation(), diag::note_template_decl_here);
1911 }
1912
1913 // In general, Instantiation isn't marked invalid to get more than one
1914 // error for multiple undefined instantiations. But the code that does
1915 // explicit declaration -> explicit definition conversion can't handle
1916 // invalid declarations, so mark as invalid in that case.
1917 if (TSK == TSK_ExplicitInstantiationDeclaration)
1918 Instantiation->setInvalidDecl();
1919 return true;
1920 }
1921
1922 /// \brief Instantiate the definition of a class from a given pattern.
1923 ///
1924 /// \param PointOfInstantiation The point of instantiation within the
1925 /// source code.
1926 ///
1927 /// \param Instantiation is the declaration whose definition is being
1928 /// instantiated. This will be either a class template specialization
1929 /// or a member class of a class template specialization.
1930 ///
1931 /// \param Pattern is the pattern from which the instantiation
1932 /// occurs. This will be either the declaration of a class template or
1933 /// the declaration of a member class of a class template.
1934 ///
1935 /// \param TemplateArgs The template arguments to be substituted into
1936 /// the pattern.
1937 ///
1938 /// \param TSK the kind of implicit or explicit instantiation to perform.
1939 ///
1940 /// \param Complain whether to complain if the class cannot be instantiated due
1941 /// to the lack of a definition.
1942 ///
1943 /// \returns true if an error occurred, false otherwise.
1944 bool
InstantiateClass(SourceLocation PointOfInstantiation,CXXRecordDecl * Instantiation,CXXRecordDecl * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs,TemplateSpecializationKind TSK,bool Complain)1945 Sema::InstantiateClass(SourceLocation PointOfInstantiation,
1946 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
1947 const MultiLevelTemplateArgumentList &TemplateArgs,
1948 TemplateSpecializationKind TSK,
1949 bool Complain) {
1950 CXXRecordDecl *PatternDef
1951 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
1952 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
1953 Instantiation->getInstantiatedFromMemberClass(),
1954 Pattern, PatternDef, TSK, Complain))
1955 return true;
1956 Pattern = PatternDef;
1957
1958 // \brief Record the point of instantiation.
1959 if (MemberSpecializationInfo *MSInfo
1960 = Instantiation->getMemberSpecializationInfo()) {
1961 MSInfo->setTemplateSpecializationKind(TSK);
1962 MSInfo->setPointOfInstantiation(PointOfInstantiation);
1963 } else if (ClassTemplateSpecializationDecl *Spec
1964 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
1965 Spec->setTemplateSpecializationKind(TSK);
1966 Spec->setPointOfInstantiation(PointOfInstantiation);
1967 }
1968
1969 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
1970 if (Inst.isInvalid())
1971 return true;
1972
1973 // Enter the scope of this instantiation. We don't use
1974 // PushDeclContext because we don't have a scope.
1975 ContextRAII SavedContext(*this, Instantiation);
1976 EnterExpressionEvaluationContext EvalContext(*this,
1977 Sema::PotentiallyEvaluated);
1978
1979 // If this is an instantiation of a local class, merge this local
1980 // instantiation scope with the enclosing scope. Otherwise, every
1981 // instantiation of a class has its own local instantiation scope.
1982 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
1983 LocalInstantiationScope Scope(*this, MergeWithParentScope);
1984
1985 // Pull attributes from the pattern onto the instantiation.
1986 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
1987
1988 // Start the definition of this instantiation.
1989 Instantiation->startDefinition();
1990
1991 // The instantiation is visible here, even if it was first declared in an
1992 // unimported module.
1993 Instantiation->setHidden(false);
1994
1995 // FIXME: This loses the as-written tag kind for an explicit instantiation.
1996 Instantiation->setTagKind(Pattern->getTagKind());
1997
1998 // Do substitution on the base class specifiers.
1999 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
2000 Instantiation->setInvalidDecl();
2001
2002 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2003 SmallVector<Decl*, 4> Fields;
2004 // Delay instantiation of late parsed attributes.
2005 LateInstantiatedAttrVec LateAttrs;
2006 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
2007
2008 for (auto *Member : Pattern->decls()) {
2009 // Don't instantiate members not belonging in this semantic context.
2010 // e.g. for:
2011 // @code
2012 // template <int i> class A {
2013 // class B *g;
2014 // };
2015 // @endcode
2016 // 'class B' has the template as lexical context but semantically it is
2017 // introduced in namespace scope.
2018 if (Member->getDeclContext() != Pattern)
2019 continue;
2020
2021 if (Member->isInvalidDecl()) {
2022 Instantiation->setInvalidDecl();
2023 continue;
2024 }
2025
2026 Decl *NewMember = Instantiator.Visit(Member);
2027 if (NewMember) {
2028 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
2029 Fields.push_back(Field);
2030 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
2031 // C++11 [temp.inst]p1: The implicit instantiation of a class template
2032 // specialization causes the implicit instantiation of the definitions
2033 // of unscoped member enumerations.
2034 // Record a point of instantiation for this implicit instantiation.
2035 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
2036 Enum->isCompleteDefinition()) {
2037 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
2038 assert(MSInfo && "no spec info for member enum specialization");
2039 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
2040 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2041 }
2042 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
2043 if (SA->isFailed()) {
2044 // A static_assert failed. Bail out; instantiating this
2045 // class is probably not meaningful.
2046 Instantiation->setInvalidDecl();
2047 break;
2048 }
2049 }
2050
2051 if (NewMember->isInvalidDecl())
2052 Instantiation->setInvalidDecl();
2053 } else {
2054 // FIXME: Eventually, a NULL return will mean that one of the
2055 // instantiations was a semantic disaster, and we'll want to mark the
2056 // declaration invalid.
2057 // For now, we expect to skip some members that we can't yet handle.
2058 }
2059 }
2060
2061 // Finish checking fields.
2062 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
2063 SourceLocation(), SourceLocation(), nullptr);
2064 CheckCompletedCXXClass(Instantiation);
2065
2066 // Instantiate late parsed attributes, and attach them to their decls.
2067 // See Sema::InstantiateAttrs
2068 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
2069 E = LateAttrs.end(); I != E; ++I) {
2070 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
2071 CurrentInstantiationScope = I->Scope;
2072
2073 // Allow 'this' within late-parsed attributes.
2074 NamedDecl *ND = dyn_cast<NamedDecl>(I->NewDecl);
2075 CXXRecordDecl *ThisContext =
2076 dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
2077 CXXThisScopeRAII ThisScope(*this, ThisContext, /*TypeQuals*/0,
2078 ND && ND->isCXXInstanceMember());
2079
2080 Attr *NewAttr =
2081 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
2082 I->NewDecl->addAttr(NewAttr);
2083 LocalInstantiationScope::deleteScopes(I->Scope,
2084 Instantiator.getStartingScope());
2085 }
2086 Instantiator.disableLateAttributeInstantiation();
2087 LateAttrs.clear();
2088
2089 ActOnFinishDelayedMemberInitializers(Instantiation);
2090
2091 // FIXME: We should do something similar for explicit instantiations so they
2092 // end up in the right module.
2093 if (TSK == TSK_ImplicitInstantiation) {
2094 Instantiation->setLocation(Pattern->getLocation());
2095 Instantiation->setLocStart(Pattern->getInnerLocStart());
2096 Instantiation->setRBraceLoc(Pattern->getRBraceLoc());
2097 }
2098
2099 if (!Instantiation->isInvalidDecl()) {
2100 // Perform any dependent diagnostics from the pattern.
2101 PerformDependentDiagnostics(Pattern, TemplateArgs);
2102
2103 // Instantiate any out-of-line class template partial
2104 // specializations now.
2105 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
2106 P = Instantiator.delayed_partial_spec_begin(),
2107 PEnd = Instantiator.delayed_partial_spec_end();
2108 P != PEnd; ++P) {
2109 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
2110 P->first, P->second)) {
2111 Instantiation->setInvalidDecl();
2112 break;
2113 }
2114 }
2115
2116 // Instantiate any out-of-line variable template partial
2117 // specializations now.
2118 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
2119 P = Instantiator.delayed_var_partial_spec_begin(),
2120 PEnd = Instantiator.delayed_var_partial_spec_end();
2121 P != PEnd; ++P) {
2122 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
2123 P->first, P->second)) {
2124 Instantiation->setInvalidDecl();
2125 break;
2126 }
2127 }
2128 }
2129
2130 // Exit the scope of this instantiation.
2131 SavedContext.pop();
2132
2133 if (!Instantiation->isInvalidDecl()) {
2134 Consumer.HandleTagDeclDefinition(Instantiation);
2135
2136 // Always emit the vtable for an explicit instantiation definition
2137 // of a polymorphic class template specialization.
2138 if (TSK == TSK_ExplicitInstantiationDefinition)
2139 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
2140 }
2141
2142 return Instantiation->isInvalidDecl();
2143 }
2144
2145 /// \brief Instantiate the definition of an enum from a given pattern.
2146 ///
2147 /// \param PointOfInstantiation The point of instantiation within the
2148 /// source code.
2149 /// \param Instantiation is the declaration whose definition is being
2150 /// instantiated. This will be a member enumeration of a class
2151 /// temploid specialization, or a local enumeration within a
2152 /// function temploid specialization.
2153 /// \param Pattern The templated declaration from which the instantiation
2154 /// occurs.
2155 /// \param TemplateArgs The template arguments to be substituted into
2156 /// the pattern.
2157 /// \param TSK The kind of implicit or explicit instantiation to perform.
2158 ///
2159 /// \return \c true if an error occurred, \c false otherwise.
InstantiateEnum(SourceLocation PointOfInstantiation,EnumDecl * Instantiation,EnumDecl * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs,TemplateSpecializationKind TSK)2160 bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
2161 EnumDecl *Instantiation, EnumDecl *Pattern,
2162 const MultiLevelTemplateArgumentList &TemplateArgs,
2163 TemplateSpecializationKind TSK) {
2164 EnumDecl *PatternDef = Pattern->getDefinition();
2165 if (DiagnoseUninstantiableTemplate(*this, PointOfInstantiation, Instantiation,
2166 Instantiation->getInstantiatedFromMemberEnum(),
2167 Pattern, PatternDef, TSK,/*Complain*/true))
2168 return true;
2169 Pattern = PatternDef;
2170
2171 // Record the point of instantiation.
2172 if (MemberSpecializationInfo *MSInfo
2173 = Instantiation->getMemberSpecializationInfo()) {
2174 MSInfo->setTemplateSpecializationKind(TSK);
2175 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2176 }
2177
2178 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2179 if (Inst.isInvalid())
2180 return true;
2181
2182 // The instantiation is visible here, even if it was first declared in an
2183 // unimported module.
2184 Instantiation->setHidden(false);
2185
2186 // Enter the scope of this instantiation. We don't use
2187 // PushDeclContext because we don't have a scope.
2188 ContextRAII SavedContext(*this, Instantiation);
2189 EnterExpressionEvaluationContext EvalContext(*this,
2190 Sema::PotentiallyEvaluated);
2191
2192 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
2193
2194 // Pull attributes from the pattern onto the instantiation.
2195 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
2196
2197 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
2198 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
2199
2200 // Exit the scope of this instantiation.
2201 SavedContext.pop();
2202
2203 return Instantiation->isInvalidDecl();
2204 }
2205
2206
2207 /// \brief Instantiate the definition of a field from the given pattern.
2208 ///
2209 /// \param PointOfInstantiation The point of instantiation within the
2210 /// source code.
2211 /// \param Instantiation is the declaration whose definition is being
2212 /// instantiated. This will be a class of a class temploid
2213 /// specialization, or a local enumeration within a function temploid
2214 /// specialization.
2215 /// \param Pattern The templated declaration from which the instantiation
2216 /// occurs.
2217 /// \param TemplateArgs The template arguments to be substituted into
2218 /// the pattern.
2219 ///
2220 /// \return \c true if an error occurred, \c false otherwise.
InstantiateInClassInitializer(SourceLocation PointOfInstantiation,FieldDecl * Instantiation,FieldDecl * Pattern,const MultiLevelTemplateArgumentList & TemplateArgs)2221 bool Sema::InstantiateInClassInitializer(
2222 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
2223 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
2224 // If there is no initializer, we don't need to do anything.
2225 if (!Pattern->hasInClassInitializer())
2226 return false;
2227
2228 assert(Instantiation->getInClassInitStyle() ==
2229 Pattern->getInClassInitStyle() &&
2230 "pattern and instantiation disagree about init style");
2231
2232 // Error out if we haven't parsed the initializer of the pattern yet because
2233 // we are waiting for the closing brace of the outer class.
2234 Expr *OldInit = Pattern->getInClassInitializer();
2235 if (!OldInit) {
2236 RecordDecl *PatternRD = Pattern->getParent();
2237 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
2238 if (OutermostClass == PatternRD) {
2239 Diag(Pattern->getLocEnd(), diag::err_in_class_initializer_not_yet_parsed)
2240 << PatternRD << Pattern;
2241 } else {
2242 Diag(Pattern->getLocEnd(),
2243 diag::err_in_class_initializer_not_yet_parsed_outer_class)
2244 << PatternRD << OutermostClass << Pattern;
2245 }
2246 Instantiation->setInvalidDecl();
2247 return true;
2248 }
2249
2250 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
2251 if (Inst.isInvalid())
2252 return true;
2253
2254 // Enter the scope of this instantiation. We don't use PushDeclContext because
2255 // we don't have a scope.
2256 ContextRAII SavedContext(*this, Instantiation->getParent());
2257 EnterExpressionEvaluationContext EvalContext(*this,
2258 Sema::PotentiallyEvaluated);
2259
2260 LocalInstantiationScope Scope(*this);
2261
2262 // Instantiate the initializer.
2263 ActOnStartCXXInClassMemberInitializer();
2264 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), /*TypeQuals=*/0);
2265
2266 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
2267 /*CXXDirectInit=*/false);
2268 Expr *Init = NewInit.get();
2269 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
2270 ActOnFinishCXXInClassMemberInitializer(
2271 Instantiation, Init ? Init->getLocStart() : SourceLocation(), Init);
2272
2273 // Exit the scope of this instantiation.
2274 SavedContext.pop();
2275
2276 // Return true if the in-class initializer is still missing.
2277 return !Instantiation->getInClassInitializer();
2278 }
2279
2280 namespace {
2281 /// \brief A partial specialization whose template arguments have matched
2282 /// a given template-id.
2283 struct PartialSpecMatchResult {
2284 ClassTemplatePartialSpecializationDecl *Partial;
2285 TemplateArgumentList *Args;
2286 };
2287 }
2288
InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,ClassTemplateSpecializationDecl * ClassTemplateSpec,TemplateSpecializationKind TSK,bool Complain)2289 bool Sema::InstantiateClassTemplateSpecialization(
2290 SourceLocation PointOfInstantiation,
2291 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2292 TemplateSpecializationKind TSK, bool Complain) {
2293 // Perform the actual instantiation on the canonical declaration.
2294 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
2295 ClassTemplateSpec->getCanonicalDecl());
2296
2297 // Check whether we have already instantiated or specialized this class
2298 // template specialization.
2299 if (ClassTemplateSpec->getSpecializationKind() != TSK_Undeclared) {
2300 if (ClassTemplateSpec->getSpecializationKind() ==
2301 TSK_ExplicitInstantiationDeclaration &&
2302 TSK == TSK_ExplicitInstantiationDefinition) {
2303 // An explicit instantiation definition follows an explicit instantiation
2304 // declaration (C++0x [temp.explicit]p10); go ahead and perform the
2305 // explicit instantiation.
2306 ClassTemplateSpec->setSpecializationKind(TSK);
2307
2308 // If this is an explicit instantiation definition, mark the
2309 // vtable as used.
2310 if (TSK == TSK_ExplicitInstantiationDefinition &&
2311 !ClassTemplateSpec->isInvalidDecl())
2312 MarkVTableUsed(PointOfInstantiation, ClassTemplateSpec, true);
2313
2314 return false;
2315 }
2316
2317 // We can only instantiate something that hasn't already been
2318 // instantiated or specialized. Fail without any diagnostics: our
2319 // caller will provide an error message.
2320 return true;
2321 }
2322
2323 if (ClassTemplateSpec->isInvalidDecl())
2324 return true;
2325
2326 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
2327 CXXRecordDecl *Pattern = nullptr;
2328
2329 // C++ [temp.class.spec.match]p1:
2330 // When a class template is used in a context that requires an
2331 // instantiation of the class, it is necessary to determine
2332 // whether the instantiation is to be generated using the primary
2333 // template or one of the partial specializations. This is done by
2334 // matching the template arguments of the class template
2335 // specialization with the template argument lists of the partial
2336 // specializations.
2337 typedef PartialSpecMatchResult MatchResult;
2338 SmallVector<MatchResult, 4> Matched;
2339 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
2340 Template->getPartialSpecializations(PartialSpecs);
2341 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
2342 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
2343 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
2344 TemplateDeductionInfo Info(FailedCandidates.getLocation());
2345 if (TemplateDeductionResult Result
2346 = DeduceTemplateArguments(Partial,
2347 ClassTemplateSpec->getTemplateArgs(),
2348 Info)) {
2349 // Store the failed-deduction information for use in diagnostics, later.
2350 // TODO: Actually use the failed-deduction info?
2351 FailedCandidates.addCandidate()
2352 .set(Partial, MakeDeductionFailureInfo(Context, Result, Info));
2353 (void)Result;
2354 } else {
2355 Matched.push_back(PartialSpecMatchResult());
2356 Matched.back().Partial = Partial;
2357 Matched.back().Args = Info.take();
2358 }
2359 }
2360
2361 // If we're dealing with a member template where the template parameters
2362 // have been instantiated, this provides the original template parameters
2363 // from which the member template's parameters were instantiated.
2364
2365 if (Matched.size() >= 1) {
2366 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
2367 if (Matched.size() == 1) {
2368 // -- If exactly one matching specialization is found, the
2369 // instantiation is generated from that specialization.
2370 // We don't need to do anything for this.
2371 } else {
2372 // -- If more than one matching specialization is found, the
2373 // partial order rules (14.5.4.2) are used to determine
2374 // whether one of the specializations is more specialized
2375 // than the others. If none of the specializations is more
2376 // specialized than all of the other matching
2377 // specializations, then the use of the class template is
2378 // ambiguous and the program is ill-formed.
2379 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
2380 PEnd = Matched.end();
2381 P != PEnd; ++P) {
2382 if (getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2383 PointOfInstantiation)
2384 == P->Partial)
2385 Best = P;
2386 }
2387
2388 // Determine if the best partial specialization is more specialized than
2389 // the others.
2390 bool Ambiguous = false;
2391 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2392 PEnd = Matched.end();
2393 P != PEnd; ++P) {
2394 if (P != Best &&
2395 getMoreSpecializedPartialSpecialization(P->Partial, Best->Partial,
2396 PointOfInstantiation)
2397 != Best->Partial) {
2398 Ambiguous = true;
2399 break;
2400 }
2401 }
2402
2403 if (Ambiguous) {
2404 // Partial ordering did not produce a clear winner. Complain.
2405 ClassTemplateSpec->setInvalidDecl();
2406 Diag(PointOfInstantiation, diag::err_partial_spec_ordering_ambiguous)
2407 << ClassTemplateSpec;
2408
2409 // Print the matching partial specializations.
2410 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
2411 PEnd = Matched.end();
2412 P != PEnd; ++P)
2413 Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
2414 << getTemplateArgumentBindingsText(
2415 P->Partial->getTemplateParameters(),
2416 *P->Args);
2417
2418 return true;
2419 }
2420 }
2421
2422 // Instantiate using the best class template partial specialization.
2423 ClassTemplatePartialSpecializationDecl *OrigPartialSpec = Best->Partial;
2424 while (OrigPartialSpec->getInstantiatedFromMember()) {
2425 // If we've found an explicit specialization of this class template,
2426 // stop here and use that as the pattern.
2427 if (OrigPartialSpec->isMemberSpecialization())
2428 break;
2429
2430 OrigPartialSpec = OrigPartialSpec->getInstantiatedFromMember();
2431 }
2432
2433 Pattern = OrigPartialSpec;
2434 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
2435 } else {
2436 // -- If no matches are found, the instantiation is generated
2437 // from the primary template.
2438 ClassTemplateDecl *OrigTemplate = Template;
2439 while (OrigTemplate->getInstantiatedFromMemberTemplate()) {
2440 // If we've found an explicit specialization of this class template,
2441 // stop here and use that as the pattern.
2442 if (OrigTemplate->isMemberSpecialization())
2443 break;
2444
2445 OrigTemplate = OrigTemplate->getInstantiatedFromMemberTemplate();
2446 }
2447
2448 Pattern = OrigTemplate->getTemplatedDecl();
2449 }
2450
2451 bool Result = InstantiateClass(PointOfInstantiation, ClassTemplateSpec,
2452 Pattern,
2453 getTemplateInstantiationArgs(ClassTemplateSpec),
2454 TSK,
2455 Complain);
2456
2457 return Result;
2458 }
2459
2460 /// \brief Instantiates the definitions of all of the member
2461 /// of the given class, which is an instantiation of a class template
2462 /// or a member class of a template.
2463 void
InstantiateClassMembers(SourceLocation PointOfInstantiation,CXXRecordDecl * Instantiation,const MultiLevelTemplateArgumentList & TemplateArgs,TemplateSpecializationKind TSK)2464 Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
2465 CXXRecordDecl *Instantiation,
2466 const MultiLevelTemplateArgumentList &TemplateArgs,
2467 TemplateSpecializationKind TSK) {
2468 // FIXME: We need to notify the ASTMutationListener that we did all of these
2469 // things, in case we have an explicit instantiation definition in a PCM, a
2470 // module, or preamble, and the declaration is in an imported AST.
2471 assert(
2472 (TSK == TSK_ExplicitInstantiationDefinition ||
2473 TSK == TSK_ExplicitInstantiationDeclaration ||
2474 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
2475 "Unexpected template specialization kind!");
2476 for (auto *D : Instantiation->decls()) {
2477 bool SuppressNew = false;
2478 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
2479 if (FunctionDecl *Pattern
2480 = Function->getInstantiatedFromMemberFunction()) {
2481 MemberSpecializationInfo *MSInfo
2482 = Function->getMemberSpecializationInfo();
2483 assert(MSInfo && "No member specialization information?");
2484 if (MSInfo->getTemplateSpecializationKind()
2485 == TSK_ExplicitSpecialization)
2486 continue;
2487
2488 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2489 Function,
2490 MSInfo->getTemplateSpecializationKind(),
2491 MSInfo->getPointOfInstantiation(),
2492 SuppressNew) ||
2493 SuppressNew)
2494 continue;
2495
2496 // C++11 [temp.explicit]p8:
2497 // An explicit instantiation definition that names a class template
2498 // specialization explicitly instantiates the class template
2499 // specialization and is only an explicit instantiation definition
2500 // of members whose definition is visible at the point of
2501 // instantiation.
2502 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
2503 continue;
2504
2505 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2506
2507 if (Function->isDefined()) {
2508 // Let the ASTConsumer know that this function has been explicitly
2509 // instantiated now, and its linkage might have changed.
2510 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
2511 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
2512 InstantiateFunctionDefinition(PointOfInstantiation, Function);
2513 } else if (TSK == TSK_ImplicitInstantiation) {
2514 PendingLocalImplicitInstantiations.push_back(
2515 std::make_pair(Function, PointOfInstantiation));
2516 }
2517 }
2518 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
2519 if (isa<VarTemplateSpecializationDecl>(Var))
2520 continue;
2521
2522 if (Var->isStaticDataMember()) {
2523 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
2524 assert(MSInfo && "No member specialization information?");
2525 if (MSInfo->getTemplateSpecializationKind()
2526 == TSK_ExplicitSpecialization)
2527 continue;
2528
2529 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2530 Var,
2531 MSInfo->getTemplateSpecializationKind(),
2532 MSInfo->getPointOfInstantiation(),
2533 SuppressNew) ||
2534 SuppressNew)
2535 continue;
2536
2537 if (TSK == TSK_ExplicitInstantiationDefinition) {
2538 // C++0x [temp.explicit]p8:
2539 // An explicit instantiation definition that names a class template
2540 // specialization explicitly instantiates the class template
2541 // specialization and is only an explicit instantiation definition
2542 // of members whose definition is visible at the point of
2543 // instantiation.
2544 if (!Var->getInstantiatedFromStaticDataMember()
2545 ->getOutOfLineDefinition())
2546 continue;
2547
2548 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2549 InstantiateStaticDataMemberDefinition(PointOfInstantiation, Var);
2550 } else {
2551 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
2552 }
2553 }
2554 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
2555 // Always skip the injected-class-name, along with any
2556 // redeclarations of nested classes, since both would cause us
2557 // to try to instantiate the members of a class twice.
2558 // Skip closure types; they'll get instantiated when we instantiate
2559 // the corresponding lambda-expression.
2560 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
2561 Record->isLambda())
2562 continue;
2563
2564 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
2565 assert(MSInfo && "No member specialization information?");
2566
2567 if (MSInfo->getTemplateSpecializationKind()
2568 == TSK_ExplicitSpecialization)
2569 continue;
2570
2571 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
2572 Record,
2573 MSInfo->getTemplateSpecializationKind(),
2574 MSInfo->getPointOfInstantiation(),
2575 SuppressNew) ||
2576 SuppressNew)
2577 continue;
2578
2579 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
2580 assert(Pattern && "Missing instantiated-from-template information");
2581
2582 if (!Record->getDefinition()) {
2583 if (!Pattern->getDefinition()) {
2584 // C++0x [temp.explicit]p8:
2585 // An explicit instantiation definition that names a class template
2586 // specialization explicitly instantiates the class template
2587 // specialization and is only an explicit instantiation definition
2588 // of members whose definition is visible at the point of
2589 // instantiation.
2590 if (TSK == TSK_ExplicitInstantiationDeclaration) {
2591 MSInfo->setTemplateSpecializationKind(TSK);
2592 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2593 }
2594
2595 continue;
2596 }
2597
2598 InstantiateClass(PointOfInstantiation, Record, Pattern,
2599 TemplateArgs,
2600 TSK);
2601 } else {
2602 if (TSK == TSK_ExplicitInstantiationDefinition &&
2603 Record->getTemplateSpecializationKind() ==
2604 TSK_ExplicitInstantiationDeclaration) {
2605 Record->setTemplateSpecializationKind(TSK);
2606 MarkVTableUsed(PointOfInstantiation, Record, true);
2607 }
2608 }
2609
2610 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
2611 if (Pattern)
2612 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
2613 TSK);
2614 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
2615 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
2616 assert(MSInfo && "No member specialization information?");
2617
2618 if (MSInfo->getTemplateSpecializationKind()
2619 == TSK_ExplicitSpecialization)
2620 continue;
2621
2622 if (CheckSpecializationInstantiationRedecl(
2623 PointOfInstantiation, TSK, Enum,
2624 MSInfo->getTemplateSpecializationKind(),
2625 MSInfo->getPointOfInstantiation(), SuppressNew) ||
2626 SuppressNew)
2627 continue;
2628
2629 if (Enum->getDefinition())
2630 continue;
2631
2632 EnumDecl *Pattern = Enum->getInstantiatedFromMemberEnum();
2633 assert(Pattern && "Missing instantiated-from-template information");
2634
2635 if (TSK == TSK_ExplicitInstantiationDefinition) {
2636 if (!Pattern->getDefinition())
2637 continue;
2638
2639 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
2640 } else {
2641 MSInfo->setTemplateSpecializationKind(TSK);
2642 MSInfo->setPointOfInstantiation(PointOfInstantiation);
2643 }
2644 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
2645 // No need to instantiate in-class initializers during explicit
2646 // instantiation.
2647 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
2648 CXXRecordDecl *ClassPattern =
2649 Instantiation->getTemplateInstantiationPattern();
2650 DeclContext::lookup_result Lookup =
2651 ClassPattern->lookup(Field->getDeclName());
2652 assert(Lookup.size() == 1);
2653 FieldDecl *Pattern = cast<FieldDecl>(Lookup[0]);
2654 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
2655 TemplateArgs);
2656 }
2657 }
2658 }
2659 }
2660
2661 /// \brief Instantiate the definitions of all of the members of the
2662 /// given class template specialization, which was named as part of an
2663 /// explicit instantiation.
2664 void
InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation,ClassTemplateSpecializationDecl * ClassTemplateSpec,TemplateSpecializationKind TSK)2665 Sema::InstantiateClassTemplateSpecializationMembers(
2666 SourceLocation PointOfInstantiation,
2667 ClassTemplateSpecializationDecl *ClassTemplateSpec,
2668 TemplateSpecializationKind TSK) {
2669 // C++0x [temp.explicit]p7:
2670 // An explicit instantiation that names a class template
2671 // specialization is an explicit instantion of the same kind
2672 // (declaration or definition) of each of its members (not
2673 // including members inherited from base classes) that has not
2674 // been previously explicitly specialized in the translation unit
2675 // containing the explicit instantiation, except as described
2676 // below.
2677 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
2678 getTemplateInstantiationArgs(ClassTemplateSpec),
2679 TSK);
2680 }
2681
2682 StmtResult
SubstStmt(Stmt * S,const MultiLevelTemplateArgumentList & TemplateArgs)2683 Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
2684 if (!S)
2685 return S;
2686
2687 TemplateInstantiator Instantiator(*this, TemplateArgs,
2688 SourceLocation(),
2689 DeclarationName());
2690 return Instantiator.TransformStmt(S);
2691 }
2692
2693 ExprResult
SubstExpr(Expr * E,const MultiLevelTemplateArgumentList & TemplateArgs)2694 Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
2695 if (!E)
2696 return E;
2697
2698 TemplateInstantiator Instantiator(*this, TemplateArgs,
2699 SourceLocation(),
2700 DeclarationName());
2701 return Instantiator.TransformExpr(E);
2702 }
2703
SubstInitializer(Expr * Init,const MultiLevelTemplateArgumentList & TemplateArgs,bool CXXDirectInit)2704 ExprResult Sema::SubstInitializer(Expr *Init,
2705 const MultiLevelTemplateArgumentList &TemplateArgs,
2706 bool CXXDirectInit) {
2707 TemplateInstantiator Instantiator(*this, TemplateArgs,
2708 SourceLocation(),
2709 DeclarationName());
2710 return Instantiator.TransformInitializer(Init, CXXDirectInit);
2711 }
2712
SubstExprs(Expr ** Exprs,unsigned NumExprs,bool IsCall,const MultiLevelTemplateArgumentList & TemplateArgs,SmallVectorImpl<Expr * > & Outputs)2713 bool Sema::SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall,
2714 const MultiLevelTemplateArgumentList &TemplateArgs,
2715 SmallVectorImpl<Expr *> &Outputs) {
2716 if (NumExprs == 0)
2717 return false;
2718
2719 TemplateInstantiator Instantiator(*this, TemplateArgs,
2720 SourceLocation(),
2721 DeclarationName());
2722 return Instantiator.TransformExprs(Exprs, NumExprs, IsCall, Outputs);
2723 }
2724
2725 NestedNameSpecifierLoc
SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,const MultiLevelTemplateArgumentList & TemplateArgs)2726 Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
2727 const MultiLevelTemplateArgumentList &TemplateArgs) {
2728 if (!NNS)
2729 return NestedNameSpecifierLoc();
2730
2731 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
2732 DeclarationName());
2733 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
2734 }
2735
2736 /// \brief Do template substitution on declaration name info.
2737 DeclarationNameInfo
SubstDeclarationNameInfo(const DeclarationNameInfo & NameInfo,const MultiLevelTemplateArgumentList & TemplateArgs)2738 Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
2739 const MultiLevelTemplateArgumentList &TemplateArgs) {
2740 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
2741 NameInfo.getName());
2742 return Instantiator.TransformDeclarationNameInfo(NameInfo);
2743 }
2744
2745 TemplateName
SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,TemplateName Name,SourceLocation Loc,const MultiLevelTemplateArgumentList & TemplateArgs)2746 Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
2747 TemplateName Name, SourceLocation Loc,
2748 const MultiLevelTemplateArgumentList &TemplateArgs) {
2749 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2750 DeclarationName());
2751 CXXScopeSpec SS;
2752 SS.Adopt(QualifierLoc);
2753 return Instantiator.TransformTemplateName(SS, Name, Loc);
2754 }
2755
Subst(const TemplateArgumentLoc * Args,unsigned NumArgs,TemplateArgumentListInfo & Result,const MultiLevelTemplateArgumentList & TemplateArgs)2756 bool Sema::Subst(const TemplateArgumentLoc *Args, unsigned NumArgs,
2757 TemplateArgumentListInfo &Result,
2758 const MultiLevelTemplateArgumentList &TemplateArgs) {
2759 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
2760 DeclarationName());
2761
2762 return Instantiator.TransformTemplateArguments(Args, NumArgs, Result);
2763 }
2764
getCanonicalParmVarDecl(const Decl * D)2765 static const Decl *getCanonicalParmVarDecl(const Decl *D) {
2766 // When storing ParmVarDecls in the local instantiation scope, we always
2767 // want to use the ParmVarDecl from the canonical function declaration,
2768 // since the map is then valid for any redeclaration or definition of that
2769 // function.
2770 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
2771 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
2772 unsigned i = PV->getFunctionScopeIndex();
2773 // This parameter might be from a freestanding function type within the
2774 // function and isn't necessarily referring to one of FD's parameters.
2775 if (FD->getParamDecl(i) == PV)
2776 return FD->getCanonicalDecl()->getParamDecl(i);
2777 }
2778 }
2779 return D;
2780 }
2781
2782
2783 llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
findInstantiationOf(const Decl * D)2784 LocalInstantiationScope::findInstantiationOf(const Decl *D) {
2785 D = getCanonicalParmVarDecl(D);
2786 for (LocalInstantiationScope *Current = this; Current;
2787 Current = Current->Outer) {
2788
2789 // Check if we found something within this scope.
2790 const Decl *CheckD = D;
2791 do {
2792 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
2793 if (Found != Current->LocalDecls.end())
2794 return &Found->second;
2795
2796 // If this is a tag declaration, it's possible that we need to look for
2797 // a previous declaration.
2798 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
2799 CheckD = Tag->getPreviousDecl();
2800 else
2801 CheckD = nullptr;
2802 } while (CheckD);
2803
2804 // If we aren't combined with our outer scope, we're done.
2805 if (!Current->CombineWithOuterScope)
2806 break;
2807 }
2808
2809 // If we're performing a partial substitution during template argument
2810 // deduction, we may not have values for template parameters yet.
2811 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
2812 isa<TemplateTemplateParmDecl>(D))
2813 return nullptr;
2814
2815 // If we didn't find the decl, then we either have a sema bug, or we have a
2816 // forward reference to a label declaration. Return null to indicate that
2817 // we have an uninstantiated label.
2818 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
2819 return nullptr;
2820 }
2821
InstantiatedLocal(const Decl * D,Decl * Inst)2822 void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
2823 D = getCanonicalParmVarDecl(D);
2824 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2825 if (Stored.isNull()) {
2826 #ifndef NDEBUG
2827 // It should not be present in any surrounding scope either.
2828 LocalInstantiationScope *Current = this;
2829 while (Current->CombineWithOuterScope && Current->Outer) {
2830 Current = Current->Outer;
2831 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2832 "Instantiated local in inner and outer scopes");
2833 }
2834 #endif
2835 Stored = Inst;
2836 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
2837 Pack->push_back(Inst);
2838 } else {
2839 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
2840 }
2841 }
2842
InstantiatedLocalPackArg(const Decl * D,Decl * Inst)2843 void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
2844 Decl *Inst) {
2845 D = getCanonicalParmVarDecl(D);
2846 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
2847 Pack->push_back(Inst);
2848 }
2849
MakeInstantiatedLocalArgPack(const Decl * D)2850 void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
2851 #ifndef NDEBUG
2852 // This should be the first time we've been told about this decl.
2853 for (LocalInstantiationScope *Current = this;
2854 Current && Current->CombineWithOuterScope; Current = Current->Outer)
2855 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
2856 "Creating local pack after instantiation of local");
2857 #endif
2858
2859 D = getCanonicalParmVarDecl(D);
2860 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
2861 DeclArgumentPack *Pack = new DeclArgumentPack;
2862 Stored = Pack;
2863 ArgumentPacks.push_back(Pack);
2864 }
2865
SetPartiallySubstitutedPack(NamedDecl * Pack,const TemplateArgument * ExplicitArgs,unsigned NumExplicitArgs)2866 void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
2867 const TemplateArgument *ExplicitArgs,
2868 unsigned NumExplicitArgs) {
2869 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
2870 "Already have a partially-substituted pack");
2871 assert((!PartiallySubstitutedPack
2872 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
2873 "Wrong number of arguments in partially-substituted pack");
2874 PartiallySubstitutedPack = Pack;
2875 ArgsInPartiallySubstitutedPack = ExplicitArgs;
2876 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
2877 }
2878
getPartiallySubstitutedPack(const TemplateArgument ** ExplicitArgs,unsigned * NumExplicitArgs) const2879 NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
2880 const TemplateArgument **ExplicitArgs,
2881 unsigned *NumExplicitArgs) const {
2882 if (ExplicitArgs)
2883 *ExplicitArgs = nullptr;
2884 if (NumExplicitArgs)
2885 *NumExplicitArgs = 0;
2886
2887 for (const LocalInstantiationScope *Current = this; Current;
2888 Current = Current->Outer) {
2889 if (Current->PartiallySubstitutedPack) {
2890 if (ExplicitArgs)
2891 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
2892 if (NumExplicitArgs)
2893 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
2894
2895 return Current->PartiallySubstitutedPack;
2896 }
2897
2898 if (!Current->CombineWithOuterScope)
2899 break;
2900 }
2901
2902 return nullptr;
2903 }
2904