1 | //===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations. |
9 | // |
10 | //===----------------------------------------------------------------------===/ |
11 | |
12 | #include "TreeTransform.h" |
13 | #include "clang/AST/ASTConsumer.h" |
14 | #include "clang/AST/ASTContext.h" |
15 | #include "clang/AST/ASTMutationListener.h" |
16 | #include "clang/AST/DeclTemplate.h" |
17 | #include "clang/AST/DeclVisitor.h" |
18 | #include "clang/AST/DependentDiagnostic.h" |
19 | #include "clang/AST/Expr.h" |
20 | #include "clang/AST/ExprCXX.h" |
21 | #include "clang/AST/PrettyDeclStackTrace.h" |
22 | #include "clang/AST/TypeLoc.h" |
23 | #include "clang/Basic/SourceManager.h" |
24 | #include "clang/Basic/TargetInfo.h" |
25 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
26 | #include "clang/Sema/Initialization.h" |
27 | #include "clang/Sema/Lookup.h" |
28 | #include "clang/Sema/ScopeInfo.h" |
29 | #include "clang/Sema/SemaInternal.h" |
30 | #include "clang/Sema/Template.h" |
31 | #include "clang/Sema/TemplateInstCallback.h" |
32 | #include "llvm/Support/TimeProfiler.h" |
33 | #include <optional> |
34 | |
35 | using namespace clang; |
36 | |
37 | static bool isDeclWithinFunction(const Decl *D) { |
38 | const DeclContext *DC = D->getDeclContext(); |
39 | if (DC->isFunctionOrMethod()) |
40 | return true; |
41 | |
42 | if (DC->isRecord()) |
43 | return cast<CXXRecordDecl>(Val: DC)->isLocalClass(); |
44 | |
45 | return false; |
46 | } |
47 | |
48 | template<typename DeclT> |
49 | static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl, |
50 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
51 | if (!OldDecl->getQualifierLoc()) |
52 | return false; |
53 | |
54 | assert((NewDecl->getFriendObjectKind() || |
55 | !OldDecl->getLexicalDeclContext()->isDependentContext()) && |
56 | "non-friend with qualified name defined in dependent context" ); |
57 | Sema::ContextRAII SavedContext( |
58 | SemaRef, |
59 | const_cast<DeclContext *>(NewDecl->getFriendObjectKind() |
60 | ? NewDecl->getLexicalDeclContext() |
61 | : OldDecl->getLexicalDeclContext())); |
62 | |
63 | NestedNameSpecifierLoc NewQualifierLoc |
64 | = SemaRef.SubstNestedNameSpecifierLoc(NNS: OldDecl->getQualifierLoc(), |
65 | TemplateArgs); |
66 | |
67 | if (!NewQualifierLoc) |
68 | return true; |
69 | |
70 | NewDecl->setQualifierInfo(NewQualifierLoc); |
71 | return false; |
72 | } |
73 | |
74 | bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl, |
75 | DeclaratorDecl *NewDecl) { |
76 | return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); |
77 | } |
78 | |
79 | bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl, |
80 | TagDecl *NewDecl) { |
81 | return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs); |
82 | } |
83 | |
84 | // Include attribute instantiation code. |
85 | #include "clang/Sema/AttrTemplateInstantiate.inc" |
86 | |
87 | static void instantiateDependentAlignedAttr( |
88 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
89 | const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) { |
90 | if (Aligned->isAlignmentExpr()) { |
91 | // The alignment expression is a constant expression. |
92 | EnterExpressionEvaluationContext Unevaluated( |
93 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
94 | ExprResult Result = S.SubstExpr(E: Aligned->getAlignmentExpr(), TemplateArgs); |
95 | if (!Result.isInvalid()) |
96 | S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion); |
97 | } else { |
98 | if (TypeSourceInfo *Result = |
99 | S.SubstType(Aligned->getAlignmentType(), TemplateArgs, |
100 | Aligned->getLocation(), DeclarationName())) { |
101 | if (!S.CheckAlignasTypeArgument(KWName: Aligned->getSpelling(), TInfo: Result, |
102 | OpLoc: Aligned->getLocation(), |
103 | R: Result->getTypeLoc().getSourceRange())) |
104 | S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion); |
105 | } |
106 | } |
107 | } |
108 | |
109 | static void instantiateDependentAlignedAttr( |
110 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
111 | const AlignedAttr *Aligned, Decl *New) { |
112 | if (!Aligned->isPackExpansion()) { |
113 | instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); |
114 | return; |
115 | } |
116 | |
117 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
118 | if (Aligned->isAlignmentExpr()) |
119 | S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(), |
120 | Unexpanded); |
121 | else |
122 | S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(), |
123 | Unexpanded); |
124 | assert(!Unexpanded.empty() && "Pack expansion without parameter packs?" ); |
125 | |
126 | // Determine whether we can expand this attribute pack yet. |
127 | bool Expand = true, RetainExpansion = false; |
128 | std::optional<unsigned> NumExpansions; |
129 | // FIXME: Use the actual location of the ellipsis. |
130 | SourceLocation EllipsisLoc = Aligned->getLocation(); |
131 | if (S.CheckParameterPacksForExpansion(EllipsisLoc, PatternRange: Aligned->getRange(), |
132 | Unexpanded, TemplateArgs, ShouldExpand&: Expand, |
133 | RetainExpansion, NumExpansions)) |
134 | return; |
135 | |
136 | if (!Expand) { |
137 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1); |
138 | instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true); |
139 | } else { |
140 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
141 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I); |
142 | instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false); |
143 | } |
144 | } |
145 | } |
146 | |
147 | static void instantiateDependentAssumeAlignedAttr( |
148 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
149 | const AssumeAlignedAttr *Aligned, Decl *New) { |
150 | // The alignment expression is a constant expression. |
151 | EnterExpressionEvaluationContext Unevaluated( |
152 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
153 | |
154 | Expr *E, *OE = nullptr; |
155 | ExprResult Result = S.SubstExpr(E: Aligned->getAlignment(), TemplateArgs); |
156 | if (Result.isInvalid()) |
157 | return; |
158 | E = Result.getAs<Expr>(); |
159 | |
160 | if (Aligned->getOffset()) { |
161 | Result = S.SubstExpr(E: Aligned->getOffset(), TemplateArgs); |
162 | if (Result.isInvalid()) |
163 | return; |
164 | OE = Result.getAs<Expr>(); |
165 | } |
166 | |
167 | S.AddAssumeAlignedAttr(D: New, CI: *Aligned, E, OE); |
168 | } |
169 | |
170 | static void instantiateDependentAlignValueAttr( |
171 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
172 | const AlignValueAttr *Aligned, Decl *New) { |
173 | // The alignment expression is a constant expression. |
174 | EnterExpressionEvaluationContext Unevaluated( |
175 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
176 | ExprResult Result = S.SubstExpr(E: Aligned->getAlignment(), TemplateArgs); |
177 | if (!Result.isInvalid()) |
178 | S.AddAlignValueAttr(D: New, CI: *Aligned, E: Result.getAs<Expr>()); |
179 | } |
180 | |
181 | static void instantiateDependentAllocAlignAttr( |
182 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
183 | const AllocAlignAttr *Align, Decl *New) { |
184 | Expr *Param = IntegerLiteral::Create( |
185 | S.getASTContext(), |
186 | llvm::APInt(64, Align->getParamIndex().getSourceIndex()), |
187 | S.getASTContext().UnsignedLongLongTy, Align->getLocation()); |
188 | S.AddAllocAlignAttr(D: New, CI: *Align, ParamExpr: Param); |
189 | } |
190 | |
191 | static void instantiateDependentAnnotationAttr( |
192 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
193 | const AnnotateAttr *Attr, Decl *New) { |
194 | EnterExpressionEvaluationContext Unevaluated( |
195 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
196 | |
197 | // If the attribute has delayed arguments it will have to instantiate those |
198 | // and handle them as new arguments for the attribute. |
199 | bool HasDelayedArgs = Attr->delayedArgs_size(); |
200 | |
201 | ArrayRef<Expr *> ArgsToInstantiate = |
202 | HasDelayedArgs |
203 | ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()} |
204 | : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()}; |
205 | |
206 | SmallVector<Expr *, 4> Args; |
207 | if (S.SubstExprs(Exprs: ArgsToInstantiate, |
208 | /*IsCall=*/false, TemplateArgs, Outputs&: Args)) |
209 | return; |
210 | |
211 | StringRef Str = Attr->getAnnotation(); |
212 | if (HasDelayedArgs) { |
213 | if (Args.size() < 1) { |
214 | S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments) |
215 | << Attr << 1; |
216 | return; |
217 | } |
218 | |
219 | if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str)) |
220 | return; |
221 | |
222 | llvm::SmallVector<Expr *, 4> ActualArgs; |
223 | ActualArgs.insert(I: ActualArgs.begin(), From: Args.begin() + 1, To: Args.end()); |
224 | std::swap(LHS&: Args, RHS&: ActualArgs); |
225 | } |
226 | S.AddAnnotationAttr(D: New, CI: *Attr, Annot: Str, Args); |
227 | } |
228 | |
229 | static Expr *instantiateDependentFunctionAttrCondition( |
230 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
231 | const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) { |
232 | Expr *Cond = nullptr; |
233 | { |
234 | Sema::ContextRAII SwitchContext(S, New); |
235 | EnterExpressionEvaluationContext Unevaluated( |
236 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
237 | ExprResult Result = S.SubstExpr(E: OldCond, TemplateArgs); |
238 | if (Result.isInvalid()) |
239 | return nullptr; |
240 | Cond = Result.getAs<Expr>(); |
241 | } |
242 | if (!Cond->isTypeDependent()) { |
243 | ExprResult Converted = S.PerformContextuallyConvertToBool(From: Cond); |
244 | if (Converted.isInvalid()) |
245 | return nullptr; |
246 | Cond = Converted.get(); |
247 | } |
248 | |
249 | SmallVector<PartialDiagnosticAt, 8> Diags; |
250 | if (OldCond->isValueDependent() && !Cond->isValueDependent() && |
251 | !Expr::isPotentialConstantExprUnevaluated(E: Cond, FD: New, Diags)) { |
252 | S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A; |
253 | for (const auto &P : Diags) |
254 | S.Diag(Loc: P.first, PD: P.second); |
255 | return nullptr; |
256 | } |
257 | return Cond; |
258 | } |
259 | |
260 | static void instantiateDependentEnableIfAttr( |
261 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
262 | const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) { |
263 | Expr *Cond = instantiateDependentFunctionAttrCondition( |
264 | S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New); |
265 | |
266 | if (Cond) |
267 | New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA, |
268 | Cond, EIA->getMessage())); |
269 | } |
270 | |
271 | static void instantiateDependentDiagnoseIfAttr( |
272 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
273 | const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) { |
274 | Expr *Cond = instantiateDependentFunctionAttrCondition( |
275 | S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New); |
276 | |
277 | if (Cond) |
278 | New->addAttr(new (S.getASTContext()) DiagnoseIfAttr( |
279 | S.getASTContext(), *DIA, Cond, DIA->getMessage(), |
280 | DIA->getDiagnosticType(), DIA->getArgDependent(), New)); |
281 | } |
282 | |
283 | // Constructs and adds to New a new instance of CUDALaunchBoundsAttr using |
284 | // template A as the base and arguments from TemplateArgs. |
285 | static void instantiateDependentCUDALaunchBoundsAttr( |
286 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
287 | const CUDALaunchBoundsAttr &Attr, Decl *New) { |
288 | // The alignment expression is a constant expression. |
289 | EnterExpressionEvaluationContext Unevaluated( |
290 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
291 | |
292 | ExprResult Result = S.SubstExpr(E: Attr.getMaxThreads(), TemplateArgs); |
293 | if (Result.isInvalid()) |
294 | return; |
295 | Expr *MaxThreads = Result.getAs<Expr>(); |
296 | |
297 | Expr *MinBlocks = nullptr; |
298 | if (Attr.getMinBlocks()) { |
299 | Result = S.SubstExpr(E: Attr.getMinBlocks(), TemplateArgs); |
300 | if (Result.isInvalid()) |
301 | return; |
302 | MinBlocks = Result.getAs<Expr>(); |
303 | } |
304 | |
305 | Expr *MaxBlocks = nullptr; |
306 | if (Attr.getMaxBlocks()) { |
307 | Result = S.SubstExpr(E: Attr.getMaxBlocks(), TemplateArgs); |
308 | if (Result.isInvalid()) |
309 | return; |
310 | MaxBlocks = Result.getAs<Expr>(); |
311 | } |
312 | |
313 | S.AddLaunchBoundsAttr(D: New, CI: Attr, MaxThreads, MinBlocks, MaxBlocks); |
314 | } |
315 | |
316 | static void |
317 | instantiateDependentModeAttr(Sema &S, |
318 | const MultiLevelTemplateArgumentList &TemplateArgs, |
319 | const ModeAttr &Attr, Decl *New) { |
320 | S.AddModeAttr(D: New, CI: Attr, Name: Attr.getMode(), |
321 | /*InInstantiation=*/true); |
322 | } |
323 | |
324 | /// Instantiation of 'declare simd' attribute and its arguments. |
325 | static void instantiateOMPDeclareSimdDeclAttr( |
326 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
327 | const OMPDeclareSimdDeclAttr &Attr, Decl *New) { |
328 | // Allow 'this' in clauses with varlists. |
329 | if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: New)) |
330 | New = FTD->getTemplatedDecl(); |
331 | auto *FD = cast<FunctionDecl>(Val: New); |
332 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext()); |
333 | SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps; |
334 | SmallVector<unsigned, 4> LinModifiers; |
335 | |
336 | auto SubstExpr = [&](Expr *E) -> ExprResult { |
337 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts())) |
338 | if (auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) { |
339 | Sema::ContextRAII SavedContext(S, FD); |
340 | LocalInstantiationScope Local(S); |
341 | if (FD->getNumParams() > PVD->getFunctionScopeIndex()) |
342 | Local.InstantiatedLocal( |
343 | PVD, FD->getParamDecl(i: PVD->getFunctionScopeIndex())); |
344 | return S.SubstExpr(E, TemplateArgs); |
345 | } |
346 | Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(), |
347 | FD->isCXXInstanceMember()); |
348 | return S.SubstExpr(E, TemplateArgs); |
349 | }; |
350 | |
351 | // Substitute a single OpenMP clause, which is a potentially-evaluated |
352 | // full-expression. |
353 | auto Subst = [&](Expr *E) -> ExprResult { |
354 | EnterExpressionEvaluationContext Evaluated( |
355 | S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
356 | ExprResult Res = SubstExpr(E); |
357 | if (Res.isInvalid()) |
358 | return Res; |
359 | return S.ActOnFinishFullExpr(Expr: Res.get(), DiscardedValue: false); |
360 | }; |
361 | |
362 | ExprResult Simdlen; |
363 | if (auto *E = Attr.getSimdlen()) |
364 | Simdlen = Subst(E); |
365 | |
366 | if (Attr.uniforms_size() > 0) { |
367 | for(auto *E : Attr.uniforms()) { |
368 | ExprResult Inst = Subst(E); |
369 | if (Inst.isInvalid()) |
370 | continue; |
371 | Uniforms.push_back(Inst.get()); |
372 | } |
373 | } |
374 | |
375 | auto AI = Attr.alignments_begin(); |
376 | for (auto *E : Attr.aligneds()) { |
377 | ExprResult Inst = Subst(E); |
378 | if (Inst.isInvalid()) |
379 | continue; |
380 | Aligneds.push_back(Inst.get()); |
381 | Inst = ExprEmpty(); |
382 | if (*AI) |
383 | Inst = S.SubstExpr(*AI, TemplateArgs); |
384 | Alignments.push_back(Inst.get()); |
385 | ++AI; |
386 | } |
387 | |
388 | auto SI = Attr.steps_begin(); |
389 | for (auto *E : Attr.linears()) { |
390 | ExprResult Inst = Subst(E); |
391 | if (Inst.isInvalid()) |
392 | continue; |
393 | Linears.push_back(Inst.get()); |
394 | Inst = ExprEmpty(); |
395 | if (*SI) |
396 | Inst = S.SubstExpr(*SI, TemplateArgs); |
397 | Steps.push_back(Inst.get()); |
398 | ++SI; |
399 | } |
400 | LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end()); |
401 | (void)S.ActOnOpenMPDeclareSimdDirective( |
402 | S.ConvertDeclToDeclGroup(Ptr: New), Attr.getBranchState(), Simdlen.get(), |
403 | Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps, |
404 | Attr.getRange()); |
405 | } |
406 | |
407 | /// Instantiation of 'declare variant' attribute and its arguments. |
408 | static void instantiateOMPDeclareVariantAttr( |
409 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
410 | const OMPDeclareVariantAttr &Attr, Decl *New) { |
411 | // Allow 'this' in clauses with varlists. |
412 | if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: New)) |
413 | New = FTD->getTemplatedDecl(); |
414 | auto *FD = cast<FunctionDecl>(Val: New); |
415 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext()); |
416 | |
417 | auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) { |
418 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts())) |
419 | if (auto *PVD = dyn_cast<ParmVarDecl>(Val: DRE->getDecl())) { |
420 | Sema::ContextRAII SavedContext(S, FD); |
421 | LocalInstantiationScope Local(S); |
422 | if (FD->getNumParams() > PVD->getFunctionScopeIndex()) |
423 | Local.InstantiatedLocal( |
424 | PVD, FD->getParamDecl(i: PVD->getFunctionScopeIndex())); |
425 | return S.SubstExpr(E, TemplateArgs); |
426 | } |
427 | Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(), |
428 | FD->isCXXInstanceMember()); |
429 | return S.SubstExpr(E, TemplateArgs); |
430 | }; |
431 | |
432 | // Substitute a single OpenMP clause, which is a potentially-evaluated |
433 | // full-expression. |
434 | auto &&Subst = [&SubstExpr, &S](Expr *E) { |
435 | EnterExpressionEvaluationContext Evaluated( |
436 | S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
437 | ExprResult Res = SubstExpr(E); |
438 | if (Res.isInvalid()) |
439 | return Res; |
440 | return S.ActOnFinishFullExpr(Expr: Res.get(), DiscardedValue: false); |
441 | }; |
442 | |
443 | ExprResult VariantFuncRef; |
444 | if (Expr *E = Attr.getVariantFuncRef()) { |
445 | // Do not mark function as is used to prevent its emission if this is the |
446 | // only place where it is used. |
447 | EnterExpressionEvaluationContext Unevaluated( |
448 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
449 | VariantFuncRef = Subst(E); |
450 | } |
451 | |
452 | // Copy the template version of the OMPTraitInfo and run substitute on all |
453 | // score and condition expressiosn. |
454 | OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo(); |
455 | TI = *Attr.getTraitInfos(); |
456 | |
457 | // Try to substitute template parameters in score and condition expressions. |
458 | auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) { |
459 | if (E) { |
460 | EnterExpressionEvaluationContext Unevaluated( |
461 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
462 | ExprResult ER = Subst(E); |
463 | if (ER.isUsable()) |
464 | E = ER.get(); |
465 | else |
466 | return true; |
467 | } |
468 | return false; |
469 | }; |
470 | if (TI.anyScoreOrCondition(Cond: SubstScoreOrConditionExpr)) |
471 | return; |
472 | |
473 | Expr *E = VariantFuncRef.get(); |
474 | |
475 | // Check function/variant ref for `omp declare variant` but not for `omp |
476 | // begin declare variant` (which use implicit attributes). |
477 | std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData = |
478 | S.checkOpenMPDeclareVariantFunction(DG: S.ConvertDeclToDeclGroup(Ptr: New), VariantRef: E, TI, |
479 | NumAppendArgs: Attr.appendArgs_size(), |
480 | SR: Attr.getRange()); |
481 | |
482 | if (!DeclVarData) |
483 | return; |
484 | |
485 | E = DeclVarData->second; |
486 | FD = DeclVarData->first; |
487 | |
488 | if (auto *VariantDRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParenImpCasts())) { |
489 | if (auto *VariantFD = dyn_cast<FunctionDecl>(Val: VariantDRE->getDecl())) { |
490 | if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) { |
491 | if (!VariantFTD->isThisDeclarationADefinition()) |
492 | return; |
493 | Sema::TentativeAnalysisScope Trap(S); |
494 | const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy( |
495 | Context&: S.Context, Args: TemplateArgs.getInnermost()); |
496 | |
497 | auto *SubstFD = S.InstantiateFunctionDeclaration(FTD: VariantFTD, Args: TAL, |
498 | Loc: New->getLocation()); |
499 | if (!SubstFD) |
500 | return; |
501 | QualType NewType = S.Context.mergeFunctionTypes( |
502 | SubstFD->getType(), FD->getType(), |
503 | /* OfBlockPointer */ false, |
504 | /* Unqualified */ false, /* AllowCXX */ true); |
505 | if (NewType.isNull()) |
506 | return; |
507 | S.InstantiateFunctionDefinition( |
508 | PointOfInstantiation: New->getLocation(), Function: SubstFD, /* Recursive */ true, |
509 | /* DefinitionRequired */ false, /* AtEndOfTU */ false); |
510 | SubstFD->setInstantiationIsPending(!SubstFD->isDefined()); |
511 | E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(), |
512 | SourceLocation(), SubstFD, |
513 | /* RefersToEnclosingVariableOrCapture */ false, |
514 | /* NameLoc */ SubstFD->getLocation(), |
515 | SubstFD->getType(), ExprValueKind::VK_PRValue); |
516 | } |
517 | } |
518 | } |
519 | |
520 | SmallVector<Expr *, 8> NothingExprs; |
521 | SmallVector<Expr *, 8> NeedDevicePtrExprs; |
522 | SmallVector<OMPInteropInfo, 4> AppendArgs; |
523 | |
524 | for (Expr *E : Attr.adjustArgsNothing()) { |
525 | ExprResult ER = Subst(E); |
526 | if (ER.isInvalid()) |
527 | continue; |
528 | NothingExprs.push_back(ER.get()); |
529 | } |
530 | for (Expr *E : Attr.adjustArgsNeedDevicePtr()) { |
531 | ExprResult ER = Subst(E); |
532 | if (ER.isInvalid()) |
533 | continue; |
534 | NeedDevicePtrExprs.push_back(ER.get()); |
535 | } |
536 | for (OMPInteropInfo &II : Attr.appendArgs()) { |
537 | // When prefer_type is implemented for append_args handle them here too. |
538 | AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync); |
539 | } |
540 | |
541 | S.ActOnOpenMPDeclareVariantDirective( |
542 | FD, VariantRef: E, TI, AdjustArgsNothing: NothingExprs, AdjustArgsNeedDevicePtr: NeedDevicePtrExprs, AppendArgs, AdjustArgsLoc: SourceLocation(), |
543 | AppendArgsLoc: SourceLocation(), SR: Attr.getRange()); |
544 | } |
545 | |
546 | static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr( |
547 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
548 | const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) { |
549 | // Both min and max expression are constant expressions. |
550 | EnterExpressionEvaluationContext Unevaluated( |
551 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
552 | |
553 | ExprResult Result = S.SubstExpr(E: Attr.getMin(), TemplateArgs); |
554 | if (Result.isInvalid()) |
555 | return; |
556 | Expr *MinExpr = Result.getAs<Expr>(); |
557 | |
558 | Result = S.SubstExpr(E: Attr.getMax(), TemplateArgs); |
559 | if (Result.isInvalid()) |
560 | return; |
561 | Expr *MaxExpr = Result.getAs<Expr>(); |
562 | |
563 | S.addAMDGPUFlatWorkGroupSizeAttr(D: New, CI: Attr, Min: MinExpr, Max: MaxExpr); |
564 | } |
565 | |
566 | ExplicitSpecifier Sema::instantiateExplicitSpecifier( |
567 | const MultiLevelTemplateArgumentList &TemplateArgs, ExplicitSpecifier ES) { |
568 | if (!ES.getExpr()) |
569 | return ES; |
570 | Expr *OldCond = ES.getExpr(); |
571 | Expr *Cond = nullptr; |
572 | { |
573 | EnterExpressionEvaluationContext Unevaluated( |
574 | *this, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
575 | ExprResult SubstResult = SubstExpr(E: OldCond, TemplateArgs); |
576 | if (SubstResult.isInvalid()) { |
577 | return ExplicitSpecifier::Invalid(); |
578 | } |
579 | Cond = SubstResult.get(); |
580 | } |
581 | ExplicitSpecifier Result(Cond, ES.getKind()); |
582 | if (!Cond->isTypeDependent()) |
583 | tryResolveExplicitSpecifier(ExplicitSpec&: Result); |
584 | return Result; |
585 | } |
586 | |
587 | static void instantiateDependentAMDGPUWavesPerEUAttr( |
588 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
589 | const AMDGPUWavesPerEUAttr &Attr, Decl *New) { |
590 | // Both min and max expression are constant expressions. |
591 | EnterExpressionEvaluationContext Unevaluated( |
592 | S, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
593 | |
594 | ExprResult Result = S.SubstExpr(E: Attr.getMin(), TemplateArgs); |
595 | if (Result.isInvalid()) |
596 | return; |
597 | Expr *MinExpr = Result.getAs<Expr>(); |
598 | |
599 | Expr *MaxExpr = nullptr; |
600 | if (auto Max = Attr.getMax()) { |
601 | Result = S.SubstExpr(E: Max, TemplateArgs); |
602 | if (Result.isInvalid()) |
603 | return; |
604 | MaxExpr = Result.getAs<Expr>(); |
605 | } |
606 | |
607 | S.addAMDGPUWavesPerEUAttr(D: New, CI: Attr, Min: MinExpr, Max: MaxExpr); |
608 | } |
609 | |
610 | // This doesn't take any template parameters, but we have a custom action that |
611 | // needs to happen when the kernel itself is instantiated. We need to run the |
612 | // ItaniumMangler to mark the names required to name this kernel. |
613 | static void instantiateDependentSYCLKernelAttr( |
614 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
615 | const SYCLKernelAttr &Attr, Decl *New) { |
616 | New->addAttr(A: Attr.clone(S.getASTContext())); |
617 | } |
618 | |
619 | /// Determine whether the attribute A might be relevant to the declaration D. |
620 | /// If not, we can skip instantiating it. The attribute may or may not have |
621 | /// been instantiated yet. |
622 | static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) { |
623 | // 'preferred_name' is only relevant to the matching specialization of the |
624 | // template. |
625 | if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) { |
626 | QualType T = PNA->getTypedefType(); |
627 | const auto *RD = cast<CXXRecordDecl>(Val: D); |
628 | if (!T->isDependentType() && !RD->isDependentContext() && |
629 | !declaresSameEntity(T->getAsCXXRecordDecl(), RD)) |
630 | return false; |
631 | for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>()) |
632 | if (S.Context.hasSameType(ExistingPNA->getTypedefType(), |
633 | PNA->getTypedefType())) |
634 | return false; |
635 | return true; |
636 | } |
637 | |
638 | if (const auto *BA = dyn_cast<BuiltinAttr>(A)) { |
639 | const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D); |
640 | switch (BA->getID()) { |
641 | case Builtin::BIforward: |
642 | // Do not treat 'std::forward' as a builtin if it takes an rvalue reference |
643 | // type and returns an lvalue reference type. The library implementation |
644 | // will produce an error in this case; don't get in its way. |
645 | if (FD && FD->getNumParams() >= 1 && |
646 | FD->getParamDecl(i: 0)->getType()->isRValueReferenceType() && |
647 | FD->getReturnType()->isLValueReferenceType()) { |
648 | return false; |
649 | } |
650 | [[fallthrough]]; |
651 | case Builtin::BImove: |
652 | case Builtin::BImove_if_noexcept: |
653 | // HACK: Super-old versions of libc++ (3.1 and earlier) provide |
654 | // std::forward and std::move overloads that sometimes return by value |
655 | // instead of by reference when building in C++98 mode. Don't treat such |
656 | // cases as builtins. |
657 | if (FD && !FD->getReturnType()->isReferenceType()) |
658 | return false; |
659 | break; |
660 | } |
661 | } |
662 | |
663 | return true; |
664 | } |
665 | |
666 | static void instantiateDependentHLSLParamModifierAttr( |
667 | Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs, |
668 | const HLSLParamModifierAttr *Attr, Decl *New) { |
669 | ParmVarDecl *P = cast<ParmVarDecl>(Val: New); |
670 | P->addAttr(A: Attr->clone(S.getASTContext())); |
671 | P->setType(S.getASTContext().getLValueReferenceType(T: P->getType())); |
672 | } |
673 | |
674 | void Sema::InstantiateAttrsForDecl( |
675 | const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl, |
676 | Decl *New, LateInstantiatedAttrVec *LateAttrs, |
677 | LocalInstantiationScope *OuterMostScope) { |
678 | if (NamedDecl *ND = dyn_cast<NamedDecl>(Val: New)) { |
679 | // FIXME: This function is called multiple times for the same template |
680 | // specialization. We should only instantiate attributes that were added |
681 | // since the previous instantiation. |
682 | for (const auto *TmplAttr : Tmpl->attrs()) { |
683 | if (!isRelevantAttr(*this, New, TmplAttr)) |
684 | continue; |
685 | |
686 | // FIXME: If any of the special case versions from InstantiateAttrs become |
687 | // applicable to template declaration, we'll need to add them here. |
688 | CXXThisScopeRAII ThisScope( |
689 | *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()), |
690 | Qualifiers(), ND->isCXXInstanceMember()); |
691 | |
692 | Attr *NewAttr = sema::instantiateTemplateAttributeForDecl( |
693 | TmplAttr, Context, *this, TemplateArgs); |
694 | if (NewAttr && isRelevantAttr(*this, New, NewAttr)) |
695 | New->addAttr(NewAttr); |
696 | } |
697 | } |
698 | } |
699 | |
700 | static Sema::RetainOwnershipKind |
701 | attrToRetainOwnershipKind(const Attr *A) { |
702 | switch (A->getKind()) { |
703 | case clang::attr::CFConsumed: |
704 | return Sema::RetainOwnershipKind::CF; |
705 | case clang::attr::OSConsumed: |
706 | return Sema::RetainOwnershipKind::OS; |
707 | case clang::attr::NSConsumed: |
708 | return Sema::RetainOwnershipKind::NS; |
709 | default: |
710 | llvm_unreachable("Wrong argument supplied" ); |
711 | } |
712 | } |
713 | |
714 | void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, |
715 | const Decl *Tmpl, Decl *New, |
716 | LateInstantiatedAttrVec *LateAttrs, |
717 | LocalInstantiationScope *OuterMostScope) { |
718 | for (const auto *TmplAttr : Tmpl->attrs()) { |
719 | if (!isRelevantAttr(*this, New, TmplAttr)) |
720 | continue; |
721 | |
722 | // FIXME: This should be generalized to more than just the AlignedAttr. |
723 | const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr); |
724 | if (Aligned && Aligned->isAlignmentDependent()) { |
725 | instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New); |
726 | continue; |
727 | } |
728 | |
729 | if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) { |
730 | instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New); |
731 | continue; |
732 | } |
733 | |
734 | if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) { |
735 | instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New); |
736 | continue; |
737 | } |
738 | |
739 | if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) { |
740 | instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New); |
741 | continue; |
742 | } |
743 | |
744 | if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) { |
745 | instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New); |
746 | continue; |
747 | } |
748 | |
749 | if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) { |
750 | instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl, |
751 | cast<FunctionDecl>(New)); |
752 | continue; |
753 | } |
754 | |
755 | if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) { |
756 | instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl, |
757 | cast<FunctionDecl>(New)); |
758 | continue; |
759 | } |
760 | |
761 | if (const auto *CUDALaunchBounds = |
762 | dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) { |
763 | instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs, |
764 | *CUDALaunchBounds, New); |
765 | continue; |
766 | } |
767 | |
768 | if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) { |
769 | instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New); |
770 | continue; |
771 | } |
772 | |
773 | if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) { |
774 | instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New); |
775 | continue; |
776 | } |
777 | |
778 | if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) { |
779 | instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New); |
780 | continue; |
781 | } |
782 | |
783 | if (const auto *AMDGPUFlatWorkGroupSize = |
784 | dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) { |
785 | instantiateDependentAMDGPUFlatWorkGroupSizeAttr( |
786 | *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New); |
787 | } |
788 | |
789 | if (const auto *AMDGPUFlatWorkGroupSize = |
790 | dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) { |
791 | instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs, |
792 | *AMDGPUFlatWorkGroupSize, New); |
793 | } |
794 | |
795 | if (const auto *ParamAttr = dyn_cast<HLSLParamModifierAttr>(TmplAttr)) { |
796 | instantiateDependentHLSLParamModifierAttr(*this, TemplateArgs, ParamAttr, |
797 | New); |
798 | continue; |
799 | } |
800 | |
801 | // Existing DLL attribute on the instantiation takes precedence. |
802 | if (TmplAttr->getKind() == attr::DLLExport || |
803 | TmplAttr->getKind() == attr::DLLImport) { |
804 | if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) { |
805 | continue; |
806 | } |
807 | } |
808 | |
809 | if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) { |
810 | AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI()); |
811 | continue; |
812 | } |
813 | |
814 | if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) || |
815 | isa<CFConsumedAttr>(TmplAttr)) { |
816 | AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr), |
817 | /*template instantiation=*/true); |
818 | continue; |
819 | } |
820 | |
821 | if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) { |
822 | if (!New->hasAttr<PointerAttr>()) |
823 | New->addAttr(A->clone(Context)); |
824 | continue; |
825 | } |
826 | |
827 | if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) { |
828 | if (!New->hasAttr<OwnerAttr>()) |
829 | New->addAttr(A->clone(Context)); |
830 | continue; |
831 | } |
832 | |
833 | if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) { |
834 | instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New); |
835 | continue; |
836 | } |
837 | |
838 | assert(!TmplAttr->isPackExpansion()); |
839 | if (TmplAttr->isLateParsed() && LateAttrs) { |
840 | // Late parsed attributes must be instantiated and attached after the |
841 | // enclosing class has been instantiated. See Sema::InstantiateClass. |
842 | LocalInstantiationScope *Saved = nullptr; |
843 | if (CurrentInstantiationScope) |
844 | Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope); |
845 | LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New)); |
846 | } else { |
847 | // Allow 'this' within late-parsed attributes. |
848 | auto *ND = cast<NamedDecl>(New); |
849 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()); |
850 | CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(), |
851 | ND->isCXXInstanceMember()); |
852 | |
853 | Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context, |
854 | *this, TemplateArgs); |
855 | if (NewAttr && isRelevantAttr(*this, New, TmplAttr)) |
856 | New->addAttr(NewAttr); |
857 | } |
858 | } |
859 | } |
860 | |
861 | /// Update instantiation attributes after template was late parsed. |
862 | /// |
863 | /// Some attributes are evaluated based on the body of template. If it is |
864 | /// late parsed, such attributes cannot be evaluated when declaration is |
865 | /// instantiated. This function is used to update instantiation attributes when |
866 | /// template definition is ready. |
867 | void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) { |
868 | for (const auto *Attr : Pattern->attrs()) { |
869 | if (auto *A = dyn_cast<StrictFPAttr>(Attr)) { |
870 | if (!Inst->hasAttr<StrictFPAttr>()) |
871 | Inst->addAttr(A->clone(getASTContext())); |
872 | continue; |
873 | } |
874 | } |
875 | } |
876 | |
877 | /// In the MS ABI, we need to instantiate default arguments of dllexported |
878 | /// default constructors along with the constructor definition. This allows IR |
879 | /// gen to emit a constructor closure which calls the default constructor with |
880 | /// its default arguments. |
881 | void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) { |
882 | assert(Context.getTargetInfo().getCXXABI().isMicrosoft() && |
883 | Ctor->isDefaultConstructor()); |
884 | unsigned NumParams = Ctor->getNumParams(); |
885 | if (NumParams == 0) |
886 | return; |
887 | DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>(); |
888 | if (!Attr) |
889 | return; |
890 | for (unsigned I = 0; I != NumParams; ++I) { |
891 | (void)CheckCXXDefaultArgExpr(CallLoc: Attr->getLocation(), FD: Ctor, |
892 | Param: Ctor->getParamDecl(I)); |
893 | CleanupVarDeclMarking(); |
894 | } |
895 | } |
896 | |
897 | /// Get the previous declaration of a declaration for the purposes of template |
898 | /// instantiation. If this finds a previous declaration, then the previous |
899 | /// declaration of the instantiation of D should be an instantiation of the |
900 | /// result of this function. |
901 | template<typename DeclT> |
902 | static DeclT *getPreviousDeclForInstantiation(DeclT *D) { |
903 | DeclT *Result = D->getPreviousDecl(); |
904 | |
905 | // If the declaration is within a class, and the previous declaration was |
906 | // merged from a different definition of that class, then we don't have a |
907 | // previous declaration for the purpose of template instantiation. |
908 | if (Result && isa<CXXRecordDecl>(D->getDeclContext()) && |
909 | D->getLexicalDeclContext() != Result->getLexicalDeclContext()) |
910 | return nullptr; |
911 | |
912 | return Result; |
913 | } |
914 | |
915 | Decl * |
916 | TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) { |
917 | llvm_unreachable("Translation units cannot be instantiated" ); |
918 | } |
919 | |
920 | Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) { |
921 | llvm_unreachable("HLSL buffer declarations cannot be instantiated" ); |
922 | } |
923 | |
924 | Decl * |
925 | TemplateDeclInstantiator::(PragmaCommentDecl *D) { |
926 | llvm_unreachable("pragma comment cannot be instantiated" ); |
927 | } |
928 | |
929 | Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl( |
930 | PragmaDetectMismatchDecl *D) { |
931 | llvm_unreachable("pragma comment cannot be instantiated" ); |
932 | } |
933 | |
934 | Decl * |
935 | TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) { |
936 | llvm_unreachable("extern \"C\" context cannot be instantiated" ); |
937 | } |
938 | |
939 | Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) { |
940 | llvm_unreachable("GUID declaration cannot be instantiated" ); |
941 | } |
942 | |
943 | Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl( |
944 | UnnamedGlobalConstantDecl *D) { |
945 | llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated" ); |
946 | } |
947 | |
948 | Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl( |
949 | TemplateParamObjectDecl *D) { |
950 | llvm_unreachable("template parameter objects cannot be instantiated" ); |
951 | } |
952 | |
953 | Decl * |
954 | TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) { |
955 | LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(), |
956 | D->getIdentifier()); |
957 | Owner->addDecl(Inst); |
958 | return Inst; |
959 | } |
960 | |
961 | Decl * |
962 | TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) { |
963 | llvm_unreachable("Namespaces cannot be instantiated" ); |
964 | } |
965 | |
966 | Decl * |
967 | TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { |
968 | NamespaceAliasDecl *Inst |
969 | = NamespaceAliasDecl::Create(C&: SemaRef.Context, DC: Owner, |
970 | NamespaceLoc: D->getNamespaceLoc(), |
971 | AliasLoc: D->getAliasLoc(), |
972 | Alias: D->getIdentifier(), |
973 | QualifierLoc: D->getQualifierLoc(), |
974 | IdentLoc: D->getTargetNameLoc(), |
975 | Namespace: D->getNamespace()); |
976 | Owner->addDecl(Inst); |
977 | return Inst; |
978 | } |
979 | |
980 | Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D, |
981 | bool IsTypeAlias) { |
982 | bool Invalid = false; |
983 | TypeSourceInfo *DI = D->getTypeSourceInfo(); |
984 | if (DI->getType()->isInstantiationDependentType() || |
985 | DI->getType()->isVariablyModifiedType()) { |
986 | DI = SemaRef.SubstType(DI, TemplateArgs, |
987 | D->getLocation(), D->getDeclName()); |
988 | if (!DI) { |
989 | Invalid = true; |
990 | DI = SemaRef.Context.getTrivialTypeSourceInfo(T: SemaRef.Context.IntTy); |
991 | } |
992 | } else { |
993 | SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: DI->getType()); |
994 | } |
995 | |
996 | // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong. |
997 | // libstdc++ relies upon this bug in its implementation of common_type. If we |
998 | // happen to be processing that implementation, fake up the g++ ?: |
999 | // semantics. See LWG issue 2141 for more information on the bug. The bugs |
1000 | // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22). |
1001 | const DecltypeType *DT = DI->getType()->getAs<DecltypeType>(); |
1002 | CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext()); |
1003 | if (DT && RD && isa<ConditionalOperator>(Val: DT->getUnderlyingExpr()) && |
1004 | DT->isReferenceType() && |
1005 | RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() && |
1006 | RD->getIdentifier() && RD->getIdentifier()->isStr("common_type" ) && |
1007 | D->getIdentifier() && D->getIdentifier()->isStr("type" ) && |
1008 | SemaRef.getSourceManager().isInSystemHeader(Loc: D->getBeginLoc())) |
1009 | // Fold it to the (non-reference) type which g++ would have produced. |
1010 | DI = SemaRef.Context.getTrivialTypeSourceInfo( |
1011 | T: DI->getType().getNonReferenceType()); |
1012 | |
1013 | // Create the new typedef |
1014 | TypedefNameDecl *Typedef; |
1015 | if (IsTypeAlias) |
1016 | Typedef = TypeAliasDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(), |
1017 | IdLoc: D->getLocation(), Id: D->getIdentifier(), TInfo: DI); |
1018 | else |
1019 | Typedef = TypedefDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(), |
1020 | IdLoc: D->getLocation(), Id: D->getIdentifier(), TInfo: DI); |
1021 | if (Invalid) |
1022 | Typedef->setInvalidDecl(); |
1023 | |
1024 | // If the old typedef was the name for linkage purposes of an anonymous |
1025 | // tag decl, re-establish that relationship for the new typedef. |
1026 | if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) { |
1027 | TagDecl *oldTag = oldTagType->getDecl(); |
1028 | if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) { |
1029 | TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl(); |
1030 | assert(!newTag->hasNameForLinkage()); |
1031 | newTag->setTypedefNameForAnonDecl(Typedef); |
1032 | } |
1033 | } |
1034 | |
1035 | if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) { |
1036 | NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: Prev, |
1037 | TemplateArgs); |
1038 | if (!InstPrev) |
1039 | return nullptr; |
1040 | |
1041 | TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(Val: InstPrev); |
1042 | |
1043 | // If the typedef types are not identical, reject them. |
1044 | SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef); |
1045 | |
1046 | Typedef->setPreviousDecl(InstPrevTypedef); |
1047 | } |
1048 | |
1049 | SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef); |
1050 | |
1051 | if (D->getUnderlyingType()->getAs<DependentNameType>()) |
1052 | SemaRef.inferGslPointerAttribute(TD: Typedef); |
1053 | |
1054 | Typedef->setAccess(D->getAccess()); |
1055 | Typedef->setReferenced(D->isReferenced()); |
1056 | |
1057 | return Typedef; |
1058 | } |
1059 | |
1060 | Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) { |
1061 | Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false); |
1062 | if (Typedef) |
1063 | Owner->addDecl(D: Typedef); |
1064 | return Typedef; |
1065 | } |
1066 | |
1067 | Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) { |
1068 | Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true); |
1069 | if (Typedef) |
1070 | Owner->addDecl(D: Typedef); |
1071 | return Typedef; |
1072 | } |
1073 | |
1074 | Decl * |
1075 | TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { |
1076 | // Create a local instantiation scope for this type alias template, which |
1077 | // will contain the instantiations of the template parameters. |
1078 | LocalInstantiationScope Scope(SemaRef); |
1079 | |
1080 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
1081 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
1082 | if (!InstParams) |
1083 | return nullptr; |
1084 | |
1085 | TypeAliasDecl *Pattern = D->getTemplatedDecl(); |
1086 | |
1087 | TypeAliasTemplateDecl *PrevAliasTemplate = nullptr; |
1088 | if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) { |
1089 | DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName()); |
1090 | if (!Found.empty()) { |
1091 | PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Val: Found.front()); |
1092 | } |
1093 | } |
1094 | |
1095 | TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>( |
1096 | Val: InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true)); |
1097 | if (!AliasInst) |
1098 | return nullptr; |
1099 | |
1100 | TypeAliasTemplateDecl *Inst |
1101 | = TypeAliasTemplateDecl::Create(C&: SemaRef.Context, DC: Owner, L: D->getLocation(), |
1102 | Name: D->getDeclName(), Params: InstParams, Decl: AliasInst); |
1103 | AliasInst->setDescribedAliasTemplate(Inst); |
1104 | if (PrevAliasTemplate) |
1105 | Inst->setPreviousDecl(PrevAliasTemplate); |
1106 | |
1107 | Inst->setAccess(D->getAccess()); |
1108 | |
1109 | if (!PrevAliasTemplate) |
1110 | Inst->setInstantiatedFromMemberTemplate(D); |
1111 | |
1112 | Owner->addDecl(Inst); |
1113 | |
1114 | return Inst; |
1115 | } |
1116 | |
1117 | Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) { |
1118 | auto *NewBD = BindingDecl::Create(C&: SemaRef.Context, DC: Owner, IdLoc: D->getLocation(), |
1119 | Id: D->getIdentifier()); |
1120 | NewBD->setReferenced(D->isReferenced()); |
1121 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewBD); |
1122 | return NewBD; |
1123 | } |
1124 | |
1125 | Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) { |
1126 | // Transform the bindings first. |
1127 | SmallVector<BindingDecl*, 16> NewBindings; |
1128 | for (auto *OldBD : D->bindings()) |
1129 | NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD))); |
1130 | ArrayRef<BindingDecl*> NewBindingArray = NewBindings; |
1131 | |
1132 | auto *NewDD = cast_or_null<DecompositionDecl>( |
1133 | Val: VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray)); |
1134 | |
1135 | if (!NewDD || NewDD->isInvalidDecl()) |
1136 | for (auto *NewBD : NewBindings) |
1137 | NewBD->setInvalidDecl(); |
1138 | |
1139 | return NewDD; |
1140 | } |
1141 | |
1142 | Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) { |
1143 | return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false); |
1144 | } |
1145 | |
1146 | Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D, |
1147 | bool InstantiatingVarTemplate, |
1148 | ArrayRef<BindingDecl*> *Bindings) { |
1149 | |
1150 | // Do substitution on the type of the declaration |
1151 | TypeSourceInfo *DI = SemaRef.SubstType( |
1152 | D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(), |
1153 | D->getDeclName(), /*AllowDeducedTST*/true); |
1154 | if (!DI) |
1155 | return nullptr; |
1156 | |
1157 | if (DI->getType()->isFunctionType()) { |
1158 | SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) |
1159 | << D->isStaticDataMember() << DI->getType(); |
1160 | return nullptr; |
1161 | } |
1162 | |
1163 | DeclContext *DC = Owner; |
1164 | if (D->isLocalExternDecl()) |
1165 | SemaRef.adjustContextForLocalExternDecl(DC); |
1166 | |
1167 | // Build the instantiated declaration. |
1168 | VarDecl *Var; |
1169 | if (Bindings) |
1170 | Var = DecompositionDecl::Create(C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), |
1171 | LSquareLoc: D->getLocation(), T: DI->getType(), TInfo: DI, |
1172 | S: D->getStorageClass(), Bindings: *Bindings); |
1173 | else |
1174 | Var = VarDecl::Create(C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), |
1175 | IdLoc: D->getLocation(), Id: D->getIdentifier(), T: DI->getType(), |
1176 | TInfo: DI, S: D->getStorageClass()); |
1177 | |
1178 | // In ARC, infer 'retaining' for variables of retainable type. |
1179 | if (SemaRef.getLangOpts().ObjCAutoRefCount && |
1180 | SemaRef.inferObjCARCLifetime(Var)) |
1181 | Var->setInvalidDecl(); |
1182 | |
1183 | if (SemaRef.getLangOpts().OpenCL) |
1184 | SemaRef.deduceOpenCLAddressSpace(Var); |
1185 | |
1186 | // Substitute the nested name specifier, if any. |
1187 | if (SubstQualifier(D, Var)) |
1188 | return nullptr; |
1189 | |
1190 | SemaRef.BuildVariableInstantiation(NewVar: Var, OldVar: D, TemplateArgs, LateAttrs, Owner, |
1191 | StartingScope, InstantiatingVarTemplate); |
1192 | if (D->isNRVOVariable() && !Var->isInvalidDecl()) { |
1193 | QualType RT; |
1194 | if (auto *F = dyn_cast<FunctionDecl>(Val: DC)) |
1195 | RT = F->getReturnType(); |
1196 | else if (isa<BlockDecl>(Val: DC)) |
1197 | RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType) |
1198 | ->getReturnType(); |
1199 | else |
1200 | llvm_unreachable("Unknown context type" ); |
1201 | |
1202 | // This is the last chance we have of checking copy elision eligibility |
1203 | // for functions in dependent contexts. The sema actions for building |
1204 | // the return statement during template instantiation will have no effect |
1205 | // regarding copy elision, since NRVO propagation runs on the scope exit |
1206 | // actions, and these are not run on instantiation. |
1207 | // This might run through some VarDecls which were returned from non-taken |
1208 | // 'if constexpr' branches, and these will end up being constructed on the |
1209 | // return slot even if they will never be returned, as a sort of accidental |
1210 | // 'optimization'. Notably, functions with 'auto' return types won't have it |
1211 | // deduced by this point. Coupled with the limitation described |
1212 | // previously, this makes it very hard to support copy elision for these. |
1213 | Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(VD: Var); |
1214 | bool NRVO = SemaRef.getCopyElisionCandidate(Info, ReturnType: RT) != nullptr; |
1215 | Var->setNRVOVariable(NRVO); |
1216 | } |
1217 | |
1218 | Var->setImplicit(D->isImplicit()); |
1219 | |
1220 | if (Var->isStaticLocal()) |
1221 | SemaRef.CheckStaticLocalForDllExport(VD: Var); |
1222 | |
1223 | if (Var->getTLSKind()) |
1224 | SemaRef.CheckThreadLocalForLargeAlignment(VD: Var); |
1225 | |
1226 | return Var; |
1227 | } |
1228 | |
1229 | Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) { |
1230 | AccessSpecDecl* AD |
1231 | = AccessSpecDecl::Create(C&: SemaRef.Context, AS: D->getAccess(), DC: Owner, |
1232 | ASLoc: D->getAccessSpecifierLoc(), ColonLoc: D->getColonLoc()); |
1233 | Owner->addHiddenDecl(AD); |
1234 | return AD; |
1235 | } |
1236 | |
1237 | Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) { |
1238 | bool Invalid = false; |
1239 | TypeSourceInfo *DI = D->getTypeSourceInfo(); |
1240 | if (DI->getType()->isInstantiationDependentType() || |
1241 | DI->getType()->isVariablyModifiedType()) { |
1242 | DI = SemaRef.SubstType(DI, TemplateArgs, |
1243 | D->getLocation(), D->getDeclName()); |
1244 | if (!DI) { |
1245 | DI = D->getTypeSourceInfo(); |
1246 | Invalid = true; |
1247 | } else if (DI->getType()->isFunctionType()) { |
1248 | // C++ [temp.arg.type]p3: |
1249 | // If a declaration acquires a function type through a type |
1250 | // dependent on a template-parameter and this causes a |
1251 | // declaration that does not use the syntactic form of a |
1252 | // function declarator to have function type, the program is |
1253 | // ill-formed. |
1254 | SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) |
1255 | << DI->getType(); |
1256 | Invalid = true; |
1257 | } |
1258 | } else { |
1259 | SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: DI->getType()); |
1260 | } |
1261 | |
1262 | Expr *BitWidth = D->getBitWidth(); |
1263 | if (Invalid) |
1264 | BitWidth = nullptr; |
1265 | else if (BitWidth) { |
1266 | // The bit-width expression is a constant expression. |
1267 | EnterExpressionEvaluationContext Unevaluated( |
1268 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
1269 | |
1270 | ExprResult InstantiatedBitWidth |
1271 | = SemaRef.SubstExpr(E: BitWidth, TemplateArgs); |
1272 | if (InstantiatedBitWidth.isInvalid()) { |
1273 | Invalid = true; |
1274 | BitWidth = nullptr; |
1275 | } else |
1276 | BitWidth = InstantiatedBitWidth.getAs<Expr>(); |
1277 | } |
1278 | |
1279 | FieldDecl *Field = SemaRef.CheckFieldDecl(Name: D->getDeclName(), |
1280 | T: DI->getType(), TInfo: DI, |
1281 | Record: cast<RecordDecl>(Val: Owner), |
1282 | Loc: D->getLocation(), |
1283 | Mutable: D->isMutable(), |
1284 | BitfieldWidth: BitWidth, |
1285 | InitStyle: D->getInClassInitStyle(), |
1286 | TSSL: D->getInnerLocStart(), |
1287 | AS: D->getAccess(), |
1288 | PrevDecl: nullptr); |
1289 | if (!Field) { |
1290 | cast<Decl>(Val: Owner)->setInvalidDecl(); |
1291 | return nullptr; |
1292 | } |
1293 | |
1294 | SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope); |
1295 | |
1296 | if (Field->hasAttrs()) |
1297 | SemaRef.CheckAlignasUnderalignment(Field); |
1298 | |
1299 | if (Invalid) |
1300 | Field->setInvalidDecl(); |
1301 | |
1302 | if (!Field->getDeclName()) { |
1303 | // Keep track of where this decl came from. |
1304 | SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Inst: Field, Tmpl: D); |
1305 | } |
1306 | if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) { |
1307 | if (Parent->isAnonymousStructOrUnion() && |
1308 | Parent->getRedeclContext()->isFunctionOrMethod()) |
1309 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field); |
1310 | } |
1311 | |
1312 | Field->setImplicit(D->isImplicit()); |
1313 | Field->setAccess(D->getAccess()); |
1314 | Owner->addDecl(Field); |
1315 | |
1316 | return Field; |
1317 | } |
1318 | |
1319 | Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) { |
1320 | bool Invalid = false; |
1321 | TypeSourceInfo *DI = D->getTypeSourceInfo(); |
1322 | |
1323 | if (DI->getType()->isVariablyModifiedType()) { |
1324 | SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified) |
1325 | << D; |
1326 | Invalid = true; |
1327 | } else if (DI->getType()->isInstantiationDependentType()) { |
1328 | DI = SemaRef.SubstType(DI, TemplateArgs, |
1329 | D->getLocation(), D->getDeclName()); |
1330 | if (!DI) { |
1331 | DI = D->getTypeSourceInfo(); |
1332 | Invalid = true; |
1333 | } else if (DI->getType()->isFunctionType()) { |
1334 | // C++ [temp.arg.type]p3: |
1335 | // If a declaration acquires a function type through a type |
1336 | // dependent on a template-parameter and this causes a |
1337 | // declaration that does not use the syntactic form of a |
1338 | // function declarator to have function type, the program is |
1339 | // ill-formed. |
1340 | SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function) |
1341 | << DI->getType(); |
1342 | Invalid = true; |
1343 | } |
1344 | } else { |
1345 | SemaRef.MarkDeclarationsReferencedInType(Loc: D->getLocation(), T: DI->getType()); |
1346 | } |
1347 | |
1348 | MSPropertyDecl *Property = MSPropertyDecl::Create( |
1349 | C&: SemaRef.Context, DC: Owner, L: D->getLocation(), N: D->getDeclName(), T: DI->getType(), |
1350 | TInfo: DI, StartL: D->getBeginLoc(), Getter: D->getGetterId(), Setter: D->getSetterId()); |
1351 | |
1352 | SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs, |
1353 | StartingScope); |
1354 | |
1355 | if (Invalid) |
1356 | Property->setInvalidDecl(); |
1357 | |
1358 | Property->setAccess(D->getAccess()); |
1359 | Owner->addDecl(Property); |
1360 | |
1361 | return Property; |
1362 | } |
1363 | |
1364 | Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) { |
1365 | NamedDecl **NamedChain = |
1366 | new (SemaRef.Context)NamedDecl*[D->getChainingSize()]; |
1367 | |
1368 | int i = 0; |
1369 | for (auto *PI : D->chain()) { |
1370 | NamedDecl *Next = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: PI, |
1371 | TemplateArgs); |
1372 | if (!Next) |
1373 | return nullptr; |
1374 | |
1375 | NamedChain[i++] = Next; |
1376 | } |
1377 | |
1378 | QualType T = cast<FieldDecl>(Val: NamedChain[i-1])->getType(); |
1379 | IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create( |
1380 | C&: SemaRef.Context, DC: Owner, L: D->getLocation(), Id: D->getIdentifier(), T, |
1381 | CH: {NamedChain, D->getChainingSize()}); |
1382 | |
1383 | for (const auto *Attr : D->attrs()) |
1384 | IndirectField->addAttr(Attr->clone(SemaRef.Context)); |
1385 | |
1386 | IndirectField->setImplicit(D->isImplicit()); |
1387 | IndirectField->setAccess(D->getAccess()); |
1388 | Owner->addDecl(IndirectField); |
1389 | return IndirectField; |
1390 | } |
1391 | |
1392 | Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) { |
1393 | // Handle friend type expressions by simply substituting template |
1394 | // parameters into the pattern type and checking the result. |
1395 | if (TypeSourceInfo *Ty = D->getFriendType()) { |
1396 | TypeSourceInfo *InstTy; |
1397 | // If this is an unsupported friend, don't bother substituting template |
1398 | // arguments into it. The actual type referred to won't be used by any |
1399 | // parts of Clang, and may not be valid for instantiating. Just use the |
1400 | // same info for the instantiated friend. |
1401 | if (D->isUnsupportedFriend()) { |
1402 | InstTy = Ty; |
1403 | } else { |
1404 | InstTy = SemaRef.SubstType(Ty, TemplateArgs, |
1405 | D->getLocation(), DeclarationName()); |
1406 | } |
1407 | if (!InstTy) |
1408 | return nullptr; |
1409 | |
1410 | FriendDecl *FD = FriendDecl::Create( |
1411 | C&: SemaRef.Context, DC: Owner, L: D->getLocation(), Friend_: InstTy, FriendL: D->getFriendLoc()); |
1412 | FD->setAccess(AS_public); |
1413 | FD->setUnsupportedFriend(D->isUnsupportedFriend()); |
1414 | Owner->addDecl(FD); |
1415 | return FD; |
1416 | } |
1417 | |
1418 | NamedDecl *ND = D->getFriendDecl(); |
1419 | assert(ND && "friend decl must be a decl or a type!" ); |
1420 | |
1421 | // All of the Visit implementations for the various potential friend |
1422 | // declarations have to be carefully written to work for friend |
1423 | // objects, with the most important detail being that the target |
1424 | // decl should almost certainly not be placed in Owner. |
1425 | Decl *NewND = Visit(ND); |
1426 | if (!NewND) return nullptr; |
1427 | |
1428 | FriendDecl *FD = |
1429 | FriendDecl::Create(C&: SemaRef.Context, DC: Owner, L: D->getLocation(), |
1430 | Friend_: cast<NamedDecl>(Val: NewND), FriendL: D->getFriendLoc()); |
1431 | FD->setAccess(AS_public); |
1432 | FD->setUnsupportedFriend(D->isUnsupportedFriend()); |
1433 | Owner->addDecl(FD); |
1434 | return FD; |
1435 | } |
1436 | |
1437 | Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) { |
1438 | Expr *AssertExpr = D->getAssertExpr(); |
1439 | |
1440 | // The expression in a static assertion is a constant expression. |
1441 | EnterExpressionEvaluationContext Unevaluated( |
1442 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
1443 | |
1444 | ExprResult InstantiatedAssertExpr |
1445 | = SemaRef.SubstExpr(E: AssertExpr, TemplateArgs); |
1446 | if (InstantiatedAssertExpr.isInvalid()) |
1447 | return nullptr; |
1448 | |
1449 | ExprResult InstantiatedMessageExpr = |
1450 | SemaRef.SubstExpr(E: D->getMessage(), TemplateArgs); |
1451 | if (InstantiatedMessageExpr.isInvalid()) |
1452 | return nullptr; |
1453 | |
1454 | return SemaRef.BuildStaticAssertDeclaration( |
1455 | StaticAssertLoc: D->getLocation(), AssertExpr: InstantiatedAssertExpr.get(), |
1456 | AssertMessageExpr: InstantiatedMessageExpr.get(), RParenLoc: D->getRParenLoc(), Failed: D->isFailed()); |
1457 | } |
1458 | |
1459 | Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) { |
1460 | EnumDecl *PrevDecl = nullptr; |
1461 | if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { |
1462 | NamedDecl *Prev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), |
1463 | D: PatternPrev, |
1464 | TemplateArgs); |
1465 | if (!Prev) return nullptr; |
1466 | PrevDecl = cast<EnumDecl>(Val: Prev); |
1467 | } |
1468 | |
1469 | EnumDecl *Enum = |
1470 | EnumDecl::Create(C&: SemaRef.Context, DC: Owner, StartLoc: D->getBeginLoc(), |
1471 | IdLoc: D->getLocation(), Id: D->getIdentifier(), PrevDecl, |
1472 | IsScoped: D->isScoped(), IsScopedUsingClassTag: D->isScopedUsingClassTag(), IsFixed: D->isFixed()); |
1473 | if (D->isFixed()) { |
1474 | if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) { |
1475 | // If we have type source information for the underlying type, it means it |
1476 | // has been explicitly set by the user. Perform substitution on it before |
1477 | // moving on. |
1478 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); |
1479 | TypeSourceInfo *NewTI = SemaRef.SubstType(T: TI, TemplateArgs, Loc: UnderlyingLoc, |
1480 | Entity: DeclarationName()); |
1481 | if (!NewTI || SemaRef.CheckEnumUnderlyingType(TI: NewTI)) |
1482 | Enum->setIntegerType(SemaRef.Context.IntTy); |
1483 | else |
1484 | Enum->setIntegerTypeSourceInfo(NewTI); |
1485 | } else { |
1486 | assert(!D->getIntegerType()->isDependentType() |
1487 | && "Dependent type without type source info" ); |
1488 | Enum->setIntegerType(D->getIntegerType()); |
1489 | } |
1490 | } |
1491 | |
1492 | SemaRef.InstantiateAttrs(TemplateArgs, D, Enum); |
1493 | |
1494 | Enum->setInstantiationOfMemberEnum(ED: D, TSK: TSK_ImplicitInstantiation); |
1495 | Enum->setAccess(D->getAccess()); |
1496 | // Forward the mangling number from the template to the instantiated decl. |
1497 | SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D)); |
1498 | // See if the old tag was defined along with a declarator. |
1499 | // If it did, mark the new tag as being associated with that declarator. |
1500 | if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D)) |
1501 | SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD); |
1502 | // See if the old tag was defined along with a typedef. |
1503 | // If it did, mark the new tag as being associated with that typedef. |
1504 | if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D)) |
1505 | SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND); |
1506 | if (SubstQualifier(D, Enum)) return nullptr; |
1507 | Owner->addDecl(Enum); |
1508 | |
1509 | EnumDecl *Def = D->getDefinition(); |
1510 | if (Def && Def != D) { |
1511 | // If this is an out-of-line definition of an enum member template, check |
1512 | // that the underlying types match in the instantiation of both |
1513 | // declarations. |
1514 | if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) { |
1515 | SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc(); |
1516 | QualType DefnUnderlying = |
1517 | SemaRef.SubstType(T: TI->getType(), TemplateArgs, |
1518 | Loc: UnderlyingLoc, Entity: DeclarationName()); |
1519 | SemaRef.CheckEnumRedeclaration(EnumLoc: Def->getLocation(), IsScoped: Def->isScoped(), |
1520 | EnumUnderlyingTy: DefnUnderlying, /*IsFixed=*/true, Prev: Enum); |
1521 | } |
1522 | } |
1523 | |
1524 | // C++11 [temp.inst]p1: The implicit instantiation of a class template |
1525 | // specialization causes the implicit instantiation of the declarations, but |
1526 | // not the definitions of scoped member enumerations. |
1527 | // |
1528 | // DR1484 clarifies that enumeration definitions inside of a template |
1529 | // declaration aren't considered entities that can be separately instantiated |
1530 | // from the rest of the entity they are declared inside of. |
1531 | if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) { |
1532 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum); |
1533 | InstantiateEnumDefinition(Enum, Pattern: Def); |
1534 | } |
1535 | |
1536 | return Enum; |
1537 | } |
1538 | |
1539 | void TemplateDeclInstantiator::InstantiateEnumDefinition( |
1540 | EnumDecl *Enum, EnumDecl *Pattern) { |
1541 | Enum->startDefinition(); |
1542 | |
1543 | // Update the location to refer to the definition. |
1544 | Enum->setLocation(Pattern->getLocation()); |
1545 | |
1546 | SmallVector<Decl*, 4> Enumerators; |
1547 | |
1548 | EnumConstantDecl *LastEnumConst = nullptr; |
1549 | for (auto *EC : Pattern->enumerators()) { |
1550 | // The specified value for the enumerator. |
1551 | ExprResult Value((Expr *)nullptr); |
1552 | if (Expr *UninstValue = EC->getInitExpr()) { |
1553 | // The enumerator's value expression is a constant expression. |
1554 | EnterExpressionEvaluationContext Unevaluated( |
1555 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
1556 | |
1557 | Value = SemaRef.SubstExpr(E: UninstValue, TemplateArgs); |
1558 | } |
1559 | |
1560 | // Drop the initial value and continue. |
1561 | bool isInvalid = false; |
1562 | if (Value.isInvalid()) { |
1563 | Value = nullptr; |
1564 | isInvalid = true; |
1565 | } |
1566 | |
1567 | EnumConstantDecl *EnumConst |
1568 | = SemaRef.CheckEnumConstant(Enum, LastEnumConst, |
1569 | IdLoc: EC->getLocation(), Id: EC->getIdentifier(), |
1570 | val: Value.get()); |
1571 | |
1572 | if (isInvalid) { |
1573 | if (EnumConst) |
1574 | EnumConst->setInvalidDecl(); |
1575 | Enum->setInvalidDecl(); |
1576 | } |
1577 | |
1578 | if (EnumConst) { |
1579 | SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst); |
1580 | |
1581 | EnumConst->setAccess(Enum->getAccess()); |
1582 | Enum->addDecl(EnumConst); |
1583 | Enumerators.push_back(EnumConst); |
1584 | LastEnumConst = EnumConst; |
1585 | |
1586 | if (Pattern->getDeclContext()->isFunctionOrMethod() && |
1587 | !Enum->isScoped()) { |
1588 | // If the enumeration is within a function or method, record the enum |
1589 | // constant as a local. |
1590 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst); |
1591 | } |
1592 | } |
1593 | } |
1594 | |
1595 | SemaRef.ActOnEnumBody(EnumLoc: Enum->getLocation(), BraceRange: Enum->getBraceRange(), EnumDecl: Enum, |
1596 | Elements: Enumerators, S: nullptr, Attr: ParsedAttributesView()); |
1597 | } |
1598 | |
1599 | Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) { |
1600 | llvm_unreachable("EnumConstantDecls can only occur within EnumDecls." ); |
1601 | } |
1602 | |
1603 | Decl * |
1604 | TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { |
1605 | llvm_unreachable("BuiltinTemplateDecls cannot be instantiated." ); |
1606 | } |
1607 | |
1608 | Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) { |
1609 | bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None); |
1610 | |
1611 | // Create a local instantiation scope for this class template, which |
1612 | // will contain the instantiations of the template parameters. |
1613 | LocalInstantiationScope Scope(SemaRef); |
1614 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
1615 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
1616 | if (!InstParams) |
1617 | return nullptr; |
1618 | |
1619 | CXXRecordDecl *Pattern = D->getTemplatedDecl(); |
1620 | |
1621 | // Instantiate the qualifier. We have to do this first in case |
1622 | // we're a friend declaration, because if we are then we need to put |
1623 | // the new declaration in the appropriate context. |
1624 | NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc(); |
1625 | if (QualifierLoc) { |
1626 | QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, |
1627 | TemplateArgs); |
1628 | if (!QualifierLoc) |
1629 | return nullptr; |
1630 | } |
1631 | |
1632 | CXXRecordDecl *PrevDecl = nullptr; |
1633 | ClassTemplateDecl *PrevClassTemplate = nullptr; |
1634 | |
1635 | if (!isFriend && getPreviousDeclForInstantiation(D: Pattern)) { |
1636 | DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName()); |
1637 | if (!Found.empty()) { |
1638 | PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Val: Found.front()); |
1639 | if (PrevClassTemplate) |
1640 | PrevDecl = PrevClassTemplate->getTemplatedDecl(); |
1641 | } |
1642 | } |
1643 | |
1644 | // If this isn't a friend, then it's a member template, in which |
1645 | // case we just want to build the instantiation in the |
1646 | // specialization. If it is a friend, we want to build it in |
1647 | // the appropriate context. |
1648 | DeclContext *DC = Owner; |
1649 | if (isFriend) { |
1650 | if (QualifierLoc) { |
1651 | CXXScopeSpec SS; |
1652 | SS.Adopt(Other: QualifierLoc); |
1653 | DC = SemaRef.computeDeclContext(SS); |
1654 | if (!DC) return nullptr; |
1655 | } else { |
1656 | DC = SemaRef.FindInstantiatedContext(Loc: Pattern->getLocation(), |
1657 | DC: Pattern->getDeclContext(), |
1658 | TemplateArgs); |
1659 | } |
1660 | |
1661 | // Look for a previous declaration of the template in the owning |
1662 | // context. |
1663 | LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(), |
1664 | Sema::LookupOrdinaryName, |
1665 | SemaRef.forRedeclarationInCurContext()); |
1666 | SemaRef.LookupQualifiedName(R, LookupCtx: DC); |
1667 | |
1668 | if (R.isSingleResult()) { |
1669 | PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>(); |
1670 | if (PrevClassTemplate) |
1671 | PrevDecl = PrevClassTemplate->getTemplatedDecl(); |
1672 | } |
1673 | |
1674 | if (!PrevClassTemplate && QualifierLoc) { |
1675 | SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope) |
1676 | << llvm::to_underlying(D->getTemplatedDecl()->getTagKind()) |
1677 | << Pattern->getDeclName() << DC << QualifierLoc.getSourceRange(); |
1678 | return nullptr; |
1679 | } |
1680 | } |
1681 | |
1682 | CXXRecordDecl *RecordInst = CXXRecordDecl::Create( |
1683 | C: SemaRef.Context, TK: Pattern->getTagKind(), DC, StartLoc: Pattern->getBeginLoc(), |
1684 | IdLoc: Pattern->getLocation(), Id: Pattern->getIdentifier(), PrevDecl, |
1685 | /*DelayTypeCreation=*/true); |
1686 | if (QualifierLoc) |
1687 | RecordInst->setQualifierInfo(QualifierLoc); |
1688 | |
1689 | SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs, |
1690 | StartingScope); |
1691 | |
1692 | ClassTemplateDecl *Inst |
1693 | = ClassTemplateDecl::Create(C&: SemaRef.Context, DC, L: D->getLocation(), |
1694 | Name: D->getIdentifier(), Params: InstParams, Decl: RecordInst); |
1695 | RecordInst->setDescribedClassTemplate(Inst); |
1696 | |
1697 | if (isFriend) { |
1698 | assert(!Owner->isDependentContext()); |
1699 | Inst->setLexicalDeclContext(Owner); |
1700 | RecordInst->setLexicalDeclContext(Owner); |
1701 | |
1702 | if (PrevClassTemplate) { |
1703 | Inst->setCommonPtr(PrevClassTemplate->getCommonPtr()); |
1704 | RecordInst->setTypeForDecl( |
1705 | PrevClassTemplate->getTemplatedDecl()->getTypeForDecl()); |
1706 | const ClassTemplateDecl *MostRecentPrevCT = |
1707 | PrevClassTemplate->getMostRecentDecl(); |
1708 | TemplateParameterList *PrevParams = |
1709 | MostRecentPrevCT->getTemplateParameters(); |
1710 | |
1711 | // Make sure the parameter lists match. |
1712 | if (!SemaRef.TemplateParameterListsAreEqual( |
1713 | RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(), |
1714 | PrevParams, true, Sema::TPL_TemplateMatch)) |
1715 | return nullptr; |
1716 | |
1717 | // Do some additional validation, then merge default arguments |
1718 | // from the existing declarations. |
1719 | if (SemaRef.CheckTemplateParameterList(NewParams: InstParams, OldParams: PrevParams, |
1720 | TPC: Sema::TPC_ClassTemplate)) |
1721 | return nullptr; |
1722 | |
1723 | Inst->setAccess(PrevClassTemplate->getAccess()); |
1724 | } else { |
1725 | Inst->setAccess(D->getAccess()); |
1726 | } |
1727 | |
1728 | Inst->setObjectOfFriendDecl(); |
1729 | // TODO: do we want to track the instantiation progeny of this |
1730 | // friend target decl? |
1731 | } else { |
1732 | Inst->setAccess(D->getAccess()); |
1733 | if (!PrevClassTemplate) |
1734 | Inst->setInstantiatedFromMemberTemplate(D); |
1735 | } |
1736 | |
1737 | Inst->setPreviousDecl(PrevClassTemplate); |
1738 | |
1739 | // Trigger creation of the type for the instantiation. |
1740 | SemaRef.Context.getInjectedClassNameType( |
1741 | Decl: RecordInst, TST: Inst->getInjectedClassNameSpecialization()); |
1742 | |
1743 | // Finish handling of friends. |
1744 | if (isFriend) { |
1745 | DC->makeDeclVisibleInContext(Inst); |
1746 | return Inst; |
1747 | } |
1748 | |
1749 | if (D->isOutOfLine()) { |
1750 | Inst->setLexicalDeclContext(D->getLexicalDeclContext()); |
1751 | RecordInst->setLexicalDeclContext(D->getLexicalDeclContext()); |
1752 | } |
1753 | |
1754 | Owner->addDecl(Inst); |
1755 | |
1756 | if (!PrevClassTemplate) { |
1757 | // Queue up any out-of-line partial specializations of this member |
1758 | // class template; the client will force their instantiation once |
1759 | // the enclosing class has been instantiated. |
1760 | SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
1761 | D->getPartialSpecializations(PS&: PartialSpecs); |
1762 | for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) |
1763 | if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) |
1764 | OutOfLinePartialSpecs.push_back(Elt: std::make_pair(x&: Inst, y&: PartialSpecs[I])); |
1765 | } |
1766 | |
1767 | return Inst; |
1768 | } |
1769 | |
1770 | Decl * |
1771 | TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl( |
1772 | ClassTemplatePartialSpecializationDecl *D) { |
1773 | ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); |
1774 | |
1775 | // Lookup the already-instantiated declaration in the instantiation |
1776 | // of the class template and return that. |
1777 | DeclContext::lookup_result Found |
1778 | = Owner->lookup(Name: ClassTemplate->getDeclName()); |
1779 | if (Found.empty()) |
1780 | return nullptr; |
1781 | |
1782 | ClassTemplateDecl *InstClassTemplate |
1783 | = dyn_cast<ClassTemplateDecl>(Val: Found.front()); |
1784 | if (!InstClassTemplate) |
1785 | return nullptr; |
1786 | |
1787 | if (ClassTemplatePartialSpecializationDecl *Result |
1788 | = InstClassTemplate->findPartialSpecInstantiatedFromMember(D)) |
1789 | return Result; |
1790 | |
1791 | return InstantiateClassTemplatePartialSpecialization(ClassTemplate: InstClassTemplate, PartialSpec: D); |
1792 | } |
1793 | |
1794 | Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) { |
1795 | assert(D->getTemplatedDecl()->isStaticDataMember() && |
1796 | "Only static data member templates are allowed." ); |
1797 | |
1798 | // Create a local instantiation scope for this variable template, which |
1799 | // will contain the instantiations of the template parameters. |
1800 | LocalInstantiationScope Scope(SemaRef); |
1801 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
1802 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
1803 | if (!InstParams) |
1804 | return nullptr; |
1805 | |
1806 | VarDecl *Pattern = D->getTemplatedDecl(); |
1807 | VarTemplateDecl *PrevVarTemplate = nullptr; |
1808 | |
1809 | if (getPreviousDeclForInstantiation(D: Pattern)) { |
1810 | DeclContext::lookup_result Found = Owner->lookup(Name: Pattern->getDeclName()); |
1811 | if (!Found.empty()) |
1812 | PrevVarTemplate = dyn_cast<VarTemplateDecl>(Val: Found.front()); |
1813 | } |
1814 | |
1815 | VarDecl *VarInst = |
1816 | cast_or_null<VarDecl>(Val: VisitVarDecl(D: Pattern, |
1817 | /*InstantiatingVarTemplate=*/true)); |
1818 | if (!VarInst) return nullptr; |
1819 | |
1820 | DeclContext *DC = Owner; |
1821 | |
1822 | VarTemplateDecl *Inst = VarTemplateDecl::Create( |
1823 | C&: SemaRef.Context, DC, L: D->getLocation(), Name: D->getIdentifier(), Params: InstParams, |
1824 | Decl: VarInst); |
1825 | VarInst->setDescribedVarTemplate(Inst); |
1826 | Inst->setPreviousDecl(PrevVarTemplate); |
1827 | |
1828 | Inst->setAccess(D->getAccess()); |
1829 | if (!PrevVarTemplate) |
1830 | Inst->setInstantiatedFromMemberTemplate(D); |
1831 | |
1832 | if (D->isOutOfLine()) { |
1833 | Inst->setLexicalDeclContext(D->getLexicalDeclContext()); |
1834 | VarInst->setLexicalDeclContext(D->getLexicalDeclContext()); |
1835 | } |
1836 | |
1837 | Owner->addDecl(Inst); |
1838 | |
1839 | if (!PrevVarTemplate) { |
1840 | // Queue up any out-of-line partial specializations of this member |
1841 | // variable template; the client will force their instantiation once |
1842 | // the enclosing class has been instantiated. |
1843 | SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs; |
1844 | D->getPartialSpecializations(PS&: PartialSpecs); |
1845 | for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) |
1846 | if (PartialSpecs[I]->getFirstDecl()->isOutOfLine()) |
1847 | OutOfLineVarPartialSpecs.push_back( |
1848 | Elt: std::make_pair(x&: Inst, y&: PartialSpecs[I])); |
1849 | } |
1850 | |
1851 | return Inst; |
1852 | } |
1853 | |
1854 | Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl( |
1855 | VarTemplatePartialSpecializationDecl *D) { |
1856 | assert(D->isStaticDataMember() && |
1857 | "Only static data member templates are allowed." ); |
1858 | |
1859 | VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); |
1860 | |
1861 | // Lookup the already-instantiated declaration and return that. |
1862 | DeclContext::lookup_result Found = Owner->lookup(Name: VarTemplate->getDeclName()); |
1863 | assert(!Found.empty() && "Instantiation found nothing?" ); |
1864 | |
1865 | VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Val: Found.front()); |
1866 | assert(InstVarTemplate && "Instantiation did not find a variable template?" ); |
1867 | |
1868 | if (VarTemplatePartialSpecializationDecl *Result = |
1869 | InstVarTemplate->findPartialSpecInstantiatedFromMember(D)) |
1870 | return Result; |
1871 | |
1872 | return InstantiateVarTemplatePartialSpecialization(VarTemplate: InstVarTemplate, PartialSpec: D); |
1873 | } |
1874 | |
1875 | Decl * |
1876 | TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { |
1877 | // Create a local instantiation scope for this function template, which |
1878 | // will contain the instantiations of the template parameters and then get |
1879 | // merged with the local instantiation scope for the function template |
1880 | // itself. |
1881 | LocalInstantiationScope Scope(SemaRef); |
1882 | Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this); |
1883 | |
1884 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
1885 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
1886 | if (!InstParams) |
1887 | return nullptr; |
1888 | |
1889 | FunctionDecl *Instantiated = nullptr; |
1890 | if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(Val: D->getTemplatedDecl())) |
1891 | Instantiated = cast_or_null<FunctionDecl>(Val: VisitCXXMethodDecl(D: DMethod, |
1892 | TemplateParams: InstParams)); |
1893 | else |
1894 | Instantiated = cast_or_null<FunctionDecl>(Val: VisitFunctionDecl( |
1895 | D: D->getTemplatedDecl(), |
1896 | TemplateParams: InstParams)); |
1897 | |
1898 | if (!Instantiated) |
1899 | return nullptr; |
1900 | |
1901 | // Link the instantiated function template declaration to the function |
1902 | // template from which it was instantiated. |
1903 | FunctionTemplateDecl *InstTemplate |
1904 | = Instantiated->getDescribedFunctionTemplate(); |
1905 | InstTemplate->setAccess(D->getAccess()); |
1906 | assert(InstTemplate && |
1907 | "VisitFunctionDecl/CXXMethodDecl didn't create a template!" ); |
1908 | |
1909 | bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None); |
1910 | |
1911 | // Link the instantiation back to the pattern *unless* this is a |
1912 | // non-definition friend declaration. |
1913 | if (!InstTemplate->getInstantiatedFromMemberTemplate() && |
1914 | !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition())) |
1915 | InstTemplate->setInstantiatedFromMemberTemplate(D); |
1916 | |
1917 | // Make declarations visible in the appropriate context. |
1918 | if (!isFriend) { |
1919 | Owner->addDecl(InstTemplate); |
1920 | } else if (InstTemplate->getDeclContext()->isRecord() && |
1921 | !getPreviousDeclForInstantiation(D)) { |
1922 | SemaRef.CheckFriendAccess(InstTemplate); |
1923 | } |
1924 | |
1925 | return InstTemplate; |
1926 | } |
1927 | |
1928 | Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) { |
1929 | CXXRecordDecl *PrevDecl = nullptr; |
1930 | if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) { |
1931 | NamedDecl *Prev = SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), |
1932 | D: PatternPrev, |
1933 | TemplateArgs); |
1934 | if (!Prev) return nullptr; |
1935 | PrevDecl = cast<CXXRecordDecl>(Val: Prev); |
1936 | } |
1937 | |
1938 | CXXRecordDecl *Record = nullptr; |
1939 | bool IsInjectedClassName = D->isInjectedClassName(); |
1940 | if (D->isLambda()) |
1941 | Record = CXXRecordDecl::CreateLambda( |
1942 | C: SemaRef.Context, DC: Owner, Info: D->getLambdaTypeInfo(), Loc: D->getLocation(), |
1943 | DependencyKind: D->getLambdaDependencyKind(), IsGeneric: D->isGenericLambda(), |
1944 | CaptureDefault: D->getLambdaCaptureDefault()); |
1945 | else |
1946 | Record = CXXRecordDecl::Create(C: SemaRef.Context, TK: D->getTagKind(), DC: Owner, |
1947 | StartLoc: D->getBeginLoc(), IdLoc: D->getLocation(), |
1948 | Id: D->getIdentifier(), PrevDecl, |
1949 | /*DelayTypeCreation=*/IsInjectedClassName); |
1950 | // Link the type of the injected-class-name to that of the outer class. |
1951 | if (IsInjectedClassName) |
1952 | (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Val: Owner)); |
1953 | |
1954 | // Substitute the nested name specifier, if any. |
1955 | if (SubstQualifier(D, Record)) |
1956 | return nullptr; |
1957 | |
1958 | SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs, |
1959 | StartingScope); |
1960 | |
1961 | Record->setImplicit(D->isImplicit()); |
1962 | // FIXME: Check against AS_none is an ugly hack to work around the issue that |
1963 | // the tag decls introduced by friend class declarations don't have an access |
1964 | // specifier. Remove once this area of the code gets sorted out. |
1965 | if (D->getAccess() != AS_none) |
1966 | Record->setAccess(D->getAccess()); |
1967 | if (!IsInjectedClassName) |
1968 | Record->setInstantiationOfMemberClass(RD: D, TSK: TSK_ImplicitInstantiation); |
1969 | |
1970 | // If the original function was part of a friend declaration, |
1971 | // inherit its namespace state. |
1972 | if (D->getFriendObjectKind()) |
1973 | Record->setObjectOfFriendDecl(); |
1974 | |
1975 | // Make sure that anonymous structs and unions are recorded. |
1976 | if (D->isAnonymousStructOrUnion()) |
1977 | Record->setAnonymousStructOrUnion(true); |
1978 | |
1979 | if (D->isLocalClass()) |
1980 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record); |
1981 | |
1982 | // Forward the mangling number from the template to the instantiated decl. |
1983 | SemaRef.Context.setManglingNumber(Record, |
1984 | SemaRef.Context.getManglingNumber(D)); |
1985 | |
1986 | // See if the old tag was defined along with a declarator. |
1987 | // If it did, mark the new tag as being associated with that declarator. |
1988 | if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D)) |
1989 | SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD); |
1990 | |
1991 | // See if the old tag was defined along with a typedef. |
1992 | // If it did, mark the new tag as being associated with that typedef. |
1993 | if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D)) |
1994 | SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND); |
1995 | |
1996 | Owner->addDecl(Record); |
1997 | |
1998 | // DR1484 clarifies that the members of a local class are instantiated as part |
1999 | // of the instantiation of their enclosing entity. |
2000 | if (D->isCompleteDefinition() && D->isLocalClass()) { |
2001 | Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef); |
2002 | |
2003 | SemaRef.InstantiateClass(PointOfInstantiation: D->getLocation(), Instantiation: Record, Pattern: D, TemplateArgs, |
2004 | TSK: TSK_ImplicitInstantiation, |
2005 | /*Complain=*/true); |
2006 | |
2007 | // For nested local classes, we will instantiate the members when we |
2008 | // reach the end of the outermost (non-nested) local class. |
2009 | if (!D->isCXXClassMember()) |
2010 | SemaRef.InstantiateClassMembers(PointOfInstantiation: D->getLocation(), Instantiation: Record, TemplateArgs, |
2011 | TSK: TSK_ImplicitInstantiation); |
2012 | |
2013 | // This class may have local implicit instantiations that need to be |
2014 | // performed within this scope. |
2015 | LocalInstantiations.perform(); |
2016 | } |
2017 | |
2018 | SemaRef.DiagnoseUnusedNestedTypedefs(Record); |
2019 | |
2020 | if (IsInjectedClassName) |
2021 | assert(Record->isInjectedClassName() && "Broken injected-class-name" ); |
2022 | |
2023 | return Record; |
2024 | } |
2025 | |
2026 | /// Adjust the given function type for an instantiation of the |
2027 | /// given declaration, to cope with modifications to the function's type that |
2028 | /// aren't reflected in the type-source information. |
2029 | /// |
2030 | /// \param D The declaration we're instantiating. |
2031 | /// \param TInfo The already-instantiated type. |
2032 | static QualType adjustFunctionTypeForInstantiation(ASTContext &Context, |
2033 | FunctionDecl *D, |
2034 | TypeSourceInfo *TInfo) { |
2035 | const FunctionProtoType *OrigFunc |
2036 | = D->getType()->castAs<FunctionProtoType>(); |
2037 | const FunctionProtoType *NewFunc |
2038 | = TInfo->getType()->castAs<FunctionProtoType>(); |
2039 | if (OrigFunc->getExtInfo() == NewFunc->getExtInfo()) |
2040 | return TInfo->getType(); |
2041 | |
2042 | FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo(); |
2043 | NewEPI.ExtInfo = OrigFunc->getExtInfo(); |
2044 | return Context.getFunctionType(ResultTy: NewFunc->getReturnType(), |
2045 | Args: NewFunc->getParamTypes(), EPI: NewEPI); |
2046 | } |
2047 | |
2048 | /// Normal class members are of more specific types and therefore |
2049 | /// don't make it here. This function serves three purposes: |
2050 | /// 1) instantiating function templates |
2051 | /// 2) substituting friend and local function declarations |
2052 | /// 3) substituting deduction guide declarations for nested class templates |
2053 | Decl *TemplateDeclInstantiator::VisitFunctionDecl( |
2054 | FunctionDecl *D, TemplateParameterList *TemplateParams, |
2055 | RewriteKind FunctionRewriteKind) { |
2056 | // Check whether there is already a function template specialization for |
2057 | // this declaration. |
2058 | FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); |
2059 | if (FunctionTemplate && !TemplateParams) { |
2060 | ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); |
2061 | |
2062 | void *InsertPos = nullptr; |
2063 | FunctionDecl *SpecFunc |
2064 | = FunctionTemplate->findSpecialization(Args: Innermost, InsertPos); |
2065 | |
2066 | // If we already have a function template specialization, return it. |
2067 | if (SpecFunc) |
2068 | return SpecFunc; |
2069 | } |
2070 | |
2071 | bool isFriend; |
2072 | if (FunctionTemplate) |
2073 | isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); |
2074 | else |
2075 | isFriend = (D->getFriendObjectKind() != Decl::FOK_None); |
2076 | |
2077 | bool MergeWithParentScope = (TemplateParams != nullptr) || |
2078 | Owner->isFunctionOrMethod() || |
2079 | !(isa<Decl>(Val: Owner) && |
2080 | cast<Decl>(Val: Owner)->isDefinedOutsideFunctionOrMethod()); |
2081 | LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); |
2082 | |
2083 | ExplicitSpecifier InstantiatedExplicitSpecifier; |
2084 | if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) { |
2085 | InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier( |
2086 | TemplateArgs, ES: DGuide->getExplicitSpecifier()); |
2087 | if (InstantiatedExplicitSpecifier.isInvalid()) |
2088 | return nullptr; |
2089 | } |
2090 | |
2091 | SmallVector<ParmVarDecl *, 4> Params; |
2092 | TypeSourceInfo *TInfo = SubstFunctionType(D, Params); |
2093 | if (!TInfo) |
2094 | return nullptr; |
2095 | QualType T = adjustFunctionTypeForInstantiation(Context&: SemaRef.Context, D, TInfo); |
2096 | |
2097 | if (TemplateParams && TemplateParams->size()) { |
2098 | auto *LastParam = |
2099 | dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->asArray().back()); |
2100 | if (LastParam && LastParam->isImplicit() && |
2101 | LastParam->hasTypeConstraint()) { |
2102 | // In abbreviated templates, the type-constraints of invented template |
2103 | // type parameters are instantiated with the function type, invalidating |
2104 | // the TemplateParameterList which relied on the template type parameter |
2105 | // not having a type constraint. Recreate the TemplateParameterList with |
2106 | // the updated parameter list. |
2107 | TemplateParams = TemplateParameterList::Create( |
2108 | C: SemaRef.Context, TemplateLoc: TemplateParams->getTemplateLoc(), |
2109 | LAngleLoc: TemplateParams->getLAngleLoc(), Params: TemplateParams->asArray(), |
2110 | RAngleLoc: TemplateParams->getRAngleLoc(), RequiresClause: TemplateParams->getRequiresClause()); |
2111 | } |
2112 | } |
2113 | |
2114 | NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); |
2115 | if (QualifierLoc) { |
2116 | QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, |
2117 | TemplateArgs); |
2118 | if (!QualifierLoc) |
2119 | return nullptr; |
2120 | } |
2121 | |
2122 | Expr *TrailingRequiresClause = D->getTrailingRequiresClause(); |
2123 | |
2124 | // If we're instantiating a local function declaration, put the result |
2125 | // in the enclosing namespace; otherwise we need to find the instantiated |
2126 | // context. |
2127 | DeclContext *DC; |
2128 | if (D->isLocalExternDecl()) { |
2129 | DC = Owner; |
2130 | SemaRef.adjustContextForLocalExternDecl(DC); |
2131 | } else if (isFriend && QualifierLoc) { |
2132 | CXXScopeSpec SS; |
2133 | SS.Adopt(Other: QualifierLoc); |
2134 | DC = SemaRef.computeDeclContext(SS); |
2135 | if (!DC) return nullptr; |
2136 | } else { |
2137 | DC = SemaRef.FindInstantiatedContext(Loc: D->getLocation(), DC: D->getDeclContext(), |
2138 | TemplateArgs); |
2139 | } |
2140 | |
2141 | DeclarationNameInfo NameInfo |
2142 | = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs); |
2143 | |
2144 | if (FunctionRewriteKind != RewriteKind::None) |
2145 | adjustForRewrite(RK: FunctionRewriteKind, Orig: D, T, TInfo, NameInfo); |
2146 | |
2147 | FunctionDecl *Function; |
2148 | if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) { |
2149 | Function = CXXDeductionGuideDecl::Create( |
2150 | C&: SemaRef.Context, DC, StartLoc: D->getInnerLocStart(), |
2151 | ES: InstantiatedExplicitSpecifier, NameInfo, T, TInfo, |
2152 | EndLocation: D->getSourceRange().getEnd(), Ctor: DGuide->getCorrespondingConstructor(), |
2153 | Kind: DGuide->getDeductionCandidateKind()); |
2154 | Function->setAccess(D->getAccess()); |
2155 | } else { |
2156 | Function = FunctionDecl::Create( |
2157 | SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo, |
2158 | D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(), |
2159 | D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(), |
2160 | TrailingRequiresClause); |
2161 | Function->setFriendConstraintRefersToEnclosingTemplate( |
2162 | D->FriendConstraintRefersToEnclosingTemplate()); |
2163 | Function->setRangeEnd(D->getSourceRange().getEnd()); |
2164 | } |
2165 | |
2166 | if (D->isInlined()) |
2167 | Function->setImplicitlyInline(); |
2168 | |
2169 | if (QualifierLoc) |
2170 | Function->setQualifierInfo(QualifierLoc); |
2171 | |
2172 | if (D->isLocalExternDecl()) |
2173 | Function->setLocalExternDecl(); |
2174 | |
2175 | DeclContext *LexicalDC = Owner; |
2176 | if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) { |
2177 | assert(D->getDeclContext()->isFileContext()); |
2178 | LexicalDC = D->getDeclContext(); |
2179 | } |
2180 | else if (D->isLocalExternDecl()) { |
2181 | LexicalDC = SemaRef.CurContext; |
2182 | } |
2183 | |
2184 | Function->setLexicalDeclContext(LexicalDC); |
2185 | |
2186 | // Attach the parameters |
2187 | for (unsigned P = 0; P < Params.size(); ++P) |
2188 | if (Params[P]) |
2189 | Params[P]->setOwningFunction(Function); |
2190 | Function->setParams(Params); |
2191 | |
2192 | if (TrailingRequiresClause) |
2193 | Function->setTrailingRequiresClause(TrailingRequiresClause); |
2194 | |
2195 | if (TemplateParams) { |
2196 | // Our resulting instantiation is actually a function template, since we |
2197 | // are substituting only the outer template parameters. For example, given |
2198 | // |
2199 | // template<typename T> |
2200 | // struct X { |
2201 | // template<typename U> friend void f(T, U); |
2202 | // }; |
2203 | // |
2204 | // X<int> x; |
2205 | // |
2206 | // We are instantiating the friend function template "f" within X<int>, |
2207 | // which means substituting int for T, but leaving "f" as a friend function |
2208 | // template. |
2209 | // Build the function template itself. |
2210 | FunctionTemplate = FunctionTemplateDecl::Create(C&: SemaRef.Context, DC, |
2211 | L: Function->getLocation(), |
2212 | Name: Function->getDeclName(), |
2213 | Params: TemplateParams, Decl: Function); |
2214 | Function->setDescribedFunctionTemplate(FunctionTemplate); |
2215 | |
2216 | FunctionTemplate->setLexicalDeclContext(LexicalDC); |
2217 | |
2218 | if (isFriend && D->isThisDeclarationADefinition()) { |
2219 | FunctionTemplate->setInstantiatedFromMemberTemplate( |
2220 | D->getDescribedFunctionTemplate()); |
2221 | } |
2222 | } else if (FunctionTemplate) { |
2223 | // Record this function template specialization. |
2224 | ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); |
2225 | Function->setFunctionTemplateSpecialization(Template: FunctionTemplate, |
2226 | TemplateArgs: TemplateArgumentList::CreateCopy(Context&: SemaRef.Context, |
2227 | Args: Innermost), |
2228 | /*InsertPos=*/nullptr); |
2229 | } else if (isFriend && D->isThisDeclarationADefinition()) { |
2230 | // Do not connect the friend to the template unless it's actually a |
2231 | // definition. We don't want non-template functions to be marked as being |
2232 | // template instantiations. |
2233 | Function->setInstantiationOfMemberFunction(FD: D, TSK: TSK_ImplicitInstantiation); |
2234 | } else if (!isFriend) { |
2235 | // If this is not a function template, and this is not a friend (that is, |
2236 | // this is a locally declared function), save the instantiation relationship |
2237 | // for the purposes of constraint instantiation. |
2238 | Function->setInstantiatedFromDecl(D); |
2239 | } |
2240 | |
2241 | if (isFriend) { |
2242 | Function->setObjectOfFriendDecl(); |
2243 | if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate()) |
2244 | FT->setObjectOfFriendDecl(); |
2245 | } |
2246 | |
2247 | if (InitFunctionInstantiation(New: Function, Tmpl: D)) |
2248 | Function->setInvalidDecl(); |
2249 | |
2250 | bool IsExplicitSpecialization = false; |
2251 | |
2252 | LookupResult Previous( |
2253 | SemaRef, Function->getDeclName(), SourceLocation(), |
2254 | D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage |
2255 | : Sema::LookupOrdinaryName, |
2256 | D->isLocalExternDecl() ? Sema::ForExternalRedeclaration |
2257 | : SemaRef.forRedeclarationInCurContext()); |
2258 | |
2259 | if (DependentFunctionTemplateSpecializationInfo *DFTSI = |
2260 | D->getDependentSpecializationInfo()) { |
2261 | assert(isFriend && "dependent specialization info on " |
2262 | "non-member non-friend function?" ); |
2263 | |
2264 | // Instantiate the explicit template arguments. |
2265 | TemplateArgumentListInfo ExplicitArgs; |
2266 | if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) { |
2267 | ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc()); |
2268 | ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc()); |
2269 | if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs, |
2270 | Outputs&: ExplicitArgs)) |
2271 | return nullptr; |
2272 | } |
2273 | |
2274 | // Map the candidates for the primary template to their instantiations. |
2275 | for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) { |
2276 | if (NamedDecl *ND = |
2277 | SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: FTD, TemplateArgs)) |
2278 | Previous.addDecl(D: ND); |
2279 | else |
2280 | return nullptr; |
2281 | } |
2282 | |
2283 | if (SemaRef.CheckFunctionTemplateSpecialization( |
2284 | FD: Function, |
2285 | ExplicitTemplateArgs: DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr, |
2286 | Previous)) |
2287 | Function->setInvalidDecl(); |
2288 | |
2289 | IsExplicitSpecialization = true; |
2290 | } else if (const ASTTemplateArgumentListInfo *ArgsWritten = |
2291 | D->getTemplateSpecializationArgsAsWritten()) { |
2292 | // The name of this function was written as a template-id. |
2293 | SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC); |
2294 | |
2295 | // Instantiate the explicit template arguments. |
2296 | TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(), |
2297 | ArgsWritten->getRAngleLoc()); |
2298 | if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs, |
2299 | Outputs&: ExplicitArgs)) |
2300 | return nullptr; |
2301 | |
2302 | if (SemaRef.CheckFunctionTemplateSpecialization(FD: Function, |
2303 | ExplicitTemplateArgs: &ExplicitArgs, |
2304 | Previous)) |
2305 | Function->setInvalidDecl(); |
2306 | |
2307 | IsExplicitSpecialization = true; |
2308 | } else if (TemplateParams || !FunctionTemplate) { |
2309 | // Look only into the namespace where the friend would be declared to |
2310 | // find a previous declaration. This is the innermost enclosing namespace, |
2311 | // as described in ActOnFriendFunctionDecl. |
2312 | SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC->getRedeclContext()); |
2313 | |
2314 | // In C++, the previous declaration we find might be a tag type |
2315 | // (class or enum). In this case, the new declaration will hide the |
2316 | // tag type. Note that this does not apply if we're declaring a |
2317 | // typedef (C++ [dcl.typedef]p4). |
2318 | if (Previous.isSingleTagDecl()) |
2319 | Previous.clear(); |
2320 | |
2321 | // Filter out previous declarations that don't match the scope. The only |
2322 | // effect this has is to remove declarations found in inline namespaces |
2323 | // for friend declarations with unqualified names. |
2324 | if (isFriend && !QualifierLoc) { |
2325 | SemaRef.FilterLookupForScope(R&: Previous, Ctx: DC, /*Scope=*/ S: nullptr, |
2326 | /*ConsiderLinkage=*/ true, |
2327 | AllowInlineNamespace: QualifierLoc.hasQualifier()); |
2328 | } |
2329 | } |
2330 | |
2331 | // Per [temp.inst], default arguments in function declarations at local scope |
2332 | // are instantiated along with the enclosing declaration. For example: |
2333 | // |
2334 | // template<typename T> |
2335 | // void ft() { |
2336 | // void f(int = []{ return T::value; }()); |
2337 | // } |
2338 | // template void ft<int>(); // error: type 'int' cannot be used prior |
2339 | // to '::' because it has no members |
2340 | // |
2341 | // The error is issued during instantiation of ft<int>() because substitution |
2342 | // into the default argument fails; the default argument is instantiated even |
2343 | // though it is never used. |
2344 | if (Function->isLocalExternDecl()) { |
2345 | for (ParmVarDecl *PVD : Function->parameters()) { |
2346 | if (!PVD->hasDefaultArg()) |
2347 | continue; |
2348 | if (SemaRef.SubstDefaultArgument(Loc: D->getInnerLocStart(), Param: PVD, TemplateArgs)) { |
2349 | // If substitution fails, the default argument is set to a |
2350 | // RecoveryExpr that wraps the uninstantiated default argument so |
2351 | // that downstream diagnostics are omitted. |
2352 | Expr *UninstExpr = PVD->getUninstantiatedDefaultArg(); |
2353 | ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( |
2354 | Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), |
2355 | SubExprs: { UninstExpr }, T: UninstExpr->getType()); |
2356 | if (ErrorResult.isUsable()) |
2357 | PVD->setDefaultArg(ErrorResult.get()); |
2358 | } |
2359 | } |
2360 | } |
2361 | |
2362 | SemaRef.CheckFunctionDeclaration(/*Scope*/ S: nullptr, NewFD: Function, Previous, |
2363 | IsMemberSpecialization: IsExplicitSpecialization, |
2364 | DeclIsDefn: Function->isThisDeclarationADefinition()); |
2365 | |
2366 | // Check the template parameter list against the previous declaration. The |
2367 | // goal here is to pick up default arguments added since the friend was |
2368 | // declared; we know the template parameter lists match, since otherwise |
2369 | // we would not have picked this template as the previous declaration. |
2370 | if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) { |
2371 | SemaRef.CheckTemplateParameterList( |
2372 | NewParams: TemplateParams, |
2373 | OldParams: FunctionTemplate->getPreviousDecl()->getTemplateParameters(), |
2374 | TPC: Function->isThisDeclarationADefinition() |
2375 | ? Sema::TPC_FriendFunctionTemplateDefinition |
2376 | : Sema::TPC_FriendFunctionTemplate); |
2377 | } |
2378 | |
2379 | // If we're introducing a friend definition after the first use, trigger |
2380 | // instantiation. |
2381 | // FIXME: If this is a friend function template definition, we should check |
2382 | // to see if any specializations have been used. |
2383 | if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) { |
2384 | if (MemberSpecializationInfo *MSInfo = |
2385 | Function->getMemberSpecializationInfo()) { |
2386 | if (MSInfo->getPointOfInstantiation().isInvalid()) { |
2387 | SourceLocation Loc = D->getLocation(); // FIXME |
2388 | MSInfo->setPointOfInstantiation(Loc); |
2389 | SemaRef.PendingLocalImplicitInstantiations.push_back( |
2390 | std::make_pair(x&: Function, y&: Loc)); |
2391 | } |
2392 | } |
2393 | } |
2394 | |
2395 | if (D->isExplicitlyDefaulted()) { |
2396 | if (SubstDefaultedFunction(New: Function, Tmpl: D)) |
2397 | return nullptr; |
2398 | } |
2399 | if (D->isDeleted()) |
2400 | SemaRef.SetDeclDeleted(dcl: Function, DelLoc: D->getLocation()); |
2401 | |
2402 | NamedDecl *PrincipalDecl = |
2403 | (TemplateParams ? cast<NamedDecl>(Val: FunctionTemplate) : Function); |
2404 | |
2405 | // If this declaration lives in a different context from its lexical context, |
2406 | // add it to the corresponding lookup table. |
2407 | if (isFriend || |
2408 | (Function->isLocalExternDecl() && !Function->getPreviousDecl())) |
2409 | DC->makeDeclVisibleInContext(D: PrincipalDecl); |
2410 | |
2411 | if (Function->isOverloadedOperator() && !DC->isRecord() && |
2412 | PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) |
2413 | PrincipalDecl->setNonMemberOperator(); |
2414 | |
2415 | return Function; |
2416 | } |
2417 | |
2418 | Decl *TemplateDeclInstantiator::VisitCXXMethodDecl( |
2419 | CXXMethodDecl *D, TemplateParameterList *TemplateParams, |
2420 | RewriteKind FunctionRewriteKind) { |
2421 | FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate(); |
2422 | if (FunctionTemplate && !TemplateParams) { |
2423 | // We are creating a function template specialization from a function |
2424 | // template. Check whether there is already a function template |
2425 | // specialization for this particular set of template arguments. |
2426 | ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); |
2427 | |
2428 | void *InsertPos = nullptr; |
2429 | FunctionDecl *SpecFunc |
2430 | = FunctionTemplate->findSpecialization(Args: Innermost, InsertPos); |
2431 | |
2432 | // If we already have a function template specialization, return it. |
2433 | if (SpecFunc) |
2434 | return SpecFunc; |
2435 | } |
2436 | |
2437 | bool isFriend; |
2438 | if (FunctionTemplate) |
2439 | isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None); |
2440 | else |
2441 | isFriend = (D->getFriendObjectKind() != Decl::FOK_None); |
2442 | |
2443 | bool MergeWithParentScope = (TemplateParams != nullptr) || |
2444 | !(isa<Decl>(Val: Owner) && |
2445 | cast<Decl>(Val: Owner)->isDefinedOutsideFunctionOrMethod()); |
2446 | LocalInstantiationScope Scope(SemaRef, MergeWithParentScope); |
2447 | |
2448 | Sema::LambdaScopeForCallOperatorInstantiationRAII LambdaScope( |
2449 | SemaRef, const_cast<CXXMethodDecl *>(D), TemplateArgs, Scope); |
2450 | |
2451 | // Instantiate enclosing template arguments for friends. |
2452 | SmallVector<TemplateParameterList *, 4> TempParamLists; |
2453 | unsigned NumTempParamLists = 0; |
2454 | if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) { |
2455 | TempParamLists.resize(N: NumTempParamLists); |
2456 | for (unsigned I = 0; I != NumTempParamLists; ++I) { |
2457 | TemplateParameterList *TempParams = D->getTemplateParameterList(I); |
2458 | TemplateParameterList *InstParams = SubstTemplateParams(List: TempParams); |
2459 | if (!InstParams) |
2460 | return nullptr; |
2461 | TempParamLists[I] = InstParams; |
2462 | } |
2463 | } |
2464 | |
2465 | auto InstantiatedExplicitSpecifier = ExplicitSpecifier::getFromDecl(D); |
2466 | // deduction guides need this |
2467 | const bool CouldInstantiate = |
2468 | InstantiatedExplicitSpecifier.getExpr() == nullptr || |
2469 | !InstantiatedExplicitSpecifier.getExpr()->isValueDependent(); |
2470 | |
2471 | // Delay the instantiation of the explicit-specifier until after the |
2472 | // constraints are checked during template argument deduction. |
2473 | if (CouldInstantiate || |
2474 | SemaRef.CodeSynthesisContexts.back().Kind != |
2475 | Sema::CodeSynthesisContext::DeducedTemplateArgumentSubstitution) { |
2476 | InstantiatedExplicitSpecifier = SemaRef.instantiateExplicitSpecifier( |
2477 | TemplateArgs, ES: InstantiatedExplicitSpecifier); |
2478 | |
2479 | if (InstantiatedExplicitSpecifier.isInvalid()) |
2480 | return nullptr; |
2481 | } else { |
2482 | InstantiatedExplicitSpecifier.setKind(ExplicitSpecKind::Unresolved); |
2483 | } |
2484 | |
2485 | // Implicit destructors/constructors created for local classes in |
2486 | // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI. |
2487 | // Unfortunately there isn't enough context in those functions to |
2488 | // conditionally populate the TSI without breaking non-template related use |
2489 | // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get |
2490 | // a proper transformation. |
2491 | if (cast<CXXRecordDecl>(Val: D->getParent())->isLambda() && |
2492 | !D->getTypeSourceInfo() && |
2493 | isa<CXXConstructorDecl, CXXDestructorDecl>(Val: D)) { |
2494 | TypeSourceInfo *TSI = |
2495 | SemaRef.Context.getTrivialTypeSourceInfo(T: D->getType()); |
2496 | D->setTypeSourceInfo(TSI); |
2497 | } |
2498 | |
2499 | SmallVector<ParmVarDecl *, 4> Params; |
2500 | TypeSourceInfo *TInfo = SubstFunctionType(D, Params); |
2501 | if (!TInfo) |
2502 | return nullptr; |
2503 | QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo); |
2504 | |
2505 | if (TemplateParams && TemplateParams->size()) { |
2506 | auto *LastParam = |
2507 | dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->asArray().back()); |
2508 | if (LastParam && LastParam->isImplicit() && |
2509 | LastParam->hasTypeConstraint()) { |
2510 | // In abbreviated templates, the type-constraints of invented template |
2511 | // type parameters are instantiated with the function type, invalidating |
2512 | // the TemplateParameterList which relied on the template type parameter |
2513 | // not having a type constraint. Recreate the TemplateParameterList with |
2514 | // the updated parameter list. |
2515 | TemplateParams = TemplateParameterList::Create( |
2516 | C: SemaRef.Context, TemplateLoc: TemplateParams->getTemplateLoc(), |
2517 | LAngleLoc: TemplateParams->getLAngleLoc(), Params: TemplateParams->asArray(), |
2518 | RAngleLoc: TemplateParams->getRAngleLoc(), RequiresClause: TemplateParams->getRequiresClause()); |
2519 | } |
2520 | } |
2521 | |
2522 | NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc(); |
2523 | if (QualifierLoc) { |
2524 | QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, |
2525 | TemplateArgs); |
2526 | if (!QualifierLoc) |
2527 | return nullptr; |
2528 | } |
2529 | |
2530 | DeclContext *DC = Owner; |
2531 | if (isFriend) { |
2532 | if (QualifierLoc) { |
2533 | CXXScopeSpec SS; |
2534 | SS.Adopt(Other: QualifierLoc); |
2535 | DC = SemaRef.computeDeclContext(SS); |
2536 | |
2537 | if (DC && SemaRef.RequireCompleteDeclContext(SS, DC)) |
2538 | return nullptr; |
2539 | } else { |
2540 | DC = SemaRef.FindInstantiatedContext(Loc: D->getLocation(), |
2541 | DC: D->getDeclContext(), |
2542 | TemplateArgs); |
2543 | } |
2544 | if (!DC) return nullptr; |
2545 | } |
2546 | |
2547 | CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: DC); |
2548 | Expr *TrailingRequiresClause = D->getTrailingRequiresClause(); |
2549 | |
2550 | DeclarationNameInfo NameInfo |
2551 | = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs); |
2552 | |
2553 | if (FunctionRewriteKind != RewriteKind::None) |
2554 | adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo); |
2555 | |
2556 | // Build the instantiated method declaration. |
2557 | CXXMethodDecl *Method = nullptr; |
2558 | |
2559 | SourceLocation StartLoc = D->getInnerLocStart(); |
2560 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: D)) { |
2561 | Method = CXXConstructorDecl::Create( |
2562 | C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, |
2563 | ES: InstantiatedExplicitSpecifier, UsesFPIntrin: Constructor->UsesFPIntrin(), |
2564 | isInline: Constructor->isInlineSpecified(), isImplicitlyDeclared: false, |
2565 | ConstexprKind: Constructor->getConstexprKind(), Inherited: InheritedConstructor(), |
2566 | TrailingRequiresClause); |
2567 | Method->setRangeEnd(Constructor->getEndLoc()); |
2568 | } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(Val: D)) { |
2569 | Method = CXXDestructorDecl::Create( |
2570 | C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, |
2571 | UsesFPIntrin: Destructor->UsesFPIntrin(), isInline: Destructor->isInlineSpecified(), isImplicitlyDeclared: false, |
2572 | ConstexprKind: Destructor->getConstexprKind(), TrailingRequiresClause); |
2573 | Method->setIneligibleOrNotSelected(true); |
2574 | Method->setRangeEnd(Destructor->getEndLoc()); |
2575 | Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName( |
2576 | Ty: SemaRef.Context.getCanonicalType( |
2577 | T: SemaRef.Context.getTypeDeclType(Record)))); |
2578 | } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(Val: D)) { |
2579 | Method = CXXConversionDecl::Create( |
2580 | C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, |
2581 | UsesFPIntrin: Conversion->UsesFPIntrin(), isInline: Conversion->isInlineSpecified(), |
2582 | ES: InstantiatedExplicitSpecifier, ConstexprKind: Conversion->getConstexprKind(), |
2583 | EndLocation: Conversion->getEndLoc(), TrailingRequiresClause); |
2584 | } else { |
2585 | StorageClass SC = D->isStatic() ? SC_Static : SC_None; |
2586 | Method = CXXMethodDecl::Create( |
2587 | C&: SemaRef.Context, RD: Record, StartLoc, NameInfo, T, TInfo, SC, |
2588 | UsesFPIntrin: D->UsesFPIntrin(), isInline: D->isInlineSpecified(), ConstexprKind: D->getConstexprKind(), |
2589 | EndLocation: D->getEndLoc(), TrailingRequiresClause); |
2590 | } |
2591 | |
2592 | if (D->isInlined()) |
2593 | Method->setImplicitlyInline(); |
2594 | |
2595 | if (QualifierLoc) |
2596 | Method->setQualifierInfo(QualifierLoc); |
2597 | |
2598 | if (TemplateParams) { |
2599 | // Our resulting instantiation is actually a function template, since we |
2600 | // are substituting only the outer template parameters. For example, given |
2601 | // |
2602 | // template<typename T> |
2603 | // struct X { |
2604 | // template<typename U> void f(T, U); |
2605 | // }; |
2606 | // |
2607 | // X<int> x; |
2608 | // |
2609 | // We are instantiating the member template "f" within X<int>, which means |
2610 | // substituting int for T, but leaving "f" as a member function template. |
2611 | // Build the function template itself. |
2612 | FunctionTemplate = FunctionTemplateDecl::Create(C&: SemaRef.Context, DC: Record, |
2613 | L: Method->getLocation(), |
2614 | Name: Method->getDeclName(), |
2615 | Params: TemplateParams, Decl: Method); |
2616 | if (isFriend) { |
2617 | FunctionTemplate->setLexicalDeclContext(Owner); |
2618 | FunctionTemplate->setObjectOfFriendDecl(); |
2619 | } else if (D->isOutOfLine()) |
2620 | FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext()); |
2621 | Method->setDescribedFunctionTemplate(FunctionTemplate); |
2622 | } else if (FunctionTemplate) { |
2623 | // Record this function template specialization. |
2624 | ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost(); |
2625 | Method->setFunctionTemplateSpecialization(FunctionTemplate, |
2626 | TemplateArgumentList::CreateCopy(Context&: SemaRef.Context, |
2627 | Args: Innermost), |
2628 | /*InsertPos=*/nullptr); |
2629 | } else if (!isFriend) { |
2630 | // Record that this is an instantiation of a member function. |
2631 | Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation); |
2632 | } |
2633 | |
2634 | // If we are instantiating a member function defined |
2635 | // out-of-line, the instantiation will have the same lexical |
2636 | // context (which will be a namespace scope) as the template. |
2637 | if (isFriend) { |
2638 | if (NumTempParamLists) |
2639 | Method->setTemplateParameterListsInfo( |
2640 | SemaRef.Context, |
2641 | llvm::ArrayRef(TempParamLists.data(), NumTempParamLists)); |
2642 | |
2643 | Method->setLexicalDeclContext(Owner); |
2644 | Method->setObjectOfFriendDecl(); |
2645 | } else if (D->isOutOfLine()) |
2646 | Method->setLexicalDeclContext(D->getLexicalDeclContext()); |
2647 | |
2648 | // Attach the parameters |
2649 | for (unsigned P = 0; P < Params.size(); ++P) |
2650 | Params[P]->setOwningFunction(Method); |
2651 | Method->setParams(Params); |
2652 | |
2653 | if (InitMethodInstantiation(New: Method, Tmpl: D)) |
2654 | Method->setInvalidDecl(); |
2655 | |
2656 | LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName, |
2657 | Sema::ForExternalRedeclaration); |
2658 | |
2659 | bool IsExplicitSpecialization = false; |
2660 | |
2661 | // If the name of this function was written as a template-id, instantiate |
2662 | // the explicit template arguments. |
2663 | if (DependentFunctionTemplateSpecializationInfo *DFTSI = |
2664 | D->getDependentSpecializationInfo()) { |
2665 | // Instantiate the explicit template arguments. |
2666 | TemplateArgumentListInfo ExplicitArgs; |
2667 | if (const auto *ArgsWritten = DFTSI->TemplateArgumentsAsWritten) { |
2668 | ExplicitArgs.setLAngleLoc(ArgsWritten->getLAngleLoc()); |
2669 | ExplicitArgs.setRAngleLoc(ArgsWritten->getRAngleLoc()); |
2670 | if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs, |
2671 | Outputs&: ExplicitArgs)) |
2672 | return nullptr; |
2673 | } |
2674 | |
2675 | // Map the candidates for the primary template to their instantiations. |
2676 | for (FunctionTemplateDecl *FTD : DFTSI->getCandidates()) { |
2677 | if (NamedDecl *ND = |
2678 | SemaRef.FindInstantiatedDecl(D->getLocation(), FTD, TemplateArgs)) |
2679 | Previous.addDecl(ND); |
2680 | else |
2681 | return nullptr; |
2682 | } |
2683 | |
2684 | if (SemaRef.CheckFunctionTemplateSpecialization( |
2685 | Method, DFTSI->TemplateArgumentsAsWritten ? &ExplicitArgs : nullptr, |
2686 | Previous)) |
2687 | Method->setInvalidDecl(); |
2688 | |
2689 | IsExplicitSpecialization = true; |
2690 | } else if (const ASTTemplateArgumentListInfo *ArgsWritten = |
2691 | D->getTemplateSpecializationArgsAsWritten()) { |
2692 | SemaRef.LookupQualifiedName(R&: Previous, LookupCtx: DC); |
2693 | |
2694 | TemplateArgumentListInfo ExplicitArgs(ArgsWritten->getLAngleLoc(), |
2695 | ArgsWritten->getRAngleLoc()); |
2696 | |
2697 | if (SemaRef.SubstTemplateArguments(Args: ArgsWritten->arguments(), TemplateArgs, |
2698 | Outputs&: ExplicitArgs)) |
2699 | return nullptr; |
2700 | |
2701 | if (SemaRef.CheckFunctionTemplateSpecialization(Method, |
2702 | &ExplicitArgs, |
2703 | Previous)) |
2704 | Method->setInvalidDecl(); |
2705 | |
2706 | IsExplicitSpecialization = true; |
2707 | } else if (!FunctionTemplate || TemplateParams || isFriend) { |
2708 | SemaRef.LookupQualifiedName(Previous, Record); |
2709 | |
2710 | // In C++, the previous declaration we find might be a tag type |
2711 | // (class or enum). In this case, the new declaration will hide the |
2712 | // tag type. Note that this does not apply if we're declaring a |
2713 | // typedef (C++ [dcl.typedef]p4). |
2714 | if (Previous.isSingleTagDecl()) |
2715 | Previous.clear(); |
2716 | } |
2717 | |
2718 | // Per [temp.inst], default arguments in member functions of local classes |
2719 | // are instantiated along with the member function declaration. For example: |
2720 | // |
2721 | // template<typename T> |
2722 | // void ft() { |
2723 | // struct lc { |
2724 | // int operator()(int p = []{ return T::value; }()); |
2725 | // }; |
2726 | // } |
2727 | // template void ft<int>(); // error: type 'int' cannot be used prior |
2728 | // to '::'because it has no members |
2729 | // |
2730 | // The error is issued during instantiation of ft<int>()::lc::operator() |
2731 | // because substitution into the default argument fails; the default argument |
2732 | // is instantiated even though it is never used. |
2733 | if (D->isInLocalScopeForInstantiation()) { |
2734 | for (unsigned P = 0; P < Params.size(); ++P) { |
2735 | if (!Params[P]->hasDefaultArg()) |
2736 | continue; |
2737 | if (SemaRef.SubstDefaultArgument(Loc: StartLoc, Param: Params[P], TemplateArgs)) { |
2738 | // If substitution fails, the default argument is set to a |
2739 | // RecoveryExpr that wraps the uninstantiated default argument so |
2740 | // that downstream diagnostics are omitted. |
2741 | Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg(); |
2742 | ExprResult ErrorResult = SemaRef.CreateRecoveryExpr( |
2743 | Begin: UninstExpr->getBeginLoc(), End: UninstExpr->getEndLoc(), |
2744 | SubExprs: { UninstExpr }, T: UninstExpr->getType()); |
2745 | if (ErrorResult.isUsable()) |
2746 | Params[P]->setDefaultArg(ErrorResult.get()); |
2747 | } |
2748 | } |
2749 | } |
2750 | |
2751 | SemaRef.CheckFunctionDeclaration(S: nullptr, NewFD: Method, Previous, |
2752 | IsMemberSpecialization: IsExplicitSpecialization, |
2753 | DeclIsDefn: Method->isThisDeclarationADefinition()); |
2754 | |
2755 | if (D->isPureVirtual()) |
2756 | SemaRef.CheckPureMethod(Method, InitRange: SourceRange()); |
2757 | |
2758 | // Propagate access. For a non-friend declaration, the access is |
2759 | // whatever we're propagating from. For a friend, it should be the |
2760 | // previous declaration we just found. |
2761 | if (isFriend && Method->getPreviousDecl()) |
2762 | Method->setAccess(Method->getPreviousDecl()->getAccess()); |
2763 | else |
2764 | Method->setAccess(D->getAccess()); |
2765 | if (FunctionTemplate) |
2766 | FunctionTemplate->setAccess(Method->getAccess()); |
2767 | |
2768 | SemaRef.CheckOverrideControl(Method); |
2769 | |
2770 | // If a function is defined as defaulted or deleted, mark it as such now. |
2771 | if (D->isExplicitlyDefaulted()) { |
2772 | if (SubstDefaultedFunction(Method, D)) |
2773 | return nullptr; |
2774 | } |
2775 | if (D->isDeletedAsWritten()) |
2776 | SemaRef.SetDeclDeleted(dcl: Method, DelLoc: Method->getLocation()); |
2777 | |
2778 | // If this is an explicit specialization, mark the implicitly-instantiated |
2779 | // template specialization as being an explicit specialization too. |
2780 | // FIXME: Is this necessary? |
2781 | if (IsExplicitSpecialization && !isFriend) |
2782 | SemaRef.CompleteMemberSpecialization(Method, Previous); |
2783 | |
2784 | // If the method is a special member function, we need to mark it as |
2785 | // ineligible so that Owner->addDecl() won't mark the class as non trivial. |
2786 | // At the end of the class instantiation, we calculate eligibility again and |
2787 | // then we adjust trivility if needed. |
2788 | // We need this check to happen only after the method parameters are set, |
2789 | // because being e.g. a copy constructor depends on the instantiated |
2790 | // arguments. |
2791 | if (auto *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method)) { |
2792 | if (Constructor->isDefaultConstructor() || |
2793 | Constructor->isCopyOrMoveConstructor()) |
2794 | Method->setIneligibleOrNotSelected(true); |
2795 | } else if (Method->isCopyAssignmentOperator() || |
2796 | Method->isMoveAssignmentOperator()) { |
2797 | Method->setIneligibleOrNotSelected(true); |
2798 | } |
2799 | |
2800 | // If there's a function template, let our caller handle it. |
2801 | if (FunctionTemplate) { |
2802 | // do nothing |
2803 | |
2804 | // Don't hide a (potentially) valid declaration with an invalid one. |
2805 | } else if (Method->isInvalidDecl() && !Previous.empty()) { |
2806 | // do nothing |
2807 | |
2808 | // Otherwise, check access to friends and make them visible. |
2809 | } else if (isFriend) { |
2810 | // We only need to re-check access for methods which we didn't |
2811 | // manage to match during parsing. |
2812 | if (!D->getPreviousDecl()) |
2813 | SemaRef.CheckFriendAccess(Method); |
2814 | |
2815 | Record->makeDeclVisibleInContext(Method); |
2816 | |
2817 | // Otherwise, add the declaration. We don't need to do this for |
2818 | // class-scope specializations because we'll have matched them with |
2819 | // the appropriate template. |
2820 | } else { |
2821 | Owner->addDecl(Method); |
2822 | } |
2823 | |
2824 | // PR17480: Honor the used attribute to instantiate member function |
2825 | // definitions |
2826 | if (Method->hasAttr<UsedAttr>()) { |
2827 | if (const auto *A = dyn_cast<CXXRecordDecl>(Val: Owner)) { |
2828 | SourceLocation Loc; |
2829 | if (const MemberSpecializationInfo *MSInfo = |
2830 | A->getMemberSpecializationInfo()) |
2831 | Loc = MSInfo->getPointOfInstantiation(); |
2832 | else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: A)) |
2833 | Loc = Spec->getPointOfInstantiation(); |
2834 | SemaRef.MarkFunctionReferenced(Loc, Method); |
2835 | } |
2836 | } |
2837 | |
2838 | return Method; |
2839 | } |
2840 | |
2841 | Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) { |
2842 | return VisitCXXMethodDecl(D); |
2843 | } |
2844 | |
2845 | Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) { |
2846 | return VisitCXXMethodDecl(D); |
2847 | } |
2848 | |
2849 | Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) { |
2850 | return VisitCXXMethodDecl(D); |
2851 | } |
2852 | |
2853 | Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) { |
2854 | return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0, |
2855 | NumExpansions: std::nullopt, |
2856 | /*ExpectParameterPack=*/false); |
2857 | } |
2858 | |
2859 | Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl( |
2860 | TemplateTypeParmDecl *D) { |
2861 | assert(D->getTypeForDecl()->isTemplateTypeParmType()); |
2862 | |
2863 | std::optional<unsigned> NumExpanded; |
2864 | |
2865 | if (const TypeConstraint *TC = D->getTypeConstraint()) { |
2866 | if (D->isPackExpansion() && !D->isExpandedParameterPack()) { |
2867 | assert(TC->getTemplateArgsAsWritten() && |
2868 | "type parameter can only be an expansion when explicit arguments " |
2869 | "are specified" ); |
2870 | // The template type parameter pack's type is a pack expansion of types. |
2871 | // Determine whether we need to expand this parameter pack into separate |
2872 | // types. |
2873 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
2874 | for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments()) |
2875 | SemaRef.collectUnexpandedParameterPacks(Arg: ArgLoc, Unexpanded); |
2876 | |
2877 | // Determine whether the set of unexpanded parameter packs can and should |
2878 | // be expanded. |
2879 | bool Expand = true; |
2880 | bool RetainExpansion = false; |
2881 | if (SemaRef.CheckParameterPacksForExpansion( |
2882 | EllipsisLoc: cast<CXXFoldExpr>(Val: TC->getImmediatelyDeclaredConstraint()) |
2883 | ->getEllipsisLoc(), |
2884 | PatternRange: SourceRange(TC->getConceptNameLoc(), |
2885 | TC->hasExplicitTemplateArgs() ? |
2886 | TC->getTemplateArgsAsWritten()->getRAngleLoc() : |
2887 | TC->getConceptNameInfo().getEndLoc()), |
2888 | Unexpanded, TemplateArgs, ShouldExpand&: Expand, RetainExpansion, NumExpansions&: NumExpanded)) |
2889 | return nullptr; |
2890 | } |
2891 | } |
2892 | |
2893 | TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create( |
2894 | C: SemaRef.Context, DC: Owner, KeyLoc: D->getBeginLoc(), NameLoc: D->getLocation(), |
2895 | D: D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), P: D->getIndex(), |
2896 | Id: D->getIdentifier(), Typename: D->wasDeclaredWithTypename(), ParameterPack: D->isParameterPack(), |
2897 | HasTypeConstraint: D->hasTypeConstraint(), NumExpanded); |
2898 | |
2899 | Inst->setAccess(AS_public); |
2900 | Inst->setImplicit(D->isImplicit()); |
2901 | if (auto *TC = D->getTypeConstraint()) { |
2902 | if (!D->isImplicit()) { |
2903 | // Invented template parameter type constraints will be instantiated |
2904 | // with the corresponding auto-typed parameter as it might reference |
2905 | // other parameters. |
2906 | if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs, |
2907 | EvaluateConstraint: EvaluateConstraints)) |
2908 | return nullptr; |
2909 | } |
2910 | } |
2911 | if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { |
2912 | TypeSourceInfo *InstantiatedDefaultArg = |
2913 | SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs, |
2914 | D->getDefaultArgumentLoc(), D->getDeclName()); |
2915 | if (InstantiatedDefaultArg) |
2916 | Inst->setDefaultArgument(InstantiatedDefaultArg); |
2917 | } |
2918 | |
2919 | // Introduce this template parameter's instantiation into the instantiation |
2920 | // scope. |
2921 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
2922 | |
2923 | return Inst; |
2924 | } |
2925 | |
2926 | Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl( |
2927 | NonTypeTemplateParmDecl *D) { |
2928 | // Substitute into the type of the non-type template parameter. |
2929 | TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc(); |
2930 | SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten; |
2931 | SmallVector<QualType, 4> ExpandedParameterPackTypes; |
2932 | bool IsExpandedParameterPack = false; |
2933 | TypeSourceInfo *DI; |
2934 | QualType T; |
2935 | bool Invalid = false; |
2936 | |
2937 | if (D->isExpandedParameterPack()) { |
2938 | // The non-type template parameter pack is an already-expanded pack |
2939 | // expansion of types. Substitute into each of the expanded types. |
2940 | ExpandedParameterPackTypes.reserve(N: D->getNumExpansionTypes()); |
2941 | ExpandedParameterPackTypesAsWritten.reserve(N: D->getNumExpansionTypes()); |
2942 | for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) { |
2943 | TypeSourceInfo *NewDI = |
2944 | SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs, |
2945 | D->getLocation(), D->getDeclName()); |
2946 | if (!NewDI) |
2947 | return nullptr; |
2948 | |
2949 | QualType NewT = |
2950 | SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); |
2951 | if (NewT.isNull()) |
2952 | return nullptr; |
2953 | |
2954 | ExpandedParameterPackTypesAsWritten.push_back(Elt: NewDI); |
2955 | ExpandedParameterPackTypes.push_back(Elt: NewT); |
2956 | } |
2957 | |
2958 | IsExpandedParameterPack = true; |
2959 | DI = D->getTypeSourceInfo(); |
2960 | T = DI->getType(); |
2961 | } else if (D->isPackExpansion()) { |
2962 | // The non-type template parameter pack's type is a pack expansion of types. |
2963 | // Determine whether we need to expand this parameter pack into separate |
2964 | // types. |
2965 | PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>(); |
2966 | TypeLoc Pattern = Expansion.getPatternLoc(); |
2967 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
2968 | SemaRef.collectUnexpandedParameterPacks(TL: Pattern, Unexpanded); |
2969 | |
2970 | // Determine whether the set of unexpanded parameter packs can and should |
2971 | // be expanded. |
2972 | bool Expand = true; |
2973 | bool RetainExpansion = false; |
2974 | std::optional<unsigned> OrigNumExpansions = |
2975 | Expansion.getTypePtr()->getNumExpansions(); |
2976 | std::optional<unsigned> NumExpansions = OrigNumExpansions; |
2977 | if (SemaRef.CheckParameterPacksForExpansion(EllipsisLoc: Expansion.getEllipsisLoc(), |
2978 | PatternRange: Pattern.getSourceRange(), |
2979 | Unexpanded, |
2980 | TemplateArgs, |
2981 | ShouldExpand&: Expand, RetainExpansion, |
2982 | NumExpansions)) |
2983 | return nullptr; |
2984 | |
2985 | if (Expand) { |
2986 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
2987 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); |
2988 | TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs, |
2989 | D->getLocation(), |
2990 | D->getDeclName()); |
2991 | if (!NewDI) |
2992 | return nullptr; |
2993 | |
2994 | QualType NewT = |
2995 | SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation()); |
2996 | if (NewT.isNull()) |
2997 | return nullptr; |
2998 | |
2999 | ExpandedParameterPackTypesAsWritten.push_back(Elt: NewDI); |
3000 | ExpandedParameterPackTypes.push_back(Elt: NewT); |
3001 | } |
3002 | |
3003 | // Note that we have an expanded parameter pack. The "type" of this |
3004 | // expanded parameter pack is the original expansion type, but callers |
3005 | // will end up using the expanded parameter pack types for type-checking. |
3006 | IsExpandedParameterPack = true; |
3007 | DI = D->getTypeSourceInfo(); |
3008 | T = DI->getType(); |
3009 | } else { |
3010 | // We cannot fully expand the pack expansion now, so substitute into the |
3011 | // pattern and create a new pack expansion type. |
3012 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); |
3013 | TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs, |
3014 | D->getLocation(), |
3015 | D->getDeclName()); |
3016 | if (!NewPattern) |
3017 | return nullptr; |
3018 | |
3019 | SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation()); |
3020 | DI = SemaRef.CheckPackExpansion(Pattern: NewPattern, EllipsisLoc: Expansion.getEllipsisLoc(), |
3021 | NumExpansions); |
3022 | if (!DI) |
3023 | return nullptr; |
3024 | |
3025 | T = DI->getType(); |
3026 | } |
3027 | } else { |
3028 | // Simple case: substitution into a parameter that is not a parameter pack. |
3029 | DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, |
3030 | D->getLocation(), D->getDeclName()); |
3031 | if (!DI) |
3032 | return nullptr; |
3033 | |
3034 | // Check that this type is acceptable for a non-type template parameter. |
3035 | T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation()); |
3036 | if (T.isNull()) { |
3037 | T = SemaRef.Context.IntTy; |
3038 | Invalid = true; |
3039 | } |
3040 | } |
3041 | |
3042 | NonTypeTemplateParmDecl *Param; |
3043 | if (IsExpandedParameterPack) |
3044 | Param = NonTypeTemplateParmDecl::Create( |
3045 | SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), |
3046 | D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), |
3047 | D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes, |
3048 | ExpandedParameterPackTypesAsWritten); |
3049 | else |
3050 | Param = NonTypeTemplateParmDecl::Create( |
3051 | SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(), |
3052 | D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), |
3053 | D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI); |
3054 | |
3055 | if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc()) |
3056 | if (AutoLoc.isConstrained()) { |
3057 | SourceLocation EllipsisLoc; |
3058 | if (IsExpandedParameterPack) |
3059 | EllipsisLoc = |
3060 | DI->getTypeLoc().getAs<PackExpansionTypeLoc>().getEllipsisLoc(); |
3061 | else if (auto *Constraint = dyn_cast_if_present<CXXFoldExpr>( |
3062 | Val: D->getPlaceholderTypeConstraint())) |
3063 | EllipsisLoc = Constraint->getEllipsisLoc(); |
3064 | // Note: We attach the uninstantiated constriant here, so that it can be |
3065 | // instantiated relative to the top level, like all our other |
3066 | // constraints. |
3067 | if (SemaRef.AttachTypeConstraint(TL: AutoLoc, /*NewConstrainedParm=*/Param, |
3068 | /*OrigConstrainedParm=*/D, EllipsisLoc)) |
3069 | Invalid = true; |
3070 | } |
3071 | |
3072 | Param->setAccess(AS_public); |
3073 | Param->setImplicit(D->isImplicit()); |
3074 | if (Invalid) |
3075 | Param->setInvalidDecl(); |
3076 | |
3077 | if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { |
3078 | EnterExpressionEvaluationContext ConstantEvaluated( |
3079 | SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated); |
3080 | ExprResult Value = SemaRef.SubstExpr(E: D->getDefaultArgument(), TemplateArgs); |
3081 | if (!Value.isInvalid()) |
3082 | Param->setDefaultArgument(Value.get()); |
3083 | } |
3084 | |
3085 | // Introduce this template parameter's instantiation into the instantiation |
3086 | // scope. |
3087 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); |
3088 | return Param; |
3089 | } |
3090 | |
3091 | static void collectUnexpandedParameterPacks( |
3092 | Sema &S, |
3093 | TemplateParameterList *Params, |
3094 | SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) { |
3095 | for (const auto &P : *Params) { |
3096 | if (P->isTemplateParameterPack()) |
3097 | continue; |
3098 | if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: P)) |
3099 | S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(), |
3100 | Unexpanded); |
3101 | if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(Val: P)) |
3102 | collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(), |
3103 | Unexpanded); |
3104 | } |
3105 | } |
3106 | |
3107 | Decl * |
3108 | TemplateDeclInstantiator::VisitTemplateTemplateParmDecl( |
3109 | TemplateTemplateParmDecl *D) { |
3110 | // Instantiate the template parameter list of the template template parameter. |
3111 | TemplateParameterList *TempParams = D->getTemplateParameters(); |
3112 | TemplateParameterList *InstParams; |
3113 | SmallVector<TemplateParameterList*, 8> ExpandedParams; |
3114 | |
3115 | bool IsExpandedParameterPack = false; |
3116 | |
3117 | if (D->isExpandedParameterPack()) { |
3118 | // The template template parameter pack is an already-expanded pack |
3119 | // expansion of template parameters. Substitute into each of the expanded |
3120 | // parameters. |
3121 | ExpandedParams.reserve(N: D->getNumExpansionTemplateParameters()); |
3122 | for (unsigned I = 0, N = D->getNumExpansionTemplateParameters(); |
3123 | I != N; ++I) { |
3124 | LocalInstantiationScope Scope(SemaRef); |
3125 | TemplateParameterList *Expansion = |
3126 | SubstTemplateParams(List: D->getExpansionTemplateParameters(I)); |
3127 | if (!Expansion) |
3128 | return nullptr; |
3129 | ExpandedParams.push_back(Elt: Expansion); |
3130 | } |
3131 | |
3132 | IsExpandedParameterPack = true; |
3133 | InstParams = TempParams; |
3134 | } else if (D->isPackExpansion()) { |
3135 | // The template template parameter pack expands to a pack of template |
3136 | // template parameters. Determine whether we need to expand this parameter |
3137 | // pack into separate parameters. |
3138 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
3139 | collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(), |
3140 | Unexpanded); |
3141 | |
3142 | // Determine whether the set of unexpanded parameter packs can and should |
3143 | // be expanded. |
3144 | bool Expand = true; |
3145 | bool RetainExpansion = false; |
3146 | std::optional<unsigned> NumExpansions; |
3147 | if (SemaRef.CheckParameterPacksForExpansion(EllipsisLoc: D->getLocation(), |
3148 | PatternRange: TempParams->getSourceRange(), |
3149 | Unexpanded, |
3150 | TemplateArgs, |
3151 | ShouldExpand&: Expand, RetainExpansion, |
3152 | NumExpansions)) |
3153 | return nullptr; |
3154 | |
3155 | if (Expand) { |
3156 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
3157 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); |
3158 | LocalInstantiationScope Scope(SemaRef); |
3159 | TemplateParameterList *Expansion = SubstTemplateParams(List: TempParams); |
3160 | if (!Expansion) |
3161 | return nullptr; |
3162 | ExpandedParams.push_back(Elt: Expansion); |
3163 | } |
3164 | |
3165 | // Note that we have an expanded parameter pack. The "type" of this |
3166 | // expanded parameter pack is the original expansion type, but callers |
3167 | // will end up using the expanded parameter pack types for type-checking. |
3168 | IsExpandedParameterPack = true; |
3169 | InstParams = TempParams; |
3170 | } else { |
3171 | // We cannot fully expand the pack expansion now, so just substitute |
3172 | // into the pattern. |
3173 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); |
3174 | |
3175 | LocalInstantiationScope Scope(SemaRef); |
3176 | InstParams = SubstTemplateParams(List: TempParams); |
3177 | if (!InstParams) |
3178 | return nullptr; |
3179 | } |
3180 | } else { |
3181 | // Perform the actual substitution of template parameters within a new, |
3182 | // local instantiation scope. |
3183 | LocalInstantiationScope Scope(SemaRef); |
3184 | InstParams = SubstTemplateParams(List: TempParams); |
3185 | if (!InstParams) |
3186 | return nullptr; |
3187 | } |
3188 | |
3189 | // Build the template template parameter. |
3190 | TemplateTemplateParmDecl *Param; |
3191 | if (IsExpandedParameterPack) |
3192 | Param = TemplateTemplateParmDecl::Create( |
3193 | SemaRef.Context, Owner, D->getLocation(), |
3194 | D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), |
3195 | D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams); |
3196 | else |
3197 | Param = TemplateTemplateParmDecl::Create( |
3198 | SemaRef.Context, Owner, D->getLocation(), |
3199 | D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), |
3200 | D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams); |
3201 | if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) { |
3202 | NestedNameSpecifierLoc QualifierLoc = |
3203 | D->getDefaultArgument().getTemplateQualifierLoc(); |
3204 | QualifierLoc = |
3205 | SemaRef.SubstNestedNameSpecifierLoc(NNS: QualifierLoc, TemplateArgs); |
3206 | TemplateName TName = SemaRef.SubstTemplateName( |
3207 | QualifierLoc, Name: D->getDefaultArgument().getArgument().getAsTemplate(), |
3208 | Loc: D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs); |
3209 | if (!TName.isNull()) |
3210 | Param->setDefaultArgument( |
3211 | C: SemaRef.Context, |
3212 | DefArg: TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName), |
3213 | D->getDefaultArgument().getTemplateQualifierLoc(), |
3214 | D->getDefaultArgument().getTemplateNameLoc())); |
3215 | } |
3216 | Param->setAccess(AS_public); |
3217 | Param->setImplicit(D->isImplicit()); |
3218 | |
3219 | // Introduce this template parameter's instantiation into the instantiation |
3220 | // scope. |
3221 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param); |
3222 | |
3223 | return Param; |
3224 | } |
3225 | |
3226 | Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { |
3227 | // Using directives are never dependent (and never contain any types or |
3228 | // expressions), so they require no explicit instantiation work. |
3229 | |
3230 | UsingDirectiveDecl *Inst |
3231 | = UsingDirectiveDecl::Create(C&: SemaRef.Context, DC: Owner, UsingLoc: D->getLocation(), |
3232 | NamespaceLoc: D->getNamespaceKeyLocation(), |
3233 | QualifierLoc: D->getQualifierLoc(), |
3234 | IdentLoc: D->getIdentLocation(), |
3235 | Nominated: D->getNominatedNamespace(), |
3236 | CommonAncestor: D->getCommonAncestor()); |
3237 | |
3238 | // Add the using directive to its declaration context |
3239 | // only if this is not a function or method. |
3240 | if (!Owner->isFunctionOrMethod()) |
3241 | Owner->addDecl(Inst); |
3242 | |
3243 | return Inst; |
3244 | } |
3245 | |
3246 | Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D, |
3247 | BaseUsingDecl *Inst, |
3248 | LookupResult *Lookup) { |
3249 | |
3250 | bool isFunctionScope = Owner->isFunctionOrMethod(); |
3251 | |
3252 | for (auto *Shadow : D->shadows()) { |
3253 | // FIXME: UsingShadowDecl doesn't preserve its immediate target, so |
3254 | // reconstruct it in the case where it matters. Hm, can we extract it from |
3255 | // the DeclSpec when parsing and save it in the UsingDecl itself? |
3256 | NamedDecl *OldTarget = Shadow->getTargetDecl(); |
3257 | if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Val: Shadow)) |
3258 | if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl()) |
3259 | OldTarget = BaseShadow; |
3260 | |
3261 | NamedDecl *InstTarget = nullptr; |
3262 | if (auto *EmptyD = |
3263 | dyn_cast<UnresolvedUsingIfExistsDecl>(Val: Shadow->getTargetDecl())) { |
3264 | InstTarget = UnresolvedUsingIfExistsDecl::Create( |
3265 | Ctx&: SemaRef.Context, DC: Owner, Loc: EmptyD->getLocation(), Name: EmptyD->getDeclName()); |
3266 | } else { |
3267 | InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl( |
3268 | Loc: Shadow->getLocation(), D: OldTarget, TemplateArgs)); |
3269 | } |
3270 | if (!InstTarget) |
3271 | return nullptr; |
3272 | |
3273 | UsingShadowDecl *PrevDecl = nullptr; |
3274 | if (Lookup && |
3275 | SemaRef.CheckUsingShadowDecl(BUD: Inst, Target: InstTarget, PreviousDecls: *Lookup, PrevShadow&: PrevDecl)) |
3276 | continue; |
3277 | |
3278 | if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(D: Shadow)) |
3279 | PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl( |
3280 | Loc: Shadow->getLocation(), D: OldPrev, TemplateArgs)); |
3281 | |
3282 | UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl( |
3283 | /*Scope*/ S: nullptr, BUD: Inst, Target: InstTarget, PrevDecl); |
3284 | SemaRef.Context.setInstantiatedFromUsingShadowDecl(Inst: InstShadow, Pattern: Shadow); |
3285 | |
3286 | if (isFunctionScope) |
3287 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow); |
3288 | } |
3289 | |
3290 | return Inst; |
3291 | } |
3292 | |
3293 | Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) { |
3294 | |
3295 | // The nested name specifier may be dependent, for example |
3296 | // template <typename T> struct t { |
3297 | // struct s1 { T f1(); }; |
3298 | // struct s2 : s1 { using s1::f1; }; |
3299 | // }; |
3300 | // template struct t<int>; |
3301 | // Here, in using s1::f1, s1 refers to t<T>::s1; |
3302 | // we need to substitute for t<int>::s1. |
3303 | NestedNameSpecifierLoc QualifierLoc |
3304 | = SemaRef.SubstNestedNameSpecifierLoc(NNS: D->getQualifierLoc(), |
3305 | TemplateArgs); |
3306 | if (!QualifierLoc) |
3307 | return nullptr; |
3308 | |
3309 | // For an inheriting constructor declaration, the name of the using |
3310 | // declaration is the name of a constructor in this class, not in the |
3311 | // base class. |
3312 | DeclarationNameInfo NameInfo = D->getNameInfo(); |
3313 | if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) |
3314 | if (auto *RD = dyn_cast<CXXRecordDecl>(Val: SemaRef.CurContext)) |
3315 | NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName( |
3316 | Ty: SemaRef.Context.getCanonicalType(T: SemaRef.Context.getRecordType(RD)))); |
3317 | |
3318 | // We only need to do redeclaration lookups if we're in a class scope (in |
3319 | // fact, it's not really even possible in non-class scopes). |
3320 | bool CheckRedeclaration = Owner->isRecord(); |
3321 | LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName, |
3322 | Sema::ForVisibleRedeclaration); |
3323 | |
3324 | UsingDecl *NewUD = UsingDecl::Create(C&: SemaRef.Context, DC: Owner, |
3325 | UsingL: D->getUsingLoc(), |
3326 | QualifierLoc, |
3327 | NameInfo, |
3328 | HasTypenameKeyword: D->hasTypename()); |
3329 | |
3330 | CXXScopeSpec SS; |
3331 | SS.Adopt(Other: QualifierLoc); |
3332 | if (CheckRedeclaration) { |
3333 | Prev.setHideTags(false); |
3334 | SemaRef.LookupQualifiedName(R&: Prev, LookupCtx: Owner); |
3335 | |
3336 | // Check for invalid redeclarations. |
3337 | if (SemaRef.CheckUsingDeclRedeclaration(UsingLoc: D->getUsingLoc(), |
3338 | HasTypenameKeyword: D->hasTypename(), SS, |
3339 | NameLoc: D->getLocation(), Previous: Prev)) |
3340 | NewUD->setInvalidDecl(); |
3341 | } |
3342 | |
3343 | if (!NewUD->isInvalidDecl() && |
3344 | SemaRef.CheckUsingDeclQualifier(UsingLoc: D->getUsingLoc(), HasTypename: D->hasTypename(), SS, |
3345 | NameInfo, NameLoc: D->getLocation(), R: nullptr, UD: D)) |
3346 | NewUD->setInvalidDecl(); |
3347 | |
3348 | SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D); |
3349 | NewUD->setAccess(D->getAccess()); |
3350 | Owner->addDecl(NewUD); |
3351 | |
3352 | // Don't process the shadow decls for an invalid decl. |
3353 | if (NewUD->isInvalidDecl()) |
3354 | return NewUD; |
3355 | |
3356 | // If the using scope was dependent, or we had dependent bases, we need to |
3357 | // recheck the inheritance |
3358 | if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName) |
3359 | SemaRef.CheckInheritingConstructorUsingDecl(UD: NewUD); |
3360 | |
3361 | return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr); |
3362 | } |
3363 | |
3364 | Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) { |
3365 | // Cannot be a dependent type, but still could be an instantiation |
3366 | EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl( |
3367 | Loc: D->getLocation(), D: D->getEnumDecl(), TemplateArgs)); |
3368 | |
3369 | if (SemaRef.RequireCompleteEnumDecl(D: EnumD, L: EnumD->getLocation())) |
3370 | return nullptr; |
3371 | |
3372 | TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs, |
3373 | D->getLocation(), D->getDeclName()); |
3374 | UsingEnumDecl *NewUD = |
3375 | UsingEnumDecl::Create(C&: SemaRef.Context, DC: Owner, UsingL: D->getUsingLoc(), |
3376 | EnumL: D->getEnumLoc(), NameL: D->getLocation(), EnumType: TSI); |
3377 | |
3378 | SemaRef.Context.setInstantiatedFromUsingEnumDecl(Inst: NewUD, Pattern: D); |
3379 | NewUD->setAccess(D->getAccess()); |
3380 | Owner->addDecl(NewUD); |
3381 | |
3382 | // Don't process the shadow decls for an invalid decl. |
3383 | if (NewUD->isInvalidDecl()) |
3384 | return NewUD; |
3385 | |
3386 | // We don't have to recheck for duplication of the UsingEnumDecl itself, as it |
3387 | // cannot be dependent, and will therefore have been checked during template |
3388 | // definition. |
3389 | |
3390 | return VisitBaseUsingDecls(D, NewUD, nullptr); |
3391 | } |
3392 | |
3393 | Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) { |
3394 | // Ignore these; we handle them in bulk when processing the UsingDecl. |
3395 | return nullptr; |
3396 | } |
3397 | |
3398 | Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl( |
3399 | ConstructorUsingShadowDecl *D) { |
3400 | // Ignore these; we handle them in bulk when processing the UsingDecl. |
3401 | return nullptr; |
3402 | } |
3403 | |
3404 | template <typename T> |
3405 | Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl( |
3406 | T *D, bool InstantiatingPackElement) { |
3407 | // If this is a pack expansion, expand it now. |
3408 | if (D->isPackExpansion() && !InstantiatingPackElement) { |
3409 | SmallVector<UnexpandedParameterPack, 2> Unexpanded; |
3410 | SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded); |
3411 | SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded); |
3412 | |
3413 | // Determine whether the set of unexpanded parameter packs can and should |
3414 | // be expanded. |
3415 | bool Expand = true; |
3416 | bool RetainExpansion = false; |
3417 | std::optional<unsigned> NumExpansions; |
3418 | if (SemaRef.CheckParameterPacksForExpansion( |
3419 | EllipsisLoc: D->getEllipsisLoc(), PatternRange: D->getSourceRange(), Unexpanded, TemplateArgs, |
3420 | ShouldExpand&: Expand, RetainExpansion, NumExpansions)) |
3421 | return nullptr; |
3422 | |
3423 | // This declaration cannot appear within a function template signature, |
3424 | // so we can't have a partial argument list for a parameter pack. |
3425 | assert(!RetainExpansion && |
3426 | "should never need to retain an expansion for UsingPackDecl" ); |
3427 | |
3428 | if (!Expand) { |
3429 | // We cannot fully expand the pack expansion now, so substitute into the |
3430 | // pattern and create a new pack expansion. |
3431 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1); |
3432 | return instantiateUnresolvedUsingDecl(D, true); |
3433 | } |
3434 | |
3435 | // Within a function, we don't have any normal way to check for conflicts |
3436 | // between shadow declarations from different using declarations in the |
3437 | // same pack expansion, but this is always ill-formed because all expansions |
3438 | // must produce (conflicting) enumerators. |
3439 | // |
3440 | // Sadly we can't just reject this in the template definition because it |
3441 | // could be valid if the pack is empty or has exactly one expansion. |
3442 | if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) { |
3443 | SemaRef.Diag(D->getEllipsisLoc(), |
3444 | diag::err_using_decl_redeclaration_expansion); |
3445 | return nullptr; |
3446 | } |
3447 | |
3448 | // Instantiate the slices of this pack and build a UsingPackDecl. |
3449 | SmallVector<NamedDecl*, 8> Expansions; |
3450 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
3451 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I); |
3452 | Decl *Slice = instantiateUnresolvedUsingDecl(D, true); |
3453 | if (!Slice) |
3454 | return nullptr; |
3455 | // Note that we can still get unresolved using declarations here, if we |
3456 | // had arguments for all packs but the pattern also contained other |
3457 | // template arguments (this only happens during partial substitution, eg |
3458 | // into the body of a generic lambda in a function template). |
3459 | Expansions.push_back(Elt: cast<NamedDecl>(Val: Slice)); |
3460 | } |
3461 | |
3462 | auto *NewD = SemaRef.BuildUsingPackDecl(InstantiatedFrom: D, Expansions); |
3463 | if (isDeclWithinFunction(D)) |
3464 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewD); |
3465 | return NewD; |
3466 | } |
3467 | |
3468 | UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D); |
3469 | SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation(); |
3470 | |
3471 | NestedNameSpecifierLoc QualifierLoc |
3472 | = SemaRef.SubstNestedNameSpecifierLoc(NNS: D->getQualifierLoc(), |
3473 | TemplateArgs); |
3474 | if (!QualifierLoc) |
3475 | return nullptr; |
3476 | |
3477 | CXXScopeSpec SS; |
3478 | SS.Adopt(Other: QualifierLoc); |
3479 | |
3480 | DeclarationNameInfo NameInfo |
3481 | = SemaRef.SubstDeclarationNameInfo(NameInfo: D->getNameInfo(), TemplateArgs); |
3482 | |
3483 | // Produce a pack expansion only if we're not instantiating a particular |
3484 | // slice of a pack expansion. |
3485 | bool InstantiatingSlice = D->getEllipsisLoc().isValid() && |
3486 | SemaRef.ArgumentPackSubstitutionIndex != -1; |
3487 | SourceLocation EllipsisLoc = |
3488 | InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc(); |
3489 | |
3490 | bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>(); |
3491 | NamedDecl *UD = SemaRef.BuildUsingDeclaration( |
3492 | /*Scope*/ S: nullptr, AS: D->getAccess(), UsingLoc: D->getUsingLoc(), |
3493 | /*HasTypename*/ HasTypenameKeyword: TD, TypenameLoc, SS, NameInfo, EllipsisLoc, |
3494 | AttrList: ParsedAttributesView(), |
3495 | /*IsInstantiation*/ true, IsUsingIfExists); |
3496 | if (UD) { |
3497 | SemaRef.InstantiateAttrs(TemplateArgs, Tmpl: D, New: UD); |
3498 | SemaRef.Context.setInstantiatedFromUsingDecl(Inst: UD, Pattern: D); |
3499 | } |
3500 | |
3501 | return UD; |
3502 | } |
3503 | |
3504 | Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl( |
3505 | UnresolvedUsingTypenameDecl *D) { |
3506 | return instantiateUnresolvedUsingDecl(D); |
3507 | } |
3508 | |
3509 | Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl( |
3510 | UnresolvedUsingValueDecl *D) { |
3511 | return instantiateUnresolvedUsingDecl(D); |
3512 | } |
3513 | |
3514 | Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl( |
3515 | UnresolvedUsingIfExistsDecl *D) { |
3516 | llvm_unreachable("referring to unresolved decl out of UsingShadowDecl" ); |
3517 | } |
3518 | |
3519 | Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) { |
3520 | SmallVector<NamedDecl*, 8> Expansions; |
3521 | for (auto *UD : D->expansions()) { |
3522 | if (NamedDecl *NewUD = |
3523 | SemaRef.FindInstantiatedDecl(Loc: D->getLocation(), D: UD, TemplateArgs)) |
3524 | Expansions.push_back(Elt: NewUD); |
3525 | else |
3526 | return nullptr; |
3527 | } |
3528 | |
3529 | auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions); |
3530 | if (isDeclWithinFunction(D)) |
3531 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewD); |
3532 | return NewD; |
3533 | } |
3534 | |
3535 | Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl( |
3536 | OMPThreadPrivateDecl *D) { |
3537 | SmallVector<Expr *, 5> Vars; |
3538 | for (auto *I : D->varlists()) { |
3539 | Expr *Var = SemaRef.SubstExpr(E: I, TemplateArgs).get(); |
3540 | assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr" ); |
3541 | Vars.push_back(Elt: Var); |
3542 | } |
3543 | |
3544 | OMPThreadPrivateDecl *TD = |
3545 | SemaRef.CheckOMPThreadPrivateDecl(Loc: D->getLocation(), VarList: Vars); |
3546 | |
3547 | TD->setAccess(AS_public); |
3548 | Owner->addDecl(TD); |
3549 | |
3550 | return TD; |
3551 | } |
3552 | |
3553 | Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) { |
3554 | SmallVector<Expr *, 5> Vars; |
3555 | for (auto *I : D->varlists()) { |
3556 | Expr *Var = SemaRef.SubstExpr(E: I, TemplateArgs).get(); |
3557 | assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr" ); |
3558 | Vars.push_back(Elt: Var); |
3559 | } |
3560 | SmallVector<OMPClause *, 4> Clauses; |
3561 | // Copy map clauses from the original mapper. |
3562 | for (OMPClause *C : D->clauselists()) { |
3563 | OMPClause *IC = nullptr; |
3564 | if (auto *AC = dyn_cast<OMPAllocatorClause>(Val: C)) { |
3565 | ExprResult NewE = SemaRef.SubstExpr(E: AC->getAllocator(), TemplateArgs); |
3566 | if (!NewE.isUsable()) |
3567 | continue; |
3568 | IC = SemaRef.ActOnOpenMPAllocatorClause( |
3569 | Allocator: NewE.get(), StartLoc: AC->getBeginLoc(), LParenLoc: AC->getLParenLoc(), EndLoc: AC->getEndLoc()); |
3570 | } else if (auto *AC = dyn_cast<OMPAlignClause>(Val: C)) { |
3571 | ExprResult NewE = SemaRef.SubstExpr(E: AC->getAlignment(), TemplateArgs); |
3572 | if (!NewE.isUsable()) |
3573 | continue; |
3574 | IC = SemaRef.ActOnOpenMPAlignClause(Alignment: NewE.get(), StartLoc: AC->getBeginLoc(), |
3575 | LParenLoc: AC->getLParenLoc(), EndLoc: AC->getEndLoc()); |
3576 | // If align clause value ends up being invalid, this can end up null. |
3577 | if (!IC) |
3578 | continue; |
3579 | } |
3580 | Clauses.push_back(Elt: IC); |
3581 | } |
3582 | |
3583 | Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective( |
3584 | Loc: D->getLocation(), VarList: Vars, Clauses, Owner); |
3585 | if (Res.get().isNull()) |
3586 | return nullptr; |
3587 | return Res.get().getSingleDecl(); |
3588 | } |
3589 | |
3590 | Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) { |
3591 | llvm_unreachable( |
3592 | "Requires directive cannot be instantiated within a dependent context" ); |
3593 | } |
3594 | |
3595 | Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl( |
3596 | OMPDeclareReductionDecl *D) { |
3597 | // Instantiate type and check if it is allowed. |
3598 | const bool RequiresInstantiation = |
3599 | D->getType()->isDependentType() || |
3600 | D->getType()->isInstantiationDependentType() || |
3601 | D->getType()->containsUnexpandedParameterPack(); |
3602 | QualType SubstReductionType; |
3603 | if (RequiresInstantiation) { |
3604 | SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType( |
3605 | TyLoc: D->getLocation(), |
3606 | ParsedType: ParsedType::make(P: SemaRef.SubstType( |
3607 | D->getType(), TemplateArgs, D->getLocation(), DeclarationName()))); |
3608 | } else { |
3609 | SubstReductionType = D->getType(); |
3610 | } |
3611 | if (SubstReductionType.isNull()) |
3612 | return nullptr; |
3613 | Expr *Combiner = D->getCombiner(); |
3614 | Expr *Init = D->getInitializer(); |
3615 | bool IsCorrect = true; |
3616 | // Create instantiated copy. |
3617 | std::pair<QualType, SourceLocation> ReductionTypes[] = { |
3618 | std::make_pair(SubstReductionType, D->getLocation())}; |
3619 | auto *PrevDeclInScope = D->getPrevDeclInScope(); |
3620 | if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { |
3621 | PrevDeclInScope = cast<OMPDeclareReductionDecl>( |
3622 | Val: SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) |
3623 | ->get<Decl *>()); |
3624 | } |
3625 | auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart( |
3626 | /*S=*/nullptr, DC: Owner, Name: D->getDeclName(), ReductionTypes: ReductionTypes, AS: D->getAccess(), |
3627 | PrevDeclInScope); |
3628 | auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl()); |
3629 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst: NewDRD); |
3630 | Expr *SubstCombiner = nullptr; |
3631 | Expr *SubstInitializer = nullptr; |
3632 | // Combiners instantiation sequence. |
3633 | if (Combiner) { |
3634 | SemaRef.ActOnOpenMPDeclareReductionCombinerStart( |
3635 | /*S=*/nullptr, D: NewDRD); |
3636 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3637 | D: cast<DeclRefExpr>(Val: D->getCombinerIn())->getDecl(), |
3638 | Inst: cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl()); |
3639 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3640 | D: cast<DeclRefExpr>(Val: D->getCombinerOut())->getDecl(), |
3641 | Inst: cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl()); |
3642 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: Owner); |
3643 | Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), |
3644 | ThisContext); |
3645 | SubstCombiner = SemaRef.SubstExpr(E: Combiner, TemplateArgs).get(); |
3646 | SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(D: NewDRD, Combiner: SubstCombiner); |
3647 | } |
3648 | // Initializers instantiation sequence. |
3649 | if (Init) { |
3650 | VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart( |
3651 | /*S=*/nullptr, D: NewDRD); |
3652 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3653 | D: cast<DeclRefExpr>(Val: D->getInitOrig())->getDecl(), |
3654 | Inst: cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl()); |
3655 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3656 | D: cast<DeclRefExpr>(Val: D->getInitPriv())->getDecl(), |
3657 | Inst: cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl()); |
3658 | if (D->getInitializerKind() == OMPDeclareReductionInitKind::Call) { |
3659 | SubstInitializer = SemaRef.SubstExpr(E: Init, TemplateArgs).get(); |
3660 | } else { |
3661 | auto *OldPrivParm = |
3662 | cast<VarDecl>(Val: cast<DeclRefExpr>(Val: D->getInitPriv())->getDecl()); |
3663 | IsCorrect = IsCorrect && OldPrivParm->hasInit(); |
3664 | if (IsCorrect) |
3665 | SemaRef.InstantiateVariableInitializer(Var: OmpPrivParm, OldVar: OldPrivParm, |
3666 | TemplateArgs); |
3667 | } |
3668 | SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(D: NewDRD, Initializer: SubstInitializer, |
3669 | OmpPrivParm); |
3670 | } |
3671 | IsCorrect = IsCorrect && SubstCombiner && |
3672 | (!Init || |
3673 | (D->getInitializerKind() == OMPDeclareReductionInitKind::Call && |
3674 | SubstInitializer) || |
3675 | (D->getInitializerKind() != OMPDeclareReductionInitKind::Call && |
3676 | !SubstInitializer)); |
3677 | |
3678 | (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd( |
3679 | /*S=*/nullptr, DeclReductions: DRD, IsValid: IsCorrect && !D->isInvalidDecl()); |
3680 | |
3681 | return NewDRD; |
3682 | } |
3683 | |
3684 | Decl * |
3685 | TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) { |
3686 | // Instantiate type and check if it is allowed. |
3687 | const bool RequiresInstantiation = |
3688 | D->getType()->isDependentType() || |
3689 | D->getType()->isInstantiationDependentType() || |
3690 | D->getType()->containsUnexpandedParameterPack(); |
3691 | QualType SubstMapperTy; |
3692 | DeclarationName VN = D->getVarName(); |
3693 | if (RequiresInstantiation) { |
3694 | SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType( |
3695 | TyLoc: D->getLocation(), |
3696 | ParsedType: ParsedType::make(P: SemaRef.SubstType(D->getType(), TemplateArgs, |
3697 | D->getLocation(), VN))); |
3698 | } else { |
3699 | SubstMapperTy = D->getType(); |
3700 | } |
3701 | if (SubstMapperTy.isNull()) |
3702 | return nullptr; |
3703 | // Create an instantiated copy of mapper. |
3704 | auto *PrevDeclInScope = D->getPrevDeclInScope(); |
3705 | if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) { |
3706 | PrevDeclInScope = cast<OMPDeclareMapperDecl>( |
3707 | Val: SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope) |
3708 | ->get<Decl *>()); |
3709 | } |
3710 | bool IsCorrect = true; |
3711 | SmallVector<OMPClause *, 6> Clauses; |
3712 | // Instantiate the mapper variable. |
3713 | DeclarationNameInfo DirName; |
3714 | SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName, |
3715 | /*S=*/nullptr, |
3716 | (*D->clauselist_begin())->getBeginLoc()); |
3717 | ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl( |
3718 | /*S=*/nullptr, MapperType: SubstMapperTy, StartLoc: D->getLocation(), VN); |
3719 | SemaRef.CurrentInstantiationScope->InstantiatedLocal( |
3720 | cast<DeclRefExpr>(Val: D->getMapperVarRef())->getDecl(), |
3721 | cast<DeclRefExpr>(Val: MapperVarRef.get())->getDecl()); |
3722 | auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Val: Owner); |
3723 | Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(), |
3724 | ThisContext); |
3725 | // Instantiate map clauses. |
3726 | for (OMPClause *C : D->clauselists()) { |
3727 | auto *OldC = cast<OMPMapClause>(Val: C); |
3728 | SmallVector<Expr *, 4> NewVars; |
3729 | for (Expr *OE : OldC->varlists()) { |
3730 | Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get(); |
3731 | if (!NE) { |
3732 | IsCorrect = false; |
3733 | break; |
3734 | } |
3735 | NewVars.push_back(NE); |
3736 | } |
3737 | if (!IsCorrect) |
3738 | break; |
3739 | NestedNameSpecifierLoc NewQualifierLoc = |
3740 | SemaRef.SubstNestedNameSpecifierLoc(NNS: OldC->getMapperQualifierLoc(), |
3741 | TemplateArgs); |
3742 | CXXScopeSpec SS; |
3743 | SS.Adopt(Other: NewQualifierLoc); |
3744 | DeclarationNameInfo NewNameInfo = |
3745 | SemaRef.SubstDeclarationNameInfo(NameInfo: OldC->getMapperIdInfo(), TemplateArgs); |
3746 | OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(), |
3747 | OldC->getEndLoc()); |
3748 | OMPClause *NewC = SemaRef.ActOnOpenMPMapClause( |
3749 | IteratorModifier: OldC->getIteratorModifier(), MapTypeModifiers: OldC->getMapTypeModifiers(), |
3750 | MapTypeModifiersLoc: OldC->getMapTypeModifiersLoc(), MapperIdScopeSpec&: SS, MapperId&: NewNameInfo, MapType: OldC->getMapType(), |
3751 | IsMapTypeImplicit: OldC->isImplicitMapType(), MapLoc: OldC->getMapLoc(), ColonLoc: OldC->getColonLoc(), |
3752 | VarList: NewVars, Locs); |
3753 | Clauses.push_back(Elt: NewC); |
3754 | } |
3755 | SemaRef.EndOpenMPDSABlock(CurDirective: nullptr); |
3756 | if (!IsCorrect) |
3757 | return nullptr; |
3758 | Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective( |
3759 | /*S=*/nullptr, DC: Owner, Name: D->getDeclName(), MapperType: SubstMapperTy, StartLoc: D->getLocation(), |
3760 | VN, AS: D->getAccess(), MapperVarRef: MapperVarRef.get(), Clauses, PrevDeclInScope); |
3761 | Decl *NewDMD = DG.get().getSingleDecl(); |
3762 | SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD); |
3763 | return NewDMD; |
3764 | } |
3765 | |
3766 | Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl( |
3767 | OMPCapturedExprDecl * /*D*/) { |
3768 | llvm_unreachable("Should not be met in templates" ); |
3769 | } |
3770 | |
3771 | Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) { |
3772 | return VisitFunctionDecl(D, TemplateParams: nullptr); |
3773 | } |
3774 | |
3775 | Decl * |
3776 | TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) { |
3777 | Decl *Inst = VisitFunctionDecl(D, nullptr); |
3778 | if (Inst && !D->getDescribedFunctionTemplate()) |
3779 | Owner->addDecl(D: Inst); |
3780 | return Inst; |
3781 | } |
3782 | |
3783 | Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) { |
3784 | return VisitCXXMethodDecl(D, TemplateParams: nullptr); |
3785 | } |
3786 | |
3787 | Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) { |
3788 | llvm_unreachable("There are only CXXRecordDecls in C++" ); |
3789 | } |
3790 | |
3791 | Decl * |
3792 | TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl( |
3793 | ClassTemplateSpecializationDecl *D) { |
3794 | // As a MS extension, we permit class-scope explicit specialization |
3795 | // of member class templates. |
3796 | ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate(); |
3797 | assert(ClassTemplate->getDeclContext()->isRecord() && |
3798 | D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && |
3799 | "can only instantiate an explicit specialization " |
3800 | "for a member class template" ); |
3801 | |
3802 | // Lookup the already-instantiated declaration in the instantiation |
3803 | // of the class template. |
3804 | ClassTemplateDecl *InstClassTemplate = |
3805 | cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl( |
3806 | Loc: D->getLocation(), D: ClassTemplate, TemplateArgs)); |
3807 | if (!InstClassTemplate) |
3808 | return nullptr; |
3809 | |
3810 | // Substitute into the template arguments of the class template explicit |
3811 | // specialization. |
3812 | TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc(). |
3813 | castAs<TemplateSpecializationTypeLoc>(); |
3814 | TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(), |
3815 | Loc.getRAngleLoc()); |
3816 | SmallVector<TemplateArgumentLoc, 4> ArgLocs; |
3817 | for (unsigned I = 0; I != Loc.getNumArgs(); ++I) |
3818 | ArgLocs.push_back(Elt: Loc.getArgLoc(i: I)); |
3819 | if (SemaRef.SubstTemplateArguments(Args: ArgLocs, TemplateArgs, Outputs&: InstTemplateArgs)) |
3820 | return nullptr; |
3821 | |
3822 | // Check that the template argument list is well-formed for this |
3823 | // class template. |
3824 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
3825 | if (SemaRef.CheckTemplateArgumentList(Template: InstClassTemplate, TemplateLoc: D->getLocation(), |
3826 | TemplateArgs&: InstTemplateArgs, PartialTemplateArgs: false, |
3827 | SugaredConverted, CanonicalConverted, |
3828 | /*UpdateArgsWithConversions=*/true)) |
3829 | return nullptr; |
3830 | |
3831 | // Figure out where to insert this class template explicit specialization |
3832 | // in the member template's set of class template explicit specializations. |
3833 | void *InsertPos = nullptr; |
3834 | ClassTemplateSpecializationDecl *PrevDecl = |
3835 | InstClassTemplate->findSpecialization(Args: CanonicalConverted, InsertPos); |
3836 | |
3837 | // Check whether we've already seen a conflicting instantiation of this |
3838 | // declaration (for instance, if there was a prior implicit instantiation). |
3839 | bool Ignored; |
3840 | if (PrevDecl && |
3841 | SemaRef.CheckSpecializationInstantiationRedecl(NewLoc: D->getLocation(), |
3842 | NewTSK: D->getSpecializationKind(), |
3843 | PrevDecl, |
3844 | PrevTSK: PrevDecl->getSpecializationKind(), |
3845 | PrevPtOfInstantiation: PrevDecl->getPointOfInstantiation(), |
3846 | SuppressNew&: Ignored)) |
3847 | return nullptr; |
3848 | |
3849 | // If PrevDecl was a definition and D is also a definition, diagnose. |
3850 | // This happens in cases like: |
3851 | // |
3852 | // template<typename T, typename U> |
3853 | // struct Outer { |
3854 | // template<typename X> struct Inner; |
3855 | // template<> struct Inner<T> {}; |
3856 | // template<> struct Inner<U> {}; |
3857 | // }; |
3858 | // |
3859 | // Outer<int, int> outer; // error: the explicit specializations of Inner |
3860 | // // have the same signature. |
3861 | if (PrevDecl && PrevDecl->getDefinition() && |
3862 | D->isThisDeclarationADefinition()) { |
3863 | SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl; |
3864 | SemaRef.Diag(PrevDecl->getDefinition()->getLocation(), |
3865 | diag::note_previous_definition); |
3866 | return nullptr; |
3867 | } |
3868 | |
3869 | // Create the class template partial specialization declaration. |
3870 | ClassTemplateSpecializationDecl *InstD = |
3871 | ClassTemplateSpecializationDecl::Create( |
3872 | Context&: SemaRef.Context, TK: D->getTagKind(), DC: Owner, StartLoc: D->getBeginLoc(), |
3873 | IdLoc: D->getLocation(), SpecializedTemplate: InstClassTemplate, Args: CanonicalConverted, PrevDecl); |
3874 | |
3875 | // Add this partial specialization to the set of class template partial |
3876 | // specializations. |
3877 | if (!PrevDecl) |
3878 | InstClassTemplate->AddSpecialization(D: InstD, InsertPos); |
3879 | |
3880 | // Substitute the nested name specifier, if any. |
3881 | if (SubstQualifier(D, InstD)) |
3882 | return nullptr; |
3883 | |
3884 | // Build the canonical type that describes the converted template |
3885 | // arguments of the class template explicit specialization. |
3886 | QualType CanonType = SemaRef.Context.getTemplateSpecializationType( |
3887 | T: TemplateName(InstClassTemplate), Args: CanonicalConverted, |
3888 | Canon: SemaRef.Context.getRecordType(InstD)); |
3889 | |
3890 | // Build the fully-sugared type for this class template |
3891 | // specialization as the user wrote in the specialization |
3892 | // itself. This means that we'll pretty-print the type retrieved |
3893 | // from the specialization's declaration the way that the user |
3894 | // actually wrote the specialization, rather than formatting the |
3895 | // name based on the "canonical" representation used to store the |
3896 | // template arguments in the specialization. |
3897 | TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( |
3898 | T: TemplateName(InstClassTemplate), TLoc: D->getLocation(), Args: InstTemplateArgs, |
3899 | Canon: CanonType); |
3900 | |
3901 | InstD->setAccess(D->getAccess()); |
3902 | InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation); |
3903 | InstD->setSpecializationKind(D->getSpecializationKind()); |
3904 | InstD->setTypeAsWritten(WrittenTy); |
3905 | InstD->setExternLoc(D->getExternLoc()); |
3906 | InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc()); |
3907 | |
3908 | Owner->addDecl(InstD); |
3909 | |
3910 | // Instantiate the members of the class-scope explicit specialization eagerly. |
3911 | // We don't have support for lazy instantiation of an explicit specialization |
3912 | // yet, and MSVC eagerly instantiates in this case. |
3913 | // FIXME: This is wrong in standard C++. |
3914 | if (D->isThisDeclarationADefinition() && |
3915 | SemaRef.InstantiateClass(PointOfInstantiation: D->getLocation(), Instantiation: InstD, Pattern: D, TemplateArgs, |
3916 | TSK: TSK_ImplicitInstantiation, |
3917 | /*Complain=*/true)) |
3918 | return nullptr; |
3919 | |
3920 | return InstD; |
3921 | } |
3922 | |
3923 | Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( |
3924 | VarTemplateSpecializationDecl *D) { |
3925 | |
3926 | TemplateArgumentListInfo VarTemplateArgsInfo; |
3927 | VarTemplateDecl *VarTemplate = D->getSpecializedTemplate(); |
3928 | assert(VarTemplate && |
3929 | "A template specialization without specialized template?" ); |
3930 | |
3931 | VarTemplateDecl *InstVarTemplate = |
3932 | cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl( |
3933 | Loc: D->getLocation(), D: VarTemplate, TemplateArgs)); |
3934 | if (!InstVarTemplate) |
3935 | return nullptr; |
3936 | |
3937 | // Substitute the current template arguments. |
3938 | if (const ASTTemplateArgumentListInfo *TemplateArgsInfo = |
3939 | D->getTemplateArgsInfo()) { |
3940 | VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc()); |
3941 | VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc()); |
3942 | |
3943 | if (SemaRef.SubstTemplateArguments(Args: TemplateArgsInfo->arguments(), |
3944 | TemplateArgs, Outputs&: VarTemplateArgsInfo)) |
3945 | return nullptr; |
3946 | } |
3947 | |
3948 | // Check that the template argument list is well-formed for this template. |
3949 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
3950 | if (SemaRef.CheckTemplateArgumentList(Template: InstVarTemplate, TemplateLoc: D->getLocation(), |
3951 | TemplateArgs&: VarTemplateArgsInfo, PartialTemplateArgs: false, |
3952 | SugaredConverted, CanonicalConverted, |
3953 | /*UpdateArgsWithConversions=*/true)) |
3954 | return nullptr; |
3955 | |
3956 | // Check whether we've already seen a declaration of this specialization. |
3957 | void *InsertPos = nullptr; |
3958 | VarTemplateSpecializationDecl *PrevDecl = |
3959 | InstVarTemplate->findSpecialization(Args: CanonicalConverted, InsertPos); |
3960 | |
3961 | // Check whether we've already seen a conflicting instantiation of this |
3962 | // declaration (for instance, if there was a prior implicit instantiation). |
3963 | bool Ignored; |
3964 | if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl( |
3965 | NewLoc: D->getLocation(), NewTSK: D->getSpecializationKind(), PrevDecl, |
3966 | PrevTSK: PrevDecl->getSpecializationKind(), |
3967 | PrevPtOfInstantiation: PrevDecl->getPointOfInstantiation(), SuppressNew&: Ignored)) |
3968 | return nullptr; |
3969 | |
3970 | return VisitVarTemplateSpecializationDecl( |
3971 | InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl); |
3972 | } |
3973 | |
3974 | Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl( |
3975 | VarTemplateDecl *VarTemplate, VarDecl *D, |
3976 | const TemplateArgumentListInfo &TemplateArgsInfo, |
3977 | ArrayRef<TemplateArgument> Converted, |
3978 | VarTemplateSpecializationDecl *PrevDecl) { |
3979 | |
3980 | // Do substitution on the type of the declaration |
3981 | TypeSourceInfo *DI = |
3982 | SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs, |
3983 | D->getTypeSpecStartLoc(), D->getDeclName()); |
3984 | if (!DI) |
3985 | return nullptr; |
3986 | |
3987 | if (DI->getType()->isFunctionType()) { |
3988 | SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function) |
3989 | << D->isStaticDataMember() << DI->getType(); |
3990 | return nullptr; |
3991 | } |
3992 | |
3993 | // Build the instantiated declaration |
3994 | VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create( |
3995 | Context&: SemaRef.Context, DC: Owner, StartLoc: D->getInnerLocStart(), IdLoc: D->getLocation(), |
3996 | SpecializedTemplate: VarTemplate, T: DI->getType(), TInfo: DI, S: D->getStorageClass(), Args: Converted); |
3997 | Var->setTemplateArgsInfo(TemplateArgsInfo); |
3998 | if (!PrevDecl) { |
3999 | void *InsertPos = nullptr; |
4000 | VarTemplate->findSpecialization(Args: Converted, InsertPos); |
4001 | VarTemplate->AddSpecialization(D: Var, InsertPos); |
4002 | } |
4003 | |
4004 | if (SemaRef.getLangOpts().OpenCL) |
4005 | SemaRef.deduceOpenCLAddressSpace(Var); |
4006 | |
4007 | // Substitute the nested name specifier, if any. |
4008 | if (SubstQualifier(D, Var)) |
4009 | return nullptr; |
4010 | |
4011 | SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner, |
4012 | StartingScope, false, PrevDecl); |
4013 | |
4014 | return Var; |
4015 | } |
4016 | |
4017 | Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) { |
4018 | llvm_unreachable("@defs is not supported in Objective-C++" ); |
4019 | } |
4020 | |
4021 | Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) { |
4022 | // FIXME: We need to be able to instantiate FriendTemplateDecls. |
4023 | unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID( |
4024 | L: DiagnosticsEngine::Error, |
4025 | FormatString: "cannot instantiate %0 yet" ); |
4026 | SemaRef.Diag(D->getLocation(), DiagID) |
4027 | << D->getDeclKindName(); |
4028 | |
4029 | return nullptr; |
4030 | } |
4031 | |
4032 | Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) { |
4033 | llvm_unreachable("Concept definitions cannot reside inside a template" ); |
4034 | } |
4035 | |
4036 | Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl( |
4037 | ImplicitConceptSpecializationDecl *D) { |
4038 | llvm_unreachable("Concept specializations cannot reside inside a template" ); |
4039 | } |
4040 | |
4041 | Decl * |
4042 | TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) { |
4043 | return RequiresExprBodyDecl::Create(C&: SemaRef.Context, DC: D->getDeclContext(), |
4044 | StartLoc: D->getBeginLoc()); |
4045 | } |
4046 | |
4047 | Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) { |
4048 | llvm_unreachable("Unexpected decl" ); |
4049 | } |
4050 | |
4051 | Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner, |
4052 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4053 | TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); |
4054 | if (D->isInvalidDecl()) |
4055 | return nullptr; |
4056 | |
4057 | Decl *SubstD; |
4058 | runWithSufficientStackSpace(Loc: D->getLocation(), Fn: [&] { |
4059 | SubstD = Instantiator.Visit(D); |
4060 | }); |
4061 | return SubstD; |
4062 | } |
4063 | |
4064 | void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK, |
4065 | FunctionDecl *Orig, QualType &T, |
4066 | TypeSourceInfo *&TInfo, |
4067 | DeclarationNameInfo &NameInfo) { |
4068 | assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual); |
4069 | |
4070 | // C++2a [class.compare.default]p3: |
4071 | // the return type is replaced with bool |
4072 | auto *FPT = T->castAs<FunctionProtoType>(); |
4073 | T = SemaRef.Context.getFunctionType( |
4074 | ResultTy: SemaRef.Context.BoolTy, Args: FPT->getParamTypes(), EPI: FPT->getExtProtoInfo()); |
4075 | |
4076 | // Update the return type in the source info too. The most straightforward |
4077 | // way is to create new TypeSourceInfo for the new type. Use the location of |
4078 | // the '= default' as the location of the new type. |
4079 | // |
4080 | // FIXME: Set the correct return type when we initially transform the type, |
4081 | // rather than delaying it to now. |
4082 | TypeSourceInfo *NewTInfo = |
4083 | SemaRef.Context.getTrivialTypeSourceInfo(T, Loc: Orig->getEndLoc()); |
4084 | auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>(); |
4085 | assert(OldLoc && "type of function is not a function type?" ); |
4086 | auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>(); |
4087 | for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I) |
4088 | NewLoc.setParam(I, OldLoc.getParam(I)); |
4089 | TInfo = NewTInfo; |
4090 | |
4091 | // and the declarator-id is replaced with operator== |
4092 | NameInfo.setName( |
4093 | SemaRef.Context.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual)); |
4094 | } |
4095 | |
4096 | FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, |
4097 | FunctionDecl *Spaceship) { |
4098 | if (Spaceship->isInvalidDecl()) |
4099 | return nullptr; |
4100 | |
4101 | // C++2a [class.compare.default]p3: |
4102 | // an == operator function is declared implicitly [...] with the same |
4103 | // access and function-definition and in the same class scope as the |
4104 | // three-way comparison operator function |
4105 | MultiLevelTemplateArgumentList NoTemplateArgs; |
4106 | NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite); |
4107 | NoTemplateArgs.addOuterRetainedLevels(Num: RD->getTemplateDepth()); |
4108 | TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs); |
4109 | Decl *R; |
4110 | if (auto *MD = dyn_cast<CXXMethodDecl>(Val: Spaceship)) { |
4111 | R = Instantiator.VisitCXXMethodDecl( |
4112 | D: MD, /*TemplateParams=*/nullptr, |
4113 | FunctionRewriteKind: TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual); |
4114 | } else { |
4115 | assert(Spaceship->getFriendObjectKind() && |
4116 | "defaulted spaceship is neither a member nor a friend" ); |
4117 | |
4118 | R = Instantiator.VisitFunctionDecl( |
4119 | D: Spaceship, /*TemplateParams=*/nullptr, |
4120 | FunctionRewriteKind: TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual); |
4121 | if (!R) |
4122 | return nullptr; |
4123 | |
4124 | FriendDecl *FD = |
4125 | FriendDecl::Create(C&: Context, DC: RD, L: Spaceship->getLocation(), |
4126 | Friend_: cast<NamedDecl>(Val: R), FriendL: Spaceship->getBeginLoc()); |
4127 | FD->setAccess(AS_public); |
4128 | RD->addDecl(FD); |
4129 | } |
4130 | return cast_or_null<FunctionDecl>(Val: R); |
4131 | } |
4132 | |
4133 | /// Instantiates a nested template parameter list in the current |
4134 | /// instantiation context. |
4135 | /// |
4136 | /// \param L The parameter list to instantiate |
4137 | /// |
4138 | /// \returns NULL if there was an error |
4139 | TemplateParameterList * |
4140 | TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) { |
4141 | // Get errors for all the parameters before bailing out. |
4142 | bool Invalid = false; |
4143 | |
4144 | unsigned N = L->size(); |
4145 | typedef SmallVector<NamedDecl *, 8> ParamVector; |
4146 | ParamVector Params; |
4147 | Params.reserve(N); |
4148 | for (auto &P : *L) { |
4149 | NamedDecl *D = cast_or_null<NamedDecl>(Visit(P)); |
4150 | Params.push_back(Elt: D); |
4151 | Invalid = Invalid || !D || D->isInvalidDecl(); |
4152 | } |
4153 | |
4154 | // Clean up if we had an error. |
4155 | if (Invalid) |
4156 | return nullptr; |
4157 | |
4158 | Expr *InstRequiresClause = L->getRequiresClause(); |
4159 | |
4160 | TemplateParameterList *InstL |
4161 | = TemplateParameterList::Create(C: SemaRef.Context, TemplateLoc: L->getTemplateLoc(), |
4162 | LAngleLoc: L->getLAngleLoc(), Params, |
4163 | RAngleLoc: L->getRAngleLoc(), RequiresClause: InstRequiresClause); |
4164 | return InstL; |
4165 | } |
4166 | |
4167 | TemplateParameterList * |
4168 | Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, |
4169 | const MultiLevelTemplateArgumentList &TemplateArgs, |
4170 | bool EvaluateConstraints) { |
4171 | TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs); |
4172 | Instantiator.setEvaluateConstraints(EvaluateConstraints); |
4173 | return Instantiator.SubstTemplateParams(L: Params); |
4174 | } |
4175 | |
4176 | /// Instantiate the declaration of a class template partial |
4177 | /// specialization. |
4178 | /// |
4179 | /// \param ClassTemplate the (instantiated) class template that is partially |
4180 | // specialized by the instantiation of \p PartialSpec. |
4181 | /// |
4182 | /// \param PartialSpec the (uninstantiated) class template partial |
4183 | /// specialization that we are instantiating. |
4184 | /// |
4185 | /// \returns The instantiated partial specialization, if successful; otherwise, |
4186 | /// NULL to indicate an error. |
4187 | ClassTemplatePartialSpecializationDecl * |
4188 | TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization( |
4189 | ClassTemplateDecl *ClassTemplate, |
4190 | ClassTemplatePartialSpecializationDecl *PartialSpec) { |
4191 | // Create a local instantiation scope for this class template partial |
4192 | // specialization, which will contain the instantiations of the template |
4193 | // parameters. |
4194 | LocalInstantiationScope Scope(SemaRef); |
4195 | |
4196 | // Substitute into the template parameters of the class template partial |
4197 | // specialization. |
4198 | TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); |
4199 | TemplateParameterList *InstParams = SubstTemplateParams(L: TempParams); |
4200 | if (!InstParams) |
4201 | return nullptr; |
4202 | |
4203 | // Substitute into the template arguments of the class template partial |
4204 | // specialization. |
4205 | const ASTTemplateArgumentListInfo *TemplArgInfo |
4206 | = PartialSpec->getTemplateArgsAsWritten(); |
4207 | TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, |
4208 | TemplArgInfo->RAngleLoc); |
4209 | if (SemaRef.SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs, |
4210 | Outputs&: InstTemplateArgs)) |
4211 | return nullptr; |
4212 | |
4213 | // Check that the template argument list is well-formed for this |
4214 | // class template. |
4215 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4216 | if (SemaRef.CheckTemplateArgumentList( |
4217 | Template: ClassTemplate, TemplateLoc: PartialSpec->getLocation(), TemplateArgs&: InstTemplateArgs, |
4218 | /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted)) |
4219 | return nullptr; |
4220 | |
4221 | // Check these arguments are valid for a template partial specialization. |
4222 | if (SemaRef.CheckTemplatePartialSpecializationArgs( |
4223 | Loc: PartialSpec->getLocation(), PrimaryTemplate: ClassTemplate, NumExplicitArgs: InstTemplateArgs.size(), |
4224 | Args: CanonicalConverted)) |
4225 | return nullptr; |
4226 | |
4227 | // Figure out where to insert this class template partial specialization |
4228 | // in the member template's set of class template partial specializations. |
4229 | void *InsertPos = nullptr; |
4230 | ClassTemplateSpecializationDecl *PrevDecl = |
4231 | ClassTemplate->findPartialSpecialization(Args: CanonicalConverted, TPL: InstParams, |
4232 | InsertPos); |
4233 | |
4234 | // Build the canonical type that describes the converted template |
4235 | // arguments of the class template partial specialization. |
4236 | QualType CanonType = SemaRef.Context.getTemplateSpecializationType( |
4237 | T: TemplateName(ClassTemplate), Args: CanonicalConverted); |
4238 | |
4239 | // Build the fully-sugared type for this class template |
4240 | // specialization as the user wrote in the specialization |
4241 | // itself. This means that we'll pretty-print the type retrieved |
4242 | // from the specialization's declaration the way that the user |
4243 | // actually wrote the specialization, rather than formatting the |
4244 | // name based on the "canonical" representation used to store the |
4245 | // template arguments in the specialization. |
4246 | TypeSourceInfo *WrittenTy |
4247 | = SemaRef.Context.getTemplateSpecializationTypeInfo( |
4248 | T: TemplateName(ClassTemplate), |
4249 | TLoc: PartialSpec->getLocation(), |
4250 | Args: InstTemplateArgs, |
4251 | Canon: CanonType); |
4252 | |
4253 | if (PrevDecl) { |
4254 | // We've already seen a partial specialization with the same template |
4255 | // parameters and template arguments. This can happen, for example, when |
4256 | // substituting the outer template arguments ends up causing two |
4257 | // class template partial specializations of a member class template |
4258 | // to have identical forms, e.g., |
4259 | // |
4260 | // template<typename T, typename U> |
4261 | // struct Outer { |
4262 | // template<typename X, typename Y> struct Inner; |
4263 | // template<typename Y> struct Inner<T, Y>; |
4264 | // template<typename Y> struct Inner<U, Y>; |
4265 | // }; |
4266 | // |
4267 | // Outer<int, int> outer; // error: the partial specializations of Inner |
4268 | // // have the same signature. |
4269 | SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared) |
4270 | << WrittenTy->getType(); |
4271 | SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here) |
4272 | << SemaRef.Context.getTypeDeclType(PrevDecl); |
4273 | return nullptr; |
4274 | } |
4275 | |
4276 | |
4277 | // Create the class template partial specialization declaration. |
4278 | ClassTemplatePartialSpecializationDecl *InstPartialSpec = |
4279 | ClassTemplatePartialSpecializationDecl::Create( |
4280 | Context&: SemaRef.Context, TK: PartialSpec->getTagKind(), DC: Owner, |
4281 | StartLoc: PartialSpec->getBeginLoc(), IdLoc: PartialSpec->getLocation(), Params: InstParams, |
4282 | SpecializedTemplate: ClassTemplate, Args: CanonicalConverted, ArgInfos: InstTemplateArgs, CanonInjectedType: CanonType, |
4283 | PrevDecl: nullptr); |
4284 | // Substitute the nested name specifier, if any. |
4285 | if (SubstQualifier(PartialSpec, InstPartialSpec)) |
4286 | return nullptr; |
4287 | |
4288 | InstPartialSpec->setInstantiatedFromMember(PartialSpec); |
4289 | InstPartialSpec->setTypeAsWritten(WrittenTy); |
4290 | |
4291 | // Check the completed partial specialization. |
4292 | SemaRef.CheckTemplatePartialSpecialization(Partial: InstPartialSpec); |
4293 | |
4294 | // Add this partial specialization to the set of class template partial |
4295 | // specializations. |
4296 | ClassTemplate->AddPartialSpecialization(D: InstPartialSpec, |
4297 | /*InsertPos=*/nullptr); |
4298 | return InstPartialSpec; |
4299 | } |
4300 | |
4301 | /// Instantiate the declaration of a variable template partial |
4302 | /// specialization. |
4303 | /// |
4304 | /// \param VarTemplate the (instantiated) variable template that is partially |
4305 | /// specialized by the instantiation of \p PartialSpec. |
4306 | /// |
4307 | /// \param PartialSpec the (uninstantiated) variable template partial |
4308 | /// specialization that we are instantiating. |
4309 | /// |
4310 | /// \returns The instantiated partial specialization, if successful; otherwise, |
4311 | /// NULL to indicate an error. |
4312 | VarTemplatePartialSpecializationDecl * |
4313 | TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization( |
4314 | VarTemplateDecl *VarTemplate, |
4315 | VarTemplatePartialSpecializationDecl *PartialSpec) { |
4316 | // Create a local instantiation scope for this variable template partial |
4317 | // specialization, which will contain the instantiations of the template |
4318 | // parameters. |
4319 | LocalInstantiationScope Scope(SemaRef); |
4320 | |
4321 | // Substitute into the template parameters of the variable template partial |
4322 | // specialization. |
4323 | TemplateParameterList *TempParams = PartialSpec->getTemplateParameters(); |
4324 | TemplateParameterList *InstParams = SubstTemplateParams(L: TempParams); |
4325 | if (!InstParams) |
4326 | return nullptr; |
4327 | |
4328 | // Substitute into the template arguments of the variable template partial |
4329 | // specialization. |
4330 | const ASTTemplateArgumentListInfo *TemplArgInfo |
4331 | = PartialSpec->getTemplateArgsAsWritten(); |
4332 | TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc, |
4333 | TemplArgInfo->RAngleLoc); |
4334 | if (SemaRef.SubstTemplateArguments(Args: TemplArgInfo->arguments(), TemplateArgs, |
4335 | Outputs&: InstTemplateArgs)) |
4336 | return nullptr; |
4337 | |
4338 | // Check that the template argument list is well-formed for this |
4339 | // class template. |
4340 | SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted; |
4341 | if (SemaRef.CheckTemplateArgumentList( |
4342 | Template: VarTemplate, TemplateLoc: PartialSpec->getLocation(), TemplateArgs&: InstTemplateArgs, |
4343 | /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted)) |
4344 | return nullptr; |
4345 | |
4346 | // Check these arguments are valid for a template partial specialization. |
4347 | if (SemaRef.CheckTemplatePartialSpecializationArgs( |
4348 | Loc: PartialSpec->getLocation(), PrimaryTemplate: VarTemplate, NumExplicitArgs: InstTemplateArgs.size(), |
4349 | Args: CanonicalConverted)) |
4350 | return nullptr; |
4351 | |
4352 | // Figure out where to insert this variable template partial specialization |
4353 | // in the member template's set of variable template partial specializations. |
4354 | void *InsertPos = nullptr; |
4355 | VarTemplateSpecializationDecl *PrevDecl = |
4356 | VarTemplate->findPartialSpecialization(Args: CanonicalConverted, TPL: InstParams, |
4357 | InsertPos); |
4358 | |
4359 | // Build the canonical type that describes the converted template |
4360 | // arguments of the variable template partial specialization. |
4361 | QualType CanonType = SemaRef.Context.getTemplateSpecializationType( |
4362 | T: TemplateName(VarTemplate), Args: CanonicalConverted); |
4363 | |
4364 | // Build the fully-sugared type for this variable template |
4365 | // specialization as the user wrote in the specialization |
4366 | // itself. This means that we'll pretty-print the type retrieved |
4367 | // from the specialization's declaration the way that the user |
4368 | // actually wrote the specialization, rather than formatting the |
4369 | // name based on the "canonical" representation used to store the |
4370 | // template arguments in the specialization. |
4371 | TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo( |
4372 | T: TemplateName(VarTemplate), TLoc: PartialSpec->getLocation(), Args: InstTemplateArgs, |
4373 | Canon: CanonType); |
4374 | |
4375 | if (PrevDecl) { |
4376 | // We've already seen a partial specialization with the same template |
4377 | // parameters and template arguments. This can happen, for example, when |
4378 | // substituting the outer template arguments ends up causing two |
4379 | // variable template partial specializations of a member variable template |
4380 | // to have identical forms, e.g., |
4381 | // |
4382 | // template<typename T, typename U> |
4383 | // struct Outer { |
4384 | // template<typename X, typename Y> pair<X,Y> p; |
4385 | // template<typename Y> pair<T, Y> p; |
4386 | // template<typename Y> pair<U, Y> p; |
4387 | // }; |
4388 | // |
4389 | // Outer<int, int> outer; // error: the partial specializations of Inner |
4390 | // // have the same signature. |
4391 | SemaRef.Diag(PartialSpec->getLocation(), |
4392 | diag::err_var_partial_spec_redeclared) |
4393 | << WrittenTy->getType(); |
4394 | SemaRef.Diag(PrevDecl->getLocation(), |
4395 | diag::note_var_prev_partial_spec_here); |
4396 | return nullptr; |
4397 | } |
4398 | |
4399 | // Do substitution on the type of the declaration |
4400 | TypeSourceInfo *DI = SemaRef.SubstType( |
4401 | PartialSpec->getTypeSourceInfo(), TemplateArgs, |
4402 | PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName()); |
4403 | if (!DI) |
4404 | return nullptr; |
4405 | |
4406 | if (DI->getType()->isFunctionType()) { |
4407 | SemaRef.Diag(PartialSpec->getLocation(), |
4408 | diag::err_variable_instantiates_to_function) |
4409 | << PartialSpec->isStaticDataMember() << DI->getType(); |
4410 | return nullptr; |
4411 | } |
4412 | |
4413 | // Create the variable template partial specialization declaration. |
4414 | VarTemplatePartialSpecializationDecl *InstPartialSpec = |
4415 | VarTemplatePartialSpecializationDecl::Create( |
4416 | Context&: SemaRef.Context, DC: Owner, StartLoc: PartialSpec->getInnerLocStart(), |
4417 | IdLoc: PartialSpec->getLocation(), Params: InstParams, SpecializedTemplate: VarTemplate, T: DI->getType(), |
4418 | TInfo: DI, S: PartialSpec->getStorageClass(), Args: CanonicalConverted, |
4419 | ArgInfos: InstTemplateArgs); |
4420 | |
4421 | // Substitute the nested name specifier, if any. |
4422 | if (SubstQualifier(PartialSpec, InstPartialSpec)) |
4423 | return nullptr; |
4424 | |
4425 | InstPartialSpec->setInstantiatedFromMember(PartialSpec); |
4426 | InstPartialSpec->setTypeAsWritten(WrittenTy); |
4427 | |
4428 | // Check the completed partial specialization. |
4429 | SemaRef.CheckTemplatePartialSpecialization(Partial: InstPartialSpec); |
4430 | |
4431 | // Add this partial specialization to the set of variable template partial |
4432 | // specializations. The instantiation of the initializer is not necessary. |
4433 | VarTemplate->AddPartialSpecialization(D: InstPartialSpec, /*InsertPos=*/nullptr); |
4434 | |
4435 | SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs, |
4436 | LateAttrs, Owner, StartingScope); |
4437 | |
4438 | return InstPartialSpec; |
4439 | } |
4440 | |
4441 | TypeSourceInfo* |
4442 | TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D, |
4443 | SmallVectorImpl<ParmVarDecl *> &Params) { |
4444 | TypeSourceInfo *OldTInfo = D->getTypeSourceInfo(); |
4445 | assert(OldTInfo && "substituting function without type source info" ); |
4446 | assert(Params.empty() && "parameter vector is non-empty at start" ); |
4447 | |
4448 | CXXRecordDecl *ThisContext = nullptr; |
4449 | Qualifiers ThisTypeQuals; |
4450 | if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D)) { |
4451 | ThisContext = cast<CXXRecordDecl>(Val: Owner); |
4452 | ThisTypeQuals = Method->getFunctionObjectParameterType().getQualifiers(); |
4453 | } |
4454 | |
4455 | TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType( |
4456 | T: OldTInfo, TemplateArgs, Loc: D->getTypeSpecStartLoc(), Entity: D->getDeclName(), |
4457 | ThisContext, ThisTypeQuals, EvaluateConstraints); |
4458 | if (!NewTInfo) |
4459 | return nullptr; |
4460 | |
4461 | TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens(); |
4462 | if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) { |
4463 | if (NewTInfo != OldTInfo) { |
4464 | // Get parameters from the new type info. |
4465 | TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens(); |
4466 | FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>(); |
4467 | unsigned NewIdx = 0; |
4468 | for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams(); |
4469 | OldIdx != NumOldParams; ++OldIdx) { |
4470 | ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx); |
4471 | if (!OldParam) |
4472 | return nullptr; |
4473 | |
4474 | LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope; |
4475 | |
4476 | std::optional<unsigned> NumArgumentsInExpansion; |
4477 | if (OldParam->isParameterPack()) |
4478 | NumArgumentsInExpansion = |
4479 | SemaRef.getNumArgumentsInExpansion(T: OldParam->getType(), |
4480 | TemplateArgs); |
4481 | if (!NumArgumentsInExpansion) { |
4482 | // Simple case: normal parameter, or a parameter pack that's |
4483 | // instantiated to a (still-dependent) parameter pack. |
4484 | ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); |
4485 | Params.push_back(Elt: NewParam); |
4486 | Scope->InstantiatedLocal(OldParam, NewParam); |
4487 | } else { |
4488 | // Parameter pack expansion: make the instantiation an argument pack. |
4489 | Scope->MakeInstantiatedLocalArgPack(OldParam); |
4490 | for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) { |
4491 | ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++); |
4492 | Params.push_back(Elt: NewParam); |
4493 | Scope->InstantiatedLocalPackArg(OldParam, NewParam); |
4494 | } |
4495 | } |
4496 | } |
4497 | } else { |
4498 | // The function type itself was not dependent and therefore no |
4499 | // substitution occurred. However, we still need to instantiate |
4500 | // the function parameters themselves. |
4501 | const FunctionProtoType *OldProto = |
4502 | cast<FunctionProtoType>(OldProtoLoc.getType()); |
4503 | for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end; |
4504 | ++i) { |
4505 | ParmVarDecl *OldParam = OldProtoLoc.getParam(i); |
4506 | if (!OldParam) { |
4507 | Params.push_back(Elt: SemaRef.BuildParmVarDeclForTypedef( |
4508 | DC: D, Loc: D->getLocation(), T: OldProto->getParamType(i))); |
4509 | continue; |
4510 | } |
4511 | |
4512 | ParmVarDecl *Parm = |
4513 | cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam)); |
4514 | if (!Parm) |
4515 | return nullptr; |
4516 | Params.push_back(Elt: Parm); |
4517 | } |
4518 | } |
4519 | } else { |
4520 | // If the type of this function, after ignoring parentheses, is not |
4521 | // *directly* a function type, then we're instantiating a function that |
4522 | // was declared via a typedef or with attributes, e.g., |
4523 | // |
4524 | // typedef int functype(int, int); |
4525 | // functype func; |
4526 | // int __cdecl meth(int, int); |
4527 | // |
4528 | // In this case, we'll just go instantiate the ParmVarDecls that we |
4529 | // synthesized in the method declaration. |
4530 | SmallVector<QualType, 4> ParamTypes; |
4531 | Sema::ExtParameterInfoBuilder ExtParamInfos; |
4532 | if (SemaRef.SubstParmTypes(Loc: D->getLocation(), Params: D->parameters(), ExtParamInfos: nullptr, |
4533 | TemplateArgs, ParamTypes, OutParams: &Params, |
4534 | ParamInfos&: ExtParamInfos)) |
4535 | return nullptr; |
4536 | } |
4537 | |
4538 | return NewTInfo; |
4539 | } |
4540 | |
4541 | /// Introduce the instantiated local variables into the local |
4542 | /// instantiation scope. |
4543 | void Sema::addInstantiatedLocalVarsToScope(FunctionDecl *Function, |
4544 | const FunctionDecl *PatternDecl, |
4545 | LocalInstantiationScope &Scope) { |
4546 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: getFunctionScopes().back()); |
4547 | |
4548 | for (auto *decl : PatternDecl->decls()) { |
4549 | if (!isa<VarDecl>(decl) || isa<ParmVarDecl>(decl)) |
4550 | continue; |
4551 | |
4552 | VarDecl *VD = cast<VarDecl>(decl); |
4553 | IdentifierInfo *II = VD->getIdentifier(); |
4554 | |
4555 | auto it = llvm::find_if(Function->decls(), [&](Decl *inst) { |
4556 | VarDecl *InstVD = dyn_cast<VarDecl>(inst); |
4557 | return InstVD && InstVD->isLocalVarDecl() && |
4558 | InstVD->getIdentifier() == II; |
4559 | }); |
4560 | |
4561 | if (it == Function->decls().end()) |
4562 | continue; |
4563 | |
4564 | Scope.InstantiatedLocal(VD, *it); |
4565 | LSI->addCapture(cast<VarDecl>(*it), /*isBlock=*/false, /*isByref=*/false, |
4566 | /*isNested=*/false, VD->getLocation(), SourceLocation(), |
4567 | VD->getType(), /*Invalid=*/false); |
4568 | } |
4569 | } |
4570 | |
4571 | /// Introduce the instantiated function parameters into the local |
4572 | /// instantiation scope, and set the parameter names to those used |
4573 | /// in the template. |
4574 | bool Sema::addInstantiatedParametersToScope( |
4575 | FunctionDecl *Function, const FunctionDecl *PatternDecl, |
4576 | LocalInstantiationScope &Scope, |
4577 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
4578 | unsigned FParamIdx = 0; |
4579 | for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) { |
4580 | const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(i: I); |
4581 | if (!PatternParam->isParameterPack()) { |
4582 | // Simple case: not a parameter pack. |
4583 | assert(FParamIdx < Function->getNumParams()); |
4584 | ParmVarDecl *FunctionParam = Function->getParamDecl(i: FParamIdx); |
4585 | FunctionParam->setDeclName(PatternParam->getDeclName()); |
4586 | // If the parameter's type is not dependent, update it to match the type |
4587 | // in the pattern. They can differ in top-level cv-qualifiers, and we want |
4588 | // the pattern's type here. If the type is dependent, they can't differ, |
4589 | // per core issue 1668. Substitute into the type from the pattern, in case |
4590 | // it's instantiation-dependent. |
4591 | // FIXME: Updating the type to work around this is at best fragile. |
4592 | if (!PatternDecl->getType()->isDependentType()) { |
4593 | QualType T = SubstType(PatternParam->getType(), TemplateArgs, |
4594 | FunctionParam->getLocation(), |
4595 | FunctionParam->getDeclName()); |
4596 | if (T.isNull()) |
4597 | return true; |
4598 | FunctionParam->setType(T); |
4599 | } |
4600 | |
4601 | Scope.InstantiatedLocal(PatternParam, FunctionParam); |
4602 | ++FParamIdx; |
4603 | continue; |
4604 | } |
4605 | |
4606 | // Expand the parameter pack. |
4607 | Scope.MakeInstantiatedLocalArgPack(PatternParam); |
4608 | std::optional<unsigned> NumArgumentsInExpansion = |
4609 | getNumArgumentsInExpansion(T: PatternParam->getType(), TemplateArgs); |
4610 | if (NumArgumentsInExpansion) { |
4611 | QualType PatternType = |
4612 | PatternParam->getType()->castAs<PackExpansionType>()->getPattern(); |
4613 | for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) { |
4614 | ParmVarDecl *FunctionParam = Function->getParamDecl(i: FParamIdx); |
4615 | FunctionParam->setDeclName(PatternParam->getDeclName()); |
4616 | if (!PatternDecl->getType()->isDependentType()) { |
4617 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg); |
4618 | QualType T = |
4619 | SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(), |
4620 | FunctionParam->getDeclName()); |
4621 | if (T.isNull()) |
4622 | return true; |
4623 | FunctionParam->setType(T); |
4624 | } |
4625 | |
4626 | Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam); |
4627 | ++FParamIdx; |
4628 | } |
4629 | } |
4630 | } |
4631 | |
4632 | return false; |
4633 | } |
4634 | |
4635 | bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, |
4636 | ParmVarDecl *Param) { |
4637 | assert(Param->hasUninstantiatedDefaultArg()); |
4638 | |
4639 | // Instantiate the expression. |
4640 | // |
4641 | // FIXME: Pass in a correct Pattern argument, otherwise |
4642 | // getTemplateInstantiationArgs uses the lexical context of FD, e.g. |
4643 | // |
4644 | // template<typename T> |
4645 | // struct A { |
4646 | // static int FooImpl(); |
4647 | // |
4648 | // template<typename Tp> |
4649 | // // bug: default argument A<T>::FooImpl() is evaluated with 2-level |
4650 | // // template argument list [[T], [Tp]], should be [[Tp]]. |
4651 | // friend A<Tp> Foo(int a); |
4652 | // }; |
4653 | // |
4654 | // template<typename T> |
4655 | // A<T> Foo(int a = A<T>::FooImpl()); |
4656 | MultiLevelTemplateArgumentList TemplateArgs = |
4657 | getTemplateInstantiationArgs(D: FD, DC: FD->getLexicalDeclContext(), |
4658 | /*Final=*/false, /*Innermost=*/std::nullopt, |
4659 | /*RelativeToPrimary=*/true); |
4660 | |
4661 | if (SubstDefaultArgument(Loc: CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true)) |
4662 | return true; |
4663 | |
4664 | if (ASTMutationListener *L = getASTMutationListener()) |
4665 | L->DefaultArgumentInstantiated(D: Param); |
4666 | |
4667 | return false; |
4668 | } |
4669 | |
4670 | void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation, |
4671 | FunctionDecl *Decl) { |
4672 | const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>(); |
4673 | if (Proto->getExceptionSpecType() != EST_Uninstantiated) |
4674 | return; |
4675 | |
4676 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl, |
4677 | InstantiatingTemplate::ExceptionSpecification()); |
4678 | if (Inst.isInvalid()) { |
4679 | // We hit the instantiation depth limit. Clear the exception specification |
4680 | // so that our callers don't have to cope with EST_Uninstantiated. |
4681 | UpdateExceptionSpec(FD: Decl, ESI: EST_None); |
4682 | return; |
4683 | } |
4684 | if (Inst.isAlreadyInstantiating()) { |
4685 | // This exception specification indirectly depends on itself. Reject. |
4686 | // FIXME: Corresponding rule in the standard? |
4687 | Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl; |
4688 | UpdateExceptionSpec(FD: Decl, ESI: EST_None); |
4689 | return; |
4690 | } |
4691 | |
4692 | // Enter the scope of this instantiation. We don't use |
4693 | // PushDeclContext because we don't have a scope. |
4694 | Sema::ContextRAII savedContext(*this, Decl); |
4695 | LocalInstantiationScope Scope(*this); |
4696 | |
4697 | MultiLevelTemplateArgumentList TemplateArgs = |
4698 | getTemplateInstantiationArgs(D: Decl, DC: Decl->getLexicalDeclContext(), |
4699 | /*Final=*/false, /*Innermost=*/std::nullopt, |
4700 | /*RelativeToPrimary*/ true); |
4701 | |
4702 | // FIXME: We can't use getTemplateInstantiationPattern(false) in general |
4703 | // here, because for a non-defining friend declaration in a class template, |
4704 | // we don't store enough information to map back to the friend declaration in |
4705 | // the template. |
4706 | FunctionDecl *Template = Proto->getExceptionSpecTemplate(); |
4707 | if (addInstantiatedParametersToScope(Function: Decl, PatternDecl: Template, Scope, TemplateArgs)) { |
4708 | UpdateExceptionSpec(FD: Decl, ESI: EST_None); |
4709 | return; |
4710 | } |
4711 | |
4712 | SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(), |
4713 | TemplateArgs); |
4714 | } |
4715 | |
4716 | /// Initializes the common fields of an instantiation function |
4717 | /// declaration (New) from the corresponding fields of its template (Tmpl). |
4718 | /// |
4719 | /// \returns true if there was an error |
4720 | bool |
4721 | TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New, |
4722 | FunctionDecl *Tmpl) { |
4723 | New->setImplicit(Tmpl->isImplicit()); |
4724 | |
4725 | // Forward the mangling number from the template to the instantiated decl. |
4726 | SemaRef.Context.setManglingNumber(New, |
4727 | SemaRef.Context.getManglingNumber(Tmpl)); |
4728 | |
4729 | // If we are performing substituting explicitly-specified template arguments |
4730 | // or deduced template arguments into a function template and we reach this |
4731 | // point, we are now past the point where SFINAE applies and have committed |
4732 | // to keeping the new function template specialization. We therefore |
4733 | // convert the active template instantiation for the function template |
4734 | // into a template instantiation for this specific function template |
4735 | // specialization, which is not a SFINAE context, so that we diagnose any |
4736 | // further errors in the declaration itself. |
4737 | // |
4738 | // FIXME: This is a hack. |
4739 | typedef Sema::CodeSynthesisContext ActiveInstType; |
4740 | ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back(); |
4741 | if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution || |
4742 | ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) { |
4743 | if (isa<FunctionTemplateDecl>(Val: ActiveInst.Entity)) { |
4744 | SemaRef.InstantiatingSpecializations.erase( |
4745 | V: {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind}); |
4746 | atTemplateEnd(Callbacks&: SemaRef.TemplateInstCallbacks, TheSema: SemaRef, Inst: ActiveInst); |
4747 | ActiveInst.Kind = ActiveInstType::TemplateInstantiation; |
4748 | ActiveInst.Entity = New; |
4749 | atTemplateBegin(Callbacks&: SemaRef.TemplateInstCallbacks, TheSema: SemaRef, Inst: ActiveInst); |
4750 | } |
4751 | } |
4752 | |
4753 | const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>(); |
4754 | assert(Proto && "Function template without prototype?" ); |
4755 | |
4756 | if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) { |
4757 | FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo(); |
4758 | |
4759 | // DR1330: In C++11, defer instantiation of a non-trivial |
4760 | // exception specification. |
4761 | // DR1484: Local classes and their members are instantiated along with the |
4762 | // containing function. |
4763 | if (SemaRef.getLangOpts().CPlusPlus11 && |
4764 | EPI.ExceptionSpec.Type != EST_None && |
4765 | EPI.ExceptionSpec.Type != EST_DynamicNone && |
4766 | EPI.ExceptionSpec.Type != EST_BasicNoexcept && |
4767 | !Tmpl->isInLocalScopeForInstantiation()) { |
4768 | FunctionDecl *ExceptionSpecTemplate = Tmpl; |
4769 | if (EPI.ExceptionSpec.Type == EST_Uninstantiated) |
4770 | ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate; |
4771 | ExceptionSpecificationType NewEST = EST_Uninstantiated; |
4772 | if (EPI.ExceptionSpec.Type == EST_Unevaluated) |
4773 | NewEST = EST_Unevaluated; |
4774 | |
4775 | // Mark the function has having an uninstantiated exception specification. |
4776 | const FunctionProtoType *NewProto |
4777 | = New->getType()->getAs<FunctionProtoType>(); |
4778 | assert(NewProto && "Template instantiation without function prototype?" ); |
4779 | EPI = NewProto->getExtProtoInfo(); |
4780 | EPI.ExceptionSpec.Type = NewEST; |
4781 | EPI.ExceptionSpec.SourceDecl = New; |
4782 | EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate; |
4783 | New->setType(SemaRef.Context.getFunctionType( |
4784 | ResultTy: NewProto->getReturnType(), Args: NewProto->getParamTypes(), EPI)); |
4785 | } else { |
4786 | Sema::ContextRAII SwitchContext(SemaRef, New); |
4787 | SemaRef.SubstExceptionSpec(New, Proto, Args: TemplateArgs); |
4788 | } |
4789 | } |
4790 | |
4791 | // Get the definition. Leaves the variable unchanged if undefined. |
4792 | const FunctionDecl *Definition = Tmpl; |
4793 | Tmpl->isDefined(Definition); |
4794 | |
4795 | SemaRef.InstantiateAttrs(TemplateArgs, Definition, New, |
4796 | LateAttrs, StartingScope); |
4797 | |
4798 | return false; |
4799 | } |
4800 | |
4801 | /// Initializes common fields of an instantiated method |
4802 | /// declaration (New) from the corresponding fields of its template |
4803 | /// (Tmpl). |
4804 | /// |
4805 | /// \returns true if there was an error |
4806 | bool |
4807 | TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New, |
4808 | CXXMethodDecl *Tmpl) { |
4809 | if (InitFunctionInstantiation(New, Tmpl)) |
4810 | return true; |
4811 | |
4812 | if (isa<CXXDestructorDecl>(Val: New) && SemaRef.getLangOpts().CPlusPlus11) |
4813 | SemaRef.AdjustDestructorExceptionSpec(Destructor: cast<CXXDestructorDecl>(Val: New)); |
4814 | |
4815 | New->setAccess(Tmpl->getAccess()); |
4816 | if (Tmpl->isVirtualAsWritten()) |
4817 | New->setVirtualAsWritten(true); |
4818 | |
4819 | // FIXME: New needs a pointer to Tmpl |
4820 | return false; |
4821 | } |
4822 | |
4823 | bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New, |
4824 | FunctionDecl *Tmpl) { |
4825 | // Transfer across any unqualified lookups. |
4826 | if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) { |
4827 | SmallVector<DeclAccessPair, 32> Lookups; |
4828 | Lookups.reserve(N: DFI->getUnqualifiedLookups().size()); |
4829 | bool AnyChanged = false; |
4830 | for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) { |
4831 | NamedDecl *D = SemaRef.FindInstantiatedDecl(Loc: New->getLocation(), |
4832 | D: DA.getDecl(), TemplateArgs); |
4833 | if (!D) |
4834 | return true; |
4835 | AnyChanged |= (D != DA.getDecl()); |
4836 | Lookups.push_back(Elt: DeclAccessPair::make(D, AS: DA.getAccess())); |
4837 | } |
4838 | |
4839 | // It's unlikely that substitution will change any declarations. Don't |
4840 | // store an unnecessary copy in that case. |
4841 | New->setDefaultedFunctionInfo( |
4842 | AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create( |
4843 | Context&: SemaRef.Context, Lookups) |
4844 | : DFI); |
4845 | } |
4846 | |
4847 | SemaRef.SetDeclDefaulted(dcl: New, DefaultLoc: Tmpl->getLocation()); |
4848 | return false; |
4849 | } |
4850 | |
4851 | /// Instantiate (or find existing instantiation of) a function template with a |
4852 | /// given set of template arguments. |
4853 | /// |
4854 | /// Usually this should not be used, and template argument deduction should be |
4855 | /// used in its place. |
4856 | FunctionDecl * |
4857 | Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, |
4858 | const TemplateArgumentList *Args, |
4859 | SourceLocation Loc) { |
4860 | FunctionDecl *FD = FTD->getTemplatedDecl(); |
4861 | |
4862 | sema::TemplateDeductionInfo Info(Loc); |
4863 | InstantiatingTemplate Inst( |
4864 | *this, Loc, FTD, Args->asArray(), |
4865 | CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info); |
4866 | if (Inst.isInvalid()) |
4867 | return nullptr; |
4868 | |
4869 | ContextRAII SavedContext(*this, FD); |
4870 | MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(), |
4871 | /*Final=*/false); |
4872 | |
4873 | return cast_or_null<FunctionDecl>(SubstDecl(D: FD, Owner: FD->getParent(), TemplateArgs: MArgs)); |
4874 | } |
4875 | |
4876 | /// Instantiate the definition of the given function from its |
4877 | /// template. |
4878 | /// |
4879 | /// \param PointOfInstantiation the point at which the instantiation was |
4880 | /// required. Note that this is not precisely a "point of instantiation" |
4881 | /// for the function, but it's close. |
4882 | /// |
4883 | /// \param Function the already-instantiated declaration of a |
4884 | /// function template specialization or member function of a class template |
4885 | /// specialization. |
4886 | /// |
4887 | /// \param Recursive if true, recursively instantiates any functions that |
4888 | /// are required by this instantiation. |
4889 | /// |
4890 | /// \param DefinitionRequired if true, then we are performing an explicit |
4891 | /// instantiation where the body of the function is required. Complain if |
4892 | /// there is no such body. |
4893 | void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, |
4894 | FunctionDecl *Function, |
4895 | bool Recursive, |
4896 | bool DefinitionRequired, |
4897 | bool AtEndOfTU) { |
4898 | if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Val: Function)) |
4899 | return; |
4900 | |
4901 | // Never instantiate an explicit specialization except if it is a class scope |
4902 | // explicit specialization. |
4903 | TemplateSpecializationKind TSK = |
4904 | Function->getTemplateSpecializationKindForInstantiation(); |
4905 | if (TSK == TSK_ExplicitSpecialization) |
4906 | return; |
4907 | |
4908 | // Never implicitly instantiate a builtin; we don't actually need a function |
4909 | // body. |
4910 | if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation && |
4911 | !DefinitionRequired) |
4912 | return; |
4913 | |
4914 | // Don't instantiate a definition if we already have one. |
4915 | const FunctionDecl *ExistingDefn = nullptr; |
4916 | if (Function->isDefined(Definition&: ExistingDefn, |
4917 | /*CheckForPendingFriendDefinition=*/true)) { |
4918 | if (ExistingDefn->isThisDeclarationADefinition()) |
4919 | return; |
4920 | |
4921 | // If we're asked to instantiate a function whose body comes from an |
4922 | // instantiated friend declaration, attach the instantiated body to the |
4923 | // corresponding declaration of the function. |
4924 | assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition()); |
4925 | Function = const_cast<FunctionDecl*>(ExistingDefn); |
4926 | } |
4927 | |
4928 | // Find the function body that we'll be substituting. |
4929 | const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern(); |
4930 | assert(PatternDecl && "instantiating a non-template" ); |
4931 | |
4932 | const FunctionDecl *PatternDef = PatternDecl->getDefinition(); |
4933 | Stmt *Pattern = nullptr; |
4934 | if (PatternDef) { |
4935 | Pattern = PatternDef->getBody(Definition&: PatternDef); |
4936 | PatternDecl = PatternDef; |
4937 | if (PatternDef->willHaveBody()) |
4938 | PatternDef = nullptr; |
4939 | } |
4940 | |
4941 | // FIXME: We need to track the instantiation stack in order to know which |
4942 | // definitions should be visible within this instantiation. |
4943 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function, |
4944 | Function->getInstantiatedFromMemberFunction(), |
4945 | PatternDecl, PatternDef, TSK, |
4946 | /*Complain*/DefinitionRequired)) { |
4947 | if (DefinitionRequired) |
4948 | Function->setInvalidDecl(); |
4949 | else if (TSK == TSK_ExplicitInstantiationDefinition || |
4950 | (Function->isConstexpr() && !Recursive)) { |
4951 | // Try again at the end of the translation unit (at which point a |
4952 | // definition will be required). |
4953 | assert(!Recursive); |
4954 | Function->setInstantiationIsPending(true); |
4955 | PendingInstantiations.push_back( |
4956 | std::make_pair(x&: Function, y&: PointOfInstantiation)); |
4957 | } else if (TSK == TSK_ImplicitInstantiation) { |
4958 | if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && |
4959 | !getSourceManager().isInSystemHeader(Loc: PatternDecl->getBeginLoc())) { |
4960 | Diag(PointOfInstantiation, diag::warn_func_template_missing) |
4961 | << Function; |
4962 | Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); |
4963 | if (getLangOpts().CPlusPlus11) |
4964 | Diag(PointOfInstantiation, diag::note_inst_declaration_hint) |
4965 | << Function; |
4966 | } |
4967 | } |
4968 | |
4969 | return; |
4970 | } |
4971 | |
4972 | // Postpone late parsed template instantiations. |
4973 | if (PatternDecl->isLateTemplateParsed() && |
4974 | !LateTemplateParser) { |
4975 | Function->setInstantiationIsPending(true); |
4976 | LateParsedInstantiations.push_back( |
4977 | std::make_pair(x&: Function, y&: PointOfInstantiation)); |
4978 | return; |
4979 | } |
4980 | |
4981 | llvm::TimeTraceScope TimeScope("InstantiateFunction" , [&]() { |
4982 | std::string Name; |
4983 | llvm::raw_string_ostream OS(Name); |
4984 | Function->getNameForDiagnostic(OS, Policy: getPrintingPolicy(), |
4985 | /*Qualified=*/true); |
4986 | return Name; |
4987 | }); |
4988 | |
4989 | // If we're performing recursive template instantiation, create our own |
4990 | // queue of pending implicit instantiations that we will instantiate later, |
4991 | // while we're still within our own instantiation context. |
4992 | // This has to happen before LateTemplateParser below is called, so that |
4993 | // it marks vtables used in late parsed templates as used. |
4994 | GlobalEagerInstantiationScope GlobalInstantiations(*this, |
4995 | /*Enabled=*/Recursive); |
4996 | LocalEagerInstantiationScope LocalInstantiations(*this); |
4997 | |
4998 | // Call the LateTemplateParser callback if there is a need to late parse |
4999 | // a templated function definition. |
5000 | if (!Pattern && PatternDecl->isLateTemplateParsed() && |
5001 | LateTemplateParser) { |
5002 | // FIXME: Optimize to allow individual templates to be deserialized. |
5003 | if (PatternDecl->isFromASTFile()) |
5004 | ExternalSource->ReadLateParsedTemplates(LPTMap&: LateParsedTemplateMap); |
5005 | |
5006 | auto LPTIter = LateParsedTemplateMap.find(Key: PatternDecl); |
5007 | assert(LPTIter != LateParsedTemplateMap.end() && |
5008 | "missing LateParsedTemplate" ); |
5009 | LateTemplateParser(OpaqueParser, *LPTIter->second); |
5010 | Pattern = PatternDecl->getBody(Definition&: PatternDecl); |
5011 | updateAttrsForLateParsedTemplate(PatternDecl, Function); |
5012 | } |
5013 | |
5014 | // Note, we should never try to instantiate a deleted function template. |
5015 | assert((Pattern || PatternDecl->isDefaulted() || |
5016 | PatternDecl->hasSkippedBody()) && |
5017 | "unexpected kind of function template definition" ); |
5018 | |
5019 | // C++1y [temp.explicit]p10: |
5020 | // Except for inline functions, declarations with types deduced from their |
5021 | // initializer or return value, and class template specializations, other |
5022 | // explicit instantiation declarations have the effect of suppressing the |
5023 | // implicit instantiation of the entity to which they refer. |
5024 | if (TSK == TSK_ExplicitInstantiationDeclaration && |
5025 | !PatternDecl->isInlined() && |
5026 | !PatternDecl->getReturnType()->getContainedAutoType()) |
5027 | return; |
5028 | |
5029 | if (PatternDecl->isInlined()) { |
5030 | // Function, and all later redeclarations of it (from imported modules, |
5031 | // for instance), are now implicitly inline. |
5032 | for (auto *D = Function->getMostRecentDecl(); /**/; |
5033 | D = D->getPreviousDecl()) { |
5034 | D->setImplicitlyInline(); |
5035 | if (D == Function) |
5036 | break; |
5037 | } |
5038 | } |
5039 | |
5040 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Function); |
5041 | if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) |
5042 | return; |
5043 | PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(), |
5044 | "instantiating function definition" ); |
5045 | |
5046 | // The instantiation is visible here, even if it was first declared in an |
5047 | // unimported module. |
5048 | Function->setVisibleDespiteOwningModule(); |
5049 | |
5050 | // Copy the source locations from the pattern. |
5051 | Function->setLocation(PatternDecl->getLocation()); |
5052 | Function->setInnerLocStart(PatternDecl->getInnerLocStart()); |
5053 | Function->setRangeEnd(PatternDecl->getEndLoc()); |
5054 | |
5055 | EnterExpressionEvaluationContext EvalContext( |
5056 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
5057 | |
5058 | // Introduce a new scope where local variable instantiations will be |
5059 | // recorded, unless we're actually a member function within a local |
5060 | // class, in which case we need to merge our results with the parent |
5061 | // scope (of the enclosing function). The exception is instantiating |
5062 | // a function template specialization, since the template to be |
5063 | // instantiated already has references to locals properly substituted. |
5064 | bool MergeWithParentScope = false; |
5065 | if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext())) |
5066 | MergeWithParentScope = |
5067 | Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization(); |
5068 | |
5069 | LocalInstantiationScope Scope(*this, MergeWithParentScope); |
5070 | auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() { |
5071 | // Special members might get their TypeSourceInfo set up w.r.t the |
5072 | // PatternDecl context, in which case parameters could still be pointing |
5073 | // back to the original class, make sure arguments are bound to the |
5074 | // instantiated record instead. |
5075 | assert(PatternDecl->isDefaulted() && |
5076 | "Special member needs to be defaulted" ); |
5077 | auto PatternSM = getDefaultedFunctionKind(FD: PatternDecl).asSpecialMember(); |
5078 | if (!(PatternSM == Sema::CXXCopyConstructor || |
5079 | PatternSM == Sema::CXXCopyAssignment || |
5080 | PatternSM == Sema::CXXMoveConstructor || |
5081 | PatternSM == Sema::CXXMoveAssignment)) |
5082 | return; |
5083 | |
5084 | auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()); |
5085 | const auto *PatternRec = |
5086 | dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext()); |
5087 | if (!NewRec || !PatternRec) |
5088 | return; |
5089 | if (!PatternRec->isLambda()) |
5090 | return; |
5091 | |
5092 | struct SpecialMemberTypeInfoRebuilder |
5093 | : TreeTransform<SpecialMemberTypeInfoRebuilder> { |
5094 | using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>; |
5095 | const CXXRecordDecl *OldDecl; |
5096 | CXXRecordDecl *NewDecl; |
5097 | |
5098 | SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O, |
5099 | CXXRecordDecl *N) |
5100 | : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {} |
5101 | |
5102 | bool TransformExceptionSpec(SourceLocation Loc, |
5103 | FunctionProtoType::ExceptionSpecInfo &ESI, |
5104 | SmallVectorImpl<QualType> &Exceptions, |
5105 | bool &Changed) { |
5106 | return false; |
5107 | } |
5108 | |
5109 | QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) { |
5110 | const RecordType *T = TL.getTypePtr(); |
5111 | RecordDecl *Record = cast_or_null<RecordDecl>( |
5112 | getDerived().TransformDecl(TL.getNameLoc(), T->getDecl())); |
5113 | if (Record != OldDecl) |
5114 | return Base::TransformRecordType(TLB, TL); |
5115 | |
5116 | QualType Result = getDerived().RebuildRecordType(NewDecl); |
5117 | if (Result.isNull()) |
5118 | return QualType(); |
5119 | |
5120 | RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(T: Result); |
5121 | NewTL.setNameLoc(TL.getNameLoc()); |
5122 | return Result; |
5123 | } |
5124 | } IR{*this, PatternRec, NewRec}; |
5125 | |
5126 | TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo()); |
5127 | assert(NewSI && "Type Transform failed?" ); |
5128 | Function->setType(NewSI->getType()); |
5129 | Function->setTypeSourceInfo(NewSI); |
5130 | |
5131 | ParmVarDecl *Parm = Function->getParamDecl(i: 0); |
5132 | TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo()); |
5133 | Parm->setType(NewParmSI->getType()); |
5134 | Parm->setTypeSourceInfo(NewParmSI); |
5135 | }; |
5136 | |
5137 | if (PatternDecl->isDefaulted()) { |
5138 | RebuildTypeSourceInfoForDefaultSpecialMembers(); |
5139 | SetDeclDefaulted(dcl: Function, DefaultLoc: PatternDecl->getLocation()); |
5140 | } else { |
5141 | MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs( |
5142 | D: Function, DC: Function->getLexicalDeclContext(), /*Final=*/false, |
5143 | /*Innermost=*/std::nullopt, RelativeToPrimary: false, Pattern: PatternDecl); |
5144 | |
5145 | // Substitute into the qualifier; we can get a substitution failure here |
5146 | // through evil use of alias templates. |
5147 | // FIXME: Is CurContext correct for this? Should we go to the (instantiation |
5148 | // of the) lexical context of the pattern? |
5149 | SubstQualifier(SemaRef&: *this, OldDecl: PatternDecl, NewDecl: Function, TemplateArgs); |
5150 | |
5151 | ActOnStartOfFunctionDef(nullptr, Function); |
5152 | |
5153 | // Enter the scope of this instantiation. We don't use |
5154 | // PushDeclContext because we don't have a scope. |
5155 | Sema::ContextRAII savedContext(*this, Function); |
5156 | |
5157 | FPFeaturesStateRAII SavedFPFeatures(*this); |
5158 | CurFPFeatures = FPOptions(getLangOpts()); |
5159 | FpPragmaStack.CurrentValue = FPOptionsOverride(); |
5160 | |
5161 | if (addInstantiatedParametersToScope(Function, PatternDecl, Scope, |
5162 | TemplateArgs)) |
5163 | return; |
5164 | |
5165 | StmtResult Body; |
5166 | if (PatternDecl->hasSkippedBody()) { |
5167 | ActOnSkippedFunctionBody(Function); |
5168 | Body = nullptr; |
5169 | } else { |
5170 | if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: Function)) { |
5171 | // If this is a constructor, instantiate the member initializers. |
5172 | InstantiateMemInitializers(New: Ctor, Tmpl: cast<CXXConstructorDecl>(Val: PatternDecl), |
5173 | TemplateArgs); |
5174 | |
5175 | // If this is an MS ABI dllexport default constructor, instantiate any |
5176 | // default arguments. |
5177 | if (Context.getTargetInfo().getCXXABI().isMicrosoft() && |
5178 | Ctor->isDefaultConstructor()) { |
5179 | InstantiateDefaultCtorDefaultArgs(Ctor); |
5180 | } |
5181 | } |
5182 | |
5183 | // Instantiate the function body. |
5184 | Body = SubstStmt(S: Pattern, TemplateArgs); |
5185 | |
5186 | if (Body.isInvalid()) |
5187 | Function->setInvalidDecl(); |
5188 | } |
5189 | // FIXME: finishing the function body while in an expression evaluation |
5190 | // context seems wrong. Investigate more. |
5191 | ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true); |
5192 | |
5193 | PerformDependentDiagnostics(PatternDecl, TemplateArgs); |
5194 | |
5195 | if (auto *Listener = getASTMutationListener()) |
5196 | Listener->FunctionDefinitionInstantiated(D: Function); |
5197 | |
5198 | savedContext.pop(); |
5199 | } |
5200 | |
5201 | DeclGroupRef DG(Function); |
5202 | Consumer.HandleTopLevelDecl(D: DG); |
5203 | |
5204 | // This class may have local implicit instantiations that need to be |
5205 | // instantiation within this scope. |
5206 | LocalInstantiations.perform(); |
5207 | Scope.Exit(); |
5208 | GlobalInstantiations.perform(); |
5209 | } |
5210 | |
5211 | VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation( |
5212 | VarTemplateDecl *VarTemplate, VarDecl *FromVar, |
5213 | const TemplateArgumentList *PartialSpecArgs, |
5214 | const TemplateArgumentListInfo &TemplateArgsInfo, |
5215 | SmallVectorImpl<TemplateArgument> &Converted, |
5216 | SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs, |
5217 | LocalInstantiationScope *StartingScope) { |
5218 | if (FromVar->isInvalidDecl()) |
5219 | return nullptr; |
5220 | |
5221 | InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar); |
5222 | if (Inst.isInvalid()) |
5223 | return nullptr; |
5224 | |
5225 | // Instantiate the first declaration of the variable template: for a partial |
5226 | // specialization of a static data member template, the first declaration may |
5227 | // or may not be the declaration in the class; if it's in the class, we want |
5228 | // to instantiate a member in the class (a declaration), and if it's outside, |
5229 | // we want to instantiate a definition. |
5230 | // |
5231 | // If we're instantiating an explicitly-specialized member template or member |
5232 | // partial specialization, don't do this. The member specialization completely |
5233 | // replaces the original declaration in this case. |
5234 | bool IsMemberSpec = false; |
5235 | MultiLevelTemplateArgumentList MultiLevelList; |
5236 | if (auto *PartialSpec = |
5237 | dyn_cast<VarTemplatePartialSpecializationDecl>(Val: FromVar)) { |
5238 | assert(PartialSpecArgs); |
5239 | IsMemberSpec = PartialSpec->isMemberSpecialization(); |
5240 | MultiLevelList.addOuterTemplateArguments( |
5241 | PartialSpec, PartialSpecArgs->asArray(), /*Final=*/false); |
5242 | } else { |
5243 | assert(VarTemplate == FromVar->getDescribedVarTemplate()); |
5244 | IsMemberSpec = VarTemplate->isMemberSpecialization(); |
5245 | MultiLevelList.addOuterTemplateArguments(VarTemplate, Converted, |
5246 | /*Final=*/false); |
5247 | } |
5248 | if (!IsMemberSpec) |
5249 | FromVar = FromVar->getFirstDecl(); |
5250 | |
5251 | TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(), |
5252 | MultiLevelList); |
5253 | |
5254 | // TODO: Set LateAttrs and StartingScope ... |
5255 | |
5256 | return cast_or_null<VarTemplateSpecializationDecl>( |
5257 | Val: Instantiator.VisitVarTemplateSpecializationDecl( |
5258 | VarTemplate, D: FromVar, TemplateArgsInfo, Converted)); |
5259 | } |
5260 | |
5261 | /// Instantiates a variable template specialization by completing it |
5262 | /// with appropriate type information and initializer. |
5263 | VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl( |
5264 | VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, |
5265 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
5266 | assert(PatternDecl->isThisDeclarationADefinition() && |
5267 | "don't have a definition to instantiate from" ); |
5268 | |
5269 | // Do substitution on the type of the declaration |
5270 | TypeSourceInfo *DI = |
5271 | SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs, |
5272 | PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName()); |
5273 | if (!DI) |
5274 | return nullptr; |
5275 | |
5276 | // Update the type of this variable template specialization. |
5277 | VarSpec->setType(DI->getType()); |
5278 | |
5279 | // Convert the declaration into a definition now. |
5280 | VarSpec->setCompleteDefinition(); |
5281 | |
5282 | // Instantiate the initializer. |
5283 | InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs); |
5284 | |
5285 | if (getLangOpts().OpenCL) |
5286 | deduceOpenCLAddressSpace(VarSpec); |
5287 | |
5288 | return VarSpec; |
5289 | } |
5290 | |
5291 | /// BuildVariableInstantiation - Used after a new variable has been created. |
5292 | /// Sets basic variable data and decides whether to postpone the |
5293 | /// variable instantiation. |
5294 | void Sema::BuildVariableInstantiation( |
5295 | VarDecl *NewVar, VarDecl *OldVar, |
5296 | const MultiLevelTemplateArgumentList &TemplateArgs, |
5297 | LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, |
5298 | LocalInstantiationScope *StartingScope, |
5299 | bool InstantiatingVarTemplate, |
5300 | VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) { |
5301 | // Instantiating a partial specialization to produce a partial |
5302 | // specialization. |
5303 | bool InstantiatingVarTemplatePartialSpec = |
5304 | isa<VarTemplatePartialSpecializationDecl>(Val: OldVar) && |
5305 | isa<VarTemplatePartialSpecializationDecl>(Val: NewVar); |
5306 | // Instantiating from a variable template (or partial specialization) to |
5307 | // produce a variable template specialization. |
5308 | bool InstantiatingSpecFromTemplate = |
5309 | isa<VarTemplateSpecializationDecl>(Val: NewVar) && |
5310 | (OldVar->getDescribedVarTemplate() || |
5311 | isa<VarTemplatePartialSpecializationDecl>(Val: OldVar)); |
5312 | |
5313 | // If we are instantiating a local extern declaration, the |
5314 | // instantiation belongs lexically to the containing function. |
5315 | // If we are instantiating a static data member defined |
5316 | // out-of-line, the instantiation will have the same lexical |
5317 | // context (which will be a namespace scope) as the template. |
5318 | if (OldVar->isLocalExternDecl()) { |
5319 | NewVar->setLocalExternDecl(); |
5320 | NewVar->setLexicalDeclContext(Owner); |
5321 | } else if (OldVar->isOutOfLine()) |
5322 | NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext()); |
5323 | NewVar->setTSCSpec(OldVar->getTSCSpec()); |
5324 | NewVar->setInitStyle(OldVar->getInitStyle()); |
5325 | NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl()); |
5326 | NewVar->setObjCForDecl(OldVar->isObjCForDecl()); |
5327 | NewVar->setConstexpr(OldVar->isConstexpr()); |
5328 | NewVar->setInitCapture(OldVar->isInitCapture()); |
5329 | NewVar->setPreviousDeclInSameBlockScope( |
5330 | OldVar->isPreviousDeclInSameBlockScope()); |
5331 | NewVar->setAccess(OldVar->getAccess()); |
5332 | |
5333 | if (!OldVar->isStaticDataMember()) { |
5334 | if (OldVar->isUsed(false)) |
5335 | NewVar->setIsUsed(); |
5336 | NewVar->setReferenced(OldVar->isReferenced()); |
5337 | } |
5338 | |
5339 | InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope); |
5340 | |
5341 | LookupResult Previous( |
5342 | *this, NewVar->getDeclName(), NewVar->getLocation(), |
5343 | NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage |
5344 | : Sema::LookupOrdinaryName, |
5345 | NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration |
5346 | : forRedeclarationInCurContext()); |
5347 | |
5348 | if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() && |
5349 | (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() || |
5350 | OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) { |
5351 | // We have a previous declaration. Use that one, so we merge with the |
5352 | // right type. |
5353 | if (NamedDecl *NewPrev = FindInstantiatedDecl( |
5354 | Loc: NewVar->getLocation(), D: OldVar->getPreviousDecl(), TemplateArgs)) |
5355 | Previous.addDecl(D: NewPrev); |
5356 | } else if (!isa<VarTemplateSpecializationDecl>(Val: NewVar) && |
5357 | OldVar->hasLinkage()) { |
5358 | LookupQualifiedName(Previous, NewVar->getDeclContext(), false); |
5359 | } else if (PrevDeclForVarTemplateSpecialization) { |
5360 | Previous.addDecl(PrevDeclForVarTemplateSpecialization); |
5361 | } |
5362 | CheckVariableDeclaration(NewVD: NewVar, Previous); |
5363 | |
5364 | if (!InstantiatingVarTemplate) { |
5365 | NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar); |
5366 | if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl()) |
5367 | NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar); |
5368 | } |
5369 | |
5370 | if (!OldVar->isOutOfLine()) { |
5371 | if (NewVar->getDeclContext()->isFunctionOrMethod()) |
5372 | CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar); |
5373 | } |
5374 | |
5375 | // Link instantiations of static data members back to the template from |
5376 | // which they were instantiated. |
5377 | // |
5378 | // Don't do this when instantiating a template (we link the template itself |
5379 | // back in that case) nor when instantiating a static data member template |
5380 | // (that's not a member specialization). |
5381 | if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate && |
5382 | !InstantiatingSpecFromTemplate) |
5383 | NewVar->setInstantiationOfStaticDataMember(VD: OldVar, |
5384 | TSK: TSK_ImplicitInstantiation); |
5385 | |
5386 | // If the pattern is an (in-class) explicit specialization, then the result |
5387 | // is also an explicit specialization. |
5388 | if (VarTemplateSpecializationDecl *OldVTSD = |
5389 | dyn_cast<VarTemplateSpecializationDecl>(Val: OldVar)) { |
5390 | if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization && |
5391 | !isa<VarTemplatePartialSpecializationDecl>(Val: OldVTSD)) |
5392 | cast<VarTemplateSpecializationDecl>(Val: NewVar)->setSpecializationKind( |
5393 | TSK_ExplicitSpecialization); |
5394 | } |
5395 | |
5396 | // Forward the mangling number from the template to the instantiated decl. |
5397 | Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar)); |
5398 | Context.setStaticLocalNumber(VD: NewVar, Number: Context.getStaticLocalNumber(VD: OldVar)); |
5399 | |
5400 | // Figure out whether to eagerly instantiate the initializer. |
5401 | if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) { |
5402 | // We're producing a template. Don't instantiate the initializer yet. |
5403 | } else if (NewVar->getType()->isUndeducedType()) { |
5404 | // We need the type to complete the declaration of the variable. |
5405 | InstantiateVariableInitializer(Var: NewVar, OldVar, TemplateArgs); |
5406 | } else if (InstantiatingSpecFromTemplate || |
5407 | (OldVar->isInline() && OldVar->isThisDeclarationADefinition() && |
5408 | !NewVar->isThisDeclarationADefinition())) { |
5409 | // Delay instantiation of the initializer for variable template |
5410 | // specializations or inline static data members until a definition of the |
5411 | // variable is needed. |
5412 | } else { |
5413 | InstantiateVariableInitializer(Var: NewVar, OldVar, TemplateArgs); |
5414 | } |
5415 | |
5416 | // Diagnose unused local variables with dependent types, where the diagnostic |
5417 | // will have been deferred. |
5418 | if (!NewVar->isInvalidDecl() && |
5419 | NewVar->getDeclContext()->isFunctionOrMethod() && |
5420 | OldVar->getType()->isDependentType()) |
5421 | DiagnoseUnusedDecl(NewVar); |
5422 | } |
5423 | |
5424 | /// Instantiate the initializer of a variable. |
5425 | void Sema::InstantiateVariableInitializer( |
5426 | VarDecl *Var, VarDecl *OldVar, |
5427 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
5428 | if (ASTMutationListener *L = getASTContext().getASTMutationListener()) |
5429 | L->VariableDefinitionInstantiated(D: Var); |
5430 | |
5431 | // We propagate the 'inline' flag with the initializer, because it |
5432 | // would otherwise imply that the variable is a definition for a |
5433 | // non-static data member. |
5434 | if (OldVar->isInlineSpecified()) |
5435 | Var->setInlineSpecified(); |
5436 | else if (OldVar->isInline()) |
5437 | Var->setImplicitlyInline(); |
5438 | |
5439 | if (OldVar->getInit()) { |
5440 | EnterExpressionEvaluationContext Evaluated( |
5441 | *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var); |
5442 | |
5443 | keepInLifetimeExtendingContext(); |
5444 | keepInMaterializeTemporaryObjectContext(); |
5445 | // Instantiate the initializer. |
5446 | ExprResult Init; |
5447 | |
5448 | { |
5449 | ContextRAII SwitchContext(*this, Var->getDeclContext()); |
5450 | Init = SubstInitializer(E: OldVar->getInit(), TemplateArgs, |
5451 | CXXDirectInit: OldVar->getInitStyle() == VarDecl::CallInit); |
5452 | } |
5453 | |
5454 | if (!Init.isInvalid()) { |
5455 | Expr *InitExpr = Init.get(); |
5456 | |
5457 | if (Var->hasAttr<DLLImportAttr>() && |
5458 | (!InitExpr || |
5459 | !InitExpr->isConstantInitializer(getASTContext(), false))) { |
5460 | // Do not dynamically initialize dllimport variables. |
5461 | } else if (InitExpr) { |
5462 | bool DirectInit = OldVar->isDirectInit(); |
5463 | AddInitializerToDecl(Var, InitExpr, DirectInit); |
5464 | } else |
5465 | ActOnUninitializedDecl(Var); |
5466 | } else { |
5467 | // FIXME: Not too happy about invalidating the declaration |
5468 | // because of a bogus initializer. |
5469 | Var->setInvalidDecl(); |
5470 | } |
5471 | } else { |
5472 | // `inline` variables are a definition and declaration all in one; we won't |
5473 | // pick up an initializer from anywhere else. |
5474 | if (Var->isStaticDataMember() && !Var->isInline()) { |
5475 | if (!Var->isOutOfLine()) |
5476 | return; |
5477 | |
5478 | // If the declaration inside the class had an initializer, don't add |
5479 | // another one to the out-of-line definition. |
5480 | if (OldVar->getFirstDecl()->hasInit()) |
5481 | return; |
5482 | } |
5483 | |
5484 | // We'll add an initializer to a for-range declaration later. |
5485 | if (Var->isCXXForRangeDecl() || Var->isObjCForDecl()) |
5486 | return; |
5487 | |
5488 | ActOnUninitializedDecl(Var); |
5489 | } |
5490 | |
5491 | if (getLangOpts().CUDA) |
5492 | checkAllowedCUDAInitializer(VD: Var); |
5493 | } |
5494 | |
5495 | /// Instantiate the definition of the given variable from its |
5496 | /// template. |
5497 | /// |
5498 | /// \param PointOfInstantiation the point at which the instantiation was |
5499 | /// required. Note that this is not precisely a "point of instantiation" |
5500 | /// for the variable, but it's close. |
5501 | /// |
5502 | /// \param Var the already-instantiated declaration of a templated variable. |
5503 | /// |
5504 | /// \param Recursive if true, recursively instantiates any functions that |
5505 | /// are required by this instantiation. |
5506 | /// |
5507 | /// \param DefinitionRequired if true, then we are performing an explicit |
5508 | /// instantiation where a definition of the variable is required. Complain |
5509 | /// if there is no such definition. |
5510 | void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation, |
5511 | VarDecl *Var, bool Recursive, |
5512 | bool DefinitionRequired, bool AtEndOfTU) { |
5513 | if (Var->isInvalidDecl()) |
5514 | return; |
5515 | |
5516 | // Never instantiate an explicitly-specialized entity. |
5517 | TemplateSpecializationKind TSK = |
5518 | Var->getTemplateSpecializationKindForInstantiation(); |
5519 | if (TSK == TSK_ExplicitSpecialization) |
5520 | return; |
5521 | |
5522 | // Find the pattern and the arguments to substitute into it. |
5523 | VarDecl *PatternDecl = Var->getTemplateInstantiationPattern(); |
5524 | assert(PatternDecl && "no pattern for templated variable" ); |
5525 | MultiLevelTemplateArgumentList TemplateArgs = |
5526 | getTemplateInstantiationArgs(Var); |
5527 | |
5528 | VarTemplateSpecializationDecl *VarSpec = |
5529 | dyn_cast<VarTemplateSpecializationDecl>(Val: Var); |
5530 | if (VarSpec) { |
5531 | // If this is a static data member template, there might be an |
5532 | // uninstantiated initializer on the declaration. If so, instantiate |
5533 | // it now. |
5534 | // |
5535 | // FIXME: This largely duplicates what we would do below. The difference |
5536 | // is that along this path we may instantiate an initializer from an |
5537 | // in-class declaration of the template and instantiate the definition |
5538 | // from a separate out-of-class definition. |
5539 | if (PatternDecl->isStaticDataMember() && |
5540 | (PatternDecl = PatternDecl->getFirstDecl())->hasInit() && |
5541 | !Var->hasInit()) { |
5542 | // FIXME: Factor out the duplicated instantiation context setup/tear down |
5543 | // code here. |
5544 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); |
5545 | if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) |
5546 | return; |
5547 | PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), |
5548 | "instantiating variable initializer" ); |
5549 | |
5550 | // The instantiation is visible here, even if it was first declared in an |
5551 | // unimported module. |
5552 | Var->setVisibleDespiteOwningModule(); |
5553 | |
5554 | // If we're performing recursive template instantiation, create our own |
5555 | // queue of pending implicit instantiations that we will instantiate |
5556 | // later, while we're still within our own instantiation context. |
5557 | GlobalEagerInstantiationScope GlobalInstantiations(*this, |
5558 | /*Enabled=*/Recursive); |
5559 | LocalInstantiationScope Local(*this); |
5560 | LocalEagerInstantiationScope LocalInstantiations(*this); |
5561 | |
5562 | // Enter the scope of this instantiation. We don't use |
5563 | // PushDeclContext because we don't have a scope. |
5564 | ContextRAII PreviousContext(*this, Var->getDeclContext()); |
5565 | InstantiateVariableInitializer(Var, OldVar: PatternDecl, TemplateArgs); |
5566 | PreviousContext.pop(); |
5567 | |
5568 | // This variable may have local implicit instantiations that need to be |
5569 | // instantiated within this scope. |
5570 | LocalInstantiations.perform(); |
5571 | Local.Exit(); |
5572 | GlobalInstantiations.perform(); |
5573 | } |
5574 | } else { |
5575 | assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && |
5576 | "not a static data member?" ); |
5577 | } |
5578 | |
5579 | VarDecl *Def = PatternDecl->getDefinition(getASTContext()); |
5580 | |
5581 | // If we don't have a definition of the variable template, we won't perform |
5582 | // any instantiation. Rather, we rely on the user to instantiate this |
5583 | // definition (or provide a specialization for it) in another translation |
5584 | // unit. |
5585 | if (!Def && !DefinitionRequired) { |
5586 | if (TSK == TSK_ExplicitInstantiationDefinition) { |
5587 | PendingInstantiations.push_back( |
5588 | std::make_pair(x&: Var, y&: PointOfInstantiation)); |
5589 | } else if (TSK == TSK_ImplicitInstantiation) { |
5590 | // Warn about missing definition at the end of translation unit. |
5591 | if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() && |
5592 | !getSourceManager().isInSystemHeader(Loc: PatternDecl->getBeginLoc())) { |
5593 | Diag(PointOfInstantiation, diag::warn_var_template_missing) |
5594 | << Var; |
5595 | Diag(PatternDecl->getLocation(), diag::note_forward_template_decl); |
5596 | if (getLangOpts().CPlusPlus11) |
5597 | Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var; |
5598 | } |
5599 | return; |
5600 | } |
5601 | } |
5602 | |
5603 | // FIXME: We need to track the instantiation stack in order to know which |
5604 | // definitions should be visible within this instantiation. |
5605 | // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember(). |
5606 | if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var, |
5607 | /*InstantiatedFromMember*/false, |
5608 | PatternDecl, Def, TSK, |
5609 | /*Complain*/DefinitionRequired)) |
5610 | return; |
5611 | |
5612 | // C++11 [temp.explicit]p10: |
5613 | // Except for inline functions, const variables of literal types, variables |
5614 | // of reference types, [...] explicit instantiation declarations |
5615 | // have the effect of suppressing the implicit instantiation of the entity |
5616 | // to which they refer. |
5617 | // |
5618 | // FIXME: That's not exactly the same as "might be usable in constant |
5619 | // expressions", which only allows constexpr variables and const integral |
5620 | // types, not arbitrary const literal types. |
5621 | if (TSK == TSK_ExplicitInstantiationDeclaration && |
5622 | !Var->mightBeUsableInConstantExpressions(C: getASTContext())) |
5623 | return; |
5624 | |
5625 | // Make sure to pass the instantiated variable to the consumer at the end. |
5626 | struct PassToConsumerRAII { |
5627 | ASTConsumer &Consumer; |
5628 | VarDecl *Var; |
5629 | |
5630 | PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var) |
5631 | : Consumer(Consumer), Var(Var) { } |
5632 | |
5633 | ~PassToConsumerRAII() { |
5634 | Consumer.HandleCXXStaticMemberVarInstantiation(D: Var); |
5635 | } |
5636 | } PassToConsumerRAII(Consumer, Var); |
5637 | |
5638 | // If we already have a definition, we're done. |
5639 | if (VarDecl *Def = Var->getDefinition()) { |
5640 | // We may be explicitly instantiating something we've already implicitly |
5641 | // instantiated. |
5642 | Def->setTemplateSpecializationKind(TSK: Var->getTemplateSpecializationKind(), |
5643 | PointOfInstantiation); |
5644 | return; |
5645 | } |
5646 | |
5647 | InstantiatingTemplate Inst(*this, PointOfInstantiation, Var); |
5648 | if (Inst.isInvalid() || Inst.isAlreadyInstantiating()) |
5649 | return; |
5650 | PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), |
5651 | "instantiating variable definition" ); |
5652 | |
5653 | // If we're performing recursive template instantiation, create our own |
5654 | // queue of pending implicit instantiations that we will instantiate later, |
5655 | // while we're still within our own instantiation context. |
5656 | GlobalEagerInstantiationScope GlobalInstantiations(*this, |
5657 | /*Enabled=*/Recursive); |
5658 | |
5659 | // Enter the scope of this instantiation. We don't use |
5660 | // PushDeclContext because we don't have a scope. |
5661 | ContextRAII PreviousContext(*this, Var->getDeclContext()); |
5662 | LocalInstantiationScope Local(*this); |
5663 | |
5664 | LocalEagerInstantiationScope LocalInstantiations(*this); |
5665 | |
5666 | VarDecl *OldVar = Var; |
5667 | if (Def->isStaticDataMember() && !Def->isOutOfLine()) { |
5668 | // We're instantiating an inline static data member whose definition was |
5669 | // provided inside the class. |
5670 | InstantiateVariableInitializer(Var, OldVar: Def, TemplateArgs); |
5671 | } else if (!VarSpec) { |
5672 | Var = cast_or_null<VarDecl>(SubstDecl(D: Def, Owner: Var->getDeclContext(), |
5673 | TemplateArgs)); |
5674 | } else if (Var->isStaticDataMember() && |
5675 | Var->getLexicalDeclContext()->isRecord()) { |
5676 | // We need to instantiate the definition of a static data member template, |
5677 | // and all we have is the in-class declaration of it. Instantiate a separate |
5678 | // declaration of the definition. |
5679 | TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(), |
5680 | TemplateArgs); |
5681 | |
5682 | TemplateArgumentListInfo TemplateArgInfo; |
5683 | if (const ASTTemplateArgumentListInfo *ArgInfo = |
5684 | VarSpec->getTemplateArgsInfo()) { |
5685 | TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc()); |
5686 | TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc()); |
5687 | for (const TemplateArgumentLoc &Arg : ArgInfo->arguments()) |
5688 | TemplateArgInfo.addArgument(Loc: Arg); |
5689 | } |
5690 | |
5691 | Var = cast_or_null<VarDecl>(Val: Instantiator.VisitVarTemplateSpecializationDecl( |
5692 | VarTemplate: VarSpec->getSpecializedTemplate(), D: Def, TemplateArgsInfo: TemplateArgInfo, |
5693 | Converted: VarSpec->getTemplateArgs().asArray(), PrevDecl: VarSpec)); |
5694 | if (Var) { |
5695 | llvm::PointerUnion<VarTemplateDecl *, |
5696 | VarTemplatePartialSpecializationDecl *> PatternPtr = |
5697 | VarSpec->getSpecializedTemplateOrPartial(); |
5698 | if (VarTemplatePartialSpecializationDecl *Partial = |
5699 | PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>()) |
5700 | cast<VarTemplateSpecializationDecl>(Val: Var)->setInstantiationOf( |
5701 | PartialSpec: Partial, TemplateArgs: &VarSpec->getTemplateInstantiationArgs()); |
5702 | |
5703 | // Attach the initializer. |
5704 | InstantiateVariableInitializer(Var, OldVar: Def, TemplateArgs); |
5705 | } |
5706 | } else |
5707 | // Complete the existing variable's definition with an appropriately |
5708 | // substituted type and initializer. |
5709 | Var = CompleteVarTemplateSpecializationDecl(VarSpec, PatternDecl: Def, TemplateArgs); |
5710 | |
5711 | PreviousContext.pop(); |
5712 | |
5713 | if (Var) { |
5714 | PassToConsumerRAII.Var = Var; |
5715 | Var->setTemplateSpecializationKind(TSK: OldVar->getTemplateSpecializationKind(), |
5716 | PointOfInstantiation: OldVar->getPointOfInstantiation()); |
5717 | } |
5718 | |
5719 | // This variable may have local implicit instantiations that need to be |
5720 | // instantiated within this scope. |
5721 | LocalInstantiations.perform(); |
5722 | Local.Exit(); |
5723 | GlobalInstantiations.perform(); |
5724 | } |
5725 | |
5726 | void |
5727 | Sema::InstantiateMemInitializers(CXXConstructorDecl *New, |
5728 | const CXXConstructorDecl *Tmpl, |
5729 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
5730 | |
5731 | SmallVector<CXXCtorInitializer*, 4> NewInits; |
5732 | bool AnyErrors = Tmpl->isInvalidDecl(); |
5733 | |
5734 | // Instantiate all the initializers. |
5735 | for (const auto *Init : Tmpl->inits()) { |
5736 | // Only instantiate written initializers, let Sema re-construct implicit |
5737 | // ones. |
5738 | if (!Init->isWritten()) |
5739 | continue; |
5740 | |
5741 | SourceLocation EllipsisLoc; |
5742 | |
5743 | if (Init->isPackExpansion()) { |
5744 | // This is a pack expansion. We should expand it now. |
5745 | TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc(); |
5746 | SmallVector<UnexpandedParameterPack, 4> Unexpanded; |
5747 | collectUnexpandedParameterPacks(TL: BaseTL, Unexpanded); |
5748 | collectUnexpandedParameterPacks(Arg: Init->getInit(), Unexpanded); |
5749 | bool ShouldExpand = false; |
5750 | bool RetainExpansion = false; |
5751 | std::optional<unsigned> NumExpansions; |
5752 | if (CheckParameterPacksForExpansion(EllipsisLoc: Init->getEllipsisLoc(), |
5753 | PatternRange: BaseTL.getSourceRange(), |
5754 | Unexpanded, |
5755 | TemplateArgs, ShouldExpand, |
5756 | RetainExpansion, |
5757 | NumExpansions)) { |
5758 | AnyErrors = true; |
5759 | New->setInvalidDecl(); |
5760 | continue; |
5761 | } |
5762 | assert(ShouldExpand && "Partial instantiation of base initializer?" ); |
5763 | |
5764 | // Loop over all of the arguments in the argument pack(s), |
5765 | for (unsigned I = 0; I != *NumExpansions; ++I) { |
5766 | Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I); |
5767 | |
5768 | // Instantiate the initializer. |
5769 | ExprResult TempInit = SubstInitializer(E: Init->getInit(), TemplateArgs, |
5770 | /*CXXDirectInit=*/true); |
5771 | if (TempInit.isInvalid()) { |
5772 | AnyErrors = true; |
5773 | break; |
5774 | } |
5775 | |
5776 | // Instantiate the base type. |
5777 | TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(), |
5778 | TemplateArgs, |
5779 | Init->getSourceLocation(), |
5780 | New->getDeclName()); |
5781 | if (!BaseTInfo) { |
5782 | AnyErrors = true; |
5783 | break; |
5784 | } |
5785 | |
5786 | // Build the initializer. |
5787 | MemInitResult NewInit = BuildBaseInitializer(BaseType: BaseTInfo->getType(), |
5788 | BaseTInfo, Init: TempInit.get(), |
5789 | ClassDecl: New->getParent(), |
5790 | EllipsisLoc: SourceLocation()); |
5791 | if (NewInit.isInvalid()) { |
5792 | AnyErrors = true; |
5793 | break; |
5794 | } |
5795 | |
5796 | NewInits.push_back(Elt: NewInit.get()); |
5797 | } |
5798 | |
5799 | continue; |
5800 | } |
5801 | |
5802 | // Instantiate the initializer. |
5803 | ExprResult TempInit = SubstInitializer(E: Init->getInit(), TemplateArgs, |
5804 | /*CXXDirectInit=*/true); |
5805 | if (TempInit.isInvalid()) { |
5806 | AnyErrors = true; |
5807 | continue; |
5808 | } |
5809 | |
5810 | MemInitResult NewInit; |
5811 | if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) { |
5812 | TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(), |
5813 | TemplateArgs, |
5814 | Init->getSourceLocation(), |
5815 | New->getDeclName()); |
5816 | if (!TInfo) { |
5817 | AnyErrors = true; |
5818 | New->setInvalidDecl(); |
5819 | continue; |
5820 | } |
5821 | |
5822 | if (Init->isBaseInitializer()) |
5823 | NewInit = BuildBaseInitializer(BaseType: TInfo->getType(), BaseTInfo: TInfo, Init: TempInit.get(), |
5824 | ClassDecl: New->getParent(), EllipsisLoc); |
5825 | else |
5826 | NewInit = BuildDelegatingInitializer(TInfo, Init: TempInit.get(), |
5827 | ClassDecl: cast<CXXRecordDecl>(Val: CurContext->getParent())); |
5828 | } else if (Init->isMemberInitializer()) { |
5829 | FieldDecl *Member = cast_or_null<FieldDecl>(Val: FindInstantiatedDecl( |
5830 | Init->getMemberLocation(), |
5831 | Init->getMember(), |
5832 | TemplateArgs)); |
5833 | if (!Member) { |
5834 | AnyErrors = true; |
5835 | New->setInvalidDecl(); |
5836 | continue; |
5837 | } |
5838 | |
5839 | NewInit = BuildMemberInitializer(Member, TempInit.get(), |
5840 | Init->getSourceLocation()); |
5841 | } else if (Init->isIndirectMemberInitializer()) { |
5842 | IndirectFieldDecl *IndirectMember = |
5843 | cast_or_null<IndirectFieldDecl>(Val: FindInstantiatedDecl( |
5844 | Init->getMemberLocation(), |
5845 | Init->getIndirectMember(), TemplateArgs)); |
5846 | |
5847 | if (!IndirectMember) { |
5848 | AnyErrors = true; |
5849 | New->setInvalidDecl(); |
5850 | continue; |
5851 | } |
5852 | |
5853 | NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(), |
5854 | Init->getSourceLocation()); |
5855 | } |
5856 | |
5857 | if (NewInit.isInvalid()) { |
5858 | AnyErrors = true; |
5859 | New->setInvalidDecl(); |
5860 | } else { |
5861 | NewInits.push_back(Elt: NewInit.get()); |
5862 | } |
5863 | } |
5864 | |
5865 | // Assign all the initializers to the new constructor. |
5866 | ActOnMemInitializers(New, |
5867 | /*FIXME: ColonLoc */ |
5868 | SourceLocation(), |
5869 | NewInits, |
5870 | AnyErrors); |
5871 | } |
5872 | |
5873 | // TODO: this could be templated if the various decl types used the |
5874 | // same method name. |
5875 | static bool isInstantiationOf(ClassTemplateDecl *Pattern, |
5876 | ClassTemplateDecl *Instance) { |
5877 | Pattern = Pattern->getCanonicalDecl(); |
5878 | |
5879 | do { |
5880 | Instance = Instance->getCanonicalDecl(); |
5881 | if (Pattern == Instance) return true; |
5882 | Instance = Instance->getInstantiatedFromMemberTemplate(); |
5883 | } while (Instance); |
5884 | |
5885 | return false; |
5886 | } |
5887 | |
5888 | static bool isInstantiationOf(FunctionTemplateDecl *Pattern, |
5889 | FunctionTemplateDecl *Instance) { |
5890 | Pattern = Pattern->getCanonicalDecl(); |
5891 | |
5892 | do { |
5893 | Instance = Instance->getCanonicalDecl(); |
5894 | if (Pattern == Instance) return true; |
5895 | Instance = Instance->getInstantiatedFromMemberTemplate(); |
5896 | } while (Instance); |
5897 | |
5898 | return false; |
5899 | } |
5900 | |
5901 | static bool |
5902 | isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern, |
5903 | ClassTemplatePartialSpecializationDecl *Instance) { |
5904 | Pattern |
5905 | = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl()); |
5906 | do { |
5907 | Instance = cast<ClassTemplatePartialSpecializationDecl>( |
5908 | Instance->getCanonicalDecl()); |
5909 | if (Pattern == Instance) |
5910 | return true; |
5911 | Instance = Instance->getInstantiatedFromMember(); |
5912 | } while (Instance); |
5913 | |
5914 | return false; |
5915 | } |
5916 | |
5917 | static bool isInstantiationOf(CXXRecordDecl *Pattern, |
5918 | CXXRecordDecl *Instance) { |
5919 | Pattern = Pattern->getCanonicalDecl(); |
5920 | |
5921 | do { |
5922 | Instance = Instance->getCanonicalDecl(); |
5923 | if (Pattern == Instance) return true; |
5924 | Instance = Instance->getInstantiatedFromMemberClass(); |
5925 | } while (Instance); |
5926 | |
5927 | return false; |
5928 | } |
5929 | |
5930 | static bool isInstantiationOf(FunctionDecl *Pattern, |
5931 | FunctionDecl *Instance) { |
5932 | Pattern = Pattern->getCanonicalDecl(); |
5933 | |
5934 | do { |
5935 | Instance = Instance->getCanonicalDecl(); |
5936 | if (Pattern == Instance) return true; |
5937 | Instance = Instance->getInstantiatedFromMemberFunction(); |
5938 | } while (Instance); |
5939 | |
5940 | return false; |
5941 | } |
5942 | |
5943 | static bool isInstantiationOf(EnumDecl *Pattern, |
5944 | EnumDecl *Instance) { |
5945 | Pattern = Pattern->getCanonicalDecl(); |
5946 | |
5947 | do { |
5948 | Instance = Instance->getCanonicalDecl(); |
5949 | if (Pattern == Instance) return true; |
5950 | Instance = Instance->getInstantiatedFromMemberEnum(); |
5951 | } while (Instance); |
5952 | |
5953 | return false; |
5954 | } |
5955 | |
5956 | static bool isInstantiationOf(UsingShadowDecl *Pattern, |
5957 | UsingShadowDecl *Instance, |
5958 | ASTContext &C) { |
5959 | return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Inst: Instance), |
5960 | Pattern); |
5961 | } |
5962 | |
5963 | static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance, |
5964 | ASTContext &C) { |
5965 | return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern); |
5966 | } |
5967 | |
5968 | template<typename T> |
5969 | static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other, |
5970 | ASTContext &Ctx) { |
5971 | // An unresolved using declaration can instantiate to an unresolved using |
5972 | // declaration, or to a using declaration or a using declaration pack. |
5973 | // |
5974 | // Multiple declarations can claim to be instantiated from an unresolved |
5975 | // using declaration if it's a pack expansion. We want the UsingPackDecl |
5976 | // in that case, not the individual UsingDecls within the pack. |
5977 | bool OtherIsPackExpansion; |
5978 | NamedDecl *OtherFrom; |
5979 | if (auto *OtherUUD = dyn_cast<T>(Other)) { |
5980 | OtherIsPackExpansion = OtherUUD->isPackExpansion(); |
5981 | OtherFrom = Ctx.getInstantiatedFromUsingDecl(Inst: OtherUUD); |
5982 | } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Val: Other)) { |
5983 | OtherIsPackExpansion = true; |
5984 | OtherFrom = OtherUPD->getInstantiatedFromUsingDecl(); |
5985 | } else if (auto *OtherUD = dyn_cast<UsingDecl>(Val: Other)) { |
5986 | OtherIsPackExpansion = false; |
5987 | OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD); |
5988 | } else { |
5989 | return false; |
5990 | } |
5991 | return Pattern->isPackExpansion() == OtherIsPackExpansion && |
5992 | declaresSameEntity(OtherFrom, Pattern); |
5993 | } |
5994 | |
5995 | static bool isInstantiationOfStaticDataMember(VarDecl *Pattern, |
5996 | VarDecl *Instance) { |
5997 | assert(Instance->isStaticDataMember()); |
5998 | |
5999 | Pattern = Pattern->getCanonicalDecl(); |
6000 | |
6001 | do { |
6002 | Instance = Instance->getCanonicalDecl(); |
6003 | if (Pattern == Instance) return true; |
6004 | Instance = Instance->getInstantiatedFromStaticDataMember(); |
6005 | } while (Instance); |
6006 | |
6007 | return false; |
6008 | } |
6009 | |
6010 | // Other is the prospective instantiation |
6011 | // D is the prospective pattern |
6012 | static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) { |
6013 | if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) |
6014 | return isInstantiationOfUnresolvedUsingDecl(Pattern: UUD, Other, Ctx); |
6015 | |
6016 | if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) |
6017 | return isInstantiationOfUnresolvedUsingDecl(Pattern: UUD, Other, Ctx); |
6018 | |
6019 | if (D->getKind() != Other->getKind()) |
6020 | return false; |
6021 | |
6022 | if (auto *Record = dyn_cast<CXXRecordDecl>(Val: Other)) |
6023 | return isInstantiationOf(Pattern: cast<CXXRecordDecl>(Val: D), Instance: Record); |
6024 | |
6025 | if (auto *Function = dyn_cast<FunctionDecl>(Val: Other)) |
6026 | return isInstantiationOf(Pattern: cast<FunctionDecl>(Val: D), Instance: Function); |
6027 | |
6028 | if (auto *Enum = dyn_cast<EnumDecl>(Val: Other)) |
6029 | return isInstantiationOf(Pattern: cast<EnumDecl>(Val: D), Instance: Enum); |
6030 | |
6031 | if (auto *Var = dyn_cast<VarDecl>(Val: Other)) |
6032 | if (Var->isStaticDataMember()) |
6033 | return isInstantiationOfStaticDataMember(Pattern: cast<VarDecl>(Val: D), Instance: Var); |
6034 | |
6035 | if (auto *Temp = dyn_cast<ClassTemplateDecl>(Val: Other)) |
6036 | return isInstantiationOf(Pattern: cast<ClassTemplateDecl>(Val: D), Instance: Temp); |
6037 | |
6038 | if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Val: Other)) |
6039 | return isInstantiationOf(Pattern: cast<FunctionTemplateDecl>(Val: D), Instance: Temp); |
6040 | |
6041 | if (auto *PartialSpec = |
6042 | dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Other)) |
6043 | return isInstantiationOf(Pattern: cast<ClassTemplatePartialSpecializationDecl>(Val: D), |
6044 | Instance: PartialSpec); |
6045 | |
6046 | if (auto *Field = dyn_cast<FieldDecl>(Val: Other)) { |
6047 | if (!Field->getDeclName()) { |
6048 | // This is an unnamed field. |
6049 | return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field), |
6050 | cast<FieldDecl>(Val: D)); |
6051 | } |
6052 | } |
6053 | |
6054 | if (auto *Using = dyn_cast<UsingDecl>(Val: Other)) |
6055 | return isInstantiationOf(Pattern: cast<UsingDecl>(Val: D), Instance: Using, C&: Ctx); |
6056 | |
6057 | if (auto *Shadow = dyn_cast<UsingShadowDecl>(Val: Other)) |
6058 | return isInstantiationOf(Pattern: cast<UsingShadowDecl>(Val: D), Instance: Shadow, C&: Ctx); |
6059 | |
6060 | return D->getDeclName() && |
6061 | D->getDeclName() == cast<NamedDecl>(Val: Other)->getDeclName(); |
6062 | } |
6063 | |
6064 | template<typename ForwardIterator> |
6065 | static NamedDecl *findInstantiationOf(ASTContext &Ctx, |
6066 | NamedDecl *D, |
6067 | ForwardIterator first, |
6068 | ForwardIterator last) { |
6069 | for (; first != last; ++first) |
6070 | if (isInstantiationOf(Ctx, D, *first)) |
6071 | return cast<NamedDecl>(*first); |
6072 | |
6073 | return nullptr; |
6074 | } |
6075 | |
6076 | /// Finds the instantiation of the given declaration context |
6077 | /// within the current instantiation. |
6078 | /// |
6079 | /// \returns NULL if there was an error |
6080 | DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC, |
6081 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
6082 | if (NamedDecl *D = dyn_cast<NamedDecl>(Val: DC)) { |
6083 | Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, FindingInstantiatedContext: true); |
6084 | return cast_or_null<DeclContext>(Val: ID); |
6085 | } else return DC; |
6086 | } |
6087 | |
6088 | /// Determine whether the given context is dependent on template parameters at |
6089 | /// level \p Level or below. |
6090 | /// |
6091 | /// Sometimes we only substitute an inner set of template arguments and leave |
6092 | /// the outer templates alone. In such cases, contexts dependent only on the |
6093 | /// outer levels are not effectively dependent. |
6094 | static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) { |
6095 | if (!DC->isDependentContext()) |
6096 | return false; |
6097 | if (!Level) |
6098 | return true; |
6099 | return cast<Decl>(Val: DC)->getTemplateDepth() > Level; |
6100 | } |
6101 | |
6102 | /// Find the instantiation of the given declaration within the |
6103 | /// current instantiation. |
6104 | /// |
6105 | /// This routine is intended to be used when \p D is a declaration |
6106 | /// referenced from within a template, that needs to mapped into the |
6107 | /// corresponding declaration within an instantiation. For example, |
6108 | /// given: |
6109 | /// |
6110 | /// \code |
6111 | /// template<typename T> |
6112 | /// struct X { |
6113 | /// enum Kind { |
6114 | /// KnownValue = sizeof(T) |
6115 | /// }; |
6116 | /// |
6117 | /// bool getKind() const { return KnownValue; } |
6118 | /// }; |
6119 | /// |
6120 | /// template struct X<int>; |
6121 | /// \endcode |
6122 | /// |
6123 | /// In the instantiation of X<int>::getKind(), we need to map the \p |
6124 | /// EnumConstantDecl for \p KnownValue (which refers to |
6125 | /// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue). |
6126 | /// \p FindInstantiatedDecl performs this mapping from within the instantiation |
6127 | /// of X<int>. |
6128 | NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, |
6129 | const MultiLevelTemplateArgumentList &TemplateArgs, |
6130 | bool FindingInstantiatedContext) { |
6131 | DeclContext *ParentDC = D->getDeclContext(); |
6132 | // Determine whether our parent context depends on any of the template |
6133 | // arguments we're currently substituting. |
6134 | bool ParentDependsOnArgs = isDependentContextAtLevel( |
6135 | DC: ParentDC, Level: TemplateArgs.getNumRetainedOuterLevels()); |
6136 | // FIXME: Parameters of pointer to functions (y below) that are themselves |
6137 | // parameters (p below) can have their ParentDC set to the translation-unit |
6138 | // - thus we can not consistently check if the ParentDC of such a parameter |
6139 | // is Dependent or/and a FunctionOrMethod. |
6140 | // For e.g. this code, during Template argument deduction tries to |
6141 | // find an instantiated decl for (T y) when the ParentDC for y is |
6142 | // the translation unit. |
6143 | // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {} |
6144 | // float baz(float(*)()) { return 0.0; } |
6145 | // Foo(baz); |
6146 | // The better fix here is perhaps to ensure that a ParmVarDecl, by the time |
6147 | // it gets here, always has a FunctionOrMethod as its ParentDC?? |
6148 | // For now: |
6149 | // - as long as we have a ParmVarDecl whose parent is non-dependent and |
6150 | // whose type is not instantiation dependent, do nothing to the decl |
6151 | // - otherwise find its instantiated decl. |
6152 | if (isa<ParmVarDecl>(Val: D) && !ParentDependsOnArgs && |
6153 | !cast<ParmVarDecl>(Val: D)->getType()->isInstantiationDependentType()) |
6154 | return D; |
6155 | if (isa<ParmVarDecl>(Val: D) || isa<NonTypeTemplateParmDecl>(Val: D) || |
6156 | isa<TemplateTypeParmDecl>(Val: D) || isa<TemplateTemplateParmDecl>(Val: D) || |
6157 | (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() || |
6158 | isa<OMPDeclareReductionDecl>(Val: ParentDC) || |
6159 | isa<OMPDeclareMapperDecl>(Val: ParentDC))) || |
6160 | (isa<CXXRecordDecl>(Val: D) && cast<CXXRecordDecl>(Val: D)->isLambda() && |
6161 | cast<CXXRecordDecl>(Val: D)->getTemplateDepth() > |
6162 | TemplateArgs.getNumRetainedOuterLevels())) { |
6163 | // D is a local of some kind. Look into the map of local |
6164 | // declarations to their instantiations. |
6165 | if (CurrentInstantiationScope) { |
6166 | if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) { |
6167 | if (Decl *FD = Found->dyn_cast<Decl *>()) |
6168 | return cast<NamedDecl>(Val: FD); |
6169 | |
6170 | int PackIdx = ArgumentPackSubstitutionIndex; |
6171 | assert(PackIdx != -1 && |
6172 | "found declaration pack but not pack expanding" ); |
6173 | typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack; |
6174 | return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]); |
6175 | } |
6176 | } |
6177 | |
6178 | // If we're performing a partial substitution during template argument |
6179 | // deduction, we may not have values for template parameters yet. They |
6180 | // just map to themselves. |
6181 | if (isa<NonTypeTemplateParmDecl>(Val: D) || isa<TemplateTypeParmDecl>(Val: D) || |
6182 | isa<TemplateTemplateParmDecl>(Val: D)) |
6183 | return D; |
6184 | |
6185 | if (D->isInvalidDecl()) |
6186 | return nullptr; |
6187 | |
6188 | // Normally this function only searches for already instantiated declaration |
6189 | // however we have to make an exclusion for local types used before |
6190 | // definition as in the code: |
6191 | // |
6192 | // template<typename T> void f1() { |
6193 | // void g1(struct x1); |
6194 | // struct x1 {}; |
6195 | // } |
6196 | // |
6197 | // In this case instantiation of the type of 'g1' requires definition of |
6198 | // 'x1', which is defined later. Error recovery may produce an enum used |
6199 | // before definition. In these cases we need to instantiate relevant |
6200 | // declarations here. |
6201 | bool NeedInstantiate = false; |
6202 | if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: D)) |
6203 | NeedInstantiate = RD->isLocalClass(); |
6204 | else if (isa<TypedefNameDecl>(Val: D) && |
6205 | isa<CXXDeductionGuideDecl>(D->getDeclContext())) |
6206 | NeedInstantiate = true; |
6207 | else |
6208 | NeedInstantiate = isa<EnumDecl>(Val: D); |
6209 | if (NeedInstantiate) { |
6210 | Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); |
6211 | CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
6212 | return cast<TypeDecl>(Val: Inst); |
6213 | } |
6214 | |
6215 | // If we didn't find the decl, then we must have a label decl that hasn't |
6216 | // been found yet. Lazily instantiate it and return it now. |
6217 | assert(isa<LabelDecl>(D)); |
6218 | |
6219 | Decl *Inst = SubstDecl(D, CurContext, TemplateArgs); |
6220 | assert(Inst && "Failed to instantiate label??" ); |
6221 | |
6222 | CurrentInstantiationScope->InstantiatedLocal(D, Inst); |
6223 | return cast<LabelDecl>(Val: Inst); |
6224 | } |
6225 | |
6226 | if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: D)) { |
6227 | if (!Record->isDependentContext()) |
6228 | return D; |
6229 | |
6230 | // Determine whether this record is the "templated" declaration describing |
6231 | // a class template or class template specialization. |
6232 | ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate(); |
6233 | if (ClassTemplate) |
6234 | ClassTemplate = ClassTemplate->getCanonicalDecl(); |
6235 | else if (ClassTemplateSpecializationDecl *Spec = |
6236 | dyn_cast<ClassTemplateSpecializationDecl>(Val: Record)) |
6237 | ClassTemplate = Spec->getSpecializedTemplate()->getCanonicalDecl(); |
6238 | |
6239 | // Walk the current context to find either the record or an instantiation of |
6240 | // it. |
6241 | DeclContext *DC = CurContext; |
6242 | while (!DC->isFileContext()) { |
6243 | // If we're performing substitution while we're inside the template |
6244 | // definition, we'll find our own context. We're done. |
6245 | if (DC->Equals(Record)) |
6246 | return Record; |
6247 | |
6248 | if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(Val: DC)) { |
6249 | // Check whether we're in the process of instantiating a class template |
6250 | // specialization of the template we're mapping. |
6251 | if (ClassTemplateSpecializationDecl *InstSpec |
6252 | = dyn_cast<ClassTemplateSpecializationDecl>(Val: InstRecord)){ |
6253 | ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate(); |
6254 | if (ClassTemplate && isInstantiationOf(Pattern: ClassTemplate, Instance: SpecTemplate)) |
6255 | return InstRecord; |
6256 | } |
6257 | |
6258 | // Check whether we're in the process of instantiating a member class. |
6259 | if (isInstantiationOf(Pattern: Record, Instance: InstRecord)) |
6260 | return InstRecord; |
6261 | } |
6262 | |
6263 | // Move to the outer template scope. |
6264 | if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: DC)) { |
6265 | if (FD->getFriendObjectKind() && |
6266 | FD->getNonTransparentDeclContext()->isFileContext()) { |
6267 | DC = FD->getLexicalDeclContext(); |
6268 | continue; |
6269 | } |
6270 | // An implicit deduction guide acts as if it's within the class template |
6271 | // specialization described by its name and first N template params. |
6272 | auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: FD); |
6273 | if (Guide && Guide->isImplicit()) { |
6274 | TemplateDecl *TD = Guide->getDeducedTemplate(); |
6275 | // Convert the arguments to an "as-written" list. |
6276 | TemplateArgumentListInfo Args(Loc, Loc); |
6277 | for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front( |
6278 | N: TD->getTemplateParameters()->size())) { |
6279 | ArrayRef<TemplateArgument> Unpacked(Arg); |
6280 | if (Arg.getKind() == TemplateArgument::Pack) |
6281 | Unpacked = Arg.pack_elements(); |
6282 | for (TemplateArgument UnpackedArg : Unpacked) |
6283 | Args.addArgument( |
6284 | Loc: getTrivialTemplateArgumentLoc(Arg: UnpackedArg, NTTPType: QualType(), Loc)); |
6285 | } |
6286 | QualType T = CheckTemplateIdType(Template: TemplateName(TD), TemplateLoc: Loc, TemplateArgs&: Args); |
6287 | if (T.isNull()) |
6288 | return nullptr; |
6289 | auto *SubstRecord = T->getAsCXXRecordDecl(); |
6290 | assert(SubstRecord && "class template id not a class type?" ); |
6291 | // Check that this template-id names the primary template and not a |
6292 | // partial or explicit specialization. (In the latter cases, it's |
6293 | // meaningless to attempt to find an instantiation of D within the |
6294 | // specialization.) |
6295 | // FIXME: The standard doesn't say what should happen here. |
6296 | if (FindingInstantiatedContext && |
6297 | usesPartialOrExplicitSpecialization( |
6298 | Loc, ClassTemplateSpec: cast<ClassTemplateSpecializationDecl>(Val: SubstRecord))) { |
6299 | Diag(Loc, diag::err_specialization_not_primary_template) |
6300 | << T << (SubstRecord->getTemplateSpecializationKind() == |
6301 | TSK_ExplicitSpecialization); |
6302 | return nullptr; |
6303 | } |
6304 | DC = SubstRecord; |
6305 | continue; |
6306 | } |
6307 | } |
6308 | |
6309 | DC = DC->getParent(); |
6310 | } |
6311 | |
6312 | // Fall through to deal with other dependent record types (e.g., |
6313 | // anonymous unions in class templates). |
6314 | } |
6315 | |
6316 | if (!ParentDependsOnArgs) |
6317 | return D; |
6318 | |
6319 | ParentDC = FindInstantiatedContext(Loc, DC: ParentDC, TemplateArgs); |
6320 | if (!ParentDC) |
6321 | return nullptr; |
6322 | |
6323 | if (ParentDC != D->getDeclContext()) { |
6324 | // We performed some kind of instantiation in the parent context, |
6325 | // so now we need to look into the instantiated parent context to |
6326 | // find the instantiation of the declaration D. |
6327 | |
6328 | // If our context used to be dependent, we may need to instantiate |
6329 | // it before performing lookup into that context. |
6330 | bool IsBeingInstantiated = false; |
6331 | if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(Val: ParentDC)) { |
6332 | if (!Spec->isDependentContext()) { |
6333 | QualType T = Context.getTypeDeclType(Spec); |
6334 | const RecordType *Tag = T->getAs<RecordType>(); |
6335 | assert(Tag && "type of non-dependent record is not a RecordType" ); |
6336 | if (Tag->isBeingDefined()) |
6337 | IsBeingInstantiated = true; |
6338 | if (!Tag->isBeingDefined() && |
6339 | RequireCompleteType(Loc, T, diag::err_incomplete_type)) |
6340 | return nullptr; |
6341 | |
6342 | ParentDC = Tag->getDecl(); |
6343 | } |
6344 | } |
6345 | |
6346 | NamedDecl *Result = nullptr; |
6347 | // FIXME: If the name is a dependent name, this lookup won't necessarily |
6348 | // find it. Does that ever matter? |
6349 | if (auto Name = D->getDeclName()) { |
6350 | DeclarationNameInfo NameInfo(Name, D->getLocation()); |
6351 | DeclarationNameInfo NewNameInfo = |
6352 | SubstDeclarationNameInfo(NameInfo, TemplateArgs); |
6353 | Name = NewNameInfo.getName(); |
6354 | if (!Name) |
6355 | return nullptr; |
6356 | DeclContext::lookup_result Found = ParentDC->lookup(Name); |
6357 | |
6358 | Result = findInstantiationOf(Ctx&: Context, D, first: Found.begin(), last: Found.end()); |
6359 | } else { |
6360 | // Since we don't have a name for the entity we're looking for, |
6361 | // our only option is to walk through all of the declarations to |
6362 | // find that name. This will occur in a few cases: |
6363 | // |
6364 | // - anonymous struct/union within a template |
6365 | // - unnamed class/struct/union/enum within a template |
6366 | // |
6367 | // FIXME: Find a better way to find these instantiations! |
6368 | Result = findInstantiationOf(Ctx&: Context, D, |
6369 | first: ParentDC->decls_begin(), |
6370 | last: ParentDC->decls_end()); |
6371 | } |
6372 | |
6373 | if (!Result) { |
6374 | if (isa<UsingShadowDecl>(Val: D)) { |
6375 | // UsingShadowDecls can instantiate to nothing because of using hiding. |
6376 | } else if (hasUncompilableErrorOccurred()) { |
6377 | // We've already complained about some ill-formed code, so most likely |
6378 | // this declaration failed to instantiate. There's no point in |
6379 | // complaining further, since this is normal in invalid code. |
6380 | // FIXME: Use more fine-grained 'invalid' tracking for this. |
6381 | } else if (IsBeingInstantiated) { |
6382 | // The class in which this member exists is currently being |
6383 | // instantiated, and we haven't gotten around to instantiating this |
6384 | // member yet. This can happen when the code uses forward declarations |
6385 | // of member classes, and introduces ordering dependencies via |
6386 | // template instantiation. |
6387 | Diag(Loc, diag::err_member_not_yet_instantiated) |
6388 | << D->getDeclName() |
6389 | << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC)); |
6390 | Diag(D->getLocation(), diag::note_non_instantiated_member_here); |
6391 | } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(Val: D)) { |
6392 | // This enumeration constant was found when the template was defined, |
6393 | // but can't be found in the instantiation. This can happen if an |
6394 | // unscoped enumeration member is explicitly specialized. |
6395 | EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext()); |
6396 | EnumDecl *Spec = cast<EnumDecl>(Val: FindInstantiatedDecl(Loc, Enum, |
6397 | TemplateArgs)); |
6398 | assert(Spec->getTemplateSpecializationKind() == |
6399 | TSK_ExplicitSpecialization); |
6400 | Diag(Loc, diag::err_enumerator_does_not_exist) |
6401 | << D->getDeclName() |
6402 | << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext())); |
6403 | Diag(Spec->getLocation(), diag::note_enum_specialized_here) |
6404 | << Context.getTypeDeclType(Spec); |
6405 | } else { |
6406 | // We should have found something, but didn't. |
6407 | llvm_unreachable("Unable to find instantiation of declaration!" ); |
6408 | } |
6409 | } |
6410 | |
6411 | D = Result; |
6412 | } |
6413 | |
6414 | return D; |
6415 | } |
6416 | |
6417 | /// Performs template instantiation for all implicit template |
6418 | /// instantiations we have seen until this point. |
6419 | void Sema::PerformPendingInstantiations(bool LocalOnly) { |
6420 | std::deque<PendingImplicitInstantiation> delayedPCHInstantiations; |
6421 | while (!PendingLocalImplicitInstantiations.empty() || |
6422 | (!LocalOnly && !PendingInstantiations.empty())) { |
6423 | PendingImplicitInstantiation Inst; |
6424 | |
6425 | if (PendingLocalImplicitInstantiations.empty()) { |
6426 | Inst = PendingInstantiations.front(); |
6427 | PendingInstantiations.pop_front(); |
6428 | } else { |
6429 | Inst = PendingLocalImplicitInstantiations.front(); |
6430 | PendingLocalImplicitInstantiations.pop_front(); |
6431 | } |
6432 | |
6433 | // Instantiate function definitions |
6434 | if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Val: Inst.first)) { |
6435 | bool DefinitionRequired = Function->getTemplateSpecializationKind() == |
6436 | TSK_ExplicitInstantiationDefinition; |
6437 | if (Function->isMultiVersion()) { |
6438 | getASTContext().forEachMultiversionedFunctionVersion( |
6439 | FD: Function, Pred: [this, Inst, DefinitionRequired](FunctionDecl *CurFD) { |
6440 | InstantiateFunctionDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Function: CurFD, Recursive: true, |
6441 | DefinitionRequired, AtEndOfTU: true); |
6442 | if (CurFD->isDefined()) |
6443 | CurFD->setInstantiationIsPending(false); |
6444 | }); |
6445 | } else { |
6446 | InstantiateFunctionDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Function, Recursive: true, |
6447 | DefinitionRequired, AtEndOfTU: true); |
6448 | if (Function->isDefined()) |
6449 | Function->setInstantiationIsPending(false); |
6450 | } |
6451 | // Definition of a PCH-ed template declaration may be available only in the TU. |
6452 | if (!LocalOnly && LangOpts.PCHInstantiateTemplates && |
6453 | TUKind == TU_Prefix && Function->instantiationIsPending()) |
6454 | delayedPCHInstantiations.push_back(x: Inst); |
6455 | continue; |
6456 | } |
6457 | |
6458 | // Instantiate variable definitions |
6459 | VarDecl *Var = cast<VarDecl>(Val: Inst.first); |
6460 | |
6461 | assert((Var->isStaticDataMember() || |
6462 | isa<VarTemplateSpecializationDecl>(Var)) && |
6463 | "Not a static data member, nor a variable template" |
6464 | " specialization?" ); |
6465 | |
6466 | // Don't try to instantiate declarations if the most recent redeclaration |
6467 | // is invalid. |
6468 | if (Var->getMostRecentDecl()->isInvalidDecl()) |
6469 | continue; |
6470 | |
6471 | // Check if the most recent declaration has changed the specialization kind |
6472 | // and removed the need for implicit instantiation. |
6473 | switch (Var->getMostRecentDecl() |
6474 | ->getTemplateSpecializationKindForInstantiation()) { |
6475 | case TSK_Undeclared: |
6476 | llvm_unreachable("Cannot instantitiate an undeclared specialization." ); |
6477 | case TSK_ExplicitInstantiationDeclaration: |
6478 | case TSK_ExplicitSpecialization: |
6479 | continue; // No longer need to instantiate this type. |
6480 | case TSK_ExplicitInstantiationDefinition: |
6481 | // We only need an instantiation if the pending instantiation *is* the |
6482 | // explicit instantiation. |
6483 | if (Var != Var->getMostRecentDecl()) |
6484 | continue; |
6485 | break; |
6486 | case TSK_ImplicitInstantiation: |
6487 | break; |
6488 | } |
6489 | |
6490 | PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(), |
6491 | "instantiating variable definition" ); |
6492 | bool DefinitionRequired = Var->getTemplateSpecializationKind() == |
6493 | TSK_ExplicitInstantiationDefinition; |
6494 | |
6495 | // Instantiate static data member definitions or variable template |
6496 | // specializations. |
6497 | InstantiateVariableDefinition(/*FIXME:*/ PointOfInstantiation: Inst.second, Var, Recursive: true, |
6498 | DefinitionRequired, AtEndOfTU: true); |
6499 | } |
6500 | |
6501 | if (!LocalOnly && LangOpts.PCHInstantiateTemplates) |
6502 | PendingInstantiations.swap(x&: delayedPCHInstantiations); |
6503 | } |
6504 | |
6505 | void Sema::PerformDependentDiagnostics(const DeclContext *Pattern, |
6506 | const MultiLevelTemplateArgumentList &TemplateArgs) { |
6507 | for (auto *DD : Pattern->ddiags()) { |
6508 | switch (DD->getKind()) { |
6509 | case DependentDiagnostic::Access: |
6510 | HandleDependentAccessCheck(DD: *DD, TemplateArgs); |
6511 | break; |
6512 | } |
6513 | } |
6514 | } |
6515 | |