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