1 | //===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/ |
---|---|
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | //===----------------------------------------------------------------------===/ |
7 | // |
8 | // This file implements C++ template instantiation. |
9 | // |
10 | //===----------------------------------------------------------------------===/ |
11 | |
12 | #include "TreeTransform.h" |
13 | #include "clang/AST/ASTConcept.h" |
14 | #include "clang/AST/ASTConsumer.h" |
15 | #include "clang/AST/ASTContext.h" |
16 | #include "clang/AST/ASTLambda.h" |
17 | #include "clang/AST/ASTMutationListener.h" |
18 | #include "clang/AST/DeclBase.h" |
19 | #include "clang/AST/DeclTemplate.h" |
20 | #include "clang/AST/DynamicRecursiveASTVisitor.h" |
21 | #include "clang/AST/Expr.h" |
22 | #include "clang/AST/ExprConcepts.h" |
23 | #include "clang/AST/PrettyDeclStackTrace.h" |
24 | #include "clang/AST/Type.h" |
25 | #include "clang/AST/TypeLoc.h" |
26 | #include "clang/AST/TypeVisitor.h" |
27 | #include "clang/Basic/LangOptions.h" |
28 | #include "clang/Basic/TargetInfo.h" |
29 | #include "clang/Sema/DeclSpec.h" |
30 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
31 | #include "clang/Sema/Initialization.h" |
32 | #include "clang/Sema/Sema.h" |
33 | #include "clang/Sema/SemaConcept.h" |
34 | #include "clang/Sema/SemaInternal.h" |
35 | #include "clang/Sema/Template.h" |
36 | #include "clang/Sema/TemplateDeduction.h" |
37 | #include "clang/Sema/TemplateInstCallback.h" |
38 | #include "llvm/ADT/StringExtras.h" |
39 | #include "llvm/Support/ErrorHandling.h" |
40 | #include "llvm/Support/SaveAndRestore.h" |
41 | #include "llvm/Support/TimeProfiler.h" |
42 | #include <optional> |
43 | |
44 | using namespace clang; |
45 | using namespace sema; |
46 | |
47 | //===----------------------------------------------------------------------===/ |
48 | // Template Instantiation Support |
49 | //===----------------------------------------------------------------------===/ |
50 | |
51 | namespace { |
52 | namespace TemplateInstArgsHelpers { |
53 | struct Response { |
54 | const Decl *NextDecl = nullptr; |
55 | bool IsDone = false; |
56 | bool ClearRelativeToPrimary = true; |
57 | static Response Done() { |
58 | Response R; |
59 | R.IsDone = true; |
60 | return R; |
61 | } |
62 | static Response ChangeDecl(const Decl *ND) { |
63 | Response R; |
64 | R.NextDecl = ND; |
65 | return R; |
66 | } |
67 | static Response ChangeDecl(const DeclContext *Ctx) { |
68 | Response R; |
69 | R.NextDecl = Decl::castFromDeclContext(Ctx); |
70 | return R; |
71 | } |
72 | |
73 | static Response UseNextDecl(const Decl *CurDecl) { |
74 | return ChangeDecl(Ctx: CurDecl->getDeclContext()); |
75 | } |
76 | |
77 | static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) { |
78 | Response R = Response::UseNextDecl(CurDecl); |
79 | R.ClearRelativeToPrimary = false; |
80 | return R; |
81 | } |
82 | }; |
83 | |
84 | // Retrieve the primary template for a lambda call operator. It's |
85 | // unfortunate that we only have the mappings of call operators rather |
86 | // than lambda classes. |
87 | const FunctionDecl * |
88 | getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) { |
89 | if (!isLambdaCallOperator(LambdaCallOperator)) |
90 | return LambdaCallOperator; |
91 | while (true) { |
92 | if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>( |
93 | LambdaCallOperator->getDescribedTemplate()); |
94 | FTD && FTD->getInstantiatedFromMemberTemplate()) { |
95 | LambdaCallOperator = |
96 | FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl(); |
97 | } else if (LambdaCallOperator->getPrimaryTemplate()) { |
98 | // Cases where the lambda operator is instantiated in |
99 | // TemplateDeclInstantiator::VisitCXXMethodDecl. |
100 | LambdaCallOperator = |
101 | LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl(); |
102 | } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator) |
103 | ->getInstantiatedFromMemberFunction()) |
104 | LambdaCallOperator = Prev; |
105 | else |
106 | break; |
107 | } |
108 | return LambdaCallOperator; |
109 | } |
110 | |
111 | struct EnclosingTypeAliasTemplateDetails { |
112 | TypeAliasTemplateDecl *Template = nullptr; |
113 | TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr; |
114 | ArrayRef<TemplateArgument> AssociatedTemplateArguments; |
115 | |
116 | explicit operator bool() noexcept { return Template; } |
117 | }; |
118 | |
119 | // Find the enclosing type alias template Decl from CodeSynthesisContexts, as |
120 | // well as its primary template and instantiating template arguments. |
121 | EnclosingTypeAliasTemplateDetails |
122 | getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) { |
123 | for (auto &CSC : llvm::reverse(C&: SemaRef.CodeSynthesisContexts)) { |
124 | if (CSC.Kind != Sema::CodeSynthesisContext::SynthesisKind:: |
125 | TypeAliasTemplateInstantiation) |
126 | continue; |
127 | EnclosingTypeAliasTemplateDetails Result; |
128 | auto *TATD = cast<TypeAliasTemplateDecl>(Val: CSC.Entity), |
129 | *Next = TATD->getInstantiatedFromMemberTemplate(); |
130 | Result = { |
131 | /*Template=*/TATD, |
132 | /*PrimaryTypeAliasDecl=*/TATD, |
133 | /*AssociatedTemplateArguments=*/CSC.template_arguments(), |
134 | }; |
135 | while (Next) { |
136 | Result.PrimaryTypeAliasDecl = Next; |
137 | Next = Next->getInstantiatedFromMemberTemplate(); |
138 | } |
139 | return Result; |
140 | } |
141 | return {}; |
142 | } |
143 | |
144 | // Check if we are currently inside of a lambda expression that is |
145 | // surrounded by a using alias declaration. e.g. |
146 | // template <class> using type = decltype([](auto) { ^ }()); |
147 | // We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never |
148 | // a DeclContext, nor does it have an associated specialization Decl from which |
149 | // we could collect these template arguments. |
150 | bool isLambdaEnclosedByTypeAliasDecl( |
151 | const FunctionDecl *LambdaCallOperator, |
152 | const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) { |
153 | struct Visitor : DynamicRecursiveASTVisitor { |
154 | Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {} |
155 | bool VisitLambdaExpr(LambdaExpr *LE) override { |
156 | // Return true to bail out of the traversal, implying the Decl contains |
157 | // the lambda. |
158 | return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) != |
159 | CallOperator; |
160 | } |
161 | const FunctionDecl *CallOperator; |
162 | }; |
163 | |
164 | QualType Underlying = |
165 | PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType(); |
166 | |
167 | return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator)) |
168 | .TraverseType(Underlying); |
169 | } |
170 | |
171 | // Add template arguments from a variable template instantiation. |
172 | Response |
173 | HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec, |
174 | MultiLevelTemplateArgumentList &Result, |
175 | bool SkipForSpecialization) { |
176 | // For a class-scope explicit specialization, there are no template arguments |
177 | // at this level, but there may be enclosing template arguments. |
178 | if (VarTemplSpec->isClassScopeExplicitSpecialization()) |
179 | return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec); |
180 | |
181 | // We're done when we hit an explicit specialization. |
182 | if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization && |
183 | !isa<VarTemplatePartialSpecializationDecl>(Val: VarTemplSpec)) |
184 | return Response::Done(); |
185 | |
186 | // If this variable template specialization was instantiated from a |
187 | // specialized member that is a variable template, we're done. |
188 | assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?"); |
189 | llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *> |
190 | Specialized = VarTemplSpec->getSpecializedTemplateOrPartial(); |
191 | if (VarTemplatePartialSpecializationDecl *Partial = |
192 | dyn_cast<VarTemplatePartialSpecializationDecl *>(Val&: Specialized)) { |
193 | if (!SkipForSpecialization) |
194 | Result.addOuterTemplateArguments( |
195 | Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(), |
196 | /*Final=*/false); |
197 | if (Partial->isMemberSpecialization()) |
198 | return Response::Done(); |
199 | } else { |
200 | VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Val&: Specialized); |
201 | if (!SkipForSpecialization) |
202 | Result.addOuterTemplateArguments( |
203 | Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(), |
204 | /*Final=*/false); |
205 | if (Tmpl->isMemberSpecialization()) |
206 | return Response::Done(); |
207 | } |
208 | return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec); |
209 | } |
210 | |
211 | // If we have a template template parameter with translation unit context, |
212 | // then we're performing substitution into a default template argument of |
213 | // this template template parameter before we've constructed the template |
214 | // that will own this template template parameter. In this case, we |
215 | // use empty template parameter lists for all of the outer templates |
216 | // to avoid performing any substitutions. |
217 | Response |
218 | HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP, |
219 | MultiLevelTemplateArgumentList &Result) { |
220 | for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I) |
221 | Result.addOuterTemplateArguments(std::nullopt); |
222 | return Response::Done(); |
223 | } |
224 | |
225 | Response HandlePartialClassTemplateSpec( |
226 | const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec, |
227 | MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) { |
228 | if (!SkipForSpecialization) |
229 | Result.addOuterRetainedLevels(Num: PartialClassTemplSpec->getTemplateDepth()); |
230 | return Response::Done(); |
231 | } |
232 | |
233 | // Add template arguments from a class template instantiation. |
234 | Response |
235 | HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec, |
236 | MultiLevelTemplateArgumentList &Result, |
237 | bool SkipForSpecialization) { |
238 | if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) { |
239 | // We're done when we hit an explicit specialization. |
240 | if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization && |
241 | !isa<ClassTemplatePartialSpecializationDecl>(Val: ClassTemplSpec)) |
242 | return Response::Done(); |
243 | |
244 | if (!SkipForSpecialization) |
245 | Result.addOuterTemplateArguments( |
246 | const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec), |
247 | ClassTemplSpec->getTemplateInstantiationArgs().asArray(), |
248 | /*Final=*/false); |
249 | |
250 | // If this class template specialization was instantiated from a |
251 | // specialized member that is a class template, we're done. |
252 | assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?"); |
253 | if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization()) |
254 | return Response::Done(); |
255 | |
256 | // If this was instantiated from a partial template specialization, we need |
257 | // to get the next level of declaration context from the partial |
258 | // specialization, as the ClassTemplateSpecializationDecl's |
259 | // DeclContext/LexicalDeclContext will be for the primary template. |
260 | if (auto *InstFromPartialTempl = |
261 | ClassTemplSpec->getSpecializedTemplateOrPartial() |
262 | .dyn_cast<ClassTemplatePartialSpecializationDecl *>()) |
263 | return Response::ChangeDecl( |
264 | InstFromPartialTempl->getLexicalDeclContext()); |
265 | } |
266 | return Response::UseNextDecl(ClassTemplSpec); |
267 | } |
268 | |
269 | Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function, |
270 | MultiLevelTemplateArgumentList &Result, |
271 | const FunctionDecl *Pattern, bool RelativeToPrimary, |
272 | bool ForConstraintInstantiation, |
273 | bool ForDefaultArgumentSubstitution) { |
274 | // Add template arguments from a function template specialization. |
275 | if (!RelativeToPrimary && |
276 | Function->getTemplateSpecializationKindForInstantiation() == |
277 | TSK_ExplicitSpecialization) |
278 | return Response::Done(); |
279 | |
280 | if (!RelativeToPrimary && |
281 | Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) { |
282 | // This is an implicit instantiation of an explicit specialization. We |
283 | // don't get any template arguments from this function but might get |
284 | // some from an enclosing template. |
285 | return Response::UseNextDecl(Function); |
286 | } else if (const TemplateArgumentList *TemplateArgs = |
287 | Function->getTemplateSpecializationArgs()) { |
288 | // Add the template arguments for this specialization. |
289 | Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function), |
290 | TemplateArgs->asArray(), |
291 | /*Final=*/false); |
292 | |
293 | if (RelativeToPrimary && |
294 | (Function->getTemplateSpecializationKind() == |
295 | TSK_ExplicitSpecialization || |
296 | (Function->getFriendObjectKind() && |
297 | !Function->getPrimaryTemplate()->getFriendObjectKind()))) |
298 | return Response::UseNextDecl(Function); |
299 | |
300 | // If this function was instantiated from a specialized member that is |
301 | // a function template, we're done. |
302 | assert(Function->getPrimaryTemplate() && "No function template?"); |
303 | if (!ForDefaultArgumentSubstitution && |
304 | Function->getPrimaryTemplate()->isMemberSpecialization()) |
305 | return Response::Done(); |
306 | |
307 | // If this function is a generic lambda specialization, we are done. |
308 | if (!ForConstraintInstantiation && |
309 | isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function)) |
310 | return Response::Done(); |
311 | |
312 | } else if (Function->getDescribedFunctionTemplate()) { |
313 | assert( |
314 | (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && |
315 | "Outer template not instantiated?"); |
316 | } |
317 | // If this is a friend or local declaration and it declares an entity at |
318 | // namespace scope, take arguments from its lexical parent |
319 | // instead of its semantic parent, unless of course the pattern we're |
320 | // instantiating actually comes from the file's context! |
321 | if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) && |
322 | Function->getNonTransparentDeclContext()->isFileContext() && |
323 | (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) { |
324 | return Response::ChangeDecl(Function->getLexicalDeclContext()); |
325 | } |
326 | |
327 | if (ForConstraintInstantiation && Function->getFriendObjectKind()) |
328 | return Response::ChangeDecl(Function->getLexicalDeclContext()); |
329 | return Response::UseNextDecl(Function); |
330 | } |
331 | |
332 | Response HandleFunctionTemplateDecl(Sema &SemaRef, |
333 | const FunctionTemplateDecl *FTD, |
334 | MultiLevelTemplateArgumentList &Result) { |
335 | if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) { |
336 | Result.addOuterTemplateArguments( |
337 | const_cast<FunctionTemplateDecl *>(FTD), |
338 | const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs( |
339 | SemaRef.Context), |
340 | /*Final=*/false); |
341 | |
342 | NestedNameSpecifier *NNS = FTD->getTemplatedDecl()->getQualifier(); |
343 | |
344 | while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) { |
345 | if (NNS->isInstantiationDependent()) { |
346 | if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) { |
347 | ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments(); |
348 | // Prefer template arguments from the injected-class-type if possible. |
349 | // For example, |
350 | // ```cpp |
351 | // template <class... Pack> struct S { |
352 | // template <class T> void foo(); |
353 | // }; |
354 | // template <class... Pack> template <class T> |
355 | // ^^^^^^^^^^^^^ InjectedTemplateArgs |
356 | // They're of kind TemplateArgument::Pack, not of |
357 | // TemplateArgument::Type. |
358 | // void S<Pack...>::foo() {} |
359 | // ^^^^^^^ |
360 | // TSTy->template_arguments() (which are of PackExpansionType) |
361 | // ``` |
362 | // This meets the contract in |
363 | // TreeTransform::TryExpandParameterPacks that the template arguments |
364 | // for unexpanded parameters should be of a Pack kind. |
365 | if (TSTy->isCurrentInstantiation()) { |
366 | auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl(); |
367 | if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate()) |
368 | Arguments = CTD->getInjectedTemplateArgs(SemaRef.Context); |
369 | else if (auto *Specialization = |
370 | dyn_cast<ClassTemplateSpecializationDecl>(RD)) |
371 | Arguments = |
372 | Specialization->getTemplateInstantiationArgs().asArray(); |
373 | } |
374 | Result.addOuterTemplateArguments( |
375 | TSTy->getTemplateName().getAsTemplateDecl(), Arguments, |
376 | /*Final=*/false); |
377 | } |
378 | } |
379 | |
380 | NNS = NNS->getPrefix(); |
381 | } |
382 | } |
383 | |
384 | return Response::ChangeDecl(FTD->getLexicalDeclContext()); |
385 | } |
386 | |
387 | Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec, |
388 | MultiLevelTemplateArgumentList &Result, |
389 | ASTContext &Context, |
390 | bool ForConstraintInstantiation) { |
391 | if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) { |
392 | assert( |
393 | (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && |
394 | "Outer template not instantiated?"); |
395 | if (ClassTemplate->isMemberSpecialization()) |
396 | return Response::Done(); |
397 | if (ForConstraintInstantiation) |
398 | Result.addOuterTemplateArguments( |
399 | const_cast<CXXRecordDecl *>(Rec), |
400 | ClassTemplate->getInjectedTemplateArgs(SemaRef.Context), |
401 | /*Final=*/false); |
402 | } |
403 | |
404 | if (const MemberSpecializationInfo *MSInfo = |
405 | Rec->getMemberSpecializationInfo()) |
406 | if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) |
407 | return Response::Done(); |
408 | |
409 | bool IsFriend = Rec->getFriendObjectKind() || |
410 | (Rec->getDescribedClassTemplate() && |
411 | Rec->getDescribedClassTemplate()->getFriendObjectKind()); |
412 | if (ForConstraintInstantiation && IsFriend && |
413 | Rec->getNonTransparentDeclContext()->isFileContext()) { |
414 | return Response::ChangeDecl(Rec->getLexicalDeclContext()); |
415 | } |
416 | |
417 | // This is to make sure we pick up the VarTemplateSpecializationDecl or the |
418 | // TypeAliasTemplateDecl that this lambda is defined inside of. |
419 | if (Rec->isLambda()) { |
420 | if (const Decl *LCD = Rec->getLambdaContextDecl()) |
421 | return Response::ChangeDecl(ND: LCD); |
422 | // Retrieve the template arguments for a using alias declaration. |
423 | // This is necessary for constraint checking, since we always keep |
424 | // constraints relative to the primary template. |
425 | if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef); |
426 | ForConstraintInstantiation && TypeAlias) { |
427 | if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(), |
428 | TypeAlias.PrimaryTypeAliasDecl)) { |
429 | Result.addOuterTemplateArguments(TypeAlias.Template, |
430 | TypeAlias.AssociatedTemplateArguments, |
431 | /*Final=*/false); |
432 | // Visit the parent of the current type alias declaration rather than |
433 | // the lambda thereof. |
434 | // E.g., in the following example: |
435 | // struct S { |
436 | // template <class> using T = decltype([]<Concept> {} ()); |
437 | // }; |
438 | // void foo() { |
439 | // S::T var; |
440 | // } |
441 | // The instantiated lambda expression (which we're visiting at 'var') |
442 | // has a function DeclContext 'foo' rather than the Record DeclContext |
443 | // S. This seems to be an oversight to me that we may want to set a |
444 | // Sema Context from the CXXScopeSpec before substituting into T. |
445 | return Response::ChangeDecl(TypeAlias.Template->getDeclContext()); |
446 | } |
447 | } |
448 | } |
449 | |
450 | return Response::UseNextDecl(Rec); |
451 | } |
452 | |
453 | Response HandleImplicitConceptSpecializationDecl( |
454 | const ImplicitConceptSpecializationDecl *CSD, |
455 | MultiLevelTemplateArgumentList &Result) { |
456 | Result.addOuterTemplateArguments( |
457 | const_cast<ImplicitConceptSpecializationDecl *>(CSD), |
458 | CSD->getTemplateArguments(), |
459 | /*Final=*/false); |
460 | return Response::UseNextDecl(CSD); |
461 | } |
462 | |
463 | Response HandleGenericDeclContext(const Decl *CurDecl) { |
464 | return Response::UseNextDecl(CurDecl); |
465 | } |
466 | } // namespace TemplateInstArgsHelpers |
467 | } // namespace |
468 | |
469 | MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs( |
470 | const NamedDecl *ND, const DeclContext *DC, bool Final, |
471 | std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary, |
472 | const FunctionDecl *Pattern, bool ForConstraintInstantiation, |
473 | bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) { |
474 | assert((ND || DC) && "Can't find arguments for a decl if one isn't provided"); |
475 | // Accumulate the set of template argument lists in this structure. |
476 | MultiLevelTemplateArgumentList Result; |
477 | getTemplateInstantiationArgs( |
478 | Result, D: ND, DC, Final, Innermost, RelativeToPrimary, Pattern, |
479 | ForConstraintInstantiation, SkipForSpecialization, |
480 | ForDefaultArgumentSubstitution); |
481 | return Result; |
482 | } |
483 | |
484 | void Sema::getTemplateInstantiationArgs( |
485 | MultiLevelTemplateArgumentList &Result, const NamedDecl *ND, |
486 | const DeclContext *DC, bool Final, |
487 | std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary, |
488 | const FunctionDecl *Pattern, bool ForConstraintInstantiation, |
489 | bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) { |
490 | assert((ND || DC) && "Can't find arguments for a decl if one isn't provided"); |
491 | // Accumulate the set of template argument lists in this structure. |
492 | |
493 | using namespace TemplateInstArgsHelpers; |
494 | const Decl *CurDecl = ND; |
495 | |
496 | if (Innermost) { |
497 | Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost, |
498 | Final); |
499 | // Populate placeholder template arguments for TemplateTemplateParmDecls. |
500 | // This is essential for the case e.g. |
501 | // |
502 | // template <class> concept Concept = false; |
503 | // template <template <Concept C> class T> void foo(T<int>) |
504 | // |
505 | // where parameter C has a depth of 1 but the substituting argument `int` |
506 | // has a depth of 0. |
507 | if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) |
508 | HandleDefaultTempArgIntoTempTempParam(TTP, Result); |
509 | CurDecl = DC ? Decl::castFromDeclContext(DC) |
510 | : Response::UseNextDecl(CurDecl).NextDecl; |
511 | } else if (!CurDecl) |
512 | CurDecl = Decl::castFromDeclContext(DC); |
513 | |
514 | while (!CurDecl->isFileContextDecl()) { |
515 | Response R; |
516 | if (const auto *VarTemplSpec = |
517 | dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) { |
518 | R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization); |
519 | } else if (const auto *PartialClassTemplSpec = |
520 | dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) { |
521 | R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result, |
522 | SkipForSpecialization); |
523 | } else if (const auto *ClassTemplSpec = |
524 | dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) { |
525 | R = HandleClassTemplateSpec(ClassTemplSpec, Result, |
526 | SkipForSpecialization); |
527 | } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) { |
528 | R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary, |
529 | ForConstraintInstantiation, |
530 | ForDefaultArgumentSubstitution); |
531 | } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) { |
532 | R = HandleRecordDecl(*this, Rec, Result, Context, |
533 | ForConstraintInstantiation); |
534 | } else if (const auto *CSD = |
535 | dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) { |
536 | R = HandleImplicitConceptSpecializationDecl(CSD, Result); |
537 | } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) { |
538 | R = HandleFunctionTemplateDecl(*this, FTD, Result); |
539 | } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) { |
540 | R = Response::ChangeDecl(CTD->getLexicalDeclContext()); |
541 | } else if (!isa<DeclContext>(Val: CurDecl)) { |
542 | R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl); |
543 | if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) { |
544 | R = HandleDefaultTempArgIntoTempTempParam(TTP, Result); |
545 | } |
546 | } else { |
547 | R = HandleGenericDeclContext(CurDecl); |
548 | } |
549 | |
550 | if (R.IsDone) |
551 | return; |
552 | if (R.ClearRelativeToPrimary) |
553 | RelativeToPrimary = false; |
554 | assert(R.NextDecl); |
555 | CurDecl = R.NextDecl; |
556 | } |
557 | } |
558 | |
559 | bool Sema::CodeSynthesisContext::isInstantiationRecord() const { |
560 | switch (Kind) { |
561 | case TemplateInstantiation: |
562 | case ExceptionSpecInstantiation: |
563 | case DefaultTemplateArgumentInstantiation: |
564 | case DefaultFunctionArgumentInstantiation: |
565 | case ExplicitTemplateArgumentSubstitution: |
566 | case DeducedTemplateArgumentSubstitution: |
567 | case PriorTemplateArgumentSubstitution: |
568 | case ConstraintsCheck: |
569 | case NestedRequirementConstraintsCheck: |
570 | return true; |
571 | |
572 | case RequirementInstantiation: |
573 | case RequirementParameterInstantiation: |
574 | case DefaultTemplateArgumentChecking: |
575 | case DeclaringSpecialMember: |
576 | case DeclaringImplicitEqualityComparison: |
577 | case DefiningSynthesizedFunction: |
578 | case ExceptionSpecEvaluation: |
579 | case ConstraintSubstitution: |
580 | case ParameterMappingSubstitution: |
581 | case ConstraintNormalization: |
582 | case RewritingOperatorAsSpaceship: |
583 | case InitializingStructuredBinding: |
584 | case MarkingClassDllexported: |
585 | case BuildingBuiltinDumpStructCall: |
586 | case LambdaExpressionSubstitution: |
587 | case BuildingDeductionGuides: |
588 | case TypeAliasTemplateInstantiation: |
589 | case PartialOrderingTTP: |
590 | return false; |
591 | |
592 | // This function should never be called when Kind's value is Memoization. |
593 | case Memoization: |
594 | break; |
595 | } |
596 | |
597 | llvm_unreachable("Invalid SynthesisKind!"); |
598 | } |
599 | |
600 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
601 | Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, |
602 | SourceLocation PointOfInstantiation, SourceRange InstantiationRange, |
603 | Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, |
604 | sema::TemplateDeductionInfo *DeductionInfo) |
605 | : SemaRef(SemaRef) { |
606 | // Don't allow further instantiation if a fatal error and an uncompilable |
607 | // error have occurred. Any diagnostics we might have raised will not be |
608 | // visible, and we do not need to construct a correct AST. |
609 | if (SemaRef.Diags.hasFatalErrorOccurred() && |
610 | SemaRef.hasUncompilableErrorOccurred()) { |
611 | Invalid = true; |
612 | return; |
613 | } |
614 | Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange); |
615 | if (!Invalid) { |
616 | CodeSynthesisContext Inst; |
617 | Inst.Kind = Kind; |
618 | Inst.PointOfInstantiation = PointOfInstantiation; |
619 | Inst.Entity = Entity; |
620 | Inst.Template = Template; |
621 | Inst.TemplateArgs = TemplateArgs.data(); |
622 | Inst.NumTemplateArgs = TemplateArgs.size(); |
623 | Inst.DeductionInfo = DeductionInfo; |
624 | Inst.InstantiationRange = InstantiationRange; |
625 | Inst.InConstraintSubstitution = |
626 | Inst.Kind == CodeSynthesisContext::ConstraintSubstitution; |
627 | if (!SemaRef.CodeSynthesisContexts.empty()) |
628 | Inst.InConstraintSubstitution |= |
629 | SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution; |
630 | |
631 | SemaRef.pushCodeSynthesisContext(Ctx: Inst); |
632 | |
633 | AlreadyInstantiating = !Inst.Entity ? false : |
634 | !SemaRef.InstantiatingSpecializations |
635 | .insert(V: {Inst.Entity->getCanonicalDecl(), Inst.Kind}) |
636 | .second; |
637 | atTemplateBegin(Callbacks&: SemaRef.TemplateInstCallbacks, TheSema: SemaRef, Inst); |
638 | } |
639 | } |
640 | |
641 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
642 | Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, |
643 | SourceRange InstantiationRange) |
644 | : InstantiatingTemplate(SemaRef, |
645 | CodeSynthesisContext::TemplateInstantiation, |
646 | PointOfInstantiation, InstantiationRange, Entity) {} |
647 | |
648 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
649 | Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, |
650 | ExceptionSpecification, SourceRange InstantiationRange) |
651 | : InstantiatingTemplate( |
652 | SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation, |
653 | PointOfInstantiation, InstantiationRange, Entity) {} |
654 | |
655 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
656 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, |
657 | TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, |
658 | SourceRange InstantiationRange) |
659 | : InstantiatingTemplate( |
660 | SemaRef, |
661 | CodeSynthesisContext::DefaultTemplateArgumentInstantiation, |
662 | PointOfInstantiation, InstantiationRange, getAsNamedDecl(P: Param), |
663 | Template, TemplateArgs) {} |
664 | |
665 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
666 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
667 | FunctionTemplateDecl *FunctionTemplate, |
668 | ArrayRef<TemplateArgument> TemplateArgs, |
669 | CodeSynthesisContext::SynthesisKind Kind, |
670 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) |
671 | : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation, |
672 | InstantiationRange, FunctionTemplate, nullptr, |
673 | TemplateArgs, &DeductionInfo) { |
674 | assert(Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || |
675 | Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution || |
676 | Kind == CodeSynthesisContext::BuildingDeductionGuides); |
677 | } |
678 | |
679 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
680 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
681 | TemplateDecl *Template, |
682 | ArrayRef<TemplateArgument> TemplateArgs, |
683 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) |
684 | : InstantiatingTemplate( |
685 | SemaRef, |
686 | CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
687 | PointOfInstantiation, InstantiationRange, Template, nullptr, |
688 | TemplateArgs, &DeductionInfo) {} |
689 | |
690 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
691 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
692 | ClassTemplatePartialSpecializationDecl *PartialSpec, |
693 | ArrayRef<TemplateArgument> TemplateArgs, |
694 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) |
695 | : InstantiatingTemplate( |
696 | SemaRef, |
697 | CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
698 | PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, |
699 | TemplateArgs, &DeductionInfo) {} |
700 | |
701 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
702 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
703 | VarTemplatePartialSpecializationDecl *PartialSpec, |
704 | ArrayRef<TemplateArgument> TemplateArgs, |
705 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) |
706 | : InstantiatingTemplate( |
707 | SemaRef, |
708 | CodeSynthesisContext::DeducedTemplateArgumentSubstitution, |
709 | PointOfInstantiation, InstantiationRange, PartialSpec, nullptr, |
710 | TemplateArgs, &DeductionInfo) {} |
711 | |
712 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
713 | Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, |
714 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
715 | : InstantiatingTemplate( |
716 | SemaRef, |
717 | CodeSynthesisContext::DefaultFunctionArgumentInstantiation, |
718 | PointOfInstantiation, InstantiationRange, Param, nullptr, |
719 | TemplateArgs) {} |
720 | |
721 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
722 | Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, |
723 | NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
724 | SourceRange InstantiationRange) |
725 | : InstantiatingTemplate( |
726 | SemaRef, |
727 | CodeSynthesisContext::PriorTemplateArgumentSubstitution, |
728 | PointOfInstantiation, InstantiationRange, Param, Template, |
729 | TemplateArgs) {} |
730 | |
731 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
732 | Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, |
733 | TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
734 | SourceRange InstantiationRange) |
735 | : InstantiatingTemplate( |
736 | SemaRef, |
737 | CodeSynthesisContext::PriorTemplateArgumentSubstitution, |
738 | PointOfInstantiation, InstantiationRange, Param, Template, |
739 | TemplateArgs) {} |
740 | |
741 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
742 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
743 | TypeAliasTemplateDecl *Entity, ArrayRef<TemplateArgument> TemplateArgs, |
744 | SourceRange InstantiationRange) |
745 | : InstantiatingTemplate( |
746 | SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation, |
747 | PointOfInstantiation, InstantiationRange, /*Entity=*/Entity, |
748 | /*Template=*/nullptr, TemplateArgs) {} |
749 | |
750 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
751 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, |
752 | NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, |
753 | SourceRange InstantiationRange) |
754 | : InstantiatingTemplate( |
755 | SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking, |
756 | PointOfInstantiation, InstantiationRange, Param, Template, |
757 | TemplateArgs) {} |
758 | |
759 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
760 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
761 | concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, |
762 | SourceRange InstantiationRange) |
763 | : InstantiatingTemplate( |
764 | SemaRef, CodeSynthesisContext::RequirementInstantiation, |
765 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
766 | /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {} |
767 | |
768 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
769 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
770 | concepts::NestedRequirement *Req, ConstraintsCheck, |
771 | SourceRange InstantiationRange) |
772 | : InstantiatingTemplate( |
773 | SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck, |
774 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
775 | /*Template=*/nullptr, /*TemplateArgs=*/{}) {} |
776 | |
777 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
778 | Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE, |
779 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) |
780 | : InstantiatingTemplate( |
781 | SemaRef, CodeSynthesisContext::RequirementParameterInstantiation, |
782 | PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr, |
783 | /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {} |
784 | |
785 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
786 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
787 | ConstraintsCheck, NamedDecl *Template, |
788 | ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange) |
789 | : InstantiatingTemplate( |
790 | SemaRef, CodeSynthesisContext::ConstraintsCheck, |
791 | PointOfInstantiation, InstantiationRange, Template, nullptr, |
792 | TemplateArgs) {} |
793 | |
794 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
795 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
796 | ConstraintSubstitution, NamedDecl *Template, |
797 | sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange) |
798 | : InstantiatingTemplate( |
799 | SemaRef, CodeSynthesisContext::ConstraintSubstitution, |
800 | PointOfInstantiation, InstantiationRange, Template, nullptr, |
801 | {}, &DeductionInfo) {} |
802 | |
803 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
804 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
805 | ConstraintNormalization, NamedDecl *Template, |
806 | SourceRange InstantiationRange) |
807 | : InstantiatingTemplate( |
808 | SemaRef, CodeSynthesisContext::ConstraintNormalization, |
809 | PointOfInstantiation, InstantiationRange, Template) {} |
810 | |
811 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
812 | Sema &SemaRef, SourceLocation PointOfInstantiation, |
813 | ParameterMappingSubstitution, NamedDecl *Template, |
814 | SourceRange InstantiationRange) |
815 | : InstantiatingTemplate( |
816 | SemaRef, CodeSynthesisContext::ParameterMappingSubstitution, |
817 | PointOfInstantiation, InstantiationRange, Template) {} |
818 | |
819 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
820 | Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity, |
821 | BuildingDeductionGuidesTag, SourceRange InstantiationRange) |
822 | : InstantiatingTemplate( |
823 | SemaRef, CodeSynthesisContext::BuildingDeductionGuides, |
824 | PointOfInstantiation, InstantiationRange, Entity) {} |
825 | |
826 | Sema::InstantiatingTemplate::InstantiatingTemplate( |
827 | Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP, |
828 | TemplateDecl *PArg, SourceRange InstantiationRange) |
829 | : InstantiatingTemplate(SemaRef, CodeSynthesisContext::PartialOrderingTTP, |
830 | ArgLoc, InstantiationRange, PArg) {} |
831 | |
832 | void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) { |
833 | Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext; |
834 | InNonInstantiationSFINAEContext = false; |
835 | |
836 | CodeSynthesisContexts.push_back(Elt: Ctx); |
837 | |
838 | if (!Ctx.isInstantiationRecord()) |
839 | ++NonInstantiationEntries; |
840 | |
841 | // Check to see if we're low on stack space. We can't do anything about this |
842 | // from here, but we can at least warn the user. |
843 | StackHandler.warnOnStackNearlyExhausted(Loc: Ctx.PointOfInstantiation); |
844 | } |
845 | |
846 | void Sema::popCodeSynthesisContext() { |
847 | auto &Active = CodeSynthesisContexts.back(); |
848 | if (!Active.isInstantiationRecord()) { |
849 | assert(NonInstantiationEntries > 0); |
850 | --NonInstantiationEntries; |
851 | } |
852 | |
853 | InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext; |
854 | |
855 | // Name lookup no longer looks in this template's defining module. |
856 | assert(CodeSynthesisContexts.size() >= |
857 | CodeSynthesisContextLookupModules.size() && |
858 | "forgot to remove a lookup module for a template instantiation"); |
859 | if (CodeSynthesisContexts.size() == |
860 | CodeSynthesisContextLookupModules.size()) { |
861 | if (Module *M = CodeSynthesisContextLookupModules.back()) |
862 | LookupModulesCache.erase(V: M); |
863 | CodeSynthesisContextLookupModules.pop_back(); |
864 | } |
865 | |
866 | // If we've left the code synthesis context for the current context stack, |
867 | // stop remembering that we've emitted that stack. |
868 | if (CodeSynthesisContexts.size() == |
869 | LastEmittedCodeSynthesisContextDepth) |
870 | LastEmittedCodeSynthesisContextDepth = 0; |
871 | |
872 | CodeSynthesisContexts.pop_back(); |
873 | } |
874 | |
875 | void Sema::InstantiatingTemplate::Clear() { |
876 | if (!Invalid) { |
877 | if (!AlreadyInstantiating) { |
878 | auto &Active = SemaRef.CodeSynthesisContexts.back(); |
879 | if (Active.Entity) |
880 | SemaRef.InstantiatingSpecializations.erase( |
881 | V: {Active.Entity->getCanonicalDecl(), Active.Kind}); |
882 | } |
883 | |
884 | atTemplateEnd(Callbacks&: SemaRef.TemplateInstCallbacks, TheSema: SemaRef, |
885 | Inst: SemaRef.CodeSynthesisContexts.back()); |
886 | |
887 | SemaRef.popCodeSynthesisContext(); |
888 | Invalid = true; |
889 | } |
890 | } |
891 | |
892 | static std::string convertCallArgsToString(Sema &S, |
893 | llvm::ArrayRef<const Expr *> Args) { |
894 | std::string Result; |
895 | llvm::raw_string_ostream OS(Result); |
896 | llvm::ListSeparator Comma; |
897 | for (const Expr *Arg : Args) { |
898 | OS << Comma; |
899 | Arg->IgnoreParens()->printPretty(OS, nullptr, |
900 | S.Context.getPrintingPolicy()); |
901 | } |
902 | return Result; |
903 | } |
904 | |
905 | bool Sema::InstantiatingTemplate::CheckInstantiationDepth( |
906 | SourceLocation PointOfInstantiation, |
907 | SourceRange InstantiationRange) { |
908 | assert(SemaRef.NonInstantiationEntries <= |
909 | SemaRef.CodeSynthesisContexts.size()); |
910 | if ((SemaRef.CodeSynthesisContexts.size() - |
911 | SemaRef.NonInstantiationEntries) |
912 | <= SemaRef.getLangOpts().InstantiationDepth) |
913 | return false; |
914 | |
915 | SemaRef.Diag(PointOfInstantiation, |
916 | diag::err_template_recursion_depth_exceeded) |
917 | << SemaRef.getLangOpts().InstantiationDepth |
918 | << InstantiationRange; |
919 | SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth) |
920 | << SemaRef.getLangOpts().InstantiationDepth; |
921 | return true; |
922 | } |
923 | |
924 | void Sema::PrintInstantiationStack(InstantiationContextDiagFuncRef DiagFunc) { |
925 | // Determine which template instantiations to skip, if any. |
926 | unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart; |
927 | unsigned Limit = Diags.getTemplateBacktraceLimit(); |
928 | if (Limit && Limit < CodeSynthesisContexts.size()) { |
929 | SkipStart = Limit / 2 + Limit % 2; |
930 | SkipEnd = CodeSynthesisContexts.size() - Limit / 2; |
931 | } |
932 | |
933 | // FIXME: In all of these cases, we need to show the template arguments |
934 | unsigned InstantiationIdx = 0; |
935 | for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator |
936 | Active = CodeSynthesisContexts.rbegin(), |
937 | ActiveEnd = CodeSynthesisContexts.rend(); |
938 | Active != ActiveEnd; |
939 | ++Active, ++InstantiationIdx) { |
940 | // Skip this instantiation? |
941 | if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) { |
942 | if (InstantiationIdx == SkipStart) { |
943 | // Note that we're skipping instantiations. |
944 | DiagFunc(Active->PointOfInstantiation, |
945 | PDiag(diag::note_instantiation_contexts_suppressed) |
946 | << unsigned(CodeSynthesisContexts.size() - Limit)); |
947 | } |
948 | continue; |
949 | } |
950 | |
951 | switch (Active->Kind) { |
952 | case CodeSynthesisContext::TemplateInstantiation: { |
953 | Decl *D = Active->Entity; |
954 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) { |
955 | unsigned DiagID = diag::note_template_member_class_here; |
956 | if (isa<ClassTemplateSpecializationDecl>(Record)) |
957 | DiagID = diag::note_template_class_instantiation_here; |
958 | DiagFunc(Active->PointOfInstantiation, |
959 | PDiag(DiagID) << Record << Active->InstantiationRange); |
960 | } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: D)) { |
961 | unsigned DiagID; |
962 | if (Function->getPrimaryTemplate()) |
963 | DiagID = diag::note_function_template_spec_here; |
964 | else |
965 | DiagID = diag::note_template_member_function_here; |
966 | DiagFunc(Active->PointOfInstantiation, |
967 | PDiag(DiagID) << Function << Active->InstantiationRange); |
968 | } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) { |
969 | DiagFunc(Active->PointOfInstantiation, |
970 | PDiag(VD->isStaticDataMember() |
971 | ? diag::note_template_static_data_member_def_here |
972 | : diag::note_template_variable_def_here) |
973 | << VD << Active->InstantiationRange); |
974 | } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Val: D)) { |
975 | DiagFunc(Active->PointOfInstantiation, |
976 | PDiag(diag::note_template_enum_def_here) |
977 | << ED << Active->InstantiationRange); |
978 | } else if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: D)) { |
979 | DiagFunc(Active->PointOfInstantiation, |
980 | PDiag(diag::note_template_nsdmi_here) |
981 | << FD << Active->InstantiationRange); |
982 | } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) { |
983 | DiagFunc(Active->PointOfInstantiation, |
984 | PDiag(diag::note_template_class_instantiation_here) |
985 | << CTD << Active->InstantiationRange); |
986 | } |
987 | break; |
988 | } |
989 | |
990 | case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: { |
991 | TemplateDecl *Template = cast<TemplateDecl>(Val: Active->Template); |
992 | SmallString<128> TemplateArgsStr; |
993 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
994 | Template->printName(OS, getPrintingPolicy()); |
995 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
996 | Policy: getPrintingPolicy()); |
997 | DiagFunc(Active->PointOfInstantiation, |
998 | PDiag(diag::note_default_arg_instantiation_here) |
999 | << OS.str() << Active->InstantiationRange); |
1000 | break; |
1001 | } |
1002 | |
1003 | case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: { |
1004 | FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Val: Active->Entity); |
1005 | DiagFunc(Active->PointOfInstantiation, |
1006 | PDiag(diag::note_explicit_template_arg_substitution_here) |
1007 | << FnTmpl |
1008 | << getTemplateArgumentBindingsText( |
1009 | FnTmpl->getTemplateParameters(), Active->TemplateArgs, |
1010 | Active->NumTemplateArgs) |
1011 | << Active->InstantiationRange); |
1012 | break; |
1013 | } |
1014 | |
1015 | case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: { |
1016 | if (FunctionTemplateDecl *FnTmpl = |
1017 | dyn_cast<FunctionTemplateDecl>(Val: Active->Entity)) { |
1018 | DiagFunc( |
1019 | Active->PointOfInstantiation, |
1020 | PDiag(diag::note_function_template_deduction_instantiation_here) |
1021 | << FnTmpl |
1022 | << getTemplateArgumentBindingsText( |
1023 | FnTmpl->getTemplateParameters(), Active->TemplateArgs, |
1024 | Active->NumTemplateArgs) |
1025 | << Active->InstantiationRange); |
1026 | } else { |
1027 | bool IsVar = isa<VarTemplateDecl>(Val: Active->Entity) || |
1028 | isa<VarTemplateSpecializationDecl>(Val: Active->Entity); |
1029 | bool IsTemplate = false; |
1030 | TemplateParameterList *Params; |
1031 | if (auto *D = dyn_cast<TemplateDecl>(Val: Active->Entity)) { |
1032 | IsTemplate = true; |
1033 | Params = D->getTemplateParameters(); |
1034 | } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>( |
1035 | Val: Active->Entity)) { |
1036 | Params = D->getTemplateParameters(); |
1037 | } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>( |
1038 | Val: Active->Entity)) { |
1039 | Params = D->getTemplateParameters(); |
1040 | } else { |
1041 | llvm_unreachable("unexpected template kind"); |
1042 | } |
1043 | |
1044 | DiagFunc(Active->PointOfInstantiation, |
1045 | PDiag(diag::note_deduced_template_arg_substitution_here) |
1046 | << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity) |
1047 | << getTemplateArgumentBindingsText(Params, |
1048 | Active->TemplateArgs, |
1049 | Active->NumTemplateArgs) |
1050 | << Active->InstantiationRange); |
1051 | } |
1052 | break; |
1053 | } |
1054 | |
1055 | case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: { |
1056 | ParmVarDecl *Param = cast<ParmVarDecl>(Val: Active->Entity); |
1057 | FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); |
1058 | |
1059 | SmallString<128> TemplateArgsStr; |
1060 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
1061 | FD->printName(OS, getPrintingPolicy()); |
1062 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
1063 | Policy: getPrintingPolicy()); |
1064 | DiagFunc(Active->PointOfInstantiation, |
1065 | PDiag(diag::note_default_function_arg_instantiation_here) |
1066 | << OS.str() << Active->InstantiationRange); |
1067 | break; |
1068 | } |
1069 | |
1070 | case CodeSynthesisContext::PriorTemplateArgumentSubstitution: { |
1071 | NamedDecl *Parm = cast<NamedDecl>(Val: Active->Entity); |
1072 | std::string Name; |
1073 | if (!Parm->getName().empty()) |
1074 | Name = std::string(" '") + Parm->getName().str() + "'"; |
1075 | |
1076 | TemplateParameterList *TemplateParams = nullptr; |
1077 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template)) |
1078 | TemplateParams = Template->getTemplateParameters(); |
1079 | else |
1080 | TemplateParams = |
1081 | cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template) |
1082 | ->getTemplateParameters(); |
1083 | DiagFunc(Active->PointOfInstantiation, |
1084 | PDiag(diag::note_prior_template_arg_substitution) |
1085 | << isa<TemplateTemplateParmDecl>(Parm) << Name |
1086 | << getTemplateArgumentBindingsText(TemplateParams, |
1087 | Active->TemplateArgs, |
1088 | Active->NumTemplateArgs) |
1089 | << Active->InstantiationRange); |
1090 | break; |
1091 | } |
1092 | |
1093 | case CodeSynthesisContext::DefaultTemplateArgumentChecking: { |
1094 | TemplateParameterList *TemplateParams = nullptr; |
1095 | if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Val: Active->Template)) |
1096 | TemplateParams = Template->getTemplateParameters(); |
1097 | else |
1098 | TemplateParams = |
1099 | cast<ClassTemplatePartialSpecializationDecl>(Val: Active->Template) |
1100 | ->getTemplateParameters(); |
1101 | |
1102 | DiagFunc(Active->PointOfInstantiation, |
1103 | PDiag(diag::note_template_default_arg_checking) |
1104 | << getTemplateArgumentBindingsText(TemplateParams, |
1105 | Active->TemplateArgs, |
1106 | Active->NumTemplateArgs) |
1107 | << Active->InstantiationRange); |
1108 | break; |
1109 | } |
1110 | |
1111 | case CodeSynthesisContext::ExceptionSpecEvaluation: |
1112 | DiagFunc(Active->PointOfInstantiation, |
1113 | PDiag(diag::note_evaluating_exception_spec_here) |
1114 | << cast<FunctionDecl>(Active->Entity)); |
1115 | break; |
1116 | |
1117 | case CodeSynthesisContext::ExceptionSpecInstantiation: |
1118 | DiagFunc(Active->PointOfInstantiation, |
1119 | PDiag(diag::note_template_exception_spec_instantiation_here) |
1120 | << cast<FunctionDecl>(Active->Entity) |
1121 | << Active->InstantiationRange); |
1122 | break; |
1123 | |
1124 | case CodeSynthesisContext::RequirementInstantiation: |
1125 | DiagFunc(Active->PointOfInstantiation, |
1126 | PDiag(diag::note_template_requirement_instantiation_here) |
1127 | << Active->InstantiationRange); |
1128 | break; |
1129 | case CodeSynthesisContext::RequirementParameterInstantiation: |
1130 | DiagFunc(Active->PointOfInstantiation, |
1131 | PDiag(diag::note_template_requirement_params_instantiation_here) |
1132 | << Active->InstantiationRange); |
1133 | break; |
1134 | |
1135 | case CodeSynthesisContext::NestedRequirementConstraintsCheck: |
1136 | DiagFunc(Active->PointOfInstantiation, |
1137 | PDiag(diag::note_nested_requirement_here) |
1138 | << Active->InstantiationRange); |
1139 | break; |
1140 | |
1141 | case CodeSynthesisContext::DeclaringSpecialMember: |
1142 | DiagFunc(Active->PointOfInstantiation, |
1143 | PDiag(diag::note_in_declaration_of_implicit_special_member) |
1144 | << cast<CXXRecordDecl>(Active->Entity) |
1145 | << Active->SpecialMember); |
1146 | break; |
1147 | |
1148 | case CodeSynthesisContext::DeclaringImplicitEqualityComparison: |
1149 | DiagFunc( |
1150 | Active->Entity->getLocation(), |
1151 | PDiag(diag::note_in_declaration_of_implicit_equality_comparison)); |
1152 | break; |
1153 | |
1154 | case CodeSynthesisContext::DefiningSynthesizedFunction: { |
1155 | // FIXME: For synthesized functions that are not defaulted, |
1156 | // produce a note. |
1157 | auto *FD = dyn_cast<FunctionDecl>(Val: Active->Entity); |
1158 | // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind() |
1159 | // will ensure that DFK.isComparison() is false. This is important because |
1160 | // we will uncondtionally dereference FD in the else if. |
1161 | DefaultedFunctionKind DFK = |
1162 | FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind(); |
1163 | if (DFK.isSpecialMember()) { |
1164 | auto *MD = cast<CXXMethodDecl>(Val: FD); |
1165 | DiagFunc(Active->PointOfInstantiation, |
1166 | PDiag(diag::note_member_synthesized_at) |
1167 | << MD->isExplicitlyDefaulted() << DFK.asSpecialMember() |
1168 | << Context.getTagDeclType(MD->getParent())); |
1169 | } else if (DFK.isComparison()) { |
1170 | QualType RecordType = FD->getParamDecl(i: 0) |
1171 | ->getType() |
1172 | .getNonReferenceType() |
1173 | .getUnqualifiedType(); |
1174 | DiagFunc(Active->PointOfInstantiation, |
1175 | PDiag(diag::note_comparison_synthesized_at) |
1176 | << (int)DFK.asComparison() << RecordType); |
1177 | } |
1178 | break; |
1179 | } |
1180 | |
1181 | case CodeSynthesisContext::RewritingOperatorAsSpaceship: |
1182 | DiagFunc(Active->Entity->getLocation(), |
1183 | PDiag(diag::note_rewriting_operator_as_spaceship)); |
1184 | break; |
1185 | |
1186 | case CodeSynthesisContext::InitializingStructuredBinding: |
1187 | DiagFunc(Active->PointOfInstantiation, |
1188 | PDiag(diag::note_in_binding_decl_init) |
1189 | << cast<BindingDecl>(Active->Entity)); |
1190 | break; |
1191 | |
1192 | case CodeSynthesisContext::MarkingClassDllexported: |
1193 | DiagFunc(Active->PointOfInstantiation, |
1194 | PDiag(diag::note_due_to_dllexported_class) |
1195 | << cast<CXXRecordDecl>(Active->Entity) |
1196 | << !getLangOpts().CPlusPlus11); |
1197 | break; |
1198 | |
1199 | case CodeSynthesisContext::BuildingBuiltinDumpStructCall: |
1200 | DiagFunc(Active->PointOfInstantiation, |
1201 | PDiag(diag::note_building_builtin_dump_struct_call) |
1202 | << convertCallArgsToString( |
1203 | *this, llvm::ArrayRef(Active->CallArgs, |
1204 | Active->NumCallArgs))); |
1205 | break; |
1206 | |
1207 | case CodeSynthesisContext::Memoization: |
1208 | break; |
1209 | |
1210 | case CodeSynthesisContext::LambdaExpressionSubstitution: |
1211 | DiagFunc(Active->PointOfInstantiation, |
1212 | PDiag(diag::note_lambda_substitution_here)); |
1213 | break; |
1214 | case CodeSynthesisContext::ConstraintsCheck: { |
1215 | unsigned DiagID = 0; |
1216 | if (!Active->Entity) { |
1217 | DiagFunc(Active->PointOfInstantiation, |
1218 | PDiag(diag::note_nested_requirement_here) |
1219 | << Active->InstantiationRange); |
1220 | break; |
1221 | } |
1222 | if (isa<ConceptDecl>(Val: Active->Entity)) |
1223 | DiagID = diag::note_concept_specialization_here; |
1224 | else if (isa<TemplateDecl>(Val: Active->Entity)) |
1225 | DiagID = diag::note_checking_constraints_for_template_id_here; |
1226 | else if (isa<VarTemplatePartialSpecializationDecl>(Val: Active->Entity)) |
1227 | DiagID = diag::note_checking_constraints_for_var_spec_id_here; |
1228 | else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Active->Entity)) |
1229 | DiagID = diag::note_checking_constraints_for_class_spec_id_here; |
1230 | else { |
1231 | assert(isa<FunctionDecl>(Active->Entity)); |
1232 | DiagID = diag::note_checking_constraints_for_function_here; |
1233 | } |
1234 | SmallString<128> TemplateArgsStr; |
1235 | llvm::raw_svector_ostream OS(TemplateArgsStr); |
1236 | cast<NamedDecl>(Val: Active->Entity)->printName(OS, Policy: getPrintingPolicy()); |
1237 | if (!isa<FunctionDecl>(Val: Active->Entity)) { |
1238 | printTemplateArgumentList(OS, Args: Active->template_arguments(), |
1239 | Policy: getPrintingPolicy()); |
1240 | } |
1241 | DiagFunc(Active->PointOfInstantiation, |
1242 | PDiag(DiagID) << OS.str() << Active->InstantiationRange); |
1243 | break; |
1244 | } |
1245 | case CodeSynthesisContext::ConstraintSubstitution: |
1246 | DiagFunc(Active->PointOfInstantiation, |
1247 | PDiag(diag::note_constraint_substitution_here) |
1248 | << Active->InstantiationRange); |
1249 | break; |
1250 | case CodeSynthesisContext::ConstraintNormalization: |
1251 | DiagFunc(Active->PointOfInstantiation, |
1252 | PDiag(diag::note_constraint_normalization_here) |
1253 | << cast<NamedDecl>(Active->Entity) |
1254 | << Active->InstantiationRange); |
1255 | break; |
1256 | case CodeSynthesisContext::ParameterMappingSubstitution: |
1257 | DiagFunc(Active->PointOfInstantiation, |
1258 | PDiag(diag::note_parameter_mapping_substitution_here) |
1259 | << Active->InstantiationRange); |
1260 | break; |
1261 | case CodeSynthesisContext::BuildingDeductionGuides: |
1262 | DiagFunc(Active->PointOfInstantiation, |
1263 | PDiag(diag::note_building_deduction_guide_here)); |
1264 | break; |
1265 | case CodeSynthesisContext::TypeAliasTemplateInstantiation: |
1266 | DiagFunc(Active->PointOfInstantiation, |
1267 | PDiag(diag::note_template_type_alias_instantiation_here) |
1268 | << cast<TypeAliasTemplateDecl>(Active->Entity) |
1269 | << Active->InstantiationRange); |
1270 | break; |
1271 | case CodeSynthesisContext::PartialOrderingTTP: |
1272 | DiagFunc(Active->PointOfInstantiation, |
1273 | PDiag(diag::note_template_arg_template_params_mismatch)); |
1274 | if (SourceLocation ParamLoc = Active->Entity->getLocation(); |
1275 | ParamLoc.isValid()) |
1276 | DiagFunc(ParamLoc, PDiag(diag::note_template_prev_declaration) |
1277 | << /*isTemplateTemplateParam=*/true |
1278 | << Active->InstantiationRange); |
1279 | break; |
1280 | } |
1281 | } |
1282 | } |
1283 | |
1284 | std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const { |
1285 | if (InNonInstantiationSFINAEContext) |
1286 | return std::optional<TemplateDeductionInfo *>(nullptr); |
1287 | |
1288 | for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator |
1289 | Active = CodeSynthesisContexts.rbegin(), |
1290 | ActiveEnd = CodeSynthesisContexts.rend(); |
1291 | Active != ActiveEnd; |
1292 | ++Active) |
1293 | { |
1294 | switch (Active->Kind) { |
1295 | case CodeSynthesisContext::TypeAliasTemplateInstantiation: |
1296 | // An instantiation of an alias template may or may not be a SFINAE |
1297 | // context, depending on what else is on the stack. |
1298 | if (isa<TypeAliasTemplateDecl>(Val: Active->Entity)) |
1299 | break; |
1300 | [[fallthrough]]; |
1301 | case CodeSynthesisContext::TemplateInstantiation: |
1302 | case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: |
1303 | case CodeSynthesisContext::ExceptionSpecInstantiation: |
1304 | case CodeSynthesisContext::ConstraintsCheck: |
1305 | case CodeSynthesisContext::ParameterMappingSubstitution: |
1306 | case CodeSynthesisContext::ConstraintNormalization: |
1307 | case CodeSynthesisContext::NestedRequirementConstraintsCheck: |
1308 | // This is a template instantiation, so there is no SFINAE. |
1309 | return std::nullopt; |
1310 | case CodeSynthesisContext::LambdaExpressionSubstitution: |
1311 | // [temp.deduct]p9 |
1312 | // A lambda-expression appearing in a function type or a template |
1313 | // parameter is not considered part of the immediate context for the |
1314 | // purposes of template argument deduction. |
1315 | // CWG2672: A lambda-expression body is never in the immediate context. |
1316 | return std::nullopt; |
1317 | |
1318 | case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: |
1319 | case CodeSynthesisContext::PriorTemplateArgumentSubstitution: |
1320 | case CodeSynthesisContext::DefaultTemplateArgumentChecking: |
1321 | case CodeSynthesisContext::RewritingOperatorAsSpaceship: |
1322 | case CodeSynthesisContext::PartialOrderingTTP: |
1323 | // A default template argument instantiation and substitution into |
1324 | // template parameters with arguments for prior parameters may or may |
1325 | // not be a SFINAE context; look further up the stack. |
1326 | break; |
1327 | |
1328 | case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: |
1329 | case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: |
1330 | // We're either substituting explicitly-specified template arguments, |
1331 | // deduced template arguments. SFINAE applies unless we are in a lambda |
1332 | // body, see [temp.deduct]p9. |
1333 | case CodeSynthesisContext::ConstraintSubstitution: |
1334 | case CodeSynthesisContext::RequirementInstantiation: |
1335 | case CodeSynthesisContext::RequirementParameterInstantiation: |
1336 | // SFINAE always applies in a constraint expression or a requirement |
1337 | // in a requires expression. |
1338 | assert(Active->DeductionInfo && "Missing deduction info pointer"); |
1339 | return Active->DeductionInfo; |
1340 | |
1341 | case CodeSynthesisContext::DeclaringSpecialMember: |
1342 | case CodeSynthesisContext::DeclaringImplicitEqualityComparison: |
1343 | case CodeSynthesisContext::DefiningSynthesizedFunction: |
1344 | case CodeSynthesisContext::InitializingStructuredBinding: |
1345 | case CodeSynthesisContext::MarkingClassDllexported: |
1346 | case CodeSynthesisContext::BuildingBuiltinDumpStructCall: |
1347 | case CodeSynthesisContext::BuildingDeductionGuides: |
1348 | // This happens in a context unrelated to template instantiation, so |
1349 | // there is no SFINAE. |
1350 | return std::nullopt; |
1351 | |
1352 | case CodeSynthesisContext::ExceptionSpecEvaluation: |
1353 | // FIXME: This should not be treated as a SFINAE context, because |
1354 | // we will cache an incorrect exception specification. However, clang |
1355 | // bootstrap relies this! See PR31692. |
1356 | break; |
1357 | |
1358 | case CodeSynthesisContext::Memoization: |
1359 | break; |
1360 | } |
1361 | |
1362 | // The inner context was transparent for SFINAE. If it occurred within a |
1363 | // non-instantiation SFINAE context, then SFINAE applies. |
1364 | if (Active->SavedInNonInstantiationSFINAEContext) |
1365 | return std::optional<TemplateDeductionInfo *>(nullptr); |
1366 | } |
1367 | |
1368 | return std::nullopt; |
1369 | } |
1370 | |
1371 | static TemplateArgument |
1372 | getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) { |
1373 | assert(S.ArgPackSubstIndex); |
1374 | assert(*S.ArgPackSubstIndex < Arg.pack_size()); |
1375 | Arg = Arg.pack_begin()[*S.ArgPackSubstIndex]; |
1376 | if (Arg.isPackExpansion()) |
1377 | Arg = Arg.getPackExpansionPattern(); |
1378 | return Arg; |
1379 | } |
1380 | |
1381 | //===----------------------------------------------------------------------===/ |
1382 | // Template Instantiation for Types |
1383 | //===----------------------------------------------------------------------===/ |
1384 | namespace { |
1385 | class TemplateInstantiator : public TreeTransform<TemplateInstantiator> { |
1386 | const MultiLevelTemplateArgumentList &TemplateArgs; |
1387 | SourceLocation Loc; |
1388 | DeclarationName Entity; |
1389 | // Whether to evaluate the C++20 constraints or simply substitute into them. |
1390 | bool EvaluateConstraints = true; |
1391 | // Whether Substitution was Incomplete, that is, we tried to substitute in |
1392 | // any user provided template arguments which were null. |
1393 | bool IsIncomplete = false; |
1394 | // Whether an incomplete substituion should be treated as an error. |
1395 | bool BailOutOnIncomplete; |
1396 | |
1397 | private: |
1398 | // CWG2770: Function parameters should be instantiated when they are |
1399 | // needed by a satisfaction check of an atomic constraint or |
1400 | // (recursively) by another function parameter. |
1401 | bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm); |
1402 | |
1403 | public: |
1404 | typedef TreeTransform<TemplateInstantiator> inherited; |
1405 | |
1406 | TemplateInstantiator(Sema &SemaRef, |
1407 | const MultiLevelTemplateArgumentList &TemplateArgs, |
1408 | SourceLocation Loc, DeclarationName Entity, |
1409 | bool BailOutOnIncomplete = false) |
1410 | : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc), |
1411 | Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {} |
1412 | |
1413 | void setEvaluateConstraints(bool B) { |
1414 | EvaluateConstraints = B; |
1415 | } |
1416 | bool getEvaluateConstraints() { |
1417 | return EvaluateConstraints; |
1418 | } |
1419 | |
1420 | /// Determine whether the given type \p T has already been |
1421 | /// transformed. |
1422 | /// |
1423 | /// For the purposes of template instantiation, a type has already been |
1424 | /// transformed if it is NULL or if it is not dependent. |
1425 | bool AlreadyTransformed(QualType T); |
1426 | |
1427 | /// Returns the location of the entity being instantiated, if known. |
1428 | SourceLocation getBaseLocation() { return Loc; } |
1429 | |
1430 | /// Returns the name of the entity being instantiated, if any. |
1431 | DeclarationName getBaseEntity() { return Entity; } |
1432 | |
1433 | /// Returns whether any substitution so far was incomplete. |
1434 | bool getIsIncomplete() const { return IsIncomplete; } |
1435 | |
1436 | /// Sets the "base" location and entity when that |
1437 | /// information is known based on another transformation. |
1438 | void setBase(SourceLocation Loc, DeclarationName Entity) { |
1439 | this->Loc = Loc; |
1440 | this->Entity = Entity; |
1441 | } |
1442 | |
1443 | unsigned TransformTemplateDepth(unsigned Depth) { |
1444 | return TemplateArgs.getNewDepth(OldDepth: Depth); |
1445 | } |
1446 | |
1447 | UnsignedOrNone getPackIndex(TemplateArgument Pack) { |
1448 | UnsignedOrNone Index = getSema().ArgPackSubstIndex; |
1449 | if (!Index) |
1450 | return std::nullopt; |
1451 | return Pack.pack_size() - 1 - *Index; |
1452 | } |
1453 | |
1454 | bool TryExpandParameterPacks(SourceLocation EllipsisLoc, |
1455 | SourceRange PatternRange, |
1456 | ArrayRef<UnexpandedParameterPack> Unexpanded, |
1457 | bool &ShouldExpand, bool &RetainExpansion, |
1458 | UnsignedOrNone &NumExpansions) { |
1459 | if (SemaRef.CurrentInstantiationScope && |
1460 | SemaRef.inConstraintSubstitution()) { |
1461 | for (UnexpandedParameterPack ParmPack : Unexpanded) { |
1462 | NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>(); |
1463 | if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(Val: VD); |
1464 | PVD && maybeInstantiateFunctionParameterToScope(OldParm: PVD)) |
1465 | return true; |
1466 | } |
1467 | } |
1468 | |
1469 | return getSema().CheckParameterPacksForExpansion( |
1470 | EllipsisLoc, PatternRange, Unexpanded, TemplateArgs, ShouldExpand, |
1471 | RetainExpansion, NumExpansions); |
1472 | } |
1473 | |
1474 | void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { |
1475 | SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack); |
1476 | } |
1477 | |
1478 | TemplateArgument ForgetPartiallySubstitutedPack() { |
1479 | TemplateArgument Result; |
1480 | if (NamedDecl *PartialPack |
1481 | = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ |
1482 | MultiLevelTemplateArgumentList &TemplateArgs |
1483 | = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); |
1484 | unsigned Depth, Index; |
1485 | std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack); |
1486 | if (TemplateArgs.hasTemplateArgument(Depth, Index)) { |
1487 | Result = TemplateArgs(Depth, Index); |
1488 | TemplateArgs.setArgument(Depth, Index, Arg: TemplateArgument()); |
1489 | } else { |
1490 | IsIncomplete = true; |
1491 | if (BailOutOnIncomplete) |
1492 | return TemplateArgument(); |
1493 | } |
1494 | } |
1495 | |
1496 | return Result; |
1497 | } |
1498 | |
1499 | void RememberPartiallySubstitutedPack(TemplateArgument Arg) { |
1500 | if (Arg.isNull()) |
1501 | return; |
1502 | |
1503 | if (NamedDecl *PartialPack |
1504 | = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){ |
1505 | MultiLevelTemplateArgumentList &TemplateArgs |
1506 | = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs); |
1507 | unsigned Depth, Index; |
1508 | std::tie(args&: Depth, args&: Index) = getDepthAndIndex(ND: PartialPack); |
1509 | TemplateArgs.setArgument(Depth, Index, Arg); |
1510 | } |
1511 | } |
1512 | |
1513 | TemplateArgument |
1514 | getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) { |
1515 | if (TA.getKind() != TemplateArgument::Pack) |
1516 | return TA; |
1517 | if (SemaRef.ArgPackSubstIndex) |
1518 | return getPackSubstitutedTemplateArgument(SemaRef, TA); |
1519 | assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() && |
1520 | "unexpected pack arguments in template rewrite"); |
1521 | TemplateArgument Arg = *TA.pack_begin(); |
1522 | if (Arg.isPackExpansion()) |
1523 | Arg = Arg.getPackExpansionPattern(); |
1524 | return Arg; |
1525 | } |
1526 | |
1527 | /// Transform the given declaration by instantiating a reference to |
1528 | /// this declaration. |
1529 | Decl *TransformDecl(SourceLocation Loc, Decl *D); |
1530 | |
1531 | void transformAttrs(Decl *Old, Decl *New) { |
1532 | SemaRef.InstantiateAttrs(TemplateArgs, Old, New); |
1533 | } |
1534 | |
1535 | void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) { |
1536 | if (Old->isParameterPack() && |
1537 | (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) { |
1538 | SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old); |
1539 | for (auto *New : NewDecls) |
1540 | SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg( |
1541 | Old, cast<VarDecl>(New)); |
1542 | return; |
1543 | } |
1544 | |
1545 | assert(NewDecls.size() == 1 && |
1546 | "should only have multiple expansions for a pack"); |
1547 | Decl *New = NewDecls.front(); |
1548 | |
1549 | // If we've instantiated the call operator of a lambda or the call |
1550 | // operator template of a generic lambda, update the "instantiation of" |
1551 | // information. |
1552 | auto *NewMD = dyn_cast<CXXMethodDecl>(Val: New); |
1553 | if (NewMD && isLambdaCallOperator(MD: NewMD)) { |
1554 | auto *OldMD = dyn_cast<CXXMethodDecl>(Val: Old); |
1555 | if (auto *NewTD = NewMD->getDescribedFunctionTemplate()) |
1556 | NewTD->setInstantiatedFromMemberTemplate( |
1557 | OldMD->getDescribedFunctionTemplate()); |
1558 | else |
1559 | NewMD->setInstantiationOfMemberFunction(OldMD, |
1560 | TSK_ImplicitInstantiation); |
1561 | } |
1562 | |
1563 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New); |
1564 | |
1565 | // We recreated a local declaration, but not by instantiating it. There |
1566 | // may be pending dependent diagnostics to produce. |
1567 | if (auto *DC = dyn_cast<DeclContext>(Old); |
1568 | DC && DC->isDependentContext() && DC->isFunctionOrMethod()) |
1569 | SemaRef.PerformDependentDiagnostics(DC, TemplateArgs); |
1570 | } |
1571 | |
1572 | /// Transform the definition of the given declaration by |
1573 | /// instantiating it. |
1574 | Decl *TransformDefinition(SourceLocation Loc, Decl *D); |
1575 | |
1576 | /// Transform the first qualifier within a scope by instantiating the |
1577 | /// declaration. |
1578 | NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc); |
1579 | |
1580 | bool TransformExceptionSpec(SourceLocation Loc, |
1581 | FunctionProtoType::ExceptionSpecInfo &ESI, |
1582 | SmallVectorImpl<QualType> &Exceptions, |
1583 | bool &Changed); |
1584 | |
1585 | /// Rebuild the exception declaration and register the declaration |
1586 | /// as an instantiated local. |
1587 | VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl, |
1588 | TypeSourceInfo *Declarator, |
1589 | SourceLocation StartLoc, |
1590 | SourceLocation NameLoc, |
1591 | IdentifierInfo *Name); |
1592 | |
1593 | /// Rebuild the Objective-C exception declaration and register the |
1594 | /// declaration as an instantiated local. |
1595 | VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, |
1596 | TypeSourceInfo *TSInfo, QualType T); |
1597 | |
1598 | /// Check for tag mismatches when instantiating an |
1599 | /// elaborated type. |
1600 | QualType RebuildElaboratedType(SourceLocation KeywordLoc, |
1601 | ElaboratedTypeKeyword Keyword, |
1602 | NestedNameSpecifierLoc QualifierLoc, |
1603 | QualType T); |
1604 | |
1605 | TemplateName |
1606 | TransformTemplateName(CXXScopeSpec &SS, TemplateName Name, |
1607 | SourceLocation NameLoc, |
1608 | QualType ObjectType = QualType(), |
1609 | NamedDecl *FirstQualifierInScope = nullptr, |
1610 | bool AllowInjectedClassName = false); |
1611 | |
1612 | const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA); |
1613 | const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA); |
1614 | const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH); |
1615 | const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS, |
1616 | const Stmt *InstS, |
1617 | const NoInlineAttr *A); |
1618 | const AlwaysInlineAttr * |
1619 | TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS, |
1620 | const AlwaysInlineAttr *A); |
1621 | const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA); |
1622 | const OpenACCRoutineDeclAttr * |
1623 | TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A); |
1624 | ExprResult TransformPredefinedExpr(PredefinedExpr *E); |
1625 | ExprResult TransformDeclRefExpr(DeclRefExpr *E); |
1626 | ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E); |
1627 | |
1628 | ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E, |
1629 | NonTypeTemplateParmDecl *D); |
1630 | ExprResult TransformSubstNonTypeTemplateParmPackExpr( |
1631 | SubstNonTypeTemplateParmPackExpr *E); |
1632 | ExprResult TransformSubstNonTypeTemplateParmExpr( |
1633 | SubstNonTypeTemplateParmExpr *E); |
1634 | |
1635 | /// Rebuild a DeclRefExpr for a VarDecl reference. |
1636 | ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc); |
1637 | |
1638 | /// Transform a reference to a function or init-capture parameter pack. |
1639 | ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD); |
1640 | |
1641 | /// Transform a FunctionParmPackExpr which was built when we couldn't |
1642 | /// expand a function parameter pack reference which refers to an expanded |
1643 | /// pack. |
1644 | ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E); |
1645 | |
1646 | QualType TransformFunctionProtoType(TypeLocBuilder &TLB, |
1647 | FunctionProtoTypeLoc TL) { |
1648 | // Call the base version; it will forward to our overridden version below. |
1649 | return inherited::TransformFunctionProtoType(TLB, TL); |
1650 | } |
1651 | |
1652 | QualType TransformInjectedClassNameType(TypeLocBuilder &TLB, |
1653 | InjectedClassNameTypeLoc TL) { |
1654 | auto Type = inherited::TransformInjectedClassNameType(TLB, TL); |
1655 | // Special case for transforming a deduction guide, we return a |
1656 | // transformed TemplateSpecializationType. |
1657 | if (Type.isNull() && |
1658 | SemaRef.CodeSynthesisContexts.back().Kind == |
1659 | Sema::CodeSynthesisContext::BuildingDeductionGuides) { |
1660 | // Return a TemplateSpecializationType for transforming a deduction |
1661 | // guide. |
1662 | if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) { |
1663 | auto Type = |
1664 | inherited::TransformType(ICT->getInjectedSpecializationType()); |
1665 | TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc()); |
1666 | return Type; |
1667 | } |
1668 | } |
1669 | return Type; |
1670 | } |
1671 | // Override the default version to handle a rewrite-template-arg-pack case |
1672 | // for building a deduction guide. |
1673 | bool TransformTemplateArgument(const TemplateArgumentLoc &Input, |
1674 | TemplateArgumentLoc &Output, |
1675 | bool Uneval = false) { |
1676 | const TemplateArgument &Arg = Input.getArgument(); |
1677 | std::vector<TemplateArgument> TArgs; |
1678 | switch (Arg.getKind()) { |
1679 | case TemplateArgument::Pack: |
1680 | assert(SemaRef.CodeSynthesisContexts.empty() || |
1681 | SemaRef.CodeSynthesisContexts.back().Kind == |
1682 | Sema::CodeSynthesisContext::BuildingDeductionGuides); |
1683 | // Literally rewrite the template argument pack, instead of unpacking |
1684 | // it. |
1685 | for (auto &pack : Arg.getPackAsArray()) { |
1686 | TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc( |
1687 | pack, QualType(), SourceLocation{}); |
1688 | TemplateArgumentLoc Output; |
1689 | if (TransformTemplateArgument(Input, Output, Uneval)) |
1690 | return true; // fails |
1691 | TArgs.push_back(x: Output.getArgument()); |
1692 | } |
1693 | Output = SemaRef.getTrivialTemplateArgumentLoc( |
1694 | TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)), |
1695 | QualType(), SourceLocation{}); |
1696 | return false; |
1697 | default: |
1698 | break; |
1699 | } |
1700 | return inherited::TransformTemplateArgument(Input, Output, Uneval); |
1701 | } |
1702 | |
1703 | UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution( |
1704 | ArrayRef<TemplateArgument> PackArgs) { |
1705 | // Don't do this when rewriting template parameters for CTAD: |
1706 | // 1) The heuristic needs the unpacked Subst* nodes to figure out the |
1707 | // expanded size, but this never applies since Subst* nodes are not |
1708 | // created in rewrite scenarios. |
1709 | // |
1710 | // 2) The heuristic substitutes into the pattern with pack expansion |
1711 | // suppressed, which does not meet the requirements for argument |
1712 | // rewriting when template arguments include a non-pack matching against |
1713 | // a pack, particularly when rewriting an alias CTAD. |
1714 | if (TemplateArgs.isRewrite()) |
1715 | return std::nullopt; |
1716 | |
1717 | return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs); |
1718 | } |
1719 | |
1720 | template<typename Fn> |
1721 | QualType TransformFunctionProtoType(TypeLocBuilder &TLB, |
1722 | FunctionProtoTypeLoc TL, |
1723 | CXXRecordDecl *ThisContext, |
1724 | Qualifiers ThisTypeQuals, |
1725 | Fn TransformExceptionSpec); |
1726 | |
1727 | ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm, |
1728 | int indexAdjustment, |
1729 | UnsignedOrNone NumExpansions, |
1730 | bool ExpectParameterPack); |
1731 | |
1732 | using inherited::TransformTemplateTypeParmType; |
1733 | /// Transforms a template type parameter type by performing |
1734 | /// substitution of the corresponding template type argument. |
1735 | QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
1736 | TemplateTypeParmTypeLoc TL, |
1737 | bool SuppressObjCLifetime); |
1738 | |
1739 | QualType BuildSubstTemplateTypeParmType( |
1740 | TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, |
1741 | Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, |
1742 | TemplateArgument Arg, SourceLocation NameLoc); |
1743 | |
1744 | /// Transforms an already-substituted template type parameter pack |
1745 | /// into either itself (if we aren't substituting into its pack expansion) |
1746 | /// or the appropriate substituted argument. |
1747 | using inherited::TransformSubstTemplateTypeParmPackType; |
1748 | QualType |
1749 | TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB, |
1750 | SubstTemplateTypeParmPackTypeLoc TL, |
1751 | bool SuppressObjCLifetime); |
1752 | |
1753 | CXXRecordDecl::LambdaDependencyKind |
1754 | ComputeLambdaDependency(LambdaScopeInfo *LSI) { |
1755 | if (auto TypeAlias = |
1756 | TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl( |
1757 | SemaRef&: getSema()); |
1758 | TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl( |
1759 | LambdaCallOperator: LSI->CallOperator, PrimaryTypeAliasDecl: TypeAlias.PrimaryTypeAliasDecl)) { |
1760 | unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth(); |
1761 | if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels()) |
1762 | return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent; |
1763 | for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments) |
1764 | if (TA.isDependent()) |
1765 | return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent; |
1766 | } |
1767 | return inherited::ComputeLambdaDependency(LSI); |
1768 | } |
1769 | |
1770 | ExprResult TransformLambdaExpr(LambdaExpr *E) { |
1771 | // Do not rebuild lambdas to avoid creating a new type. |
1772 | // Lambdas have already been processed inside their eval contexts. |
1773 | if (SemaRef.RebuildingImmediateInvocation) |
1774 | return E; |
1775 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true, |
1776 | /*InstantiatingLambdaOrBlock=*/true); |
1777 | Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this); |
1778 | |
1779 | return inherited::TransformLambdaExpr(E); |
1780 | } |
1781 | |
1782 | ExprResult TransformBlockExpr(BlockExpr *E) { |
1783 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true, |
1784 | /*InstantiatingLambdaOrBlock=*/true); |
1785 | return inherited::TransformBlockExpr(E); |
1786 | } |
1787 | |
1788 | ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, |
1789 | LambdaScopeInfo *LSI) { |
1790 | CXXMethodDecl *MD = LSI->CallOperator; |
1791 | for (ParmVarDecl *PVD : MD->parameters()) { |
1792 | assert(PVD && "null in a parameter list"); |
1793 | if (!PVD->hasDefaultArg()) |
1794 | continue; |
1795 | Expr *UninstExpr = PVD->getUninstantiatedDefaultArg(); |
1796 | // FIXME: Obtain the source location for the '=' token. |
1797 | SourceLocation EqualLoc = UninstExpr->getBeginLoc(); |
1798 | if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) { |
1799 | // If substitution fails, the default argument is set to a |
1800 | // RecoveryExpr that wraps the uninstantiated default argument so |
1801 | // that downstream diagnostics are omitted. |
1802 | ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( |
1803 | UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr}, |
1804 | UninstExpr->getType()); |
1805 | if (ErrorResult.isUsable()) |
1806 | PVD->setDefaultArg(ErrorResult.get()); |
1807 | } |
1808 | } |
1809 | return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI); |
1810 | } |
1811 | |
1812 | StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) { |
1813 | // Currently, we instantiate the body when instantiating the lambda |
1814 | // expression. However, `EvaluateConstraints` is disabled during the |
1815 | // instantiation of the lambda expression, causing the instantiation |
1816 | // failure of the return type requirement in the body. If p0588r1 is fully |
1817 | // implemented, the body will be lazily instantiated, and this problem |
1818 | // will not occur. Here, `EvaluateConstraints` is temporarily set to |
1819 | // `true` to temporarily fix this issue. |
1820 | // FIXME: This temporary fix can be removed after fully implementing |
1821 | // p0588r1. |
1822 | llvm::SaveAndRestore _(EvaluateConstraints, true); |
1823 | return inherited::TransformLambdaBody(E, Body); |
1824 | } |
1825 | |
1826 | ExprResult TransformRequiresExpr(RequiresExpr *E) { |
1827 | LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true); |
1828 | ExprResult TransReq = inherited::TransformRequiresExpr(E); |
1829 | if (TransReq.isInvalid()) |
1830 | return TransReq; |
1831 | assert(TransReq.get() != E && |
1832 | "Do not change value of isSatisfied for the existing expression. " |
1833 | "Create a new expression instead."); |
1834 | if (E->getBody()->isDependentContext()) { |
1835 | Sema::SFINAETrap Trap(SemaRef); |
1836 | // We recreate the RequiresExpr body, but not by instantiating it. |
1837 | // Produce pending diagnostics for dependent access check. |
1838 | SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs); |
1839 | // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis. |
1840 | if (Trap.hasErrorOccurred()) |
1841 | TransReq.getAs<RequiresExpr>()->setSatisfied(false); |
1842 | } |
1843 | return TransReq; |
1844 | } |
1845 | |
1846 | bool TransformRequiresExprRequirements( |
1847 | ArrayRef<concepts::Requirement *> Reqs, |
1848 | SmallVectorImpl<concepts::Requirement *> &Transformed) { |
1849 | bool SatisfactionDetermined = false; |
1850 | for (concepts::Requirement *Req : Reqs) { |
1851 | concepts::Requirement *TransReq = nullptr; |
1852 | if (!SatisfactionDetermined) { |
1853 | if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Val: Req)) |
1854 | TransReq = TransformTypeRequirement(Req: TypeReq); |
1855 | else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Val: Req)) |
1856 | TransReq = TransformExprRequirement(Req: ExprReq); |
1857 | else |
1858 | TransReq = TransformNestedRequirement( |
1859 | Req: cast<concepts::NestedRequirement>(Val: Req)); |
1860 | if (!TransReq) |
1861 | return true; |
1862 | if (!TransReq->isDependent() && !TransReq->isSatisfied()) |
1863 | // [expr.prim.req]p6 |
1864 | // [...] The substitution and semantic constraint checking |
1865 | // proceeds in lexical order and stops when a condition that |
1866 | // determines the result of the requires-expression is |
1867 | // encountered. [..] |
1868 | SatisfactionDetermined = true; |
1869 | } else |
1870 | TransReq = Req; |
1871 | Transformed.push_back(Elt: TransReq); |
1872 | } |
1873 | return false; |
1874 | } |
1875 | |
1876 | TemplateParameterList *TransformTemplateParameterList( |
1877 | TemplateParameterList *OrigTPL) { |
1878 | if (!OrigTPL || !OrigTPL->size()) return OrigTPL; |
1879 | |
1880 | DeclContext *Owner = OrigTPL->getParam(Idx: 0)->getDeclContext(); |
1881 | TemplateDeclInstantiator DeclInstantiator(getSema(), |
1882 | /* DeclContext *Owner */ Owner, TemplateArgs); |
1883 | DeclInstantiator.setEvaluateConstraints(EvaluateConstraints); |
1884 | return DeclInstantiator.SubstTemplateParams(List: OrigTPL); |
1885 | } |
1886 | |
1887 | concepts::TypeRequirement * |
1888 | TransformTypeRequirement(concepts::TypeRequirement *Req); |
1889 | concepts::ExprRequirement * |
1890 | TransformExprRequirement(concepts::ExprRequirement *Req); |
1891 | concepts::NestedRequirement * |
1892 | TransformNestedRequirement(concepts::NestedRequirement *Req); |
1893 | ExprResult TransformRequiresTypeParams( |
1894 | SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE, |
1895 | RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params, |
1896 | SmallVectorImpl<QualType> &PTypes, |
1897 | SmallVectorImpl<ParmVarDecl *> &TransParams, |
1898 | Sema::ExtParameterInfoBuilder &PInfos); |
1899 | |
1900 | private: |
1901 | ExprResult |
1902 | transformNonTypeTemplateParmRef(Decl *AssociatedDecl, |
1903 | const NonTypeTemplateParmDecl *parm, |
1904 | SourceLocation loc, TemplateArgument arg, |
1905 | UnsignedOrNone PackIndex, bool Final); |
1906 | }; |
1907 | } |
1908 | |
1909 | bool TemplateInstantiator::AlreadyTransformed(QualType T) { |
1910 | if (T.isNull()) |
1911 | return true; |
1912 | |
1913 | if (T->isInstantiationDependentType() || T->isVariablyModifiedType() || |
1914 | T->containsUnexpandedParameterPack()) |
1915 | return false; |
1916 | |
1917 | getSema().MarkDeclarationsReferencedInType(Loc, T); |
1918 | return true; |
1919 | } |
1920 | |
1921 | Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) { |
1922 | if (!D) |
1923 | return nullptr; |
1924 | |
1925 | if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: D)) { |
1926 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { |
1927 | // If the corresponding template argument is NULL or non-existent, it's |
1928 | // because we are performing instantiation from explicitly-specified |
1929 | // template arguments in a function template, but there were some |
1930 | // arguments left unspecified. |
1931 | if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(), |
1932 | Index: TTP->getPosition())) { |
1933 | IsIncomplete = true; |
1934 | return BailOutOnIncomplete ? nullptr : D; |
1935 | } |
1936 | |
1937 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); |
1938 | |
1939 | if (TTP->isParameterPack()) { |
1940 | assert(Arg.getKind() == TemplateArgument::Pack && |
1941 | "Missing argument pack"); |
1942 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); |
1943 | } |
1944 | |
1945 | TemplateName Template = Arg.getAsTemplate(); |
1946 | assert(!Template.isNull() && Template.getAsTemplateDecl() && |
1947 | "Wrong kind of template template argument"); |
1948 | return Template.getAsTemplateDecl(); |
1949 | } |
1950 | |
1951 | // Fall through to find the instantiated declaration for this template |
1952 | // template parameter. |
1953 | } |
1954 | |
1955 | if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Val: D); |
1956 | PVD && SemaRef.CurrentInstantiationScope && |
1957 | SemaRef.inConstraintSubstitution() && |
1958 | maybeInstantiateFunctionParameterToScope(PVD)) |
1959 | return nullptr; |
1960 | |
1961 | return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs); |
1962 | } |
1963 | |
1964 | bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope( |
1965 | ParmVarDecl *OldParm) { |
1966 | if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(OldParm)) |
1967 | return false; |
1968 | |
1969 | if (!OldParm->isParameterPack()) |
1970 | return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0, |
1971 | /*NumExpansions=*/std::nullopt, |
1972 | /*ExpectParameterPack=*/false); |
1973 | |
1974 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
1975 | |
1976 | // Find the parameter packs that could be expanded. |
1977 | TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc(); |
1978 | PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>(); |
1979 | TypeLoc Pattern = ExpansionTL.getPatternLoc(); |
1980 | SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded); |
1981 | assert(!Unexpanded.empty() && "Pack expansion without parameter packs?"); |
1982 | |
1983 | bool ShouldExpand = false; |
1984 | bool RetainExpansion = false; |
1985 | UnsignedOrNone OrigNumExpansions = |
1986 | ExpansionTL.getTypePtr()->getNumExpansions(); |
1987 | UnsignedOrNone NumExpansions = OrigNumExpansions; |
1988 | if (TryExpandParameterPacks(EllipsisLoc: ExpansionTL.getEllipsisLoc(), |
1989 | PatternRange: Pattern.getSourceRange(), Unexpanded, |
1990 | ShouldExpand, RetainExpansion, NumExpansions)) |
1991 | return true; |
1992 | |
1993 | assert(ShouldExpand && !RetainExpansion && |
1994 | "Shouldn't preserve pack expansion when evaluating constraints"); |
1995 | ExpandingFunctionParameterPack(Pack: OldParm); |
1996 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
1997 | Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I); |
1998 | if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0, |
1999 | /*NumExpansions=*/OrigNumExpansions, |
2000 | /*ExpectParameterPack=*/false)) |
2001 | return true; |
2002 | } |
2003 | return false; |
2004 | } |
2005 | |
2006 | Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) { |
2007 | Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs); |
2008 | if (!Inst) |
2009 | return nullptr; |
2010 | |
2011 | getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
2012 | return Inst; |
2013 | } |
2014 | |
2015 | bool TemplateInstantiator::TransformExceptionSpec( |
2016 | SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, |
2017 | SmallVectorImpl<QualType> &Exceptions, bool &Changed) { |
2018 | if (ESI.Type == EST_Uninstantiated) { |
2019 | ESI.instantiate(); |
2020 | Changed = true; |
2021 | } |
2022 | return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed); |
2023 | } |
2024 | |
2025 | NamedDecl * |
2026 | TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D, |
2027 | SourceLocation Loc) { |
2028 | // If the first part of the nested-name-specifier was a template type |
2029 | // parameter, instantiate that type parameter down to a tag type. |
2030 | if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(Val: D)) { |
2031 | const TemplateTypeParmType *TTP |
2032 | = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD)); |
2033 | |
2034 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { |
2035 | // FIXME: This needs testing w/ member access expressions. |
2036 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex()); |
2037 | |
2038 | if (TTP->isParameterPack()) { |
2039 | assert(Arg.getKind() == TemplateArgument::Pack && |
2040 | "Missing argument pack"); |
2041 | |
2042 | if (!getSema().ArgPackSubstIndex) |
2043 | return nullptr; |
2044 | |
2045 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); |
2046 | } |
2047 | |
2048 | QualType T = Arg.getAsType(); |
2049 | if (T.isNull()) |
2050 | return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D)); |
2051 | |
2052 | if (const TagType *Tag = T->getAs<TagType>()) |
2053 | return Tag->getDecl(); |
2054 | |
2055 | // The resulting type is not a tag; complain. |
2056 | getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T; |
2057 | return nullptr; |
2058 | } |
2059 | } |
2060 | |
2061 | return cast_or_null<NamedDecl>(Val: TransformDecl(Loc, D)); |
2062 | } |
2063 | |
2064 | VarDecl * |
2065 | TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl, |
2066 | TypeSourceInfo *Declarator, |
2067 | SourceLocation StartLoc, |
2068 | SourceLocation NameLoc, |
2069 | IdentifierInfo *Name) { |
2070 | VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator, |
2071 | StartLoc, NameLoc, Name); |
2072 | if (Var) |
2073 | getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); |
2074 | return Var; |
2075 | } |
2076 | |
2077 | VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl, |
2078 | TypeSourceInfo *TSInfo, |
2079 | QualType T) { |
2080 | VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T); |
2081 | if (Var) |
2082 | getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var); |
2083 | return Var; |
2084 | } |
2085 | |
2086 | QualType |
2087 | TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc, |
2088 | ElaboratedTypeKeyword Keyword, |
2089 | NestedNameSpecifierLoc QualifierLoc, |
2090 | QualType T) { |
2091 | if (const TagType *TT = T->getAs<TagType>()) { |
2092 | TagDecl* TD = TT->getDecl(); |
2093 | |
2094 | SourceLocation TagLocation = KeywordLoc; |
2095 | |
2096 | IdentifierInfo *Id = TD->getIdentifier(); |
2097 | |
2098 | // TODO: should we even warn on struct/class mismatches for this? Seems |
2099 | // like it's likely to produce a lot of spurious errors. |
2100 | if (Id && Keyword != ElaboratedTypeKeyword::None && |
2101 | Keyword != ElaboratedTypeKeyword::Typename) { |
2102 | TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword); |
2103 | if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false, |
2104 | TagLocation, Id)) { |
2105 | SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag) |
2106 | << Id |
2107 | << FixItHint::CreateReplacement(SourceRange(TagLocation), |
2108 | TD->getKindName()); |
2109 | SemaRef.Diag(TD->getLocation(), diag::note_previous_use); |
2110 | } |
2111 | } |
2112 | } |
2113 | |
2114 | return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T); |
2115 | } |
2116 | |
2117 | TemplateName TemplateInstantiator::TransformTemplateName( |
2118 | CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc, |
2119 | QualType ObjectType, NamedDecl *FirstQualifierInScope, |
2120 | bool AllowInjectedClassName) { |
2121 | if (TemplateTemplateParmDecl *TTP |
2122 | = dyn_cast_or_null<TemplateTemplateParmDecl>(Val: Name.getAsTemplateDecl())) { |
2123 | if (TTP->getDepth() < TemplateArgs.getNumLevels()) { |
2124 | // If the corresponding template argument is NULL or non-existent, it's |
2125 | // because we are performing instantiation from explicitly-specified |
2126 | // template arguments in a function template, but there were some |
2127 | // arguments left unspecified. |
2128 | if (!TemplateArgs.hasTemplateArgument(Depth: TTP->getDepth(), |
2129 | Index: TTP->getPosition())) { |
2130 | IsIncomplete = true; |
2131 | return BailOutOnIncomplete ? TemplateName() : Name; |
2132 | } |
2133 | |
2134 | TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition()); |
2135 | |
2136 | if (TemplateArgs.isRewrite()) { |
2137 | // We're rewriting the template parameter as a reference to another |
2138 | // template parameter. |
2139 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
2140 | assert(Arg.getKind() == TemplateArgument::Template && |
2141 | "unexpected nontype template argument kind in template rewrite"); |
2142 | return Arg.getAsTemplate(); |
2143 | } |
2144 | |
2145 | auto [AssociatedDecl, Final] = |
2146 | TemplateArgs.getAssociatedDecl(Depth: TTP->getDepth()); |
2147 | UnsignedOrNone PackIndex = std::nullopt; |
2148 | if (TTP->isParameterPack()) { |
2149 | assert(Arg.getKind() == TemplateArgument::Pack && |
2150 | "Missing argument pack"); |
2151 | |
2152 | if (!getSema().ArgPackSubstIndex) { |
2153 | // We have the template argument pack to substitute, but we're not |
2154 | // actually expanding the enclosing pack expansion yet. So, just |
2155 | // keep the entire argument pack. |
2156 | return getSema().Context.getSubstTemplateTemplateParmPack( |
2157 | Arg, AssociatedDecl, TTP->getIndex(), Final); |
2158 | } |
2159 | |
2160 | PackIndex = getPackIndex(Pack: Arg); |
2161 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); |
2162 | } |
2163 | |
2164 | TemplateName Template = Arg.getAsTemplate(); |
2165 | assert(!Template.isNull() && "Null template template argument"); |
2166 | |
2167 | return getSema().Context.getSubstTemplateTemplateParm( |
2168 | Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final); |
2169 | } |
2170 | } |
2171 | |
2172 | if (SubstTemplateTemplateParmPackStorage *SubstPack |
2173 | = Name.getAsSubstTemplateTemplateParmPack()) { |
2174 | if (!getSema().ArgPackSubstIndex) |
2175 | return Name; |
2176 | |
2177 | TemplateArgument Pack = SubstPack->getArgumentPack(); |
2178 | TemplateName Template = |
2179 | getPackSubstitutedTemplateArgument(getSema(), Pack).getAsTemplate(); |
2180 | return getSema().Context.getSubstTemplateTemplateParm( |
2181 | Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(), |
2182 | getPackIndex(Pack), SubstPack->getFinal()); |
2183 | } |
2184 | |
2185 | return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType, |
2186 | FirstQualifierInScope, |
2187 | AllowInjectedClassName); |
2188 | } |
2189 | |
2190 | ExprResult |
2191 | TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) { |
2192 | if (!E->isTypeDependent()) |
2193 | return E; |
2194 | |
2195 | return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind()); |
2196 | } |
2197 | |
2198 | ExprResult |
2199 | TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E, |
2200 | NonTypeTemplateParmDecl *NTTP) { |
2201 | // If the corresponding template argument is NULL or non-existent, it's |
2202 | // because we are performing instantiation from explicitly-specified |
2203 | // template arguments in a function template, but there were some |
2204 | // arguments left unspecified. |
2205 | if (!TemplateArgs.hasTemplateArgument(Depth: NTTP->getDepth(), |
2206 | Index: NTTP->getPosition())) { |
2207 | IsIncomplete = true; |
2208 | return BailOutOnIncomplete ? ExprError() : E; |
2209 | } |
2210 | |
2211 | TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition()); |
2212 | |
2213 | if (TemplateArgs.isRewrite()) { |
2214 | // We're rewriting the template parameter as a reference to another |
2215 | // template parameter. |
2216 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
2217 | assert(Arg.getKind() == TemplateArgument::Expression && |
2218 | "unexpected nontype template argument kind in template rewrite"); |
2219 | // FIXME: This can lead to the same subexpression appearing multiple times |
2220 | // in a complete expression. |
2221 | return Arg.getAsExpr(); |
2222 | } |
2223 | |
2224 | auto [AssociatedDecl, Final] = |
2225 | TemplateArgs.getAssociatedDecl(Depth: NTTP->getDepth()); |
2226 | UnsignedOrNone PackIndex = std::nullopt; |
2227 | if (NTTP->isParameterPack()) { |
2228 | assert(Arg.getKind() == TemplateArgument::Pack && |
2229 | "Missing argument pack"); |
2230 | |
2231 | if (!getSema().ArgPackSubstIndex) { |
2232 | // We have an argument pack, but we can't select a particular argument |
2233 | // out of it yet. Therefore, we'll build an expression to hold on to that |
2234 | // argument pack. |
2235 | QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs, |
2236 | E->getLocation(), |
2237 | NTTP->getDeclName()); |
2238 | if (TargetType.isNull()) |
2239 | return ExprError(); |
2240 | |
2241 | QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context); |
2242 | if (TargetType->isRecordType()) |
2243 | ExprType.addConst(); |
2244 | return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr( |
2245 | ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue, |
2246 | E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final); |
2247 | } |
2248 | PackIndex = getPackIndex(Pack: Arg); |
2249 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); |
2250 | } |
2251 | return transformNonTypeTemplateParmRef(AssociatedDecl: AssociatedDecl, parm: NTTP, loc: E->getLocation(), |
2252 | arg: Arg, PackIndex, Final: Final); |
2253 | } |
2254 | |
2255 | const AnnotateAttr * |
2256 | TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) { |
2257 | SmallVector<Expr *> Args; |
2258 | for (Expr *Arg : AA->args()) { |
2259 | ExprResult Res = getDerived().TransformExpr(Arg); |
2260 | if (Res.isUsable()) |
2261 | Args.push_back(Res.get()); |
2262 | } |
2263 | return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(), |
2264 | Args.data(), Args.size(), AA->getRange()); |
2265 | } |
2266 | |
2267 | const CXXAssumeAttr * |
2268 | TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) { |
2269 | ExprResult Res = getDerived().TransformExpr(AA->getAssumption()); |
2270 | if (!Res.isUsable()) |
2271 | return AA; |
2272 | |
2273 | Res = getSema().ActOnFinishFullExpr(Res.get(), |
2274 | /*DiscardedValue=*/false); |
2275 | if (!Res.isUsable()) |
2276 | return AA; |
2277 | |
2278 | if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) { |
2279 | Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(), |
2280 | AA->getRange()); |
2281 | if (!Res.isUsable()) |
2282 | return AA; |
2283 | } |
2284 | |
2285 | return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(), |
2286 | AA->getRange()); |
2287 | } |
2288 | |
2289 | const LoopHintAttr * |
2290 | TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) { |
2291 | Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get(); |
2292 | |
2293 | if (TransformedExpr == LH->getValue()) |
2294 | return LH; |
2295 | |
2296 | // Generate error if there is a problem with the value. |
2297 | if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(), |
2298 | LH->getSemanticSpelling() == |
2299 | LoopHintAttr::Pragma_unroll)) |
2300 | return LH; |
2301 | |
2302 | LoopHintAttr::OptionType Option = LH->getOption(); |
2303 | LoopHintAttr::LoopHintState State = LH->getState(); |
2304 | |
2305 | llvm::APSInt ValueAPS = |
2306 | TransformedExpr->EvaluateKnownConstInt(Ctx: getSema().getASTContext()); |
2307 | // The values of 0 and 1 block any unrolling of the loop. |
2308 | if (ValueAPS.isZero() || ValueAPS.isOne()) { |
2309 | Option = LoopHintAttr::Unroll; |
2310 | State = LoopHintAttr::Disable; |
2311 | } |
2312 | |
2313 | // Create new LoopHintValueAttr with integral expression in place of the |
2314 | // non-type template parameter. |
2315 | return LoopHintAttr::CreateImplicit(getSema().Context, Option, State, |
2316 | TransformedExpr, *LH); |
2317 | } |
2318 | const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr( |
2319 | const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) { |
2320 | if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A)) |
2321 | return nullptr; |
2322 | |
2323 | return A; |
2324 | } |
2325 | const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr( |
2326 | const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) { |
2327 | if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A)) |
2328 | return nullptr; |
2329 | |
2330 | return A; |
2331 | } |
2332 | |
2333 | const CodeAlignAttr * |
2334 | TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) { |
2335 | Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get(); |
2336 | return getSema().BuildCodeAlignAttr(*CA, TransformedExpr); |
2337 | } |
2338 | const OpenACCRoutineDeclAttr * |
2339 | TemplateInstantiator::TransformOpenACCRoutineDeclAttr( |
2340 | const OpenACCRoutineDeclAttr *A) { |
2341 | llvm_unreachable("RoutineDecl should only be a declaration attribute, as it " |
2342 | "applies to a Function Decl (and a few places for VarDecl)"); |
2343 | } |
2344 | |
2345 | ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef( |
2346 | Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm, |
2347 | SourceLocation loc, TemplateArgument arg, UnsignedOrNone PackIndex, |
2348 | bool Final) { |
2349 | ExprResult result; |
2350 | |
2351 | // Determine the substituted parameter type. We can usually infer this from |
2352 | // the template argument, but not always. |
2353 | auto SubstParamType = [&] { |
2354 | QualType T; |
2355 | if (parm->isExpandedParameterPack()) |
2356 | T = parm->getExpansionType(*SemaRef.ArgPackSubstIndex); |
2357 | else |
2358 | T = parm->getType(); |
2359 | if (parm->isParameterPack() && isa<PackExpansionType>(Val: T)) |
2360 | T = cast<PackExpansionType>(Val&: T)->getPattern(); |
2361 | return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName()); |
2362 | }; |
2363 | |
2364 | bool refParam = false; |
2365 | |
2366 | // The template argument itself might be an expression, in which case we just |
2367 | // return that expression. This happens when substituting into an alias |
2368 | // template. |
2369 | if (arg.getKind() == TemplateArgument::Expression) { |
2370 | Expr *argExpr = arg.getAsExpr(); |
2371 | result = argExpr; |
2372 | if (argExpr->isLValue()) { |
2373 | if (argExpr->getType()->isRecordType()) { |
2374 | // Check whether the parameter was actually a reference. |
2375 | QualType paramType = SubstParamType(); |
2376 | if (paramType.isNull()) |
2377 | return ExprError(); |
2378 | refParam = paramType->isReferenceType(); |
2379 | } else { |
2380 | refParam = true; |
2381 | } |
2382 | } |
2383 | } else if (arg.getKind() == TemplateArgument::Declaration || |
2384 | arg.getKind() == TemplateArgument::NullPtr) { |
2385 | if (arg.getKind() == TemplateArgument::Declaration) { |
2386 | ValueDecl *VD = arg.getAsDecl(); |
2387 | |
2388 | // Find the instantiation of the template argument. This is |
2389 | // required for nested templates. |
2390 | VD = cast_or_null<ValueDecl>( |
2391 | getSema().FindInstantiatedDecl(loc, VD, TemplateArgs)); |
2392 | if (!VD) |
2393 | return ExprError(); |
2394 | } |
2395 | |
2396 | QualType paramType = arg.getNonTypeTemplateArgumentType(); |
2397 | assert(!paramType.isNull() && "type substitution failed for param type"); |
2398 | assert(!paramType->isDependentType() && "param type still dependent"); |
2399 | result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc); |
2400 | refParam = paramType->isReferenceType(); |
2401 | } else { |
2402 | QualType paramType = arg.getNonTypeTemplateArgumentType(); |
2403 | result = SemaRef.BuildExpressionFromNonTypeTemplateArgument(arg, loc); |
2404 | refParam = paramType->isReferenceType(); |
2405 | assert(result.isInvalid() || |
2406 | SemaRef.Context.hasSameType(result.get()->getType(), |
2407 | paramType.getNonReferenceType())); |
2408 | } |
2409 | |
2410 | if (result.isInvalid()) |
2411 | return ExprError(); |
2412 | |
2413 | Expr *resultExpr = result.get(); |
2414 | return new (SemaRef.Context) SubstNonTypeTemplateParmExpr( |
2415 | resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr, |
2416 | AssociatedDecl, parm->getIndex(), PackIndex, refParam, Final); |
2417 | } |
2418 | |
2419 | ExprResult |
2420 | TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr( |
2421 | SubstNonTypeTemplateParmPackExpr *E) { |
2422 | if (!getSema().ArgPackSubstIndex) { |
2423 | // We aren't expanding the parameter pack, so just return ourselves. |
2424 | return E; |
2425 | } |
2426 | |
2427 | TemplateArgument Pack = E->getArgumentPack(); |
2428 | TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack); |
2429 | return transformNonTypeTemplateParmRef( |
2430 | AssociatedDecl: E->getAssociatedDecl(), parm: E->getParameterPack(), |
2431 | loc: E->getParameterPackLocation(), arg: Arg, PackIndex: getPackIndex(Pack), Final: E->getFinal()); |
2432 | } |
2433 | |
2434 | ExprResult |
2435 | TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr( |
2436 | SubstNonTypeTemplateParmExpr *E) { |
2437 | ExprResult SubstReplacement = E->getReplacement(); |
2438 | if (!isa<ConstantExpr>(Val: SubstReplacement.get())) |
2439 | SubstReplacement = TransformExpr(E->getReplacement()); |
2440 | if (SubstReplacement.isInvalid()) |
2441 | return true; |
2442 | QualType SubstType = TransformType(E->getParameterType(Ctx: getSema().Context)); |
2443 | if (SubstType.isNull()) |
2444 | return true; |
2445 | // The type may have been previously dependent and not now, which means we |
2446 | // might have to implicit cast the argument to the new type, for example: |
2447 | // template<auto T, decltype(T) U> |
2448 | // concept C = sizeof(U) == 4; |
2449 | // void foo() requires C<2, 'a'> { } |
2450 | // When normalizing foo(), we first form the normalized constraints of C: |
2451 | // AtomicExpr(sizeof(U) == 4, |
2452 | // U=SubstNonTypeTemplateParmExpr(Param=U, |
2453 | // Expr=DeclRef(U), |
2454 | // Type=decltype(T))) |
2455 | // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to |
2456 | // produce: |
2457 | // AtomicExpr(sizeof(U) == 4, |
2458 | // U=SubstNonTypeTemplateParmExpr(Param=U, |
2459 | // Expr=ImpCast( |
2460 | // decltype(2), |
2461 | // SubstNTTPE(Param=U, Expr='a', |
2462 | // Type=char)), |
2463 | // Type=decltype(2))) |
2464 | // The call to CheckTemplateArgument here produces the ImpCast. |
2465 | TemplateArgument SugaredConverted, CanonicalConverted; |
2466 | if (SemaRef |
2467 | .CheckTemplateArgument(E->getParameter(), SubstType, |
2468 | SubstReplacement.get(), SugaredConverted, |
2469 | CanonicalConverted, |
2470 | /*StrictCheck=*/false, Sema::CTAK_Specified) |
2471 | .isInvalid()) |
2472 | return true; |
2473 | return transformNonTypeTemplateParmRef( |
2474 | AssociatedDecl: E->getAssociatedDecl(), parm: E->getParameter(), loc: E->getExprLoc(), |
2475 | arg: SugaredConverted, PackIndex: E->getPackIndex(), Final: E->getFinal()); |
2476 | } |
2477 | |
2478 | ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD, |
2479 | SourceLocation Loc) { |
2480 | DeclarationNameInfo NameInfo(PD->getDeclName(), Loc); |
2481 | return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD); |
2482 | } |
2483 | |
2484 | ExprResult |
2485 | TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) { |
2486 | if (getSema().ArgPackSubstIndex) { |
2487 | // We can expand this parameter pack now. |
2488 | ValueDecl *D = E->getExpansion(I: *getSema().ArgPackSubstIndex); |
2489 | ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(Loc: E->getExprLoc(), D)); |
2490 | if (!VD) |
2491 | return ExprError(); |
2492 | return RebuildVarDeclRefExpr(PD: VD, Loc: E->getExprLoc()); |
2493 | } |
2494 | |
2495 | QualType T = TransformType(E->getType()); |
2496 | if (T.isNull()) |
2497 | return ExprError(); |
2498 | |
2499 | // Transform each of the parameter expansions into the corresponding |
2500 | // parameters in the instantiation of the function decl. |
2501 | SmallVector<ValueDecl *, 8> Vars; |
2502 | Vars.reserve(N: E->getNumExpansions()); |
2503 | for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end(); |
2504 | I != End; ++I) { |
2505 | ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(Loc: E->getExprLoc(), D: *I)); |
2506 | if (!D) |
2507 | return ExprError(); |
2508 | Vars.push_back(Elt: D); |
2509 | } |
2510 | |
2511 | auto *PackExpr = |
2512 | FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: E->getParameterPack(), |
2513 | NameLoc: E->getParameterPackLocation(), Params: Vars); |
2514 | getSema().MarkFunctionParmPackReferenced(PackExpr); |
2515 | return PackExpr; |
2516 | } |
2517 | |
2518 | ExprResult |
2519 | TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E, |
2520 | ValueDecl *PD) { |
2521 | typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; |
2522 | llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found |
2523 | = getSema().CurrentInstantiationScope->findInstantiationOf(PD); |
2524 | assert(Found && "no instantiation for parameter pack"); |
2525 | |
2526 | Decl *TransformedDecl; |
2527 | if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: *Found)) { |
2528 | // If this is a reference to a function parameter pack which we can |
2529 | // substitute but can't yet expand, build a FunctionParmPackExpr for it. |
2530 | if (!getSema().ArgPackSubstIndex) { |
2531 | QualType T = TransformType(E->getType()); |
2532 | if (T.isNull()) |
2533 | return ExprError(); |
2534 | auto *PackExpr = FunctionParmPackExpr::Create(Context: getSema().Context, T, ParamPack: PD, |
2535 | NameLoc: E->getExprLoc(), Params: *Pack); |
2536 | getSema().MarkFunctionParmPackReferenced(PackExpr); |
2537 | return PackExpr; |
2538 | } |
2539 | |
2540 | TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex]; |
2541 | } else { |
2542 | TransformedDecl = cast<Decl *>(Val&: *Found); |
2543 | } |
2544 | |
2545 | // We have either an unexpanded pack or a specific expansion. |
2546 | return RebuildVarDeclRefExpr(PD: cast<ValueDecl>(Val: TransformedDecl), |
2547 | Loc: E->getExprLoc()); |
2548 | } |
2549 | |
2550 | ExprResult |
2551 | TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) { |
2552 | NamedDecl *D = E->getDecl(); |
2553 | |
2554 | // Handle references to non-type template parameters and non-type template |
2555 | // parameter packs. |
2556 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: D)) { |
2557 | if (NTTP->getDepth() < TemplateArgs.getNumLevels()) |
2558 | return TransformTemplateParmRefExpr(E, NTTP); |
2559 | |
2560 | // We have a non-type template parameter that isn't fully substituted; |
2561 | // FindInstantiatedDecl will find it in the local instantiation scope. |
2562 | } |
2563 | |
2564 | // Handle references to function parameter packs. |
2565 | if (VarDecl *PD = dyn_cast<VarDecl>(Val: D)) |
2566 | if (PD->isParameterPack()) |
2567 | return TransformFunctionParmPackRefExpr(E, PD); |
2568 | |
2569 | return inherited::TransformDeclRefExpr(E); |
2570 | } |
2571 | |
2572 | ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr( |
2573 | CXXDefaultArgExpr *E) { |
2574 | assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())-> |
2575 | getDescribedFunctionTemplate() && |
2576 | "Default arg expressions are never formed in dependent cases."); |
2577 | return SemaRef.BuildCXXDefaultArgExpr( |
2578 | E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()), |
2579 | E->getParam()); |
2580 | } |
2581 | |
2582 | template<typename Fn> |
2583 | QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB, |
2584 | FunctionProtoTypeLoc TL, |
2585 | CXXRecordDecl *ThisContext, |
2586 | Qualifiers ThisTypeQuals, |
2587 | Fn TransformExceptionSpec) { |
2588 | // If this is a lambda or block, the transformation MUST be done in the |
2589 | // CurrentInstantiationScope since it introduces a mapping of |
2590 | // the original to the newly created transformed parameters. |
2591 | // |
2592 | // In that case, TemplateInstantiator::TransformLambdaExpr will |
2593 | // have already pushed a scope for this prototype, so don't create |
2594 | // a second one. |
2595 | LocalInstantiationScope *Current = getSema().CurrentInstantiationScope; |
2596 | std::optional<LocalInstantiationScope> Scope; |
2597 | if (!Current || !Current->isLambdaOrBlock()) |
2598 | Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true); |
2599 | |
2600 | return inherited::TransformFunctionProtoType( |
2601 | TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec); |
2602 | } |
2603 | |
2604 | ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam( |
2605 | ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions, |
2606 | bool ExpectParameterPack) { |
2607 | auto NewParm = SemaRef.SubstParmVarDecl( |
2608 | OldParm, TemplateArgs, indexAdjustment, NumExpansions, |
2609 | ExpectParameterPack, EvaluateConstraints); |
2610 | if (NewParm && SemaRef.getLangOpts().OpenCL) |
2611 | SemaRef.deduceOpenCLAddressSpace(NewParm); |
2612 | return NewParm; |
2613 | } |
2614 | |
2615 | QualType TemplateInstantiator::BuildSubstTemplateTypeParmType( |
2616 | TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final, |
2617 | Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex, |
2618 | TemplateArgument Arg, SourceLocation NameLoc) { |
2619 | QualType Replacement = Arg.getAsType(); |
2620 | |
2621 | // If the template parameter had ObjC lifetime qualifiers, |
2622 | // then any such qualifiers on the replacement type are ignored. |
2623 | if (SuppressObjCLifetime) { |
2624 | Qualifiers RQs; |
2625 | RQs = Replacement.getQualifiers(); |
2626 | RQs.removeObjCLifetime(); |
2627 | Replacement = |
2628 | SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs); |
2629 | } |
2630 | |
2631 | // TODO: only do this uniquing once, at the start of instantiation. |
2632 | QualType Result = getSema().Context.getSubstTemplateTypeParmType( |
2633 | Replacement, AssociatedDecl, Index, PackIndex, Final); |
2634 | SubstTemplateTypeParmTypeLoc NewTL = |
2635 | TLB.push<SubstTemplateTypeParmTypeLoc>(T: Result); |
2636 | NewTL.setNameLoc(NameLoc); |
2637 | return Result; |
2638 | } |
2639 | |
2640 | QualType |
2641 | TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB, |
2642 | TemplateTypeParmTypeLoc TL, |
2643 | bool SuppressObjCLifetime) { |
2644 | const TemplateTypeParmType *T = TL.getTypePtr(); |
2645 | if (T->getDepth() < TemplateArgs.getNumLevels()) { |
2646 | // Replace the template type parameter with its corresponding |
2647 | // template argument. |
2648 | |
2649 | // If the corresponding template argument is NULL or doesn't exist, it's |
2650 | // because we are performing instantiation from explicitly-specified |
2651 | // template arguments in a function template class, but there were some |
2652 | // arguments left unspecified. |
2653 | if (!TemplateArgs.hasTemplateArgument(Depth: T->getDepth(), Index: T->getIndex())) { |
2654 | IsIncomplete = true; |
2655 | if (BailOutOnIncomplete) |
2656 | return QualType(); |
2657 | |
2658 | TemplateTypeParmTypeLoc NewTL |
2659 | = TLB.push<TemplateTypeParmTypeLoc>(TL.getType()); |
2660 | NewTL.setNameLoc(TL.getNameLoc()); |
2661 | return TL.getType(); |
2662 | } |
2663 | |
2664 | TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex()); |
2665 | |
2666 | if (TemplateArgs.isRewrite()) { |
2667 | // We're rewriting the template parameter as a reference to another |
2668 | // template parameter. |
2669 | Arg = getTemplateArgumentPackPatternForRewrite(TA: Arg); |
2670 | assert(Arg.getKind() == TemplateArgument::Type && |
2671 | "unexpected nontype template argument kind in template rewrite"); |
2672 | QualType NewT = Arg.getAsType(); |
2673 | TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc()); |
2674 | return NewT; |
2675 | } |
2676 | |
2677 | auto [AssociatedDecl, Final] = |
2678 | TemplateArgs.getAssociatedDecl(Depth: T->getDepth()); |
2679 | UnsignedOrNone PackIndex = std::nullopt; |
2680 | if (T->isParameterPack()) { |
2681 | assert(Arg.getKind() == TemplateArgument::Pack && |
2682 | "Missing argument pack"); |
2683 | |
2684 | if (!getSema().ArgPackSubstIndex) { |
2685 | // We have the template argument pack, but we're not expanding the |
2686 | // enclosing pack expansion yet. Just save the template argument |
2687 | // pack for later substitution. |
2688 | QualType Result = getSema().Context.getSubstTemplateTypeParmPackType( |
2689 | AssociatedDecl, T->getIndex(), Final, Arg); |
2690 | SubstTemplateTypeParmPackTypeLoc NewTL |
2691 | = TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result); |
2692 | NewTL.setNameLoc(TL.getNameLoc()); |
2693 | return Result; |
2694 | } |
2695 | |
2696 | // PackIndex starts from last element. |
2697 | PackIndex = getPackIndex(Pack: Arg); |
2698 | Arg = getPackSubstitutedTemplateArgument(getSema(), Arg); |
2699 | } |
2700 | |
2701 | assert(Arg.getKind() == TemplateArgument::Type && |
2702 | "Template argument kind mismatch"); |
2703 | |
2704 | return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final: Final, |
2705 | AssociatedDecl: AssociatedDecl, Index: T->getIndex(), |
2706 | PackIndex, Arg, NameLoc: TL.getNameLoc()); |
2707 | } |
2708 | |
2709 | // The template type parameter comes from an inner template (e.g., |
2710 | // the template parameter list of a member template inside the |
2711 | // template we are instantiating). Create a new template type |
2712 | // parameter with the template "level" reduced by one. |
2713 | TemplateTypeParmDecl *NewTTPDecl = nullptr; |
2714 | if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl()) |
2715 | NewTTPDecl = cast_or_null<TemplateTypeParmDecl>( |
2716 | TransformDecl(Loc: TL.getNameLoc(), D: OldTTPDecl)); |
2717 | QualType Result = getSema().Context.getTemplateTypeParmType( |
2718 | T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(), |
2719 | T->isParameterPack(), NewTTPDecl); |
2720 | TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(T: Result); |
2721 | NewTL.setNameLoc(TL.getNameLoc()); |
2722 | return Result; |
2723 | } |
2724 | |
2725 | QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType( |
2726 | TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, |
2727 | bool SuppressObjCLifetime) { |
2728 | const SubstTemplateTypeParmPackType *T = TL.getTypePtr(); |
2729 | |
2730 | Decl *NewReplaced = TransformDecl(Loc: TL.getNameLoc(), D: T->getAssociatedDecl()); |
2731 | |
2732 | if (!getSema().ArgPackSubstIndex) { |
2733 | // We aren't expanding the parameter pack, so just return ourselves. |
2734 | QualType Result = TL.getType(); |
2735 | if (NewReplaced != T->getAssociatedDecl()) |
2736 | Result = getSema().Context.getSubstTemplateTypeParmPackType( |
2737 | NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack()); |
2738 | SubstTemplateTypeParmPackTypeLoc NewTL = |
2739 | TLB.push<SubstTemplateTypeParmPackTypeLoc>(T: Result); |
2740 | NewTL.setNameLoc(TL.getNameLoc()); |
2741 | return Result; |
2742 | } |
2743 | |
2744 | TemplateArgument Pack = T->getArgumentPack(); |
2745 | TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack); |
2746 | return BuildSubstTemplateTypeParmType( |
2747 | TLB, SuppressObjCLifetime, Final: T->getFinal(), AssociatedDecl: NewReplaced, Index: T->getIndex(), |
2748 | PackIndex: getPackIndex(Pack), Arg, NameLoc: TL.getNameLoc()); |
2749 | } |
2750 | |
2751 | static concepts::Requirement::SubstitutionDiagnostic * |
2752 | createSubstDiag(Sema &S, TemplateDeductionInfo &Info, |
2753 | Sema::EntityPrinter Printer) { |
2754 | SmallString<128> Message; |
2755 | SourceLocation ErrorLoc; |
2756 | if (Info.hasSFINAEDiagnostic()) { |
2757 | PartialDiagnosticAt PDA(SourceLocation(), |
2758 | PartialDiagnostic::NullDiagnostic{}); |
2759 | Info.takeSFINAEDiagnostic(PD&: PDA); |
2760 | PDA.second.EmitToString(Diags&: S.getDiagnostics(), Buf&: Message); |
2761 | ErrorLoc = PDA.first; |
2762 | } else { |
2763 | ErrorLoc = Info.getLocation(); |
2764 | } |
2765 | SmallString<128> Entity; |
2766 | llvm::raw_svector_ostream OS(Entity); |
2767 | Printer(OS); |
2768 | const ASTContext &C = S.Context; |
2769 | return new (C) concepts::Requirement::SubstitutionDiagnostic{ |
2770 | .SubstitutedEntity: C.backupStr(S: Entity), .DiagLoc: ErrorLoc, .DiagMessage: C.backupStr(S: Message)}; |
2771 | } |
2772 | |
2773 | concepts::Requirement::SubstitutionDiagnostic * |
2774 | Sema::createSubstDiagAt(SourceLocation Location, EntityPrinter Printer) { |
2775 | SmallString<128> Entity; |
2776 | llvm::raw_svector_ostream OS(Entity); |
2777 | Printer(OS); |
2778 | const ASTContext &C = Context; |
2779 | return new (C) concepts::Requirement::SubstitutionDiagnostic{ |
2780 | /*SubstitutedEntity=*/C.backupStr(S: Entity), |
2781 | /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()}; |
2782 | } |
2783 | |
2784 | ExprResult TemplateInstantiator::TransformRequiresTypeParams( |
2785 | SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE, |
2786 | RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params, |
2787 | SmallVectorImpl<QualType> &PTypes, |
2788 | SmallVectorImpl<ParmVarDecl *> &TransParams, |
2789 | Sema::ExtParameterInfoBuilder &PInfos) { |
2790 | |
2791 | TemplateDeductionInfo Info(KWLoc); |
2792 | Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, |
2793 | RE, Info, |
2794 | SourceRange{KWLoc, RBraceLoc}); |
2795 | Sema::SFINAETrap Trap(SemaRef); |
2796 | |
2797 | unsigned ErrorIdx; |
2798 | if (getDerived().TransformFunctionTypeParams( |
2799 | KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes, |
2800 | &TransParams, PInfos, &ErrorIdx) || |
2801 | Trap.hasErrorOccurred()) { |
2802 | SmallVector<concepts::Requirement *, 4> TransReqs; |
2803 | ParmVarDecl *FailedDecl = Params[ErrorIdx]; |
2804 | // Add a 'failed' Requirement to contain the error that caused the failure |
2805 | // here. |
2806 | TransReqs.push_back(RebuildTypeRequirement(createSubstDiag( |
2807 | SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; }))); |
2808 | return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(), |
2809 | TransParams, RE->getRParenLoc(), |
2810 | TransReqs, RBraceLoc); |
2811 | } |
2812 | |
2813 | return ExprResult{}; |
2814 | } |
2815 | |
2816 | concepts::TypeRequirement * |
2817 | TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) { |
2818 | if (!Req->isDependent() && !AlwaysRebuild()) |
2819 | return Req; |
2820 | if (Req->isSubstitutionFailure()) { |
2821 | if (AlwaysRebuild()) |
2822 | return RebuildTypeRequirement( |
2823 | Req->getSubstitutionDiagnostic()); |
2824 | return Req; |
2825 | } |
2826 | |
2827 | Sema::SFINAETrap Trap(SemaRef); |
2828 | TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc()); |
2829 | Sema::InstantiatingTemplate TypeInst(SemaRef, |
2830 | Req->getType()->getTypeLoc().getBeginLoc(), Req, Info, |
2831 | Req->getType()->getTypeLoc().getSourceRange()); |
2832 | if (TypeInst.isInvalid()) |
2833 | return nullptr; |
2834 | TypeSourceInfo *TransType = TransformType(Req->getType()); |
2835 | if (!TransType || Trap.hasErrorOccurred()) |
2836 | return RebuildTypeRequirement(createSubstDiag(SemaRef, Info, |
2837 | [&] (llvm::raw_ostream& OS) { |
2838 | Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy()); |
2839 | })); |
2840 | return RebuildTypeRequirement(TransType); |
2841 | } |
2842 | |
2843 | concepts::ExprRequirement * |
2844 | TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) { |
2845 | if (!Req->isDependent() && !AlwaysRebuild()) |
2846 | return Req; |
2847 | |
2848 | Sema::SFINAETrap Trap(SemaRef); |
2849 | |
2850 | llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> |
2851 | TransExpr; |
2852 | if (Req->isExprSubstitutionFailure()) |
2853 | TransExpr = Req->getExprSubstitutionDiagnostic(); |
2854 | else { |
2855 | Expr *E = Req->getExpr(); |
2856 | TemplateDeductionInfo Info(E->getBeginLoc()); |
2857 | Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info, |
2858 | E->getSourceRange()); |
2859 | if (ExprInst.isInvalid()) |
2860 | return nullptr; |
2861 | ExprResult TransExprRes = TransformExpr(E); |
2862 | if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() && |
2863 | TransExprRes.get()->hasPlaceholderType()) |
2864 | TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get()); |
2865 | if (TransExprRes.isInvalid() || Trap.hasErrorOccurred()) |
2866 | TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) { |
2867 | E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy()); |
2868 | }); |
2869 | else |
2870 | TransExpr = TransExprRes.get(); |
2871 | } |
2872 | |
2873 | std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq; |
2874 | const auto &RetReq = Req->getReturnTypeRequirement(); |
2875 | if (RetReq.isEmpty()) |
2876 | TransRetReq.emplace(); |
2877 | else if (RetReq.isSubstitutionFailure()) |
2878 | TransRetReq.emplace(args: RetReq.getSubstitutionDiagnostic()); |
2879 | else if (RetReq.isTypeConstraint()) { |
2880 | TemplateParameterList *OrigTPL = |
2881 | RetReq.getTypeConstraintTemplateParameterList(); |
2882 | TemplateDeductionInfo Info(OrigTPL->getTemplateLoc()); |
2883 | Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), |
2884 | Req, Info, OrigTPL->getSourceRange()); |
2885 | if (TPLInst.isInvalid()) |
2886 | return nullptr; |
2887 | TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL); |
2888 | if (!TPL || Trap.hasErrorOccurred()) |
2889 | TransRetReq.emplace(createSubstDiag(SemaRef, Info, |
2890 | [&] (llvm::raw_ostream& OS) { |
2891 | RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint() |
2892 | ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy()); |
2893 | })); |
2894 | else { |
2895 | TPLInst.Clear(); |
2896 | TransRetReq.emplace(args&: TPL); |
2897 | } |
2898 | } |
2899 | assert(TransRetReq && "All code paths leading here must set TransRetReq"); |
2900 | if (Expr *E = TransExpr.dyn_cast<Expr *>()) |
2901 | return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(), |
2902 | std::move(*TransRetReq)); |
2903 | return RebuildExprRequirement( |
2904 | cast<concepts::Requirement::SubstitutionDiagnostic *>(Val&: TransExpr), |
2905 | Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq)); |
2906 | } |
2907 | |
2908 | concepts::NestedRequirement * |
2909 | TemplateInstantiator::TransformNestedRequirement( |
2910 | concepts::NestedRequirement *Req) { |
2911 | if (!Req->isDependent() && !AlwaysRebuild()) |
2912 | return Req; |
2913 | if (Req->hasInvalidConstraint()) { |
2914 | if (AlwaysRebuild()) |
2915 | return RebuildNestedRequirement(Req->getInvalidConstraintEntity(), |
2916 | Req->getConstraintSatisfaction()); |
2917 | return Req; |
2918 | } |
2919 | Sema::InstantiatingTemplate ReqInst(SemaRef, |
2920 | Req->getConstraintExpr()->getBeginLoc(), Req, |
2921 | Sema::InstantiatingTemplate::ConstraintsCheck{}, |
2922 | Req->getConstraintExpr()->getSourceRange()); |
2923 | if (!getEvaluateConstraints()) { |
2924 | ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr()); |
2925 | if (TransConstraint.isInvalid() || !TransConstraint.get()) |
2926 | return nullptr; |
2927 | if (TransConstraint.get()->isInstantiationDependent()) |
2928 | return new (SemaRef.Context) |
2929 | concepts::NestedRequirement(TransConstraint.get()); |
2930 | ConstraintSatisfaction Satisfaction; |
2931 | return new (SemaRef.Context) concepts::NestedRequirement( |
2932 | SemaRef.Context, TransConstraint.get(), Satisfaction); |
2933 | } |
2934 | |
2935 | ExprResult TransConstraint; |
2936 | ConstraintSatisfaction Satisfaction; |
2937 | TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc()); |
2938 | { |
2939 | EnterExpressionEvaluationContext ContextRAII( |
2940 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
2941 | Sema::SFINAETrap Trap(SemaRef); |
2942 | Sema::InstantiatingTemplate ConstrInst(SemaRef, |
2943 | Req->getConstraintExpr()->getBeginLoc(), Req, Info, |
2944 | Req->getConstraintExpr()->getSourceRange()); |
2945 | if (ConstrInst.isInvalid()) |
2946 | return nullptr; |
2947 | llvm::SmallVector<Expr *> Result; |
2948 | if (!SemaRef.CheckConstraintSatisfaction( |
2949 | nullptr, |
2950 | AssociatedConstraint(Req->getConstraintExpr(), |
2951 | SemaRef.ArgPackSubstIndex), |
2952 | Result, TemplateArgs, Req->getConstraintExpr()->getSourceRange(), |
2953 | Satisfaction) && |
2954 | !Result.empty()) |
2955 | TransConstraint = Result[0]; |
2956 | assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled " |
2957 | "by CheckConstraintSatisfaction."); |
2958 | } |
2959 | ASTContext &C = SemaRef.Context; |
2960 | if (TransConstraint.isUsable() && |
2961 | TransConstraint.get()->isInstantiationDependent()) |
2962 | return new (C) concepts::NestedRequirement(TransConstraint.get()); |
2963 | if (TransConstraint.isInvalid() || !TransConstraint.get() || |
2964 | Satisfaction.HasSubstitutionFailure()) { |
2965 | SmallString<128> Entity; |
2966 | llvm::raw_svector_ostream OS(Entity); |
2967 | Req->getConstraintExpr()->printPretty(OS, nullptr, |
2968 | SemaRef.getPrintingPolicy()); |
2969 | return new (C) concepts::NestedRequirement( |
2970 | SemaRef.Context, C.backupStr(Entity), Satisfaction); |
2971 | } |
2972 | return new (C) |
2973 | concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction); |
2974 | } |
2975 | |
2976 | TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T, |
2977 | const MultiLevelTemplateArgumentList &Args, |
2978 | SourceLocation Loc, |
2979 | DeclarationName Entity, |
2980 | bool AllowDeducedTST) { |
2981 | assert(!CodeSynthesisContexts.empty() && |
2982 | "Cannot perform an instantiation without some context on the " |
2983 | "instantiation stack"); |
2984 | |
2985 | if (!T->getType()->isInstantiationDependentType() && |
2986 | !T->getType()->isVariablyModifiedType()) |
2987 | return T; |
2988 | |
2989 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
2990 | return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T) |
2991 | : Instantiator.TransformType(T); |
2992 | } |
2993 | |
2994 | TypeSourceInfo *Sema::SubstType(TypeLoc TL, |
2995 | const MultiLevelTemplateArgumentList &Args, |
2996 | SourceLocation Loc, |
2997 | DeclarationName Entity) { |
2998 | assert(!CodeSynthesisContexts.empty() && |
2999 | "Cannot perform an instantiation without some context on the " |
3000 | "instantiation stack"); |
3001 | |
3002 | if (TL.getType().isNull()) |
3003 | return nullptr; |
3004 | |
3005 | if (!TL.getType()->isInstantiationDependentType() && |
3006 | !TL.getType()->isVariablyModifiedType()) { |
3007 | // FIXME: Make a copy of the TypeLoc data here, so that we can |
3008 | // return a new TypeSourceInfo. Inefficient! |
3009 | TypeLocBuilder TLB; |
3010 | TLB.pushFullCopy(L: TL); |
3011 | return TLB.getTypeSourceInfo(Context, T: TL.getType()); |
3012 | } |
3013 | |
3014 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
3015 | TypeLocBuilder TLB; |
3016 | TLB.reserve(Requested: TL.getFullDataSize()); |
3017 | QualType Result = Instantiator.TransformType(TLB, TL); |
3018 | if (Result.isNull()) |
3019 | return nullptr; |
3020 | |
3021 | return TLB.getTypeSourceInfo(Context, T: Result); |
3022 | } |
3023 | |
3024 | /// Deprecated form of the above. |
3025 | QualType Sema::SubstType(QualType T, |
3026 | const MultiLevelTemplateArgumentList &TemplateArgs, |
3027 | SourceLocation Loc, DeclarationName Entity, |
3028 | bool *IsIncompleteSubstitution) { |
3029 | assert(!CodeSynthesisContexts.empty() && |
3030 | "Cannot perform an instantiation without some context on the " |
3031 | "instantiation stack"); |
3032 | |
3033 | // If T is not a dependent type or a variably-modified type, there |
3034 | // is nothing to do. |
3035 | if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType()) |
3036 | return T; |
3037 | |
3038 | TemplateInstantiator Instantiator( |
3039 | *this, TemplateArgs, Loc, Entity, |
3040 | /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr); |
3041 | QualType QT = Instantiator.TransformType(T); |
3042 | if (IsIncompleteSubstitution && Instantiator.getIsIncomplete()) |
3043 | *IsIncompleteSubstitution = true; |
3044 | return QT; |
3045 | } |
3046 | |
3047 | static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) { |
3048 | if (T->getType()->isInstantiationDependentType() || |
3049 | T->getType()->isVariablyModifiedType()) |
3050 | return true; |
3051 | |
3052 | TypeLoc TL = T->getTypeLoc().IgnoreParens(); |
3053 | if (!TL.getAs<FunctionProtoTypeLoc>()) |
3054 | return false; |
3055 | |
3056 | FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>(); |
3057 | for (ParmVarDecl *P : FP.getParams()) { |
3058 | // This must be synthesized from a typedef. |
3059 | if (!P) continue; |
3060 | |
3061 | // If there are any parameters, a new TypeSourceInfo that refers to the |
3062 | // instantiated parameters must be built. |
3063 | return true; |
3064 | } |
3065 | |
3066 | return false; |
3067 | } |
3068 | |
3069 | TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T, |
3070 | const MultiLevelTemplateArgumentList &Args, |
3071 | SourceLocation Loc, |
3072 | DeclarationName Entity, |
3073 | CXXRecordDecl *ThisContext, |
3074 | Qualifiers ThisTypeQuals, |
3075 | bool EvaluateConstraints) { |
3076 | assert(!CodeSynthesisContexts.empty() && |
3077 | "Cannot perform an instantiation without some context on the " |
3078 | "instantiation stack"); |
3079 | |
3080 | if (!NeedsInstantiationAsFunctionType(T)) |
3081 | return T; |
3082 | |
3083 | TemplateInstantiator Instantiator(*this, Args, Loc, Entity); |
3084 | Instantiator.setEvaluateConstraints(EvaluateConstraints); |
3085 | |
3086 | TypeLocBuilder TLB; |
3087 | |
3088 | TypeLoc TL = T->getTypeLoc(); |
3089 | TLB.reserve(Requested: TL.getFullDataSize()); |
3090 | |
3091 | QualType Result; |
3092 | |
3093 | if (FunctionProtoTypeLoc Proto = |
3094 | TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) { |
3095 | // Instantiate the type, other than its exception specification. The |
3096 | // exception specification is instantiated in InitFunctionInstantiation |
3097 | // once we've built the FunctionDecl. |
3098 | // FIXME: Set the exception specification to EST_Uninstantiated here, |
3099 | // instead of rebuilding the function type again later. |
3100 | Result = Instantiator.TransformFunctionProtoType( |
3101 | TLB, TL: Proto, ThisContext, ThisTypeQuals, |
3102 | TransformExceptionSpec: [](FunctionProtoType::ExceptionSpecInfo &ESI, |
3103 | bool &Changed) { return false; }); |
3104 | } else { |
3105 | Result = Instantiator.TransformType(TLB, TL); |
3106 | } |
3107 | // When there are errors resolving types, clang may use IntTy as a fallback, |
3108 | // breaking our assumption that function declarations have function types. |
3109 | if (Result.isNull() || !Result->isFunctionType()) |
3110 | return nullptr; |
3111 | |
3112 | return TLB.getTypeSourceInfo(Context, T: Result); |
3113 | } |
3114 | |
3115 | bool Sema::SubstExceptionSpec(SourceLocation Loc, |
3116 | FunctionProtoType::ExceptionSpecInfo &ESI, |
3117 | SmallVectorImpl<QualType> &ExceptionStorage, |
3118 | const MultiLevelTemplateArgumentList &Args) { |
3119 | bool Changed = false; |
3120 | TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName()); |
3121 | return Instantiator.TransformExceptionSpec(Loc, ESI, Exceptions&: ExceptionStorage, |
3122 | Changed); |
3123 | } |
3124 | |
3125 | void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, |
3126 | const MultiLevelTemplateArgumentList &Args) { |
3127 | FunctionProtoType::ExceptionSpecInfo ESI = |
3128 | Proto->getExtProtoInfo().ExceptionSpec; |
3129 | |
3130 | SmallVector<QualType, 4> ExceptionStorage; |
3131 | if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(), |
3132 | ESI, ExceptionStorage, Args)) |
3133 | // On error, recover by dropping the exception specification. |
3134 | ESI.Type = EST_None; |
3135 | |
3136 | UpdateExceptionSpec(FD: New, ESI); |
3137 | } |
3138 | |
3139 | namespace { |
3140 | |
3141 | struct GetContainedInventedTypeParmVisitor : |
3142 | public TypeVisitor<GetContainedInventedTypeParmVisitor, |
3143 | TemplateTypeParmDecl *> { |
3144 | using TypeVisitor<GetContainedInventedTypeParmVisitor, |
3145 | TemplateTypeParmDecl *>::Visit; |
3146 | |
3147 | TemplateTypeParmDecl *Visit(QualType T) { |
3148 | if (T.isNull()) |
3149 | return nullptr; |
3150 | return Visit(T: T.getTypePtr()); |
3151 | } |
3152 | // The deduced type itself. |
3153 | TemplateTypeParmDecl *VisitTemplateTypeParmType( |
3154 | const TemplateTypeParmType *T) { |
3155 | if (!T->getDecl() || !T->getDecl()->isImplicit()) |
3156 | return nullptr; |
3157 | return T->getDecl(); |
3158 | } |
3159 | |
3160 | // Only these types can contain 'auto' types, and subsequently be replaced |
3161 | // by references to invented parameters. |
3162 | |
3163 | TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) { |
3164 | return Visit(T: T->getNamedType()); |
3165 | } |
3166 | |
3167 | TemplateTypeParmDecl *VisitPointerType(const PointerType *T) { |
3168 | return Visit(T: T->getPointeeType()); |
3169 | } |
3170 | |
3171 | TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) { |
3172 | return Visit(T: T->getPointeeType()); |
3173 | } |
3174 | |
3175 | TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) { |
3176 | return Visit(T: T->getPointeeTypeAsWritten()); |
3177 | } |
3178 | |
3179 | TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) { |
3180 | return Visit(T: T->getPointeeType()); |
3181 | } |
3182 | |
3183 | TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) { |
3184 | return Visit(T: T->getElementType()); |
3185 | } |
3186 | |
3187 | TemplateTypeParmDecl *VisitDependentSizedExtVectorType( |
3188 | const DependentSizedExtVectorType *T) { |
3189 | return Visit(T: T->getElementType()); |
3190 | } |
3191 | |
3192 | TemplateTypeParmDecl *VisitVectorType(const VectorType *T) { |
3193 | return Visit(T: T->getElementType()); |
3194 | } |
3195 | |
3196 | TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) { |
3197 | return VisitFunctionType(T); |
3198 | } |
3199 | |
3200 | TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) { |
3201 | return Visit(T: T->getReturnType()); |
3202 | } |
3203 | |
3204 | TemplateTypeParmDecl *VisitParenType(const ParenType *T) { |
3205 | return Visit(T: T->getInnerType()); |
3206 | } |
3207 | |
3208 | TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) { |
3209 | return Visit(T: T->getModifiedType()); |
3210 | } |
3211 | |
3212 | TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) { |
3213 | return Visit(T: T->getUnderlyingType()); |
3214 | } |
3215 | |
3216 | TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) { |
3217 | return Visit(T: T->getOriginalType()); |
3218 | } |
3219 | |
3220 | TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) { |
3221 | return Visit(T: T->getPattern()); |
3222 | } |
3223 | }; |
3224 | |
3225 | } // namespace |
3226 | |
3227 | bool Sema::SubstTypeConstraint( |
3228 | TemplateTypeParmDecl *Inst, const TypeConstraint *TC, |
3229 | const MultiLevelTemplateArgumentList &TemplateArgs, |
3230 | bool EvaluateConstraints) { |
3231 | const ASTTemplateArgumentListInfo *TemplArgInfo = |
3232 | TC->getTemplateArgsAsWritten(); |
3233 | |
3234 | if (!EvaluateConstraints) { |
3235 | UnsignedOrNone Index = TC->getArgPackSubstIndex(); |
3236 | if (!Index) |
3237 | Index = SemaRef.ArgPackSubstIndex; |
3238 | Inst->setTypeConstraint(CR: TC->getConceptReference(), |
3239 | ImmediatelyDeclaredConstraint: TC->getImmediatelyDeclaredConstraint(), ArgPackSubstIndex: Index); |
3240 | return false; |
3241 | } |
3242 | |
3243 | TemplateArgumentListInfo InstArgs; |
3244 | |
3245 | if (TemplArgInfo) { |
3246 | InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc); |
3247 | InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc); |
3248 | if (SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs, |
3249 | Outputs&: InstArgs)) |
3250 | return true; |
3251 | } |
3252 | return AttachTypeConstraint( |
3253 | NS: TC->getNestedNameSpecifierLoc(), NameInfo: TC->getConceptNameInfo(), |
3254 | NamedConcept: TC->getNamedConcept(), |
3255 | /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), TemplateArgs: &InstArgs, ConstrainedParameter: Inst, |
3256 | EllipsisLoc: Inst->isParameterPack() |
3257 | ? cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint()) |
3258 | ->getEllipsisLoc() |
3259 | : SourceLocation()); |
3260 | } |
3261 | |
3262 | ParmVarDecl * |
3263 | Sema::SubstParmVarDecl(ParmVarDecl *OldParm, |
3264 | const MultiLevelTemplateArgumentList &TemplateArgs, |
3265 | int indexAdjustment, UnsignedOrNone NumExpansions, |
3266 | bool ExpectParameterPack, bool EvaluateConstraint) { |
3267 | TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo(); |
3268 | TypeSourceInfo *NewDI = nullptr; |
3269 | |
3270 | TypeLoc OldTL = OldDI->getTypeLoc(); |
3271 | if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) { |
3272 | |
3273 | // We have a function parameter pack. Substitute into the pattern of the |
3274 | // expansion. |
3275 | NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs, |
3276 | OldParm->getLocation(), OldParm->getDeclName()); |
3277 | if (!NewDI) |
3278 | return nullptr; |
3279 | |
3280 | if (NewDI->getType()->containsUnexpandedParameterPack()) { |
3281 | // We still have unexpanded parameter packs, which means that |
3282 | // our function parameter is still a function parameter pack. |
3283 | // Therefore, make its type a pack expansion type. |
3284 | NewDI = CheckPackExpansion(Pattern: NewDI, EllipsisLoc: ExpansionTL.getEllipsisLoc(), |
3285 | NumExpansions); |
3286 | } else if (ExpectParameterPack) { |
3287 | // We expected to get a parameter pack but didn't (because the type |
3288 | // itself is not a pack expansion type), so complain. This can occur when |
3289 | // the substitution goes through an alias template that "loses" the |
3290 | // pack expansion. |
3291 | Diag(OldParm->getLocation(), |
3292 | diag::err_function_parameter_pack_without_parameter_packs) |
3293 | << NewDI->getType(); |
3294 | return nullptr; |
3295 | } |
3296 | } else { |
3297 | NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(), |
3298 | OldParm->getDeclName()); |
3299 | } |
3300 | |
3301 | if (!NewDI) |
3302 | return nullptr; |
3303 | |
3304 | if (NewDI->getType()->isVoidType()) { |
3305 | Diag(OldParm->getLocation(), diag::err_param_with_void_type); |
3306 | return nullptr; |
3307 | } |
3308 | |
3309 | // In abbreviated templates, TemplateTypeParmDecls with possible |
3310 | // TypeConstraints are created when the parameter list is originally parsed. |
3311 | // The TypeConstraints can therefore reference other functions parameters in |
3312 | // the abbreviated function template, which is why we must instantiate them |
3313 | // here, when the instantiated versions of those referenced parameters are in |
3314 | // scope. |
3315 | if (TemplateTypeParmDecl *TTP = |
3316 | GetContainedInventedTypeParmVisitor().Visit(T: OldDI->getType())) { |
3317 | if (const TypeConstraint *TC = TTP->getTypeConstraint()) { |
3318 | auto *Inst = cast_or_null<TemplateTypeParmDecl>( |
3319 | FindInstantiatedDecl(Loc: TTP->getLocation(), D: TTP, TemplateArgs)); |
3320 | // We will first get here when instantiating the abbreviated function |
3321 | // template's described function, but we might also get here later. |
3322 | // Make sure we do not instantiate the TypeConstraint more than once. |
3323 | if (Inst && !Inst->getTypeConstraint()) { |
3324 | if (SubstTypeConstraint(Inst: Inst, TC, TemplateArgs, EvaluateConstraints: EvaluateConstraint)) |
3325 | return nullptr; |
3326 | } |
3327 | } |
3328 | } |
3329 | |
3330 | ParmVarDecl *NewParm = CheckParameter(DC: Context.getTranslationUnitDecl(), |
3331 | StartLoc: OldParm->getInnerLocStart(), |
3332 | NameLoc: OldParm->getLocation(), |
3333 | Name: OldParm->getIdentifier(), |
3334 | T: NewDI->getType(), TSInfo: NewDI, |
3335 | SC: OldParm->getStorageClass()); |
3336 | if (!NewParm) |
3337 | return nullptr; |
3338 | |
3339 | // Mark the (new) default argument as uninstantiated (if any). |
3340 | if (OldParm->hasUninstantiatedDefaultArg()) { |
3341 | Expr *Arg = OldParm->getUninstantiatedDefaultArg(); |
3342 | NewParm->setUninstantiatedDefaultArg(Arg); |
3343 | } else if (OldParm->hasUnparsedDefaultArg()) { |
3344 | NewParm->setUnparsedDefaultArg(); |
3345 | UnparsedDefaultArgInstantiations[OldParm].push_back(NewVal: NewParm); |
3346 | } else if (Expr *Arg = OldParm->getDefaultArg()) { |
3347 | // Default arguments cannot be substituted until the declaration context |
3348 | // for the associated function or lambda capture class is available. |
3349 | // This is necessary for cases like the following where construction of |
3350 | // the lambda capture class for the outer lambda is dependent on the |
3351 | // parameter types but where the default argument is dependent on the |
3352 | // outer lambda's declaration context. |
3353 | // template <typename T> |
3354 | // auto f() { |
3355 | // return [](T = []{ return T{}; }()) { return 0; }; |
3356 | // } |
3357 | NewParm->setUninstantiatedDefaultArg(Arg); |
3358 | } |
3359 | |
3360 | NewParm->setExplicitObjectParameterLoc( |
3361 | OldParm->getExplicitObjectParamThisLoc()); |
3362 | NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg()); |
3363 | |
3364 | if (OldParm->isParameterPack() && !NewParm->isParameterPack()) { |
3365 | // Add the new parameter to the instantiated parameter pack. |
3366 | CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm); |
3367 | } else { |
3368 | // Introduce an Old -> New mapping |
3369 | CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm); |
3370 | } |
3371 | |
3372 | // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext |
3373 | // can be anything, is this right ? |
3374 | NewParm->setDeclContext(CurContext); |
3375 | |
3376 | NewParm->setScopeInfo(scopeDepth: OldParm->getFunctionScopeDepth(), |
3377 | parameterIndex: OldParm->getFunctionScopeIndex() + indexAdjustment); |
3378 | |
3379 | InstantiateAttrs(TemplateArgs, OldParm, NewParm); |
3380 | |
3381 | return NewParm; |
3382 | } |
3383 | |
3384 | bool Sema::SubstParmTypes( |
3385 | SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, |
3386 | const FunctionProtoType::ExtParameterInfo *ExtParamInfos, |
3387 | const MultiLevelTemplateArgumentList &TemplateArgs, |
3388 | SmallVectorImpl<QualType> &ParamTypes, |
3389 | SmallVectorImpl<ParmVarDecl *> *OutParams, |
3390 | ExtParameterInfoBuilder &ParamInfos) { |
3391 | assert(!CodeSynthesisContexts.empty() && |
3392 | "Cannot perform an instantiation without some context on the " |
3393 | "instantiation stack"); |
3394 | |
3395 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, |
3396 | DeclarationName()); |
3397 | return Instantiator.TransformFunctionTypeParams( |
3398 | Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos); |
3399 | } |
3400 | |
3401 | bool Sema::SubstDefaultArgument( |
3402 | SourceLocation Loc, |
3403 | ParmVarDecl *Param, |
3404 | const MultiLevelTemplateArgumentList &TemplateArgs, |
3405 | bool ForCallExpr) { |
3406 | FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext()); |
3407 | Expr *PatternExpr = Param->getUninstantiatedDefaultArg(); |
3408 | |
3409 | EnterExpressionEvaluationContext EvalContext( |
3410 | *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param); |
3411 | |
3412 | InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost()); |
3413 | if (Inst.isInvalid()) |
3414 | return true; |
3415 | if (Inst.isAlreadyInstantiating()) { |
3416 | Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD; |
3417 | Param->setInvalidDecl(); |
3418 | return true; |
3419 | } |
3420 | |
3421 | ExprResult Result; |
3422 | // C++ [dcl.fct.default]p5: |
3423 | // The names in the [default argument] expression are bound, and |
3424 | // the semantic constraints are checked, at the point where the |
3425 | // default argument expression appears. |
3426 | ContextRAII SavedContext(*this, FD); |
3427 | { |
3428 | std::optional<LocalInstantiationScope> LIS; |
3429 | |
3430 | if (ForCallExpr) { |
3431 | // When instantiating a default argument due to use in a call expression, |
3432 | // an instantiation scope that includes the parameters of the callee is |
3433 | // required to satisfy references from the default argument. For example: |
3434 | // template<typename T> void f(T a, int = decltype(a)()); |
3435 | // void g() { f(0); } |
3436 | LIS.emplace(args&: *this); |
3437 | FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern( |
3438 | /*ForDefinition*/ false); |
3439 | if (addInstantiatedParametersToScope(Function: FD, PatternDecl: PatternFD, Scope&: *LIS, TemplateArgs)) |
3440 | return true; |
3441 | } |
3442 | |
3443 | runWithSufficientStackSpace(Loc, Fn: [&] { |
3444 | Result = SubstInitializer(E: PatternExpr, TemplateArgs, |
3445 | /*DirectInit*/ CXXDirectInit: false); |
3446 | }); |
3447 | } |
3448 | if (Result.isInvalid()) |
3449 | return true; |
3450 | |
3451 | if (ForCallExpr) { |
3452 | // Check the expression as an initializer for the parameter. |
3453 | InitializedEntity Entity |
3454 | = InitializedEntity::InitializeParameter(Context, Parm: Param); |
3455 | InitializationKind Kind = InitializationKind::CreateCopy( |
3456 | InitLoc: Param->getLocation(), |
3457 | /*FIXME:EqualLoc*/ EqualLoc: PatternExpr->getBeginLoc()); |
3458 | Expr *ResultE = Result.getAs<Expr>(); |
3459 | |
3460 | InitializationSequence InitSeq(*this, Entity, Kind, ResultE); |
3461 | Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: ResultE); |
3462 | if (Result.isInvalid()) |
3463 | return true; |
3464 | |
3465 | Result = |
3466 | ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(), |
3467 | /*DiscardedValue*/ false); |
3468 | } else { |
3469 | // FIXME: Obtain the source location for the '=' token. |
3470 | SourceLocation EqualLoc = PatternExpr->getBeginLoc(); |
3471 | Result = ConvertParamDefaultArgument(Param, DefaultArg: Result.getAs<Expr>(), EqualLoc); |
3472 | } |
3473 | if (Result.isInvalid()) |
3474 | return true; |
3475 | |
3476 | // Remember the instantiated default argument. |
3477 | Param->setDefaultArg(Result.getAs<Expr>()); |
3478 | |
3479 | return false; |
3480 | } |
3481 | |
3482 | bool |
3483 | Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation, |
3484 | CXXRecordDecl *Pattern, |
3485 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
3486 | bool Invalid = false; |
3487 | SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases; |
3488 | for (const auto &Base : Pattern->bases()) { |
3489 | if (!Base.getType()->isDependentType()) { |
3490 | if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) { |
3491 | if (RD->isInvalidDecl()) |
3492 | Instantiation->setInvalidDecl(); |
3493 | } |
3494 | InstantiatedBases.push_back(Elt: new (Context) CXXBaseSpecifier(Base)); |
3495 | continue; |
3496 | } |
3497 | |
3498 | SourceLocation EllipsisLoc; |
3499 | TypeSourceInfo *BaseTypeLoc; |
3500 | if (Base.isPackExpansion()) { |
3501 | // This is a pack expansion. See whether we should expand it now, or |
3502 | // wait until later. |
3503 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
3504 | collectUnexpandedParameterPacks(TL: Base.getTypeSourceInfo()->getTypeLoc(), |
3505 | Unexpanded); |
3506 | bool ShouldExpand = false; |
3507 | bool RetainExpansion = false; |
3508 | UnsignedOrNone NumExpansions = std::nullopt; |
3509 | if (CheckParameterPacksForExpansion(EllipsisLoc: Base.getEllipsisLoc(), |
3510 | PatternRange: Base.getSourceRange(), |
3511 | Unexpanded, |
3512 | TemplateArgs, ShouldExpand, |
3513 | RetainExpansion, |
3514 | NumExpansions)) { |
3515 | Invalid = true; |
3516 | continue; |
3517 | } |
3518 | |
3519 | // If we should expand this pack expansion now, do so. |
3520 | if (ShouldExpand) { |
3521 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
3522 | Sema::ArgPackSubstIndexRAII SubstIndex(*this, I); |
3523 | |
3524 | TypeSourceInfo *BaseTypeLoc = SubstType(T: Base.getTypeSourceInfo(), |
3525 | Args: TemplateArgs, |
3526 | Loc: Base.getSourceRange().getBegin(), |
3527 | Entity: DeclarationName()); |
3528 | if (!BaseTypeLoc) { |
3529 | Invalid = true; |
3530 | continue; |
3531 | } |
3532 | |
3533 | if (CXXBaseSpecifier *InstantiatedBase |
3534 | = CheckBaseSpecifier(Class: Instantiation, |
3535 | SpecifierRange: Base.getSourceRange(), |
3536 | Virtual: Base.isVirtual(), |
3537 | Access: Base.getAccessSpecifierAsWritten(), |
3538 | TInfo: BaseTypeLoc, |
3539 | EllipsisLoc: SourceLocation())) |
3540 | InstantiatedBases.push_back(Elt: InstantiatedBase); |
3541 | else |
3542 | Invalid = true; |
3543 | } |
3544 | |
3545 | continue; |
3546 | } |
3547 | |
3548 | // The resulting base specifier will (still) be a pack expansion. |
3549 | EllipsisLoc = Base.getEllipsisLoc(); |
3550 | Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt); |
3551 | BaseTypeLoc = SubstType(T: Base.getTypeSourceInfo(), |
3552 | Args: TemplateArgs, |
3553 | Loc: Base.getSourceRange().getBegin(), |
3554 | Entity: DeclarationName()); |
3555 | } else { |
3556 | BaseTypeLoc = SubstType(T: Base.getTypeSourceInfo(), |
3557 | Args: TemplateArgs, |
3558 | Loc: Base.getSourceRange().getBegin(), |
3559 | Entity: DeclarationName()); |
3560 | } |
3561 | |
3562 | if (!BaseTypeLoc) { |
3563 | Invalid = true; |
3564 | continue; |
3565 | } |
3566 | |
3567 | if (CXXBaseSpecifier *InstantiatedBase |
3568 | = CheckBaseSpecifier(Class: Instantiation, |
3569 | SpecifierRange: Base.getSourceRange(), |
3570 | Virtual: Base.isVirtual(), |
3571 | Access: Base.getAccessSpecifierAsWritten(), |
3572 | TInfo: BaseTypeLoc, |
3573 | EllipsisLoc)) |
3574 | InstantiatedBases.push_back(Elt: InstantiatedBase); |
3575 | else |
3576 | Invalid = true; |
3577 | } |
3578 | |
3579 | if (!Invalid && AttachBaseSpecifiers(Class: Instantiation, Bases: InstantiatedBases)) |
3580 | Invalid = true; |
3581 | |
3582 | return Invalid; |
3583 | } |
3584 | |
3585 | // Defined via #include from SemaTemplateInstantiateDecl.cpp |
3586 | namespace clang { |
3587 | namespace sema { |
3588 | Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, |
3589 | const MultiLevelTemplateArgumentList &TemplateArgs); |
3590 | Attr *instantiateTemplateAttributeForDecl( |
3591 | const Attr *At, ASTContext &C, Sema &S, |
3592 | const MultiLevelTemplateArgumentList &TemplateArgs); |
3593 | } |
3594 | } |
3595 | |
3596 | bool |
3597 | Sema::InstantiateClass(SourceLocation PointOfInstantiation, |
3598 | CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, |
3599 | const MultiLevelTemplateArgumentList &TemplateArgs, |
3600 | TemplateSpecializationKind TSK, |
3601 | bool Complain) { |
3602 | CXXRecordDecl *PatternDef |
3603 | = cast_or_null<CXXRecordDecl>(Val: Pattern->getDefinition()); |
3604 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, |
3605 | Instantiation->getInstantiatedFromMemberClass(), |
3606 | Pattern, PatternDef, TSK, Complain)) |
3607 | return true; |
3608 | |
3609 | llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() { |
3610 | llvm::TimeTraceMetadata M; |
3611 | llvm::raw_string_ostream OS(M.Detail); |
3612 | Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(), |
3613 | /*Qualified=*/true); |
3614 | if (llvm::isTimeTraceVerbose()) { |
3615 | auto Loc = SourceMgr.getExpansionLoc(Loc: Instantiation->getLocation()); |
3616 | M.File = SourceMgr.getFilename(SpellingLoc: Loc); |
3617 | M.Line = SourceMgr.getExpansionLineNumber(Loc: Loc); |
3618 | } |
3619 | return M; |
3620 | }); |
3621 | |
3622 | Pattern = PatternDef; |
3623 | |
3624 | // Record the point of instantiation. |
3625 | if (MemberSpecializationInfo *MSInfo |
3626 | = Instantiation->getMemberSpecializationInfo()) { |
3627 | MSInfo->setTemplateSpecializationKind(TSK); |
3628 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
3629 | } else if (ClassTemplateSpecializationDecl *Spec |
3630 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: Instantiation)) { |
3631 | Spec->setTemplateSpecializationKind(TSK); |
3632 | Spec->setPointOfInstantiation(PointOfInstantiation); |
3633 | } |
3634 | |
3635 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
3636 | if (Inst.isInvalid()) |
3637 | return true; |
3638 | assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller"); |
3639 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
3640 | "instantiating class definition"); |
3641 | |
3642 | // Enter the scope of this instantiation. We don't use |
3643 | // PushDeclContext because we don't have a scope. |
3644 | ContextRAII SavedContext(*this, Instantiation); |
3645 | EnterExpressionEvaluationContext EvalContext( |
3646 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
3647 | |
3648 | // If this is an instantiation of a local class, merge this local |
3649 | // instantiation scope with the enclosing scope. Otherwise, every |
3650 | // instantiation of a class has its own local instantiation scope. |
3651 | bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod(); |
3652 | LocalInstantiationScope Scope(*this, MergeWithParentScope); |
3653 | |
3654 | // Some class state isn't processed immediately but delayed till class |
3655 | // instantiation completes. We may not be ready to handle any delayed state |
3656 | // already on the stack as it might correspond to a different class, so save |
3657 | // it now and put it back later. |
3658 | SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this); |
3659 | |
3660 | // Pull attributes from the pattern onto the instantiation. |
3661 | InstantiateAttrs(TemplateArgs, Pattern, Instantiation); |
3662 | |
3663 | // Start the definition of this instantiation. |
3664 | Instantiation->startDefinition(); |
3665 | |
3666 | // The instantiation is visible here, even if it was first declared in an |
3667 | // unimported module. |
3668 | Instantiation->setVisibleDespiteOwningModule(); |
3669 | |
3670 | // FIXME: This loses the as-written tag kind for an explicit instantiation. |
3671 | Instantiation->setTagKind(Pattern->getTagKind()); |
3672 | |
3673 | // Do substitution on the base class specifiers. |
3674 | if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs)) |
3675 | Instantiation->setInvalidDecl(); |
3676 | |
3677 | TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); |
3678 | Instantiator.setEvaluateConstraints(false); |
3679 | SmallVector<Decl*, 4> Fields; |
3680 | // Delay instantiation of late parsed attributes. |
3681 | LateInstantiatedAttrVec LateAttrs; |
3682 | Instantiator.enableLateAttributeInstantiation(LA: &LateAttrs); |
3683 | |
3684 | bool MightHaveConstexprVirtualFunctions = false; |
3685 | for (auto *Member : Pattern->decls()) { |
3686 | // Don't instantiate members not belonging in this semantic context. |
3687 | // e.g. for: |
3688 | // @code |
3689 | // template <int i> class A { |
3690 | // class B *g; |
3691 | // }; |
3692 | // @endcode |
3693 | // 'class B' has the template as lexical context but semantically it is |
3694 | // introduced in namespace scope. |
3695 | if (Member->getDeclContext() != Pattern) |
3696 | continue; |
3697 | |
3698 | // BlockDecls can appear in a default-member-initializer. They must be the |
3699 | // child of a BlockExpr, so we only know how to instantiate them from there. |
3700 | // Similarly, lambda closure types are recreated when instantiating the |
3701 | // corresponding LambdaExpr. |
3702 | if (isa<BlockDecl>(Member) || |
3703 | (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda())) |
3704 | continue; |
3705 | |
3706 | if (Member->isInvalidDecl()) { |
3707 | Instantiation->setInvalidDecl(); |
3708 | continue; |
3709 | } |
3710 | |
3711 | Decl *NewMember = Instantiator.Visit(Member); |
3712 | if (NewMember) { |
3713 | if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) { |
3714 | Fields.push_back(Field); |
3715 | } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) { |
3716 | // C++11 [temp.inst]p1: The implicit instantiation of a class template |
3717 | // specialization causes the implicit instantiation of the definitions |
3718 | // of unscoped member enumerations. |
3719 | // Record a point of instantiation for this implicit instantiation. |
3720 | if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() && |
3721 | Enum->isCompleteDefinition()) { |
3722 | MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo(); |
3723 | assert(MSInfo && "no spec info for member enum specialization"); |
3724 | MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation); |
3725 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
3726 | } |
3727 | } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) { |
3728 | if (SA->isFailed()) { |
3729 | // A static_assert failed. Bail out; instantiating this |
3730 | // class is probably not meaningful. |
3731 | Instantiation->setInvalidDecl(); |
3732 | break; |
3733 | } |
3734 | } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) { |
3735 | if (MD->isConstexpr() && !MD->getFriendObjectKind() && |
3736 | (MD->isVirtualAsWritten() || Instantiation->getNumBases())) |
3737 | MightHaveConstexprVirtualFunctions = true; |
3738 | } |
3739 | |
3740 | if (NewMember->isInvalidDecl()) |
3741 | Instantiation->setInvalidDecl(); |
3742 | } else { |
3743 | // FIXME: Eventually, a NULL return will mean that one of the |
3744 | // instantiations was a semantic disaster, and we'll want to mark the |
3745 | // declaration invalid. |
3746 | // For now, we expect to skip some members that we can't yet handle. |
3747 | } |
3748 | } |
3749 | |
3750 | // Finish checking fields. |
3751 | ActOnFields(S: nullptr, RecLoc: Instantiation->getLocation(), TagDecl: Instantiation, Fields, |
3752 | LBrac: SourceLocation(), RBrac: SourceLocation(), AttrList: ParsedAttributesView()); |
3753 | CheckCompletedCXXClass(S: nullptr, Record: Instantiation); |
3754 | |
3755 | // Default arguments are parsed, if not instantiated. We can go instantiate |
3756 | // default arg exprs for default constructors if necessary now. Unless we're |
3757 | // parsing a class, in which case wait until that's finished. |
3758 | if (ParsingClassDepth == 0) |
3759 | ActOnFinishCXXNonNestedClass(); |
3760 | |
3761 | // Instantiate late parsed attributes, and attach them to their decls. |
3762 | // See Sema::InstantiateAttrs |
3763 | for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(), |
3764 | E = LateAttrs.end(); I != E; ++I) { |
3765 | assert(CurrentInstantiationScope == Instantiator.getStartingScope()); |
3766 | CurrentInstantiationScope = I->Scope; |
3767 | |
3768 | // Allow 'this' within late-parsed attributes. |
3769 | auto *ND = cast<NamedDecl>(Val: I->NewDecl); |
3770 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); |
3771 | CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), |
3772 | ND->isCXXInstanceMember()); |
3773 | |
3774 | Attr *NewAttr = |
3775 | instantiateTemplateAttribute(At: I->TmplAttr, C&: Context, S&: *this, TemplateArgs); |
3776 | if (NewAttr) |
3777 | I->NewDecl->addAttr(A: NewAttr); |
3778 | LocalInstantiationScope::deleteScopes(Scope: I->Scope, |
3779 | Outermost: Instantiator.getStartingScope()); |
3780 | } |
3781 | Instantiator.disableLateAttributeInstantiation(); |
3782 | LateAttrs.clear(); |
3783 | |
3784 | ActOnFinishDelayedMemberInitializers(Instantiation); |
3785 | |
3786 | // FIXME: We should do something similar for explicit instantiations so they |
3787 | // end up in the right module. |
3788 | if (TSK == TSK_ImplicitInstantiation) { |
3789 | Instantiation->setLocation(Pattern->getLocation()); |
3790 | Instantiation->setLocStart(Pattern->getInnerLocStart()); |
3791 | Instantiation->setBraceRange(Pattern->getBraceRange()); |
3792 | } |
3793 | |
3794 | if (!Instantiation->isInvalidDecl()) { |
3795 | // Perform any dependent diagnostics from the pattern. |
3796 | if (Pattern->isDependentContext()) |
3797 | PerformDependentDiagnostics(Pattern, TemplateArgs); |
3798 | |
3799 | // Instantiate any out-of-line class template partial |
3800 | // specializations now. |
3801 | for (TemplateDeclInstantiator::delayed_partial_spec_iterator |
3802 | P = Instantiator.delayed_partial_spec_begin(), |
3803 | PEnd = Instantiator.delayed_partial_spec_end(); |
3804 | P != PEnd; ++P) { |
3805 | if (!Instantiator.InstantiateClassTemplatePartialSpecialization( |
3806 | ClassTemplate: P->first, PartialSpec: P->second)) { |
3807 | Instantiation->setInvalidDecl(); |
3808 | break; |
3809 | } |
3810 | } |
3811 | |
3812 | // Instantiate any out-of-line variable template partial |
3813 | // specializations now. |
3814 | for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator |
3815 | P = Instantiator.delayed_var_partial_spec_begin(), |
3816 | PEnd = Instantiator.delayed_var_partial_spec_end(); |
3817 | P != PEnd; ++P) { |
3818 | if (!Instantiator.InstantiateVarTemplatePartialSpecialization( |
3819 | VarTemplate: P->first, PartialSpec: P->second)) { |
3820 | Instantiation->setInvalidDecl(); |
3821 | break; |
3822 | } |
3823 | } |
3824 | } |
3825 | |
3826 | // Exit the scope of this instantiation. |
3827 | SavedContext.pop(); |
3828 | |
3829 | if (!Instantiation->isInvalidDecl()) { |
3830 | // Always emit the vtable for an explicit instantiation definition |
3831 | // of a polymorphic class template specialization. Otherwise, eagerly |
3832 | // instantiate only constexpr virtual functions in preparation for their use |
3833 | // in constant evaluation. |
3834 | if (TSK == TSK_ExplicitInstantiationDefinition) |
3835 | MarkVTableUsed(Loc: PointOfInstantiation, Class: Instantiation, DefinitionRequired: true); |
3836 | else if (MightHaveConstexprVirtualFunctions) |
3837 | MarkVirtualMembersReferenced(Loc: PointOfInstantiation, RD: Instantiation, |
3838 | /*ConstexprOnly*/ true); |
3839 | } |
3840 | |
3841 | Consumer.HandleTagDeclDefinition(Instantiation); |
3842 | |
3843 | return Instantiation->isInvalidDecl(); |
3844 | } |
3845 | |
3846 | bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation, |
3847 | EnumDecl *Instantiation, EnumDecl *Pattern, |
3848 | const MultiLevelTemplateArgumentList &TemplateArgs, |
3849 | TemplateSpecializationKind TSK) { |
3850 | EnumDecl *PatternDef = Pattern->getDefinition(); |
3851 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation, |
3852 | Instantiation->getInstantiatedFromMemberEnum(), |
3853 | Pattern, PatternDef, TSK,/*Complain*/true)) |
3854 | return true; |
3855 | Pattern = PatternDef; |
3856 | |
3857 | // Record the point of instantiation. |
3858 | if (MemberSpecializationInfo *MSInfo |
3859 | = Instantiation->getMemberSpecializationInfo()) { |
3860 | MSInfo->setTemplateSpecializationKind(TSK); |
3861 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
3862 | } |
3863 | |
3864 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
3865 | if (Inst.isInvalid()) |
3866 | return true; |
3867 | if (Inst.isAlreadyInstantiating()) |
3868 | return false; |
3869 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
3870 | "instantiating enum definition"); |
3871 | |
3872 | // The instantiation is visible here, even if it was first declared in an |
3873 | // unimported module. |
3874 | Instantiation->setVisibleDespiteOwningModule(); |
3875 | |
3876 | // Enter the scope of this instantiation. We don't use |
3877 | // PushDeclContext because we don't have a scope. |
3878 | ContextRAII SavedContext(*this, Instantiation); |
3879 | EnterExpressionEvaluationContext EvalContext( |
3880 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
3881 | |
3882 | LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true); |
3883 | |
3884 | // Pull attributes from the pattern onto the instantiation. |
3885 | InstantiateAttrs(TemplateArgs, Pattern, Instantiation); |
3886 | |
3887 | TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs); |
3888 | Instantiator.InstantiateEnumDefinition(Enum: Instantiation, Pattern); |
3889 | |
3890 | // Exit the scope of this instantiation. |
3891 | SavedContext.pop(); |
3892 | |
3893 | return Instantiation->isInvalidDecl(); |
3894 | } |
3895 | |
3896 | bool Sema::InstantiateInClassInitializer( |
3897 | SourceLocation PointOfInstantiation, FieldDecl *Instantiation, |
3898 | FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) { |
3899 | // If there is no initializer, we don't need to do anything. |
3900 | if (!Pattern->hasInClassInitializer()) |
3901 | return false; |
3902 | |
3903 | assert(Instantiation->getInClassInitStyle() == |
3904 | Pattern->getInClassInitStyle() && |
3905 | "pattern and instantiation disagree about init style"); |
3906 | |
3907 | // Error out if we haven't parsed the initializer of the pattern yet because |
3908 | // we are waiting for the closing brace of the outer class. |
3909 | Expr *OldInit = Pattern->getInClassInitializer(); |
3910 | if (!OldInit) { |
3911 | RecordDecl *PatternRD = Pattern->getParent(); |
3912 | RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext(); |
3913 | Diag(PointOfInstantiation, |
3914 | diag::err_default_member_initializer_not_yet_parsed) |
3915 | << OutermostClass << Pattern; |
3916 | Diag(Pattern->getEndLoc(), |
3917 | diag::note_default_member_initializer_not_yet_parsed); |
3918 | Instantiation->setInvalidDecl(); |
3919 | return true; |
3920 | } |
3921 | |
3922 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation); |
3923 | if (Inst.isInvalid()) |
3924 | return true; |
3925 | if (Inst.isAlreadyInstantiating()) { |
3926 | // Error out if we hit an instantiation cycle for this initializer. |
3927 | Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle) |
3928 | << Instantiation; |
3929 | return true; |
3930 | } |
3931 | PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(), |
3932 | "instantiating default member init"); |
3933 | |
3934 | // Enter the scope of this instantiation. We don't use PushDeclContext because |
3935 | // we don't have a scope. |
3936 | ContextRAII SavedContext(*this, Instantiation->getParent()); |
3937 | EnterExpressionEvaluationContext EvalContext( |
3938 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
3939 | ExprEvalContexts.back().DelayedDefaultInitializationContext = { |
3940 | PointOfInstantiation, Instantiation, CurContext}; |
3941 | |
3942 | LocalInstantiationScope Scope(*this, true); |
3943 | |
3944 | // Instantiate the initializer. |
3945 | ActOnStartCXXInClassMemberInitializer(); |
3946 | CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers()); |
3947 | |
3948 | ExprResult NewInit = SubstInitializer(E: OldInit, TemplateArgs, |
3949 | /*CXXDirectInit=*/false); |
3950 | Expr *Init = NewInit.get(); |
3951 | assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class"); |
3952 | ActOnFinishCXXInClassMemberInitializer( |
3953 | VarDecl: Instantiation, EqualLoc: Init ? Init->getBeginLoc() : SourceLocation(), Init); |
3954 | |
3955 | if (auto *L = getASTMutationListener()) |
3956 | L->DefaultMemberInitializerInstantiated(D: Instantiation); |
3957 | |
3958 | // Return true if the in-class initializer is still missing. |
3959 | return !Instantiation->getInClassInitializer(); |
3960 | } |
3961 | |
3962 | namespace { |
3963 | /// A partial specialization whose template arguments have matched |
3964 | /// a given template-id. |
3965 | struct PartialSpecMatchResult { |
3966 | ClassTemplatePartialSpecializationDecl *Partial; |
3967 | TemplateArgumentList *Args; |
3968 | }; |
3969 | } |
3970 | |
3971 | bool Sema::usesPartialOrExplicitSpecialization( |
3972 | SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) { |
3973 | if (ClassTemplateSpec->getTemplateSpecializationKind() == |
3974 | TSK_ExplicitSpecialization) |
3975 | return true; |
3976 | |
3977 | SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
3978 | ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate(); |
3979 | CTD->getPartialSpecializations(PS&: PartialSpecs); |
3980 | for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) { |
3981 | // C++ [temp.spec.partial.member]p2: |
3982 | // If the primary member template is explicitly specialized for a given |
3983 | // (implicit) specialization of the enclosing class template, the partial |
3984 | // specializations of the member template are ignored for this |
3985 | // specialization of the enclosing class template. If a partial |
3986 | // specialization of the member template is explicitly specialized for a |
3987 | // given (implicit) specialization of the enclosing class template, the |
3988 | // primary member template and its other partial specializations are still |
3989 | // considered for this specialization of the enclosing class template. |
3990 | if (CTD->getMostRecentDecl()->isMemberSpecialization() && |
3991 | !CTPSD->getMostRecentDecl()->isMemberSpecialization()) |
3992 | continue; |
3993 | |
3994 | TemplateDeductionInfo Info(Loc); |
3995 | if (DeduceTemplateArguments(Partial: CTPSD, |
3996 | TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), |
3997 | Info) == TemplateDeductionResult::Success) |
3998 | return true; |
3999 | } |
4000 | |
4001 | return false; |
4002 | } |
4003 | |
4004 | /// Get the instantiation pattern to use to instantiate the definition of a |
4005 | /// given ClassTemplateSpecializationDecl (either the pattern of the primary |
4006 | /// template or of a partial specialization). |
4007 | static ActionResult<CXXRecordDecl *> getPatternForClassTemplateSpecialization( |
4008 | Sema &S, SourceLocation PointOfInstantiation, |
4009 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
4010 | TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) { |
4011 | Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec); |
4012 | if (Inst.isInvalid()) |
4013 | return {/*Invalid=*/true}; |
4014 | if (Inst.isAlreadyInstantiating()) |
4015 | return {/*Invalid=*/false}; |
4016 | |
4017 | llvm::PointerUnion<ClassTemplateDecl *, |
4018 | ClassTemplatePartialSpecializationDecl *> |
4019 | Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); |
4020 | if (!isa<ClassTemplatePartialSpecializationDecl *>(Val: Specialized)) { |
4021 | // Find best matching specialization. |
4022 | ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); |
4023 | |
4024 | // C++ [temp.class.spec.match]p1: |
4025 | // When a class template is used in a context that requires an |
4026 | // instantiation of the class, it is necessary to determine |
4027 | // whether the instantiation is to be generated using the primary |
4028 | // template or one of the partial specializations. This is done by |
4029 | // matching the template arguments of the class template |
4030 | // specialization with the template argument lists of the partial |
4031 | // specializations. |
4032 | typedef PartialSpecMatchResult MatchResult; |
4033 | SmallVector<MatchResult, 4> Matched, ExtraMatched; |
4034 | SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
4035 | Template->getPartialSpecializations(PS&: PartialSpecs); |
4036 | TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation); |
4037 | for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) { |
4038 | // C++ [temp.spec.partial.member]p2: |
4039 | // If the primary member template is explicitly specialized for a given |
4040 | // (implicit) specialization of the enclosing class template, the |
4041 | // partial specializations of the member template are ignored for this |
4042 | // specialization of the enclosing class template. If a partial |
4043 | // specialization of the member template is explicitly specialized for a |
4044 | // given (implicit) specialization of the enclosing class template, the |
4045 | // primary member template and its other partial specializations are |
4046 | // still considered for this specialization of the enclosing class |
4047 | // template. |
4048 | if (Template->getMostRecentDecl()->isMemberSpecialization() && |
4049 | !Partial->getMostRecentDecl()->isMemberSpecialization()) |
4050 | continue; |
4051 | |
4052 | TemplateDeductionInfo Info(FailedCandidates.getLocation()); |
4053 | if (TemplateDeductionResult Result = S.DeduceTemplateArguments( |
4054 | Partial, TemplateArgs: ClassTemplateSpec->getTemplateArgs().asArray(), Info); |
4055 | Result != TemplateDeductionResult::Success) { |
4056 | // Store the failed-deduction information for use in diagnostics, later. |
4057 | // TODO: Actually use the failed-deduction info? |
4058 | FailedCandidates.addCandidate().set( |
4059 | Found: DeclAccessPair::make(Template, AS_public), Spec: Partial, |
4060 | Info: MakeDeductionFailureInfo(Context&: S.Context, TDK: Result, Info)); |
4061 | (void)Result; |
4062 | } else { |
4063 | auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched; |
4064 | List.push_back(Elt: MatchResult{.Partial: Partial, .Args: Info.takeCanonical()}); |
4065 | } |
4066 | } |
4067 | if (Matched.empty() && PrimaryStrictPackMatch) |
4068 | Matched = std::move(ExtraMatched); |
4069 | |
4070 | // If we're dealing with a member template where the template parameters |
4071 | // have been instantiated, this provides the original template parameters |
4072 | // from which the member template's parameters were instantiated. |
4073 | |
4074 | if (Matched.size() >= 1) { |
4075 | SmallVectorImpl<MatchResult>::iterator Best = Matched.begin(); |
4076 | if (Matched.size() == 1) { |
4077 | // -- If exactly one matching specialization is found, the |
4078 | // instantiation is generated from that specialization. |
4079 | // We don't need to do anything for this. |
4080 | } else { |
4081 | // -- If more than one matching specialization is found, the |
4082 | // partial order rules (14.5.4.2) are used to determine |
4083 | // whether one of the specializations is more specialized |
4084 | // than the others. If none of the specializations is more |
4085 | // specialized than all of the other matching |
4086 | // specializations, then the use of the class template is |
4087 | // ambiguous and the program is ill-formed. |
4088 | for (SmallVectorImpl<MatchResult>::iterator P = Best + 1, |
4089 | PEnd = Matched.end(); |
4090 | P != PEnd; ++P) { |
4091 | if (S.getMoreSpecializedPartialSpecialization( |
4092 | PS1: P->Partial, PS2: Best->Partial, Loc: PointOfInstantiation) == |
4093 | P->Partial) |
4094 | Best = P; |
4095 | } |
4096 | |
4097 | // Determine if the best partial specialization is more specialized than |
4098 | // the others. |
4099 | bool Ambiguous = false; |
4100 | for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), |
4101 | PEnd = Matched.end(); |
4102 | P != PEnd; ++P) { |
4103 | if (P != Best && S.getMoreSpecializedPartialSpecialization( |
4104 | PS1: P->Partial, PS2: Best->Partial, |
4105 | Loc: PointOfInstantiation) != Best->Partial) { |
4106 | Ambiguous = true; |
4107 | break; |
4108 | } |
4109 | } |
4110 | |
4111 | if (Ambiguous) { |
4112 | // Partial ordering did not produce a clear winner. Complain. |
4113 | Inst.Clear(); |
4114 | ClassTemplateSpec->setInvalidDecl(); |
4115 | S.Diag(PointOfInstantiation, |
4116 | diag::err_partial_spec_ordering_ambiguous) |
4117 | << ClassTemplateSpec; |
4118 | |
4119 | // Print the matching partial specializations. |
4120 | for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(), |
4121 | PEnd = Matched.end(); |
4122 | P != PEnd; ++P) |
4123 | S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match) |
4124 | << S.getTemplateArgumentBindingsText( |
4125 | P->Partial->getTemplateParameters(), *P->Args); |
4126 | |
4127 | return {/*Invalid=*/true}; |
4128 | } |
4129 | } |
4130 | |
4131 | ClassTemplateSpec->setInstantiationOf(PartialSpec: Best->Partial, TemplateArgs: Best->Args); |
4132 | } else { |
4133 | // -- If no matches are found, the instantiation is generated |
4134 | // from the primary template. |
4135 | } |
4136 | } |
4137 | |
4138 | CXXRecordDecl *Pattern = nullptr; |
4139 | Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial(); |
4140 | if (auto *PartialSpec = |
4141 | Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) { |
4142 | // Instantiate using the best class template partial specialization. |
4143 | while (PartialSpec->getInstantiatedFromMember()) { |
4144 | // If we've found an explicit specialization of this class template, |
4145 | // stop here and use that as the pattern. |
4146 | if (PartialSpec->isMemberSpecialization()) |
4147 | break; |
4148 | |
4149 | PartialSpec = PartialSpec->getInstantiatedFromMember(); |
4150 | } |
4151 | Pattern = PartialSpec; |
4152 | } else { |
4153 | ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate(); |
4154 | while (Template->getInstantiatedFromMemberTemplate()) { |
4155 | // If we've found an explicit specialization of this class template, |
4156 | // stop here and use that as the pattern. |
4157 | if (Template->isMemberSpecialization()) |
4158 | break; |
4159 | |
4160 | Template = Template->getInstantiatedFromMemberTemplate(); |
4161 | } |
4162 | Pattern = Template->getTemplatedDecl(); |
4163 | } |
4164 | |
4165 | return Pattern; |
4166 | } |
4167 | |
4168 | bool Sema::InstantiateClassTemplateSpecialization( |
4169 | SourceLocation PointOfInstantiation, |
4170 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
4171 | TemplateSpecializationKind TSK, bool Complain, |
4172 | bool PrimaryStrictPackMatch) { |
4173 | // Perform the actual instantiation on the canonical declaration. |
4174 | ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>( |
4175 | ClassTemplateSpec->getCanonicalDecl()); |
4176 | if (ClassTemplateSpec->isInvalidDecl()) |
4177 | return true; |
4178 | |
4179 | bool HadAvaibilityWarning = |
4180 | ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr) |
4181 | .first != AR_Available; |
4182 | |
4183 | ActionResult<CXXRecordDecl *> Pattern = |
4184 | getPatternForClassTemplateSpecialization(S&: *this, PointOfInstantiation, |
4185 | ClassTemplateSpec, TSK, |
4186 | PrimaryStrictPackMatch); |
4187 | |
4188 | if (!Pattern.isUsable()) |
4189 | return Pattern.isInvalid(); |
4190 | |
4191 | bool Err = InstantiateClass( |
4192 | PointOfInstantiation, Instantiation: ClassTemplateSpec, Pattern: Pattern.get(), |
4193 | TemplateArgs: getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain); |
4194 | |
4195 | // If we haven't already warn on avaibility, consider the avaibility |
4196 | // attributes of the partial specialization. |
4197 | // Note that - because we need to have deduced the partial specialization - |
4198 | // We can only emit these warnings when the specialization is instantiated. |
4199 | if (!Err && !HadAvaibilityWarning) { |
4200 | assert(ClassTemplateSpec->getTemplateSpecializationKind() != |
4201 | TSK_Undeclared); |
4202 | DiagnoseAvailabilityOfDecl(ClassTemplateSpec, PointOfInstantiation); |
4203 | } |
4204 | return Err; |
4205 | } |
4206 | |
4207 | void |
4208 | Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation, |
4209 | CXXRecordDecl *Instantiation, |
4210 | const MultiLevelTemplateArgumentList &TemplateArgs, |
4211 | TemplateSpecializationKind TSK) { |
4212 | // FIXME: We need to notify the ASTMutationListener that we did all of these |
4213 | // things, in case we have an explicit instantiation definition in a PCM, a |
4214 | // module, or preamble, and the declaration is in an imported AST. |
4215 | assert( |
4216 | (TSK == TSK_ExplicitInstantiationDefinition || |
4217 | TSK == TSK_ExplicitInstantiationDeclaration || |
4218 | (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && |
4219 | "Unexpected template specialization kind!"); |
4220 | for (auto *D : Instantiation->decls()) { |
4221 | bool SuppressNew = false; |
4222 | if (auto *Function = dyn_cast<FunctionDecl>(D)) { |
4223 | if (FunctionDecl *Pattern = |
4224 | Function->getInstantiatedFromMemberFunction()) { |
4225 | |
4226 | if (Function->getTrailingRequiresClause()) { |
4227 | ConstraintSatisfaction Satisfaction; |
4228 | if (CheckFunctionConstraints(Function, Satisfaction) || |
4229 | !Satisfaction.IsSatisfied) { |
4230 | continue; |
4231 | } |
4232 | } |
4233 | |
4234 | if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
4235 | continue; |
4236 | |
4237 | TemplateSpecializationKind PrevTSK = |
4238 | Function->getTemplateSpecializationKind(); |
4239 | if (PrevTSK == TSK_ExplicitSpecialization) |
4240 | continue; |
4241 | |
4242 | if (CheckSpecializationInstantiationRedecl( |
4243 | PointOfInstantiation, TSK, Function, PrevTSK, |
4244 | Function->getPointOfInstantiation(), SuppressNew) || |
4245 | SuppressNew) |
4246 | continue; |
4247 | |
4248 | // C++11 [temp.explicit]p8: |
4249 | // An explicit instantiation definition that names a class template |
4250 | // specialization explicitly instantiates the class template |
4251 | // specialization and is only an explicit instantiation definition |
4252 | // of members whose definition is visible at the point of |
4253 | // instantiation. |
4254 | if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined()) |
4255 | continue; |
4256 | |
4257 | Function->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
4258 | |
4259 | if (Function->isDefined()) { |
4260 | // Let the ASTConsumer know that this function has been explicitly |
4261 | // instantiated now, and its linkage might have changed. |
4262 | Consumer.HandleTopLevelDecl(DeclGroupRef(Function)); |
4263 | } else if (TSK == TSK_ExplicitInstantiationDefinition) { |
4264 | InstantiateFunctionDefinition(PointOfInstantiation, Function); |
4265 | } else if (TSK == TSK_ImplicitInstantiation) { |
4266 | PendingLocalImplicitInstantiations.push_back( |
4267 | std::make_pair(Function, PointOfInstantiation)); |
4268 | } |
4269 | } |
4270 | } else if (auto *Var = dyn_cast<VarDecl>(D)) { |
4271 | if (isa<VarTemplateSpecializationDecl>(Var)) |
4272 | continue; |
4273 | |
4274 | if (Var->isStaticDataMember()) { |
4275 | if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
4276 | continue; |
4277 | |
4278 | MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo(); |
4279 | assert(MSInfo && "No member specialization information?"); |
4280 | if (MSInfo->getTemplateSpecializationKind() |
4281 | == TSK_ExplicitSpecialization) |
4282 | continue; |
4283 | |
4284 | if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, |
4285 | Var, |
4286 | MSInfo->getTemplateSpecializationKind(), |
4287 | MSInfo->getPointOfInstantiation(), |
4288 | SuppressNew) || |
4289 | SuppressNew) |
4290 | continue; |
4291 | |
4292 | if (TSK == TSK_ExplicitInstantiationDefinition) { |
4293 | // C++0x [temp.explicit]p8: |
4294 | // An explicit instantiation definition that names a class template |
4295 | // specialization explicitly instantiates the class template |
4296 | // specialization and is only an explicit instantiation definition |
4297 | // of members whose definition is visible at the point of |
4298 | // instantiation. |
4299 | if (!Var->getInstantiatedFromStaticDataMember()->getDefinition()) |
4300 | continue; |
4301 | |
4302 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
4303 | InstantiateVariableDefinition(PointOfInstantiation, Var); |
4304 | } else { |
4305 | Var->setTemplateSpecializationKind(TSK, PointOfInstantiation); |
4306 | } |
4307 | } |
4308 | } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) { |
4309 | if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>()) |
4310 | continue; |
4311 | |
4312 | // Always skip the injected-class-name, along with any |
4313 | // redeclarations of nested classes, since both would cause us |
4314 | // to try to instantiate the members of a class twice. |
4315 | // Skip closure types; they'll get instantiated when we instantiate |
4316 | // the corresponding lambda-expression. |
4317 | if (Record->isInjectedClassName() || Record->getPreviousDecl() || |
4318 | Record->isLambda()) |
4319 | continue; |
4320 | |
4321 | MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo(); |
4322 | assert(MSInfo && "No member specialization information?"); |
4323 | |
4324 | if (MSInfo->getTemplateSpecializationKind() |
4325 | == TSK_ExplicitSpecialization) |
4326 | continue; |
4327 | |
4328 | if (Context.getTargetInfo().getTriple().isOSWindows() && |
4329 | TSK == TSK_ExplicitInstantiationDeclaration) { |
4330 | // On Windows, explicit instantiation decl of the outer class doesn't |
4331 | // affect the inner class. Typically extern template declarations are |
4332 | // used in combination with dll import/export annotations, but those |
4333 | // are not propagated from the outer class templates to inner classes. |
4334 | // Therefore, do not instantiate inner classes on this platform, so |
4335 | // that users don't end up with undefined symbols during linking. |
4336 | continue; |
4337 | } |
4338 | |
4339 | if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK, |
4340 | Record, |
4341 | MSInfo->getTemplateSpecializationKind(), |
4342 | MSInfo->getPointOfInstantiation(), |
4343 | SuppressNew) || |
4344 | SuppressNew) |
4345 | continue; |
4346 | |
4347 | CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass(); |
4348 | assert(Pattern && "Missing instantiated-from-template information"); |
4349 | |
4350 | if (!Record->getDefinition()) { |
4351 | if (!Pattern->getDefinition()) { |
4352 | // C++0x [temp.explicit]p8: |
4353 | // An explicit instantiation definition that names a class template |
4354 | // specialization explicitly instantiates the class template |
4355 | // specialization and is only an explicit instantiation definition |
4356 | // of members whose definition is visible at the point of |
4357 | // instantiation. |
4358 | if (TSK == TSK_ExplicitInstantiationDeclaration) { |
4359 | MSInfo->setTemplateSpecializationKind(TSK); |
4360 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
4361 | } |
4362 | |
4363 | continue; |
4364 | } |
4365 | |
4366 | InstantiateClass(PointOfInstantiation, Record, Pattern, |
4367 | TemplateArgs, |
4368 | TSK); |
4369 | } else { |
4370 | if (TSK == TSK_ExplicitInstantiationDefinition && |
4371 | Record->getTemplateSpecializationKind() == |
4372 | TSK_ExplicitInstantiationDeclaration) { |
4373 | Record->setTemplateSpecializationKind(TSK); |
4374 | MarkVTableUsed(PointOfInstantiation, Record, true); |
4375 | } |
4376 | } |
4377 | |
4378 | Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition()); |
4379 | if (Pattern) |
4380 | InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs, |
4381 | TSK); |
4382 | } else if (auto *Enum = dyn_cast<EnumDecl>(D)) { |
4383 | MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo(); |
4384 | assert(MSInfo && "No member specialization information?"); |
4385 | |
4386 | if (MSInfo->getTemplateSpecializationKind() |
4387 | == TSK_ExplicitSpecialization) |
4388 | continue; |
4389 | |
4390 | if (CheckSpecializationInstantiationRedecl( |
4391 | PointOfInstantiation, TSK, Enum, |
4392 | MSInfo->getTemplateSpecializationKind(), |
4393 | MSInfo->getPointOfInstantiation(), SuppressNew) || |
4394 | SuppressNew) |
4395 | continue; |
4396 | |
4397 | if (Enum->getDefinition()) |
4398 | continue; |
4399 | |
4400 | EnumDecl *Pattern = Enum->getTemplateInstantiationPattern(); |
4401 | assert(Pattern && "Missing instantiated-from-template information"); |
4402 | |
4403 | if (TSK == TSK_ExplicitInstantiationDefinition) { |
4404 | if (!Pattern->getDefinition()) |
4405 | continue; |
4406 | |
4407 | InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK); |
4408 | } else { |
4409 | MSInfo->setTemplateSpecializationKind(TSK); |
4410 | MSInfo->setPointOfInstantiation(PointOfInstantiation); |
4411 | } |
4412 | } else if (auto *Field = dyn_cast<FieldDecl>(D)) { |
4413 | // No need to instantiate in-class initializers during explicit |
4414 | // instantiation. |
4415 | if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) { |
4416 | CXXRecordDecl *ClassPattern = |
4417 | Instantiation->getTemplateInstantiationPattern(); |
4418 | DeclContext::lookup_result Lookup = |
4419 | ClassPattern->lookup(Field->getDeclName()); |
4420 | FieldDecl *Pattern = Lookup.find_first<FieldDecl>(); |
4421 | assert(Pattern); |
4422 | InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern, |
4423 | TemplateArgs); |
4424 | } |
4425 | } |
4426 | } |
4427 | } |
4428 | |
4429 | void |
4430 | Sema::InstantiateClassTemplateSpecializationMembers( |
4431 | SourceLocation PointOfInstantiation, |
4432 | ClassTemplateSpecializationDecl *ClassTemplateSpec, |
4433 | TemplateSpecializationKind TSK) { |
4434 | // C++0x [temp.explicit]p7: |
4435 | // An explicit instantiation that names a class template |
4436 | // specialization is an explicit instantion of the same kind |
4437 | // (declaration or definition) of each of its members (not |
4438 | // including members inherited from base classes) that has not |
4439 | // been previously explicitly specialized in the translation unit |
4440 | // containing the explicit instantiation, except as described |
4441 | // below. |
4442 | InstantiateClassMembers(PointOfInstantiation, Instantiation: ClassTemplateSpec, |
4443 | TemplateArgs: getTemplateInstantiationArgs(ClassTemplateSpec), |
4444 | TSK); |
4445 | } |
4446 | |
4447 | StmtResult |
4448 | Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) { |
4449 | if (!S) |
4450 | return S; |
4451 | |
4452 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
4453 | SourceLocation(), |
4454 | DeclarationName()); |
4455 | return Instantiator.TransformStmt(S); |
4456 | } |
4457 | |
4458 | bool Sema::SubstTemplateArgument( |
4459 | const TemplateArgumentLoc &Input, |
4460 | const MultiLevelTemplateArgumentList &TemplateArgs, |
4461 | TemplateArgumentLoc &Output, SourceLocation Loc, |
4462 | const DeclarationName &Entity) { |
4463 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity); |
4464 | return Instantiator.TransformTemplateArgument(Input, Output); |
4465 | } |
4466 | |
4467 | bool Sema::SubstTemplateArguments( |
4468 | ArrayRef<TemplateArgumentLoc> Args, |
4469 | const MultiLevelTemplateArgumentList &TemplateArgs, |
4470 | TemplateArgumentListInfo &Out) { |
4471 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
4472 | DeclarationName()); |
4473 | return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out); |
4474 | } |
4475 | |
4476 | ExprResult |
4477 | Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { |
4478 | if (!E) |
4479 | return E; |
4480 | |
4481 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
4482 | SourceLocation(), |
4483 | DeclarationName()); |
4484 | return Instantiator.TransformExpr(E); |
4485 | } |
4486 | |
4487 | ExprResult |
4488 | Sema::SubstCXXIdExpr(Expr *E, |
4489 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4490 | if (!E) |
4491 | return E; |
4492 | |
4493 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
4494 | DeclarationName()); |
4495 | return Instantiator.TransformAddressOfOperand(E); |
4496 | } |
4497 | |
4498 | ExprResult |
4499 | Sema::SubstConstraintExpr(Expr *E, |
4500 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4501 | // FIXME: should call SubstExpr directly if this function is equivalent or |
4502 | // should it be different? |
4503 | return SubstExpr(E, TemplateArgs); |
4504 | } |
4505 | |
4506 | ExprResult Sema::SubstConstraintExprWithoutSatisfaction( |
4507 | Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) { |
4508 | if (!E) |
4509 | return E; |
4510 | |
4511 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
4512 | DeclarationName()); |
4513 | Instantiator.setEvaluateConstraints(false); |
4514 | return Instantiator.TransformExpr(E); |
4515 | } |
4516 | |
4517 | ExprResult Sema::SubstInitializer(Expr *Init, |
4518 | const MultiLevelTemplateArgumentList &TemplateArgs, |
4519 | bool CXXDirectInit) { |
4520 | TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(), |
4521 | DeclarationName()); |
4522 | return Instantiator.TransformInitializer(Init, CXXDirectInit); |
4523 | } |
4524 | |
4525 | bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, |
4526 | const MultiLevelTemplateArgumentList &TemplateArgs, |
4527 | SmallVectorImpl<Expr *> &Outputs) { |
4528 | if (Exprs.empty()) |
4529 | return false; |
4530 | |
4531 | TemplateInstantiator Instantiator(*this, TemplateArgs, |
4532 | SourceLocation(), |
4533 | DeclarationName()); |
4534 | return Instantiator.TransformExprs(Exprs.data(), Exprs.size(), |
4535 | IsCall, Outputs); |
4536 | } |
4537 | |
4538 | NestedNameSpecifierLoc |
4539 | Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, |
4540 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4541 | if (!NNS) |
4542 | return NestedNameSpecifierLoc(); |
4543 | |
4544 | TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(), |
4545 | DeclarationName()); |
4546 | return Instantiator.TransformNestedNameSpecifierLoc(NNS); |
4547 | } |
4548 | |
4549 | DeclarationNameInfo |
4550 | Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, |
4551 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4552 | TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(), |
4553 | NameInfo.getName()); |
4554 | return Instantiator.TransformDeclarationNameInfo(NameInfo); |
4555 | } |
4556 | |
4557 | TemplateName |
4558 | Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, |
4559 | TemplateName Name, SourceLocation Loc, |
4560 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4561 | TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, |
4562 | DeclarationName()); |
4563 | CXXScopeSpec SS; |
4564 | SS.Adopt(Other: QualifierLoc); |
4565 | return Instantiator.TransformTemplateName(SS, Name, NameLoc: Loc); |
4566 | } |
4567 | |
4568 | static const Decl *getCanonicalParmVarDecl(const Decl *D) { |
4569 | // When storing ParmVarDecls in the local instantiation scope, we always |
4570 | // want to use the ParmVarDecl from the canonical function declaration, |
4571 | // since the map is then valid for any redeclaration or definition of that |
4572 | // function. |
4573 | if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(Val: D)) { |
4574 | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { |
4575 | unsigned i = PV->getFunctionScopeIndex(); |
4576 | // This parameter might be from a freestanding function type within the |
4577 | // function and isn't necessarily referring to one of FD's parameters. |
4578 | if (i < FD->getNumParams() && FD->getParamDecl(i) == PV) |
4579 | return FD->getCanonicalDecl()->getParamDecl(i); |
4580 | } |
4581 | } |
4582 | return D; |
4583 | } |
4584 | |
4585 | llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * |
4586 | LocalInstantiationScope::getInstantiationOfIfExists(const Decl *D) { |
4587 | D = getCanonicalParmVarDecl(D); |
4588 | for (LocalInstantiationScope *Current = this; Current; |
4589 | Current = Current->Outer) { |
4590 | |
4591 | // Check if we found something within this scope. |
4592 | const Decl *CheckD = D; |
4593 | do { |
4594 | LocalDeclsMap::iterator Found = Current->LocalDecls.find(Val: CheckD); |
4595 | if (Found != Current->LocalDecls.end()) |
4596 | return &Found->second; |
4597 | |
4598 | // If this is a tag declaration, it's possible that we need to look for |
4599 | // a previous declaration. |
4600 | if (const TagDecl *Tag = dyn_cast<TagDecl>(Val: CheckD)) |
4601 | CheckD = Tag->getPreviousDecl(); |
4602 | else |
4603 | CheckD = nullptr; |
4604 | } while (CheckD); |
4605 | |
4606 | // If we aren't combined with our outer scope, we're done. |
4607 | if (!Current->CombineWithOuterScope) |
4608 | break; |
4609 | } |
4610 | |
4611 | return nullptr; |
4612 | } |
4613 | |
4614 | llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> * |
4615 | LocalInstantiationScope::findInstantiationOf(const Decl *D) { |
4616 | auto *Result = getInstantiationOfIfExists(D); |
4617 | if (Result) |
4618 | return Result; |
4619 | // If we're performing a partial substitution during template argument |
4620 | // deduction, we may not have values for template parameters yet. |
4621 | if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) || |
4622 | isa<TemplateTemplateParmDecl>(Val: D)) |
4623 | return nullptr; |
4624 | |
4625 | // Local types referenced prior to definition may require instantiation. |
4626 | if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
4627 | if (RD->isLocalClass()) |
4628 | return nullptr; |
4629 | |
4630 | // Enumeration types referenced prior to definition may appear as a result of |
4631 | // error recovery. |
4632 | if (isa<EnumDecl>(Val: D)) |
4633 | return nullptr; |
4634 | |
4635 | // Materialized typedefs/type alias for implicit deduction guides may require |
4636 | // instantiation. |
4637 | if (isa<TypedefNameDecl>(Val: D) && |
4638 | isa<CXXDeductionGuideDecl>(Val: D->getDeclContext())) |
4639 | return nullptr; |
4640 | |
4641 | // If we didn't find the decl, then we either have a sema bug, or we have a |
4642 | // forward reference to a label declaration. Return null to indicate that |
4643 | // we have an uninstantiated label. |
4644 | assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope"); |
4645 | return nullptr; |
4646 | } |
4647 | |
4648 | void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) { |
4649 | D = getCanonicalParmVarDecl(D); |
4650 | llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; |
4651 | if (Stored.isNull()) { |
4652 | #ifndef NDEBUG |
4653 | // It should not be present in any surrounding scope either. |
4654 | LocalInstantiationScope *Current = this; |
4655 | while (Current->CombineWithOuterScope && Current->Outer) { |
4656 | Current = Current->Outer; |
4657 | assert(!Current->LocalDecls.contains(D) && |
4658 | "Instantiated local in inner and outer scopes"); |
4659 | } |
4660 | #endif |
4661 | Stored = Inst; |
4662 | } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Val&: Stored)) { |
4663 | Pack->push_back(Elt: cast<ValueDecl>(Val: Inst)); |
4664 | } else { |
4665 | assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local"); |
4666 | } |
4667 | } |
4668 | |
4669 | void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D, |
4670 | VarDecl *Inst) { |
4671 | D = getCanonicalParmVarDecl(D); |
4672 | DeclArgumentPack *Pack = cast<DeclArgumentPack *>(Val&: LocalDecls[D]); |
4673 | Pack->push_back(Inst); |
4674 | } |
4675 | |
4676 | void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) { |
4677 | #ifndef NDEBUG |
4678 | // This should be the first time we've been told about this decl. |
4679 | for (LocalInstantiationScope *Current = this; |
4680 | Current && Current->CombineWithOuterScope; Current = Current->Outer) |
4681 | assert(!Current->LocalDecls.contains(D) && |
4682 | "Creating local pack after instantiation of local"); |
4683 | #endif |
4684 | |
4685 | D = getCanonicalParmVarDecl(D); |
4686 | llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D]; |
4687 | DeclArgumentPack *Pack = new DeclArgumentPack; |
4688 | Stored = Pack; |
4689 | ArgumentPacks.push_back(Elt: Pack); |
4690 | } |
4691 | |
4692 | bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) { |
4693 | for (DeclArgumentPack *Pack : ArgumentPacks) |
4694 | if (llvm::is_contained(Range&: *Pack, Element: D)) |
4695 | return true; |
4696 | return false; |
4697 | } |
4698 | |
4699 | void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack, |
4700 | const TemplateArgument *ExplicitArgs, |
4701 | unsigned NumExplicitArgs) { |
4702 | assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && |
4703 | "Already have a partially-substituted pack"); |
4704 | assert((!PartiallySubstitutedPack |
4705 | || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && |
4706 | "Wrong number of arguments in partially-substituted pack"); |
4707 | PartiallySubstitutedPack = Pack; |
4708 | ArgsInPartiallySubstitutedPack = ExplicitArgs; |
4709 | NumArgsInPartiallySubstitutedPack = NumExplicitArgs; |
4710 | } |
4711 | |
4712 | NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack( |
4713 | const TemplateArgument **ExplicitArgs, |
4714 | unsigned *NumExplicitArgs) const { |
4715 | if (ExplicitArgs) |
4716 | *ExplicitArgs = nullptr; |
4717 | if (NumExplicitArgs) |
4718 | *NumExplicitArgs = 0; |
4719 | |
4720 | for (const LocalInstantiationScope *Current = this; Current; |
4721 | Current = Current->Outer) { |
4722 | if (Current->PartiallySubstitutedPack) { |
4723 | if (ExplicitArgs) |
4724 | *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack; |
4725 | if (NumExplicitArgs) |
4726 | *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack; |
4727 | |
4728 | return Current->PartiallySubstitutedPack; |
4729 | } |
4730 | |
4731 | if (!Current->CombineWithOuterScope) |
4732 | break; |
4733 | } |
4734 | |
4735 | return nullptr; |
4736 | } |
4737 |
Definitions
- Response
- Done
- ChangeDecl
- ChangeDecl
- UseNextDecl
- DontClearRelativeToPrimaryNextDecl
- getPrimaryTemplateOfGenericLambda
- EnclosingTypeAliasTemplateDetails
- operator bool
- getEnclosingTypeAliasTemplateDecl
- isLambdaEnclosedByTypeAliasDecl
- HandleVarTemplateSpec
- HandleDefaultTempArgIntoTempTempParam
- HandlePartialClassTemplateSpec
- HandleClassTemplateSpec
- HandleFunction
- HandleFunctionTemplateDecl
- HandleRecordDecl
- HandleImplicitConceptSpecializationDecl
- HandleGenericDeclContext
- getTemplateInstantiationArgs
- getTemplateInstantiationArgs
- isInstantiationRecord
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- InstantiatingTemplate
- pushCodeSynthesisContext
- popCodeSynthesisContext
- Clear
- convertCallArgsToString
- CheckInstantiationDepth
- PrintInstantiationStack
- isSFINAEContext
- getPackSubstitutedTemplateArgument
- TemplateInstantiator
- TemplateInstantiator
- setEvaluateConstraints
- getEvaluateConstraints
- getBaseLocation
- getBaseEntity
- getIsIncomplete
- setBase
- TransformTemplateDepth
- getPackIndex
- TryExpandParameterPacks
- ExpandingFunctionParameterPack
- ForgetPartiallySubstitutedPack
- RememberPartiallySubstitutedPack
- getTemplateArgumentPackPatternForRewrite
- transformAttrs
- transformedLocalDecl
- TransformFunctionProtoType
- TransformInjectedClassNameType
- TransformTemplateArgument
- ComputeSizeOfPackExprWithoutSubstitution
- ComputeLambdaDependency
- TransformLambdaExpr
- TransformBlockExpr
- RebuildLambdaExpr
- TransformLambdaBody
- TransformRequiresExpr
- TransformRequiresExprRequirements
- TransformTemplateParameterList
- AlreadyTransformed
- TransformDecl
- maybeInstantiateFunctionParameterToScope
- TransformDefinition
- TransformExceptionSpec
- TransformFirstQualifierInScope
- RebuildExceptionDecl
- RebuildObjCExceptionDecl
- RebuildElaboratedType
- TransformTemplateName
- TransformPredefinedExpr
- TransformTemplateParmRefExpr
- TransformAnnotateAttr
- TransformCXXAssumeAttr
- TransformLoopHintAttr
- TransformStmtNoInlineAttr
- TransformStmtAlwaysInlineAttr
- TransformCodeAlignAttr
- TransformOpenACCRoutineDeclAttr
- transformNonTypeTemplateParmRef
- TransformSubstNonTypeTemplateParmPackExpr
- TransformSubstNonTypeTemplateParmExpr
- RebuildVarDeclRefExpr
- TransformFunctionParmPackExpr
- TransformFunctionParmPackRefExpr
- TransformDeclRefExpr
- TransformCXXDefaultArgExpr
- TransformFunctionProtoType
- TransformFunctionTypeParam
- BuildSubstTemplateTypeParmType
- TransformTemplateTypeParmType
- TransformSubstTemplateTypeParmPackType
- createSubstDiag
- createSubstDiagAt
- TransformRequiresTypeParams
- TransformTypeRequirement
- TransformExprRequirement
- TransformNestedRequirement
- SubstType
- SubstType
- SubstType
- NeedsInstantiationAsFunctionType
- SubstFunctionDeclType
- SubstExceptionSpec
- SubstExceptionSpec
- GetContainedInventedTypeParmVisitor
- Visit
- VisitTemplateTypeParmType
- VisitElaboratedType
- VisitPointerType
- VisitBlockPointerType
- VisitReferenceType
- VisitMemberPointerType
- VisitArrayType
- VisitDependentSizedExtVectorType
- VisitVectorType
- VisitFunctionProtoType
- VisitFunctionType
- VisitParenType
- VisitAttributedType
- VisitMacroQualifiedType
- VisitAdjustedType
- VisitPackExpansionType
- SubstTypeConstraint
- SubstParmVarDecl
- SubstParmTypes
- SubstDefaultArgument
- SubstBaseSpecifiers
- InstantiateClass
- InstantiateEnum
- InstantiateInClassInitializer
- PartialSpecMatchResult
- usesPartialOrExplicitSpecialization
- getPatternForClassTemplateSpecialization
- InstantiateClassTemplateSpecialization
- InstantiateClassMembers
- InstantiateClassTemplateSpecializationMembers
- SubstStmt
- SubstTemplateArgument
- SubstTemplateArguments
- SubstExpr
- SubstCXXIdExpr
- SubstConstraintExpr
- SubstConstraintExprWithoutSatisfaction
- SubstInitializer
- SubstExprs
- SubstNestedNameSpecifierLoc
- SubstDeclarationNameInfo
- SubstTemplateName
- getCanonicalParmVarDecl
- getInstantiationOfIfExists
- findInstantiationOf
- InstantiatedLocal
- InstantiatedLocalPackArg
- MakeInstantiatedLocalArgPack
- isLocalPackExpansion
- SetPartiallySubstitutedPack
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more