Bug Summary

File:src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
Warning:line 6189, column 13
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiateDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include/clang/Sema -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../include -I /usr/src/gnu/usr.bin/clang/libclangSema/obj -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp

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

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
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//
9// This file defines the Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TemplateParameterList;
70class TranslationUnitDecl;
71class UsingDirectiveDecl;
72
73/// Captures the result of checking the availability of a
74/// declaration.
75enum AvailabilityResult {
76 AR_Available = 0,
77 AR_NotYetIntroduced,
78 AR_Deprecated,
79 AR_Unavailable
80};
81
82/// Decl - This represents one declaration (or definition), e.g. a variable,
83/// typedef, function, struct, etc.
84///
85/// Note: There are objects tacked on before the *beginning* of Decl
86/// (and its subclasses) in its Decl::operator new(). Proper alignment
87/// of all subclasses (not requiring more than the alignment of Decl) is
88/// asserted in DeclBase.cpp.
89class alignas(8) Decl {
90public:
91 /// Lists the kind of concrete classes of Decl.
92 enum Kind {
93#define DECL(DERIVED, BASE) DERIVED,
94#define ABSTRACT_DECL(DECL)
95#define DECL_RANGE(BASE, START, END) \
96 first##BASE = START, last##BASE = END,
97#define LAST_DECL_RANGE(BASE, START, END) \
98 first##BASE = START, last##BASE = END
99#include "clang/AST/DeclNodes.inc"
100 };
101
102 /// A placeholder type used to construct an empty shell of a
103 /// decl-derived type that will be filled in later (e.g., by some
104 /// deserialization method).
105 struct EmptyShell {};
106
107 /// IdentifierNamespace - The different namespaces in which
108 /// declarations may appear. According to C99 6.2.3, there are
109 /// four namespaces, labels, tags, members and ordinary
110 /// identifiers. C++ describes lookup completely differently:
111 /// certain lookups merely "ignore" certain kinds of declarations,
112 /// usually based on whether the declaration is of a type, etc.
113 ///
114 /// These are meant as bitmasks, so that searches in
115 /// C++ can look into the "tag" namespace during ordinary lookup.
116 ///
117 /// Decl currently provides 15 bits of IDNS bits.
118 enum IdentifierNamespace {
119 /// Labels, declared with 'x:' and referenced with 'goto x'.
120 IDNS_Label = 0x0001,
121
122 /// Tags, declared with 'struct foo;' and referenced with
123 /// 'struct foo'. All tags are also types. This is what
124 /// elaborated-type-specifiers look for in C.
125 /// This also contains names that conflict with tags in the
126 /// same scope but that are otherwise ordinary names (non-type
127 /// template parameters and indirect field declarations).
128 IDNS_Tag = 0x0002,
129
130 /// Types, declared with 'struct foo', typedefs, etc.
131 /// This is what elaborated-type-specifiers look for in C++,
132 /// but note that it's ill-formed to find a non-tag.
133 IDNS_Type = 0x0004,
134
135 /// Members, declared with object declarations within tag
136 /// definitions. In C, these can only be found by "qualified"
137 /// lookup in member expressions. In C++, they're found by
138 /// normal lookup.
139 IDNS_Member = 0x0008,
140
141 /// Namespaces, declared with 'namespace foo {}'.
142 /// Lookup for nested-name-specifiers find these.
143 IDNS_Namespace = 0x0010,
144
145 /// Ordinary names. In C, everything that's not a label, tag,
146 /// member, or function-local extern ends up here.
147 IDNS_Ordinary = 0x0020,
148
149 /// Objective C \@protocol.
150 IDNS_ObjCProtocol = 0x0040,
151
152 /// This declaration is a friend function. A friend function
153 /// declaration is always in this namespace but may also be in
154 /// IDNS_Ordinary if it was previously declared.
155 IDNS_OrdinaryFriend = 0x0080,
156
157 /// This declaration is a friend class. A friend class
158 /// declaration is always in this namespace but may also be in
159 /// IDNS_Tag|IDNS_Type if it was previously declared.
160 IDNS_TagFriend = 0x0100,
161
162 /// This declaration is a using declaration. A using declaration
163 /// *introduces* a number of other declarations into the current
164 /// scope, and those declarations use the IDNS of their targets,
165 /// but the actual using declarations go in this namespace.
166 IDNS_Using = 0x0200,
167
168 /// This declaration is a C++ operator declared in a non-class
169 /// context. All such operators are also in IDNS_Ordinary.
170 /// C++ lexical operator lookup looks for these.
171 IDNS_NonMemberOperator = 0x0400,
172
173 /// This declaration is a function-local extern declaration of a
174 /// variable or function. This may also be IDNS_Ordinary if it
175 /// has been declared outside any function. These act mostly like
176 /// invisible friend declarations, but are also visible to unqualified
177 /// lookup within the scope of the declaring function.
178 IDNS_LocalExtern = 0x0800,
179
180 /// This declaration is an OpenMP user defined reduction construction.
181 IDNS_OMPReduction = 0x1000,
182
183 /// This declaration is an OpenMP user defined mapper.
184 IDNS_OMPMapper = 0x2000,
185 };
186
187 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
188 /// parameter types in method declarations. Other than remembering
189 /// them and mangling them into the method's signature string, these
190 /// are ignored by the compiler; they are consumed by certain
191 /// remote-messaging frameworks.
192 ///
193 /// in, inout, and out are mutually exclusive and apply only to
194 /// method parameters. bycopy and byref are mutually exclusive and
195 /// apply only to method parameters (?). oneway applies only to
196 /// results. All of these expect their corresponding parameter to
197 /// have a particular type. None of this is currently enforced by
198 /// clang.
199 ///
200 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
201 enum ObjCDeclQualifier {
202 OBJC_TQ_None = 0x0,
203 OBJC_TQ_In = 0x1,
204 OBJC_TQ_Inout = 0x2,
205 OBJC_TQ_Out = 0x4,
206 OBJC_TQ_Bycopy = 0x8,
207 OBJC_TQ_Byref = 0x10,
208 OBJC_TQ_Oneway = 0x20,
209
210 /// The nullability qualifier is set when the nullability of the
211 /// result or parameter was expressed via a context-sensitive
212 /// keyword.
213 OBJC_TQ_CSNullability = 0x40
214 };
215
216 /// The kind of ownership a declaration has, for visibility purposes.
217 /// This enumeration is designed such that higher values represent higher
218 /// levels of name hiding.
219 enum class ModuleOwnershipKind : unsigned {
220 /// This declaration is not owned by a module.
221 Unowned,
222
223 /// This declaration has an owning module, but is globally visible
224 /// (typically because its owning module is visible and we know that
225 /// modules cannot later become hidden in this compilation).
226 /// After serialization and deserialization, this will be converted
227 /// to VisibleWhenImported.
228 Visible,
229
230 /// This declaration has an owning module, and is visible when that
231 /// module is imported.
232 VisibleWhenImported,
233
234 /// This declaration has an owning module, but is only visible to
235 /// lookups that occur within that module.
236 ModulePrivate
237 };
238
239protected:
240 /// The next declaration within the same lexical
241 /// DeclContext. These pointers form the linked list that is
242 /// traversed via DeclContext's decls_begin()/decls_end().
243 ///
244 /// The extra two bits are used for the ModuleOwnershipKind.
245 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
246
247private:
248 friend class DeclContext;
249
250 struct MultipleDC {
251 DeclContext *SemanticDC;
252 DeclContext *LexicalDC;
253 };
254
255 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
256 /// For declarations that don't contain C++ scope specifiers, it contains
257 /// the DeclContext where the Decl was declared.
258 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
259 /// with the context where it semantically belongs (SemanticDC) and the
260 /// context where it was lexically declared (LexicalDC).
261 /// e.g.:
262 ///
263 /// namespace A {
264 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
265 /// }
266 /// void A::f(); // SemanticDC == namespace 'A'
267 /// // LexicalDC == global namespace
268 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
269
270 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
3
Calling 'PointerUnion::is'
6
Returning from 'PointerUnion::is'
7
Returning zero, which participates in a condition later
271 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
272
273 MultipleDC *getMultipleDC() const {
274 return DeclCtx.get<MultipleDC*>();
275 }
276
277 DeclContext *getSemanticDC() const {
278 return DeclCtx.get<DeclContext*>();
279 }
280
281 /// Loc - The location of this decl.
282 SourceLocation Loc;
283
284 /// DeclKind - This indicates which class this is.
285 unsigned DeclKind : 7;
286
287 /// InvalidDecl - This indicates a semantic error occurred.
288 unsigned InvalidDecl : 1;
289
290 /// HasAttrs - This indicates whether the decl has attributes or not.
291 unsigned HasAttrs : 1;
292
293 /// Implicit - Whether this declaration was implicitly generated by
294 /// the implementation rather than explicitly written by the user.
295 unsigned Implicit : 1;
296
297 /// Whether this declaration was "used", meaning that a definition is
298 /// required.
299 unsigned Used : 1;
300
301 /// Whether this declaration was "referenced".
302 /// The difference with 'Used' is whether the reference appears in a
303 /// evaluated context or not, e.g. functions used in uninstantiated templates
304 /// are regarded as "referenced" but not "used".
305 unsigned Referenced : 1;
306
307 /// Whether this declaration is a top-level declaration (function,
308 /// global variable, etc.) that is lexically inside an objc container
309 /// definition.
310 unsigned TopLevelDeclInObjCContainer : 1;
311
312 /// Whether statistic collection is enabled.
313 static bool StatisticsEnabled;
314
315protected:
316 friend class ASTDeclReader;
317 friend class ASTDeclWriter;
318 friend class ASTNodeImporter;
319 friend class ASTReader;
320 friend class CXXClassMemberWrapper;
321 friend class LinkageComputer;
322 template<typename decl_type> friend class Redeclarable;
323
324 /// Access - Used by C++ decls for the access specifier.
325 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
326 unsigned Access : 2;
327
328 /// Whether this declaration was loaded from an AST file.
329 unsigned FromASTFile : 1;
330
331 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
332 unsigned IdentifierNamespace : 14;
333
334 /// If 0, we have not computed the linkage of this declaration.
335 /// Otherwise, it is the linkage + 1.
336 mutable unsigned CacheValidAndLinkage : 3;
337
338 /// Allocate memory for a deserialized declaration.
339 ///
340 /// This routine must be used to allocate memory for any declaration that is
341 /// deserialized from a module file.
342 ///
343 /// \param Size The size of the allocated object.
344 /// \param Ctx The context in which we will allocate memory.
345 /// \param ID The global ID of the deserialized declaration.
346 /// \param Extra The amount of extra space to allocate after the object.
347 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
348 std::size_t Extra = 0);
349
350 /// Allocate memory for a non-deserialized declaration.
351 void *operator new(std::size_t Size, const ASTContext &Ctx,
352 DeclContext *Parent, std::size_t Extra = 0);
353
354private:
355 bool AccessDeclContextSanity() const;
356
357 /// Get the module ownership kind to use for a local lexical child of \p DC,
358 /// which may be either a local or (rarely) an imported declaration.
359 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
360 if (DC) {
361 auto *D = cast<Decl>(DC);
362 auto MOK = D->getModuleOwnershipKind();
363 if (MOK != ModuleOwnershipKind::Unowned &&
364 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
365 return MOK;
366 // If D is not local and we have no local module storage, then we don't
367 // need to track module ownership at all.
368 }
369 return ModuleOwnershipKind::Unowned;
370 }
371
372public:
373 Decl() = delete;
374 Decl(const Decl&) = delete;
375 Decl(Decl &&) = delete;
376 Decl &operator=(const Decl&) = delete;
377 Decl &operator=(Decl&&) = delete;
378
379protected:
380 Decl(Kind DK, DeclContext *DC, SourceLocation L)
381 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
382 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
383 Implicit(false), Used(false), Referenced(false),
384 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
385 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
386 CacheValidAndLinkage(0) {
387 if (StatisticsEnabled) add(DK);
388 }
389
390 Decl(Kind DK, EmptyShell Empty)
391 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
392 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
393 Access(AS_none), FromASTFile(0),
394 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
395 CacheValidAndLinkage(0) {
396 if (StatisticsEnabled) add(DK);
397 }
398
399 virtual ~Decl();
400
401 /// Update a potentially out-of-date declaration.
402 void updateOutOfDate(IdentifierInfo &II) const;
403
404 Linkage getCachedLinkage() const {
405 return Linkage(CacheValidAndLinkage - 1);
406 }
407
408 void setCachedLinkage(Linkage L) const {
409 CacheValidAndLinkage = L + 1;
410 }
411
412 bool hasCachedLinkage() const {
413 return CacheValidAndLinkage;
414 }
415
416public:
417 /// Source range that this declaration covers.
418 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
419 return SourceRange(getLocation(), getLocation());
420 }
421
422 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
423 return getSourceRange().getBegin();
424 }
425
426 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
427 return getSourceRange().getEnd();
428 }
429
430 SourceLocation getLocation() const { return Loc; }
431 void setLocation(SourceLocation L) { Loc = L; }
432
433 Kind getKind() const { return static_cast<Kind>(DeclKind); }
434 const char *getDeclKindName() const;
435
436 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
437 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
438
439 DeclContext *getDeclContext() {
440 if (isInSemaDC())
2
Calling 'Decl::isInSemaDC'
8
Returning from 'Decl::isInSemaDC'
9
Taking false branch
441 return getSemanticDC();
442 return getMultipleDC()->SemanticDC;
10
Returning pointer, which participates in a condition later
443 }
444 const DeclContext *getDeclContext() const {
445 return const_cast<Decl*>(this)->getDeclContext();
446 }
447
448 /// Find the innermost non-closure ancestor of this declaration,
449 /// walking up through blocks, lambdas, etc. If that ancestor is
450 /// not a code context (!isFunctionOrMethod()), returns null.
451 ///
452 /// A declaration may be its own non-closure context.
453 Decl *getNonClosureContext();
454 const Decl *getNonClosureContext() const {
455 return const_cast<Decl*>(this)->getNonClosureContext();
456 }
457
458 TranslationUnitDecl *getTranslationUnitDecl();
459 const TranslationUnitDecl *getTranslationUnitDecl() const {
460 return const_cast<Decl*>(this)->getTranslationUnitDecl();
461 }
462
463 bool isInAnonymousNamespace() const;
464
465 bool isInStdNamespace() const;
466
467 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
468
469 /// Helper to get the language options from the ASTContext.
470 /// Defined out of line to avoid depending on ASTContext.h.
471 const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__));
472
473 void setAccess(AccessSpecifier AS) {
474 Access = AS;
475 assert(AccessDeclContextSanity())((void)0);
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())((void)0);
480 return AccessSpecifier(Access);
481 }
482
483 /// Retrieve the access specifier for this declaration, even though
484 /// it may not yet have been properly set.
485 AccessSpecifier getAccessUnsafe() const {
486 return AccessSpecifier(Access);
487 }
488
489 bool hasAttrs() const { return HasAttrs; }
490
491 void setAttrs(const AttrVec& Attrs) {
492 return setAttrsImpl(Attrs, getASTContext());
493 }
494
495 AttrVec &getAttrs() {
496 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
497 }
498
499 const AttrVec &getAttrs() const;
500 void dropAttrs();
501 void addAttr(Attr *A);
502
503 using attr_iterator = AttrVec::const_iterator;
504 using attr_range = llvm::iterator_range<attr_iterator>;
505
506 attr_range attrs() const {
507 return attr_range(attr_begin(), attr_end());
508 }
509
510 attr_iterator attr_begin() const {
511 return hasAttrs() ? getAttrs().begin() : nullptr;
512 }
513 attr_iterator attr_end() const {
514 return hasAttrs() ? getAttrs().end() : nullptr;
515 }
516
517 template <typename T>
518 void dropAttr() {
519 if (!HasAttrs) return;
520
521 AttrVec &Vec = getAttrs();
522 llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
523
524 if (Vec.empty())
525 HasAttrs = false;
526 }
527
528 template <typename T>
529 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
530 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_begin() const {
535 return specific_attr_iterator<T>(attr_begin());
536 }
537
538 template <typename T>
539 specific_attr_iterator<T> specific_attr_end() const {
540 return specific_attr_iterator<T>(attr_end());
541 }
542
543 template<typename T> T *getAttr() const {
544 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
545 }
546
547 template<typename T> bool hasAttr() const {
548 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
549 }
550
551 /// getMaxAlignment - return the maximum alignment specified by attributes
552 /// on this decl, 0 if there are none.
553 unsigned getMaxAlignment() const;
554
555 /// setInvalidDecl - Indicates the Decl had a semantic error. This
556 /// allows for graceful error recovery.
557 void setInvalidDecl(bool Invalid = true);
558 bool isInvalidDecl() const { return (bool) InvalidDecl; }
559
560 /// isImplicit - Indicates whether the declaration was implicitly
561 /// generated by the implementation. If false, this declaration
562 /// was written explicitly in the source code.
563 bool isImplicit() const { return Implicit; }
564 void setImplicit(bool I = true) { Implicit = I; }
565
566 /// Whether *any* (re-)declaration of the entity was used, meaning that
567 /// a definition is required.
568 ///
569 /// \param CheckUsedAttr When true, also consider the "used" attribute
570 /// (in addition to the "used" bit set by \c setUsed()) when determining
571 /// whether the function is used.
572 bool isUsed(bool CheckUsedAttr = true) const;
573
574 /// Set whether the declaration is used, in the sense of odr-use.
575 ///
576 /// This should only be used immediately after creating a declaration.
577 /// It intentionally doesn't notify any listeners.
578 void setIsUsed() { getCanonicalDecl()->Used = true; }
579
580 /// Mark the declaration used, in the sense of odr-use.
581 ///
582 /// This notifies any mutation listeners in addition to setting a bit
583 /// indicating the declaration is used.
584 void markUsed(ASTContext &C);
585
586 /// Whether any declaration of this entity was referenced.
587 bool isReferenced() const;
588
589 /// Whether this declaration was referenced. This should not be relied
590 /// upon for anything other than debugging.
591 bool isThisDeclarationReferenced() const { return Referenced; }
592
593 void setReferenced(bool R = true) { Referenced = R; }
594
595 /// Whether this declaration is a top-level declaration (function,
596 /// global variable, etc.) that is lexically inside an objc container
597 /// definition.
598 bool isTopLevelDeclInObjCContainer() const {
599 return TopLevelDeclInObjCContainer;
600 }
601
602 void setTopLevelDeclInObjCContainer(bool V = true) {
603 TopLevelDeclInObjCContainer = V;
604 }
605
606 /// Looks on this and related declarations for an applicable
607 /// external source symbol attribute.
608 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
609
610 /// Whether this declaration was marked as being private to the
611 /// module in which it was defined.
612 bool isModulePrivate() const {
613 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
614 }
615
616 /// Return true if this declaration has an attribute which acts as
617 /// definition of the entity, such as 'alias' or 'ifunc'.
618 bool hasDefiningAttr() const;
619
620 /// Return this declaration's defining attribute if it has one.
621 const Attr *getDefiningAttr() const;
622
623protected:
624 /// Specify that this declaration was marked as being private
625 /// to the module in which it was defined.
626 void setModulePrivate() {
627 // The module-private specifier has no effect on unowned declarations.
628 // FIXME: We should track this in some way for source fidelity.
629 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
630 return;
631 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
632 }
633
634public:
635 /// Set the FromASTFile flag. This indicates that this declaration
636 /// was deserialized and not parsed from source code and enables
637 /// features such as module ownership information.
638 void setFromASTFile() {
639 FromASTFile = true;
640 }
641
642 /// Set the owning module ID. This may only be called for
643 /// deserialized Decls.
644 void setOwningModuleID(unsigned ID) {
645 assert(isFromASTFile() && "Only works on a deserialized declaration")((void)0);
646 *((unsigned*)this - 2) = ID;
647 }
648
649public:
650 /// Determine the availability of the given declaration.
651 ///
652 /// This routine will determine the most restrictive availability of
653 /// the given declaration (e.g., preferring 'unavailable' to
654 /// 'deprecated').
655 ///
656 /// \param Message If non-NULL and the result is not \c
657 /// AR_Available, will be set to a (possibly empty) message
658 /// describing why the declaration has not been introduced, is
659 /// deprecated, or is unavailable.
660 ///
661 /// \param EnclosingVersion The version to compare with. If empty, assume the
662 /// deployment target version.
663 ///
664 /// \param RealizedPlatform If non-NULL and the availability result is found
665 /// in an available attribute it will set to the platform which is written in
666 /// the available attribute.
667 AvailabilityResult
668 getAvailability(std::string *Message = nullptr,
669 VersionTuple EnclosingVersion = VersionTuple(),
670 StringRef *RealizedPlatform = nullptr) const;
671
672 /// Retrieve the version of the target platform in which this
673 /// declaration was introduced.
674 ///
675 /// \returns An empty version tuple if this declaration has no 'introduced'
676 /// availability attributes, or the version tuple that's specified in the
677 /// attribute otherwise.
678 VersionTuple getVersionIntroduced() const;
679
680 /// Determine whether this declaration is marked 'deprecated'.
681 ///
682 /// \param Message If non-NULL and the declaration is deprecated,
683 /// this will be set to the message describing why the declaration
684 /// was deprecated (which may be empty).
685 bool isDeprecated(std::string *Message = nullptr) const {
686 return getAvailability(Message) == AR_Deprecated;
687 }
688
689 /// Determine whether this declaration is marked 'unavailable'.
690 ///
691 /// \param Message If non-NULL and the declaration is unavailable,
692 /// this will be set to the message describing why the declaration
693 /// was made unavailable (which may be empty).
694 bool isUnavailable(std::string *Message = nullptr) const {
695 return getAvailability(Message) == AR_Unavailable;
696 }
697
698 /// Determine whether this is a weak-imported symbol.
699 ///
700 /// Weak-imported symbols are typically marked with the
701 /// 'weak_import' attribute, but may also be marked with an
702 /// 'availability' attribute where we're targing a platform prior to
703 /// the introduction of this feature.
704 bool isWeakImported() const;
705
706 /// Determines whether this symbol can be weak-imported,
707 /// e.g., whether it would be well-formed to add the weak_import
708 /// attribute.
709 ///
710 /// \param IsDefinition Set to \c true to indicate that this
711 /// declaration cannot be weak-imported because it has a definition.
712 bool canBeWeakImported(bool &IsDefinition) const;
713
714 /// Determine whether this declaration came from an AST file (such as
715 /// a precompiled header or module) rather than having been parsed.
716 bool isFromASTFile() const { return FromASTFile; }
717
718 /// Retrieve the global declaration ID associated with this
719 /// declaration, which specifies where this Decl was loaded from.
720 unsigned getGlobalID() const {
721 if (isFromASTFile())
722 return *((const unsigned*)this - 1);
723 return 0;
724 }
725
726 /// Retrieve the global ID of the module that owns this particular
727 /// declaration.
728 unsigned getOwningModuleID() const {
729 if (isFromASTFile())
730 return *((const unsigned*)this - 2);
731 return 0;
732 }
733
734private:
735 Module *getOwningModuleSlow() const;
736
737protected:
738 bool hasLocalOwningModuleStorage() const;
739
740public:
741 /// Get the imported owning module, if this decl is from an imported
742 /// (non-local) module.
743 Module *getImportedOwningModule() const {
744 if (!isFromASTFile() || !hasOwningModule())
745 return nullptr;
746
747 return getOwningModuleSlow();
748 }
749
750 /// Get the local owning module, if known. Returns nullptr if owner is
751 /// not yet known or declaration is not from a module.
752 Module *getLocalOwningModule() const {
753 if (isFromASTFile() || !hasOwningModule())
754 return nullptr;
755
756 assert(hasLocalOwningModuleStorage() &&((void)0)
757 "owned local decl but no local module storage")((void)0);
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&((void)0)
762 hasLocalOwningModuleStorage() &&((void)0)
763 "should not have a cached owning module")((void)0);
764 reinterpret_cast<Module **>(this)[-1] = M;
765 }
766
767 /// Is this declaration owned by some module?
768 bool hasOwningModule() const {
769 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
770 }
771
772 /// Get the module that owns this declaration (for visibility purposes).
773 Module *getOwningModule() const {
774 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
775 }
776
777 /// Get the module that owns this declaration for linkage purposes.
778 /// There only ever is such a module under the C++ Modules TS.
779 ///
780 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
781 /// all declarations in a global module fragment are unowned.
782 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
783
784 /// Determine whether this declaration is definitely visible to name lookup,
785 /// independent of whether the owning module is visible.
786 /// Note: The declaration may be visible even if this returns \c false if the
787 /// owning module is visible within the query context. This is a low-level
788 /// helper function; most code should be calling Sema::isVisible() instead.
789 bool isUnconditionallyVisible() const {
790 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
791 }
792
793 /// Set that this declaration is globally visible, even if it came from a
794 /// module that is not visible.
795 void setVisibleDespiteOwningModule() {
796 if (!isUnconditionallyVisible())
797 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
798 }
799
800 /// Get the kind of module ownership for this declaration.
801 ModuleOwnershipKind getModuleOwnershipKind() const {
802 return NextInContextAndBits.getInt();
803 }
804
805 /// Set whether this declaration is hidden from name lookup.
806 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
807 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&((void)0)
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&((void)0)
809 !hasLocalOwningModuleStorage()) &&((void)0)
810 "no storage available for owning module for this declaration")((void)0);
811 NextInContextAndBits.setInt(MOK);
812 }
813
814 unsigned getIdentifierNamespace() const {
815 return IdentifierNamespace;
816 }
817
818 bool isInIdentifierNamespace(unsigned NS) const {
819 return getIdentifierNamespace() & NS;
820 }
821
822 static unsigned getIdentifierNamespaceForKind(Kind DK);
823
824 bool hasTagIdentifierNamespace() const {
825 return isTagIdentifierNamespace(getIdentifierNamespace());
826 }
827
828 static bool isTagIdentifierNamespace(unsigned NS) {
829 // TagDecls have Tag and Type set and may also have TagFriend.
830 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
831 }
832
833 /// getLexicalDeclContext - The declaration context where this Decl was
834 /// lexically declared (LexicalDC). May be different from
835 /// getDeclContext() (SemanticDC).
836 /// e.g.:
837 ///
838 /// namespace A {
839 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
840 /// }
841 /// void A::f(); // SemanticDC == namespace 'A'
842 /// // LexicalDC == global namespace
843 DeclContext *getLexicalDeclContext() {
844 if (isInSemaDC())
845 return getSemanticDC();
846 return getMultipleDC()->LexicalDC;
847 }
848 const DeclContext *getLexicalDeclContext() const {
849 return const_cast<Decl*>(this)->getLexicalDeclContext();
850 }
851
852 /// Determine whether this declaration is declared out of line (outside its
853 /// semantic context).
854 virtual bool isOutOfLine() const;
855
856 /// setDeclContext - Set both the semantic and lexical DeclContext
857 /// to DC.
858 void setDeclContext(DeclContext *DC);
859
860 void setLexicalDeclContext(DeclContext *DC);
861
862 /// Determine whether this declaration is a templated entity (whether it is
863 // within the scope of a template parameter).
864 bool isTemplated() const;
865
866 /// Determine the number of levels of template parameter surrounding this
867 /// declaration.
868 unsigned getTemplateDepth() const;
869
870 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
871 /// scoped decl is defined outside the current function or method. This is
872 /// roughly global variables and functions, but also handles enums (which
873 /// could be defined inside or outside a function etc).
874 bool isDefinedOutsideFunctionOrMethod() const {
875 return getParentFunctionOrMethod() == nullptr;
876 }
877
878 /// Determine whether a substitution into this declaration would occur as
879 /// part of a substitution into a dependent local scope. Such a substitution
880 /// transitively substitutes into all constructs nested within this
881 /// declaration.
882 ///
883 /// This recognizes non-defining declarations as well as members of local
884 /// classes and lambdas:
885 /// \code
886 /// template<typename T> void foo() { void bar(); }
887 /// template<typename T> void foo2() { class ABC { void bar(); }; }
888 /// template<typename T> inline int x = [](){ return 0; }();
889 /// \endcode
890 bool isInLocalScopeForInstantiation() const;
891
892 /// If this decl is defined inside a function/method/block it returns
893 /// the corresponding DeclContext, otherwise it returns null.
894 const DeclContext *getParentFunctionOrMethod() const;
895 DeclContext *getParentFunctionOrMethod() {
896 return const_cast<DeclContext*>(
897 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
898 }
899
900 /// Retrieves the "canonical" declaration of the given declaration.
901 virtual Decl *getCanonicalDecl() { return this; }
902 const Decl *getCanonicalDecl() const {
903 return const_cast<Decl*>(this)->getCanonicalDecl();
904 }
905
906 /// Whether this particular Decl is a canonical one.
907 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
908
909protected:
910 /// Returns the next redeclaration or itself if this is the only decl.
911 ///
912 /// Decl subclasses that can be redeclared should override this method so that
913 /// Decl::redecl_iterator can iterate over them.
914 virtual Decl *getNextRedeclarationImpl() { return this; }
915
916 /// Implementation of getPreviousDecl(), to be overridden by any
917 /// subclass that has a redeclaration chain.
918 virtual Decl *getPreviousDeclImpl() { return nullptr; }
919
920 /// Implementation of getMostRecentDecl(), to be overridden by any
921 /// subclass that has a redeclaration chain.
922 virtual Decl *getMostRecentDeclImpl() { return this; }
923
924public:
925 /// Iterates through all the redeclarations of the same decl.
926 class redecl_iterator {
927 /// Current - The current declaration.
928 Decl *Current = nullptr;
929 Decl *Starter;
930
931 public:
932 using value_type = Decl *;
933 using reference = const value_type &;
934 using pointer = const value_type *;
935 using iterator_category = std::forward_iterator_tag;
936 using difference_type = std::ptrdiff_t;
937
938 redecl_iterator() = default;
939 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
940
941 reference operator*() const { return Current; }
942 value_type operator->() const { return Current; }
943
944 redecl_iterator& operator++() {
945 assert(Current && "Advancing while iterator has reached end")((void)0);
946 // Get either previous decl or latest decl.
947 Decl *Next = Current->getNextRedeclarationImpl();
948 assert(Next && "Should return next redeclaration or itself, never null!")((void)0);
949 Current = (Next != Starter) ? Next : nullptr;
950 return *this;
951 }
952
953 redecl_iterator operator++(int) {
954 redecl_iterator tmp(*this);
955 ++(*this);
956 return tmp;
957 }
958
959 friend bool operator==(redecl_iterator x, redecl_iterator y) {
960 return x.Current == y.Current;
961 }
962
963 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
964 return x.Current != y.Current;
965 }
966 };
967
968 using redecl_range = llvm::iterator_range<redecl_iterator>;
969
970 /// Returns an iterator range for all the redeclarations of the same
971 /// decl. It will iterate at least once (when this decl is the only one).
972 redecl_range redecls() const {
973 return redecl_range(redecls_begin(), redecls_end());
974 }
975
976 redecl_iterator redecls_begin() const {
977 return redecl_iterator(const_cast<Decl *>(this));
978 }
979
980 redecl_iterator redecls_end() const { return redecl_iterator(); }
981
982 /// Retrieve the previous declaration that declares the same entity
983 /// as this declaration, or NULL if there is no previous declaration.
984 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
985
986 /// Retrieve the previous declaration that declares the same entity
987 /// as this declaration, or NULL if there is no previous declaration.
988 const Decl *getPreviousDecl() const {
989 return const_cast<Decl *>(this)->getPreviousDeclImpl();
990 }
991
992 /// True if this is the first declaration in its redeclaration chain.
993 bool isFirstDecl() const {
994 return getPreviousDecl() == nullptr;
995 }
996
997 /// Retrieve the most recent declaration that declares the same entity
998 /// as this declaration (which may be this declaration).
999 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
1000
1001 /// Retrieve the most recent declaration that declares the same entity
1002 /// as this declaration (which may be this declaration).
1003 const Decl *getMostRecentDecl() const {
1004 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
1005 }
1006
1007 /// getBody - If this Decl represents a declaration for a body of code,
1008 /// such as a function or method definition, this method returns the
1009 /// top-level Stmt* of that body. Otherwise this method returns null.
1010 virtual Stmt* getBody() const { return nullptr; }
1011
1012 /// Returns true if this \c Decl represents a declaration for a body of
1013 /// code, such as a function or method definition.
1014 /// Note that \c hasBody can also return true if any redeclaration of this
1015 /// \c Decl represents a declaration for a body of code.
1016 virtual bool hasBody() const { return getBody() != nullptr; }
1017
1018 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1019 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1020 SourceLocation getBodyRBrace() const;
1021
1022 // global temp stats (until we have a per-module visitor)
1023 static void add(Kind k);
1024 static void EnableStatistics();
1025 static void PrintStats();
1026
1027 /// isTemplateParameter - Determines whether this declaration is a
1028 /// template parameter.
1029 bool isTemplateParameter() const;
1030
1031 /// isTemplateParameter - Determines whether this declaration is a
1032 /// template parameter pack.
1033 bool isTemplateParameterPack() const;
1034
1035 /// Whether this declaration is a parameter pack.
1036 bool isParameterPack() const;
1037
1038 /// returns true if this declaration is a template
1039 bool isTemplateDecl() const;
1040
1041 /// Whether this declaration is a function or function template.
1042 bool isFunctionOrFunctionTemplate() const {
1043 return (DeclKind >= Decl::firstFunction &&
1044 DeclKind <= Decl::lastFunction) ||
1045 DeclKind == FunctionTemplate;
1046 }
1047
1048 /// If this is a declaration that describes some template, this
1049 /// method returns that template declaration.
1050 ///
1051 /// Note that this returns nullptr for partial specializations, because they
1052 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1053 /// those cases.
1054 TemplateDecl *getDescribedTemplate() const;
1055
1056 /// If this is a declaration that describes some template or partial
1057 /// specialization, this returns the corresponding template parameter list.
1058 const TemplateParameterList *getDescribedTemplateParams() const;
1059
1060 /// Returns the function itself, or the templated function if this is a
1061 /// function template.
1062 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1063
1064 const FunctionDecl *getAsFunction() const {
1065 return const_cast<Decl *>(this)->getAsFunction();
1066 }
1067
1068 /// Changes the namespace of this declaration to reflect that it's
1069 /// a function-local extern declaration.
1070 ///
1071 /// These declarations appear in the lexical context of the extern
1072 /// declaration, but in the semantic context of the enclosing namespace
1073 /// scope.
1074 void setLocalExternDecl() {
1075 Decl *Prev = getPreviousDecl();
1076 IdentifierNamespace &= ~IDNS_Ordinary;
1077
1078 // It's OK for the declaration to still have the "invisible friend" flag or
1079 // the "conflicts with tag declarations in this scope" flag for the outer
1080 // scope.
1081 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&((void)0)
1082 "namespace is not ordinary")((void)0);
1083
1084 IdentifierNamespace |= IDNS_LocalExtern;
1085 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1086 IdentifierNamespace |= IDNS_Ordinary;
1087 }
1088
1089 /// Determine whether this is a block-scope declaration with linkage.
1090 /// This will either be a local variable declaration declared 'extern', or a
1091 /// local function declaration.
1092 bool isLocalExternDecl() {
1093 return IdentifierNamespace & IDNS_LocalExtern;
1094 }
1095
1096 /// Changes the namespace of this declaration to reflect that it's
1097 /// the object of a friend declaration.
1098 ///
1099 /// These declarations appear in the lexical context of the friending
1100 /// class, but in the semantic context of the actual entity. This property
1101 /// applies only to a specific decl object; other redeclarations of the
1102 /// same entity may not (and probably don't) share this property.
1103 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1104 unsigned OldNS = IdentifierNamespace;
1105 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |((void)0)
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |((void)0)
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((void)0)
1108 "namespace includes neither ordinary nor tag")((void)0);
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |((void)0)
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |((void)0)
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&((void)0)
1112 "namespace includes other than ordinary or tag")((void)0);
1113
1114 Decl *Prev = getPreviousDecl();
1115 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1116
1117 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1118 IdentifierNamespace |= IDNS_TagFriend;
1119 if (PerformFriendInjection ||
1120 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1121 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1122 }
1123
1124 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1125 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1126 IdentifierNamespace |= IDNS_OrdinaryFriend;
1127 if (PerformFriendInjection ||
1128 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1129 IdentifierNamespace |= IDNS_Ordinary;
1130 }
1131 }
1132
1133 enum FriendObjectKind {
1134 FOK_None, ///< Not a friend object.
1135 FOK_Declared, ///< A friend of a previously-declared entity.
1136 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1137 };
1138
1139 /// Determines whether this declaration is the object of a
1140 /// friend declaration and, if so, what kind.
1141 ///
1142 /// There is currently no direct way to find the associated FriendDecl.
1143 FriendObjectKind getFriendObjectKind() const {
1144 unsigned mask =
1145 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1146 if (!mask) return FOK_None;
1147 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1148 : FOK_Undeclared);
1149 }
1150
1151 /// Specifies that this declaration is a C++ overloaded non-member.
1152 void setNonMemberOperator() {
1153 assert(getKind() == Function || getKind() == FunctionTemplate)((void)0);
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&((void)0)
1155 "visible non-member operators should be in ordinary namespace")((void)0);
1156 IdentifierNamespace |= IDNS_NonMemberOperator;
1157 }
1158
1159 static bool classofKind(Kind K) { return true; }
1160 static DeclContext *castToDeclContext(const Decl *);
1161 static Decl *castFromDeclContext(const DeclContext *);
1162
1163 void print(raw_ostream &Out, unsigned Indentation = 0,
1164 bool PrintInstantiation = false) const;
1165 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1166 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1167 static void printGroup(Decl** Begin, unsigned NumDecls,
1168 raw_ostream &Out, const PrintingPolicy &Policy,
1169 unsigned Indentation = 0);
1170
1171 // Debuggers don't usually respect default arguments.
1172 void dump() const;
1173
1174 // Same as dump(), but forces color printing.
1175 void dumpColor() const;
1176
1177 void dump(raw_ostream &Out, bool Deserialize = false,
1178 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1179
1180 /// \return Unique reproducible object identifier
1181 int64_t getID() const;
1182
1183 /// Looks through the Decl's underlying type to extract a FunctionType
1184 /// when possible. Will return null if the type underlying the Decl does not
1185 /// have a FunctionType.
1186 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1187
1188private:
1189 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1190 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1191 ASTContext &Ctx);
1192
1193protected:
1194 ASTMutationListener *getASTMutationListener() const;
1195};
1196
1197/// Determine whether two declarations declare the same entity.
1198inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1199 if (!D1 || !D2)
1200 return false;
1201
1202 if (D1 == D2)
1203 return true;
1204
1205 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1206}
1207
1208/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1209/// doing something to a specific decl.
1210class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1211 const Decl *TheDecl;
1212 SourceLocation Loc;
1213 SourceManager &SM;
1214 const char *Message;
1215
1216public:
1217 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1218 SourceManager &sm, const char *Msg)
1219 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1220
1221 void print(raw_ostream &OS) const override;
1222};
1223} // namespace clang
1224
1225// Required to determine the layout of the PointerUnion<NamedDecl*> before
1226// seeing the NamedDecl definition being first used in DeclListNode::operator*.
1227namespace llvm {
1228 template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> {
1229 static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; }
1230 static inline ::clang::NamedDecl *getFromVoidPointer(void *P) {
1231 return static_cast<::clang::NamedDecl *>(P);
1232 }
1233 static constexpr int NumLowBitsAvailable = 3;
1234 };
1235}
1236
1237namespace clang {
1238/// A list storing NamedDecls in the lookup tables.
1239class DeclListNode {
1240 friend class ASTContext; // allocate, deallocate nodes.
1241 friend class StoredDeclsList;
1242public:
1243 using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>;
1244 class iterator {
1245 friend class DeclContextLookupResult;
1246 friend class StoredDeclsList;
1247
1248 Decls Ptr;
1249 iterator(Decls Node) : Ptr(Node) { }
1250 public:
1251 using difference_type = ptrdiff_t;
1252 using value_type = NamedDecl*;
1253 using pointer = void;
1254 using reference = value_type;
1255 using iterator_category = std::forward_iterator_tag;
1256
1257 iterator() = default;
1258
1259 reference operator*() const {
1260 assert(Ptr && "dereferencing end() iterator")((void)0);
1261 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1262 return CurNode->D;
1263 return Ptr.get<NamedDecl*>();
1264 }
1265 void operator->() const { } // Unsupported.
1266 bool operator==(const iterator &X) const { return Ptr == X.Ptr; }
1267 bool operator!=(const iterator &X) const { return Ptr != X.Ptr; }
1268 inline iterator &operator++() { // ++It
1269 assert(!Ptr.isNull() && "Advancing empty iterator")((void)0);
1270
1271 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1272 Ptr = CurNode->Rest;
1273 else
1274 Ptr = nullptr;
1275 return *this;
1276 }
1277 iterator operator++(int) { // It++
1278 iterator temp = *this;
1279 ++(*this);
1280 return temp;
1281 }
1282 // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I)
1283 iterator end() { return iterator(); }
1284 };
1285private:
1286 NamedDecl *D = nullptr;
1287 Decls Rest = nullptr;
1288 DeclListNode(NamedDecl *ND) : D(ND) {}
1289};
1290
1291/// The results of name lookup within a DeclContext.
1292class DeclContextLookupResult {
1293 using Decls = DeclListNode::Decls;
1294
1295 /// When in collection form, this is what the Data pointer points to.
1296 Decls Result;
1297
1298public:
1299 DeclContextLookupResult() = default;
1300 DeclContextLookupResult(Decls Result) : Result(Result) {}
1301
1302 using iterator = DeclListNode::iterator;
1303 using const_iterator = iterator;
1304 using reference = iterator::reference;
1305
1306 iterator begin() { return iterator(Result); }
1307 iterator end() { return iterator(); }
1308 const_iterator begin() const {
1309 return const_cast<DeclContextLookupResult*>(this)->begin();
1310 }
1311 const_iterator end() const { return iterator(); }
1312
1313 bool empty() const { return Result.isNull(); }
1314 bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); }
1315 reference front() const { return *begin(); }
1316
1317 // Find the first declaration of the given type in the list. Note that this
1318 // is not in general the earliest-declared declaration, and should only be
1319 // used when it's not possible for there to be more than one match or where
1320 // it doesn't matter which one is found.
1321 template<class T> T *find_first() const {
1322 for (auto *D : *this)
1323 if (T *Decl = dyn_cast<T>(D))
1324 return Decl;
1325
1326 return nullptr;
1327 }
1328};
1329
1330/// DeclContext - This is used only as base class of specific decl types that
1331/// can act as declaration contexts. These decls are (only the top classes
1332/// that directly derive from DeclContext are mentioned, not their subclasses):
1333///
1334/// TranslationUnitDecl
1335/// ExternCContext
1336/// NamespaceDecl
1337/// TagDecl
1338/// OMPDeclareReductionDecl
1339/// OMPDeclareMapperDecl
1340/// FunctionDecl
1341/// ObjCMethodDecl
1342/// ObjCContainerDecl
1343/// LinkageSpecDecl
1344/// ExportDecl
1345/// BlockDecl
1346/// CapturedDecl
1347class DeclContext {
1348 /// For makeDeclVisibleInContextImpl
1349 friend class ASTDeclReader;
1350 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1351 /// hasNeedToReconcileExternalVisibleStorage
1352 friend class ExternalASTSource;
1353 /// For CreateStoredDeclsMap
1354 friend class DependentDiagnostic;
1355 /// For hasNeedToReconcileExternalVisibleStorage,
1356 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1357 friend class ASTWriter;
1358
1359 // We use uint64_t in the bit-fields below since some bit-fields
1360 // cross the unsigned boundary and this breaks the packing.
1361
1362 /// Stores the bits used by DeclContext.
1363 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1364 /// methods in DeclContext should be updated appropriately.
1365 class DeclContextBitfields {
1366 friend class DeclContext;
1367 /// DeclKind - This indicates which class this is.
1368 uint64_t DeclKind : 7;
1369
1370 /// Whether this declaration context also has some external
1371 /// storage that contains additional declarations that are lexically
1372 /// part of this context.
1373 mutable uint64_t ExternalLexicalStorage : 1;
1374
1375 /// Whether this declaration context also has some external
1376 /// storage that contains additional declarations that are visible
1377 /// in this context.
1378 mutable uint64_t ExternalVisibleStorage : 1;
1379
1380 /// Whether this declaration context has had externally visible
1381 /// storage added since the last lookup. In this case, \c LookupPtr's
1382 /// invariant may not hold and needs to be fixed before we perform
1383 /// another lookup.
1384 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1385
1386 /// If \c true, this context may have local lexical declarations
1387 /// that are missing from the lookup table.
1388 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1389
1390 /// If \c true, the external source may have lexical declarations
1391 /// that are missing from the lookup table.
1392 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1393
1394 /// If \c true, lookups should only return identifier from
1395 /// DeclContext scope (for example TranslationUnit). Used in
1396 /// LookupQualifiedName()
1397 mutable uint64_t UseQualifiedLookup : 1;
1398 };
1399
1400 /// Number of bits in DeclContextBitfields.
1401 enum { NumDeclContextBits = 13 };
1402
1403 /// Stores the bits used by TagDecl.
1404 /// If modified NumTagDeclBits and the accessor
1405 /// methods in TagDecl should be updated appropriately.
1406 class TagDeclBitfields {
1407 friend class TagDecl;
1408 /// For the bits in DeclContextBitfields
1409 uint64_t : NumDeclContextBits;
1410
1411 /// The TagKind enum.
1412 uint64_t TagDeclKind : 3;
1413
1414 /// True if this is a definition ("struct foo {};"), false if it is a
1415 /// declaration ("struct foo;"). It is not considered a definition
1416 /// until the definition has been fully processed.
1417 uint64_t IsCompleteDefinition : 1;
1418
1419 /// True if this is currently being defined.
1420 uint64_t IsBeingDefined : 1;
1421
1422 /// True if this tag declaration is "embedded" (i.e., defined or declared
1423 /// for the very first time) in the syntax of a declarator.
1424 uint64_t IsEmbeddedInDeclarator : 1;
1425
1426 /// True if this tag is free standing, e.g. "struct foo;".
1427 uint64_t IsFreeStanding : 1;
1428
1429 /// Indicates whether it is possible for declarations of this kind
1430 /// to have an out-of-date definition.
1431 ///
1432 /// This option is only enabled when modules are enabled.
1433 uint64_t MayHaveOutOfDateDef : 1;
1434
1435 /// Has the full definition of this type been required by a use somewhere in
1436 /// the TU.
1437 uint64_t IsCompleteDefinitionRequired : 1;
1438 };
1439
1440 /// Number of non-inherited bits in TagDeclBitfields.
1441 enum { NumTagDeclBits = 9 };
1442
1443 /// Stores the bits used by EnumDecl.
1444 /// If modified NumEnumDeclBit and the accessor
1445 /// methods in EnumDecl should be updated appropriately.
1446 class EnumDeclBitfields {
1447 friend class EnumDecl;
1448 /// For the bits in DeclContextBitfields.
1449 uint64_t : NumDeclContextBits;
1450 /// For the bits in TagDeclBitfields.
1451 uint64_t : NumTagDeclBits;
1452
1453 /// Width in bits required to store all the non-negative
1454 /// enumerators of this enum.
1455 uint64_t NumPositiveBits : 8;
1456
1457 /// Width in bits required to store all the negative
1458 /// enumerators of this enum.
1459 uint64_t NumNegativeBits : 8;
1460
1461 /// True if this tag declaration is a scoped enumeration. Only
1462 /// possible in C++11 mode.
1463 uint64_t IsScoped : 1;
1464
1465 /// If this tag declaration is a scoped enum,
1466 /// then this is true if the scoped enum was declared using the class
1467 /// tag, false if it was declared with the struct tag. No meaning is
1468 /// associated if this tag declaration is not a scoped enum.
1469 uint64_t IsScopedUsingClassTag : 1;
1470
1471 /// True if this is an enumeration with fixed underlying type. Only
1472 /// possible in C++11, Microsoft extensions, or Objective C mode.
1473 uint64_t IsFixed : 1;
1474
1475 /// True if a valid hash is stored in ODRHash.
1476 uint64_t HasODRHash : 1;
1477 };
1478
1479 /// Number of non-inherited bits in EnumDeclBitfields.
1480 enum { NumEnumDeclBits = 20 };
1481
1482 /// Stores the bits used by RecordDecl.
1483 /// If modified NumRecordDeclBits and the accessor
1484 /// methods in RecordDecl should be updated appropriately.
1485 class RecordDeclBitfields {
1486 friend class RecordDecl;
1487 /// For the bits in DeclContextBitfields.
1488 uint64_t : NumDeclContextBits;
1489 /// For the bits in TagDeclBitfields.
1490 uint64_t : NumTagDeclBits;
1491
1492 /// This is true if this struct ends with a flexible
1493 /// array member (e.g. int X[]) or if this union contains a struct that does.
1494 /// If so, this cannot be contained in arrays or other structs as a member.
1495 uint64_t HasFlexibleArrayMember : 1;
1496
1497 /// Whether this is the type of an anonymous struct or union.
1498 uint64_t AnonymousStructOrUnion : 1;
1499
1500 /// This is true if this struct has at least one member
1501 /// containing an Objective-C object pointer type.
1502 uint64_t HasObjectMember : 1;
1503
1504 /// This is true if struct has at least one member of
1505 /// 'volatile' type.
1506 uint64_t HasVolatileMember : 1;
1507
1508 /// Whether the field declarations of this record have been loaded
1509 /// from external storage. To avoid unnecessary deserialization of
1510 /// methods/nested types we allow deserialization of just the fields
1511 /// when needed.
1512 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1513
1514 /// Basic properties of non-trivial C structs.
1515 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1516 uint64_t NonTrivialToPrimitiveCopy : 1;
1517 uint64_t NonTrivialToPrimitiveDestroy : 1;
1518
1519 /// The following bits indicate whether this is or contains a C union that
1520 /// is non-trivial to default-initialize, destruct, or copy. These bits
1521 /// imply the associated basic non-triviality predicates declared above.
1522 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1523 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1524 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1525
1526 /// Indicates whether this struct is destroyed in the callee.
1527 uint64_t ParamDestroyedInCallee : 1;
1528
1529 /// Represents the way this type is passed to a function.
1530 uint64_t ArgPassingRestrictions : 2;
1531 };
1532
1533 /// Number of non-inherited bits in RecordDeclBitfields.
1534 enum { NumRecordDeclBits = 14 };
1535
1536 /// Stores the bits used by OMPDeclareReductionDecl.
1537 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1538 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1539 class OMPDeclareReductionDeclBitfields {
1540 friend class OMPDeclareReductionDecl;
1541 /// For the bits in DeclContextBitfields
1542 uint64_t : NumDeclContextBits;
1543
1544 /// Kind of initializer,
1545 /// function call or omp_priv<init_expr> initializtion.
1546 uint64_t InitializerKind : 2;
1547 };
1548
1549 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1550 enum { NumOMPDeclareReductionDeclBits = 2 };
1551
1552 /// Stores the bits used by FunctionDecl.
1553 /// If modified NumFunctionDeclBits and the accessor
1554 /// methods in FunctionDecl and CXXDeductionGuideDecl
1555 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1556 class FunctionDeclBitfields {
1557 friend class FunctionDecl;
1558 /// For IsCopyDeductionCandidate
1559 friend class CXXDeductionGuideDecl;
1560 /// For the bits in DeclContextBitfields.
1561 uint64_t : NumDeclContextBits;
1562
1563 uint64_t SClass : 3;
1564 uint64_t IsInline : 1;
1565 uint64_t IsInlineSpecified : 1;
1566
1567 uint64_t IsVirtualAsWritten : 1;
1568 uint64_t IsPure : 1;
1569 uint64_t HasInheritedPrototype : 1;
1570 uint64_t HasWrittenPrototype : 1;
1571 uint64_t IsDeleted : 1;
1572 /// Used by CXXMethodDecl
1573 uint64_t IsTrivial : 1;
1574
1575 /// This flag indicates whether this function is trivial for the purpose of
1576 /// calls. This is meaningful only when this function is a copy/move
1577 /// constructor or a destructor.
1578 uint64_t IsTrivialForCall : 1;
1579
1580 uint64_t IsDefaulted : 1;
1581 uint64_t IsExplicitlyDefaulted : 1;
1582 uint64_t HasDefaultedFunctionInfo : 1;
1583 uint64_t HasImplicitReturnZero : 1;
1584 uint64_t IsLateTemplateParsed : 1;
1585
1586 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1587 uint64_t ConstexprKind : 2;
1588 uint64_t InstantiationIsPending : 1;
1589
1590 /// Indicates if the function uses __try.
1591 uint64_t UsesSEHTry : 1;
1592
1593 /// Indicates if the function was a definition
1594 /// but its body was skipped.
1595 uint64_t HasSkippedBody : 1;
1596
1597 /// Indicates if the function declaration will
1598 /// have a body, once we're done parsing it.
1599 uint64_t WillHaveBody : 1;
1600
1601 /// Indicates that this function is a multiversioned
1602 /// function using attribute 'target'.
1603 uint64_t IsMultiVersion : 1;
1604
1605 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1606 /// the Deduction Guide is the implicitly generated 'copy
1607 /// deduction candidate' (is used during overload resolution).
1608 uint64_t IsCopyDeductionCandidate : 1;
1609
1610 /// Store the ODRHash after first calculation.
1611 uint64_t HasODRHash : 1;
1612
1613 /// Indicates if the function uses Floating Point Constrained Intrinsics
1614 uint64_t UsesFPIntrin : 1;
1615 };
1616
1617 /// Number of non-inherited bits in FunctionDeclBitfields.
1618 enum { NumFunctionDeclBits = 27 };
1619
1620 /// Stores the bits used by CXXConstructorDecl. If modified
1621 /// NumCXXConstructorDeclBits and the accessor
1622 /// methods in CXXConstructorDecl should be updated appropriately.
1623 class CXXConstructorDeclBitfields {
1624 friend class CXXConstructorDecl;
1625 /// For the bits in DeclContextBitfields.
1626 uint64_t : NumDeclContextBits;
1627 /// For the bits in FunctionDeclBitfields.
1628 uint64_t : NumFunctionDeclBits;
1629
1630 /// 24 bits to fit in the remaining available space.
1631 /// Note that this makes CXXConstructorDeclBitfields take
1632 /// exactly 64 bits and thus the width of NumCtorInitializers
1633 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1634 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1635 uint64_t NumCtorInitializers : 21;
1636 uint64_t IsInheritingConstructor : 1;
1637
1638 /// Whether this constructor has a trail-allocated explicit specifier.
1639 uint64_t HasTrailingExplicitSpecifier : 1;
1640 /// If this constructor does't have a trail-allocated explicit specifier.
1641 /// Whether this constructor is explicit specified.
1642 uint64_t IsSimpleExplicit : 1;
1643 };
1644
1645 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1646 enum {
1647 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1648 };
1649
1650 /// Stores the bits used by ObjCMethodDecl.
1651 /// If modified NumObjCMethodDeclBits and the accessor
1652 /// methods in ObjCMethodDecl should be updated appropriately.
1653 class ObjCMethodDeclBitfields {
1654 friend class ObjCMethodDecl;
1655
1656 /// For the bits in DeclContextBitfields.
1657 uint64_t : NumDeclContextBits;
1658
1659 /// The conventional meaning of this method; an ObjCMethodFamily.
1660 /// This is not serialized; instead, it is computed on demand and
1661 /// cached.
1662 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1663
1664 /// instance (true) or class (false) method.
1665 uint64_t IsInstance : 1;
1666 uint64_t IsVariadic : 1;
1667
1668 /// True if this method is the getter or setter for an explicit property.
1669 uint64_t IsPropertyAccessor : 1;
1670
1671 /// True if this method is a synthesized property accessor stub.
1672 uint64_t IsSynthesizedAccessorStub : 1;
1673
1674 /// Method has a definition.
1675 uint64_t IsDefined : 1;
1676
1677 /// Method redeclaration in the same interface.
1678 uint64_t IsRedeclaration : 1;
1679
1680 /// Is redeclared in the same interface.
1681 mutable uint64_t HasRedeclaration : 1;
1682
1683 /// \@required/\@optional
1684 uint64_t DeclImplementation : 2;
1685
1686 /// in, inout, etc.
1687 uint64_t objcDeclQualifier : 7;
1688
1689 /// Indicates whether this method has a related result type.
1690 uint64_t RelatedResultType : 1;
1691
1692 /// Whether the locations of the selector identifiers are in a
1693 /// "standard" position, a enum SelectorLocationsKind.
1694 uint64_t SelLocsKind : 2;
1695
1696 /// Whether this method overrides any other in the class hierarchy.
1697 ///
1698 /// A method is said to override any method in the class's
1699 /// base classes, its protocols, or its categories' protocols, that has
1700 /// the same selector and is of the same kind (class or instance).
1701 /// A method in an implementation is not considered as overriding the same
1702 /// method in the interface or its categories.
1703 uint64_t IsOverriding : 1;
1704
1705 /// Indicates if the method was a definition but its body was skipped.
1706 uint64_t HasSkippedBody : 1;
1707 };
1708
1709 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1710 enum { NumObjCMethodDeclBits = 24 };
1711
1712 /// Stores the bits used by ObjCContainerDecl.
1713 /// If modified NumObjCContainerDeclBits and the accessor
1714 /// methods in ObjCContainerDecl should be updated appropriately.
1715 class ObjCContainerDeclBitfields {
1716 friend class ObjCContainerDecl;
1717 /// For the bits in DeclContextBitfields
1718 uint32_t : NumDeclContextBits;
1719
1720 // Not a bitfield but this saves space.
1721 // Note that ObjCContainerDeclBitfields is full.
1722 SourceLocation AtStart;
1723 };
1724
1725 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1726 /// Note that here we rely on the fact that SourceLocation is 32 bits
1727 /// wide. We check this with the static_assert in the ctor of DeclContext.
1728 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1729
1730 /// Stores the bits used by LinkageSpecDecl.
1731 /// If modified NumLinkageSpecDeclBits and the accessor
1732 /// methods in LinkageSpecDecl should be updated appropriately.
1733 class LinkageSpecDeclBitfields {
1734 friend class LinkageSpecDecl;
1735 /// For the bits in DeclContextBitfields.
1736 uint64_t : NumDeclContextBits;
1737
1738 /// The language for this linkage specification with values
1739 /// in the enum LinkageSpecDecl::LanguageIDs.
1740 uint64_t Language : 3;
1741
1742 /// True if this linkage spec has braces.
1743 /// This is needed so that hasBraces() returns the correct result while the
1744 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1745 /// not used, so it doesn't need to be serialized.
1746 uint64_t HasBraces : 1;
1747 };
1748
1749 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1750 enum { NumLinkageSpecDeclBits = 4 };
1751
1752 /// Stores the bits used by BlockDecl.
1753 /// If modified NumBlockDeclBits and the accessor
1754 /// methods in BlockDecl should be updated appropriately.
1755 class BlockDeclBitfields {
1756 friend class BlockDecl;
1757 /// For the bits in DeclContextBitfields.
1758 uint64_t : NumDeclContextBits;
1759
1760 uint64_t IsVariadic : 1;
1761 uint64_t CapturesCXXThis : 1;
1762 uint64_t BlockMissingReturnType : 1;
1763 uint64_t IsConversionFromLambda : 1;
1764
1765 /// A bit that indicates this block is passed directly to a function as a
1766 /// non-escaping parameter.
1767 uint64_t DoesNotEscape : 1;
1768
1769 /// A bit that indicates whether it's possible to avoid coying this block to
1770 /// the heap when it initializes or is assigned to a local variable with
1771 /// automatic storage.
1772 uint64_t CanAvoidCopyToHeap : 1;
1773 };
1774
1775 /// Number of non-inherited bits in BlockDeclBitfields.
1776 enum { NumBlockDeclBits = 5 };
1777
1778 /// Pointer to the data structure used to lookup declarations
1779 /// within this context (or a DependentStoredDeclsMap if this is a
1780 /// dependent context). We maintain the invariant that, if the map
1781 /// contains an entry for a DeclarationName (and we haven't lazily
1782 /// omitted anything), then it contains all relevant entries for that
1783 /// name (modulo the hasExternalDecls() flag).
1784 mutable StoredDeclsMap *LookupPtr = nullptr;
1785
1786protected:
1787 /// This anonymous union stores the bits belonging to DeclContext and classes
1788 /// deriving from it. The goal is to use otherwise wasted
1789 /// space in DeclContext to store data belonging to derived classes.
1790 /// The space saved is especially significient when pointers are aligned
1791 /// to 8 bytes. In this case due to alignment requirements we have a
1792 /// little less than 8 bytes free in DeclContext which we can use.
1793 /// We check that none of the classes in this union is larger than
1794 /// 8 bytes with static_asserts in the ctor of DeclContext.
1795 union {
1796 DeclContextBitfields DeclContextBits;
1797 TagDeclBitfields TagDeclBits;
1798 EnumDeclBitfields EnumDeclBits;
1799 RecordDeclBitfields RecordDeclBits;
1800 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1801 FunctionDeclBitfields FunctionDeclBits;
1802 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1803 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1804 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1805 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1806 BlockDeclBitfields BlockDeclBits;
1807
1808 static_assert(sizeof(DeclContextBitfields) <= 8,
1809 "DeclContextBitfields is larger than 8 bytes!");
1810 static_assert(sizeof(TagDeclBitfields) <= 8,
1811 "TagDeclBitfields is larger than 8 bytes!");
1812 static_assert(sizeof(EnumDeclBitfields) <= 8,
1813 "EnumDeclBitfields is larger than 8 bytes!");
1814 static_assert(sizeof(RecordDeclBitfields) <= 8,
1815 "RecordDeclBitfields is larger than 8 bytes!");
1816 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1817 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1818 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1819 "FunctionDeclBitfields is larger than 8 bytes!");
1820 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1821 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1822 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1823 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1824 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1825 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1826 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1827 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1828 static_assert(sizeof(BlockDeclBitfields) <= 8,
1829 "BlockDeclBitfields is larger than 8 bytes!");
1830 };
1831
1832 /// FirstDecl - The first declaration stored within this declaration
1833 /// context.
1834 mutable Decl *FirstDecl = nullptr;
1835
1836 /// LastDecl - The last declaration stored within this declaration
1837 /// context. FIXME: We could probably cache this value somewhere
1838 /// outside of the DeclContext, to reduce the size of DeclContext by
1839 /// another pointer.
1840 mutable Decl *LastDecl = nullptr;
1841
1842 /// Build up a chain of declarations.
1843 ///
1844 /// \returns the first/last pair of declarations.
1845 static std::pair<Decl *, Decl *>
1846 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1847
1848 DeclContext(Decl::Kind K);
1849
1850public:
1851 ~DeclContext();
1852
1853 Decl::Kind getDeclKind() const {
1854 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1855 }
1856
1857 const char *getDeclKindName() const;
1858
1859 /// getParent - Returns the containing DeclContext.
1860 DeclContext *getParent() {
1861 return cast<Decl>(this)->getDeclContext();
1862 }
1863 const DeclContext *getParent() const {
1864 return const_cast<DeclContext*>(this)->getParent();
1865 }
1866
1867 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1868 /// different from getParent, e.g.:
1869 ///
1870 /// namespace A {
1871 /// struct S;
1872 /// }
1873 /// struct A::S {}; // getParent() == namespace 'A'
1874 /// // getLexicalParent() == translation unit
1875 ///
1876 DeclContext *getLexicalParent() {
1877 return cast<Decl>(this)->getLexicalDeclContext();
1878 }
1879 const DeclContext *getLexicalParent() const {
1880 return const_cast<DeclContext*>(this)->getLexicalParent();
1881 }
1882
1883 DeclContext *getLookupParent();
1884
1885 const DeclContext *getLookupParent() const {
1886 return const_cast<DeclContext*>(this)->getLookupParent();
1887 }
1888
1889 ASTContext &getParentASTContext() const {
1890 return cast<Decl>(this)->getASTContext();
1891 }
1892
1893 bool isClosure() const { return getDeclKind() == Decl::Block; }
1894
1895 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1896 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1897 const BlockDecl *getInnermostBlockDecl() const;
1898
1899 bool isObjCContainer() const {
1900 switch (getDeclKind()) {
1901 case Decl::ObjCCategory:
1902 case Decl::ObjCCategoryImpl:
1903 case Decl::ObjCImplementation:
1904 case Decl::ObjCInterface:
1905 case Decl::ObjCProtocol:
1906 return true;
1907 default:
1908 return false;
1909 }
1910 }
1911
1912 bool isFunctionOrMethod() const {
1913 switch (getDeclKind()) {
28
Control jumps to the 'default' case at line 1918
1914 case Decl::Block:
1915 case Decl::Captured:
1916 case Decl::ObjCMethod:
1917 return true;
1918 default:
1919 return getDeclKind() >= Decl::firstFunction &&
29
Assuming the condition is false
30
Returning zero, which participates in a condition later
1920 getDeclKind() <= Decl::lastFunction;
1921 }
1922 }
1923
1924 /// Test whether the context supports looking up names.
1925 bool isLookupContext() const {
1926 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1927 getDeclKind() != Decl::Export;
1928 }
1929
1930 bool isFileContext() const {
1931 return getDeclKind() == Decl::TranslationUnit ||
1932 getDeclKind() == Decl::Namespace;
1933 }
1934
1935 bool isTranslationUnit() const {
1936 return getDeclKind() == Decl::TranslationUnit;
1937 }
1938
1939 bool isRecord() const {
1940 return getDeclKind() >= Decl::firstRecord &&
1941 getDeclKind() <= Decl::lastRecord;
1942 }
1943
1944 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1945
1946 bool isStdNamespace() const;
1947
1948 bool isInlineNamespace() const;
1949
1950 /// Determines whether this context is dependent on a
1951 /// template parameter.
1952 bool isDependentContext() const;
1953
1954 /// isTransparentContext - Determines whether this context is a
1955 /// "transparent" context, meaning that the members declared in this
1956 /// context are semantically declared in the nearest enclosing
1957 /// non-transparent (opaque) context but are lexically declared in
1958 /// this context. For example, consider the enumerators of an
1959 /// enumeration type:
1960 /// @code
1961 /// enum E {
1962 /// Val1
1963 /// };
1964 /// @endcode
1965 /// Here, E is a transparent context, so its enumerator (Val1) will
1966 /// appear (semantically) that it is in the same context of E.
1967 /// Examples of transparent contexts include: enumerations (except for
1968 /// C++0x scoped enums), and C++ linkage specifications.
1969 bool isTransparentContext() const;
1970
1971 /// Determines whether this context or some of its ancestors is a
1972 /// linkage specification context that specifies C linkage.
1973 bool isExternCContext() const;
1974
1975 /// Retrieve the nearest enclosing C linkage specification context.
1976 const LinkageSpecDecl *getExternCContext() const;
1977
1978 /// Determines whether this context or some of its ancestors is a
1979 /// linkage specification context that specifies C++ linkage.
1980 bool isExternCXXContext() const;
1981
1982 /// Determine whether this declaration context is equivalent
1983 /// to the declaration context DC.
1984 bool Equals(const DeclContext *DC) const {
1985 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1986 }
1987
1988 /// Determine whether this declaration context encloses the
1989 /// declaration context DC.
1990 bool Encloses(const DeclContext *DC) const;
1991
1992 /// Find the nearest non-closure ancestor of this context,
1993 /// i.e. the innermost semantic parent of this context which is not
1994 /// a closure. A context may be its own non-closure ancestor.
1995 Decl *getNonClosureAncestor();
1996 const Decl *getNonClosureAncestor() const {
1997 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1998 }
1999
2000 /// getPrimaryContext - There may be many different
2001 /// declarations of the same entity (including forward declarations
2002 /// of classes, multiple definitions of namespaces, etc.), each with
2003 /// a different set of declarations. This routine returns the
2004 /// "primary" DeclContext structure, which will contain the
2005 /// information needed to perform name lookup into this context.
2006 DeclContext *getPrimaryContext();
2007 const DeclContext *getPrimaryContext() const {
2008 return const_cast<DeclContext*>(this)->getPrimaryContext();
2009 }
2010
2011 /// getRedeclContext - Retrieve the context in which an entity conflicts with
2012 /// other entities of the same name, or where it is a redeclaration if the
2013 /// two entities are compatible. This skips through transparent contexts.
2014 DeclContext *getRedeclContext();
2015 const DeclContext *getRedeclContext() const {
2016 return const_cast<DeclContext *>(this)->getRedeclContext();
2017 }
2018
2019 /// Retrieve the nearest enclosing namespace context.
2020 DeclContext *getEnclosingNamespaceContext();
2021 const DeclContext *getEnclosingNamespaceContext() const {
2022 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
2023 }
2024
2025 /// Retrieve the outermost lexically enclosing record context.
2026 RecordDecl *getOuterLexicalRecordContext();
2027 const RecordDecl *getOuterLexicalRecordContext() const {
2028 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
2029 }
2030
2031 /// Test if this context is part of the enclosing namespace set of
2032 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
2033 /// isn't a namespace, this is equivalent to Equals().
2034 ///
2035 /// The enclosing namespace set of a namespace is the namespace and, if it is
2036 /// inline, its enclosing namespace, recursively.
2037 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
2038
2039 /// Collects all of the declaration contexts that are semantically
2040 /// connected to this declaration context.
2041 ///
2042 /// For declaration contexts that have multiple semantically connected but
2043 /// syntactically distinct contexts, such as C++ namespaces, this routine
2044 /// retrieves the complete set of such declaration contexts in source order.
2045 /// For example, given:
2046 ///
2047 /// \code
2048 /// namespace N {
2049 /// int x;
2050 /// }
2051 /// namespace N {
2052 /// int y;
2053 /// }
2054 /// \endcode
2055 ///
2056 /// The \c Contexts parameter will contain both definitions of N.
2057 ///
2058 /// \param Contexts Will be cleared and set to the set of declaration
2059 /// contexts that are semanticaly connected to this declaration context,
2060 /// in source order, including this context (which may be the only result,
2061 /// for non-namespace contexts).
2062 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2063
2064 /// decl_iterator - Iterates through the declarations stored
2065 /// within this context.
2066 class decl_iterator {
2067 /// Current - The current declaration.
2068 Decl *Current = nullptr;
2069
2070 public:
2071 using value_type = Decl *;
2072 using reference = const value_type &;
2073 using pointer = const value_type *;
2074 using iterator_category = std::forward_iterator_tag;
2075 using difference_type = std::ptrdiff_t;
2076
2077 decl_iterator() = default;
2078 explicit decl_iterator(Decl *C) : Current(C) {}
2079
2080 reference operator*() const { return Current; }
2081
2082 // This doesn't meet the iterator requirements, but it's convenient
2083 value_type operator->() const { return Current; }
2084
2085 decl_iterator& operator++() {
2086 Current = Current->getNextDeclInContext();
2087 return *this;
2088 }
2089
2090 decl_iterator operator++(int) {
2091 decl_iterator tmp(*this);
2092 ++(*this);
2093 return tmp;
2094 }
2095
2096 friend bool operator==(decl_iterator x, decl_iterator y) {
2097 return x.Current == y.Current;
2098 }
2099
2100 friend bool operator!=(decl_iterator x, decl_iterator y) {
2101 return x.Current != y.Current;
2102 }
2103 };
2104
2105 using decl_range = llvm::iterator_range<decl_iterator>;
2106
2107 /// decls_begin/decls_end - Iterate over the declarations stored in
2108 /// this context.
2109 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2110 decl_iterator decls_begin() const;
2111 decl_iterator decls_end() const { return decl_iterator(); }
2112 bool decls_empty() const;
2113
2114 /// noload_decls_begin/end - Iterate over the declarations stored in this
2115 /// context that are currently loaded; don't attempt to retrieve anything
2116 /// from an external source.
2117 decl_range noload_decls() const {
2118 return decl_range(noload_decls_begin(), noload_decls_end());
2119 }
2120 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2121 decl_iterator noload_decls_end() const { return decl_iterator(); }
2122
2123 /// specific_decl_iterator - Iterates over a subrange of
2124 /// declarations stored in a DeclContext, providing only those that
2125 /// are of type SpecificDecl (or a class derived from it). This
2126 /// iterator is used, for example, to provide iteration over just
2127 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2128 template<typename SpecificDecl>
2129 class specific_decl_iterator {
2130 /// Current - The current, underlying declaration iterator, which
2131 /// will either be NULL or will point to a declaration of
2132 /// type SpecificDecl.
2133 DeclContext::decl_iterator Current;
2134
2135 /// SkipToNextDecl - Advances the current position up to the next
2136 /// declaration of type SpecificDecl that also meets the criteria
2137 /// required by Acceptable.
2138 void SkipToNextDecl() {
2139 while (*Current && !isa<SpecificDecl>(*Current))
2140 ++Current;
2141 }
2142
2143 public:
2144 using value_type = SpecificDecl *;
2145 // TODO: Add reference and pointer types (with some appropriate proxy type)
2146 // if we ever have a need for them.
2147 using reference = void;
2148 using pointer = void;
2149 using difference_type =
2150 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2151 using iterator_category = std::forward_iterator_tag;
2152
2153 specific_decl_iterator() = default;
2154
2155 /// specific_decl_iterator - Construct a new iterator over a
2156 /// subset of the declarations the range [C,
2157 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2158 /// member function of SpecificDecl that should return true for
2159 /// all of the SpecificDecl instances that will be in the subset
2160 /// of iterators. For example, if you want Objective-C instance
2161 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2162 /// &ObjCMethodDecl::isInstanceMethod.
2163 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2164 SkipToNextDecl();
2165 }
2166
2167 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2168
2169 // This doesn't meet the iterator requirements, but it's convenient
2170 value_type operator->() const { return **this; }
2171
2172 specific_decl_iterator& operator++() {
2173 ++Current;
2174 SkipToNextDecl();
2175 return *this;
2176 }
2177
2178 specific_decl_iterator operator++(int) {
2179 specific_decl_iterator tmp(*this);
2180 ++(*this);
2181 return tmp;
2182 }
2183
2184 friend bool operator==(const specific_decl_iterator& x,
2185 const specific_decl_iterator& y) {
2186 return x.Current == y.Current;
2187 }
2188
2189 friend bool operator!=(const specific_decl_iterator& x,
2190 const specific_decl_iterator& y) {
2191 return x.Current != y.Current;
2192 }
2193 };
2194
2195 /// Iterates over a filtered subrange of declarations stored
2196 /// in a DeclContext.
2197 ///
2198 /// This iterator visits only those declarations that are of type
2199 /// SpecificDecl (or a class derived from it) and that meet some
2200 /// additional run-time criteria. This iterator is used, for
2201 /// example, to provide access to the instance methods within an
2202 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2203 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2204 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2205 class filtered_decl_iterator {
2206 /// Current - The current, underlying declaration iterator, which
2207 /// will either be NULL or will point to a declaration of
2208 /// type SpecificDecl.
2209 DeclContext::decl_iterator Current;
2210
2211 /// SkipToNextDecl - Advances the current position up to the next
2212 /// declaration of type SpecificDecl that also meets the criteria
2213 /// required by Acceptable.
2214 void SkipToNextDecl() {
2215 while (*Current &&
2216 (!isa<SpecificDecl>(*Current) ||
2217 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2218 ++Current;
2219 }
2220
2221 public:
2222 using value_type = SpecificDecl *;
2223 // TODO: Add reference and pointer types (with some appropriate proxy type)
2224 // if we ever have a need for them.
2225 using reference = void;
2226 using pointer = void;
2227 using difference_type =
2228 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2229 using iterator_category = std::forward_iterator_tag;
2230
2231 filtered_decl_iterator() = default;
2232
2233 /// filtered_decl_iterator - Construct a new iterator over a
2234 /// subset of the declarations the range [C,
2235 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2236 /// member function of SpecificDecl that should return true for
2237 /// all of the SpecificDecl instances that will be in the subset
2238 /// of iterators. For example, if you want Objective-C instance
2239 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2240 /// &ObjCMethodDecl::isInstanceMethod.
2241 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2242 SkipToNextDecl();
2243 }
2244
2245 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2246 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2247
2248 filtered_decl_iterator& operator++() {
2249 ++Current;
2250 SkipToNextDecl();
2251 return *this;
2252 }
2253
2254 filtered_decl_iterator operator++(int) {
2255 filtered_decl_iterator tmp(*this);
2256 ++(*this);
2257 return tmp;
2258 }
2259
2260 friend bool operator==(const filtered_decl_iterator& x,
2261 const filtered_decl_iterator& y) {
2262 return x.Current == y.Current;
2263 }
2264
2265 friend bool operator!=(const filtered_decl_iterator& x,
2266 const filtered_decl_iterator& y) {
2267 return x.Current != y.Current;
2268 }
2269 };
2270
2271 /// Add the declaration D into this context.
2272 ///
2273 /// This routine should be invoked when the declaration D has first
2274 /// been declared, to place D into the context where it was
2275 /// (lexically) defined. Every declaration must be added to one
2276 /// (and only one!) context, where it can be visited via
2277 /// [decls_begin(), decls_end()). Once a declaration has been added
2278 /// to its lexical context, the corresponding DeclContext owns the
2279 /// declaration.
2280 ///
2281 /// If D is also a NamedDecl, it will be made visible within its
2282 /// semantic context via makeDeclVisibleInContext.
2283 void addDecl(Decl *D);
2284
2285 /// Add the declaration D into this context, but suppress
2286 /// searches for external declarations with the same name.
2287 ///
2288 /// Although analogous in function to addDecl, this removes an
2289 /// important check. This is only useful if the Decl is being
2290 /// added in response to an external search; in all other cases,
2291 /// addDecl() is the right function to use.
2292 /// See the ASTImporter for use cases.
2293 void addDeclInternal(Decl *D);
2294
2295 /// Add the declaration D to this context without modifying
2296 /// any lookup tables.
2297 ///
2298 /// This is useful for some operations in dependent contexts where
2299 /// the semantic context might not be dependent; this basically
2300 /// only happens with friends.
2301 void addHiddenDecl(Decl *D);
2302
2303 /// Removes a declaration from this context.
2304 void removeDecl(Decl *D);
2305
2306 /// Checks whether a declaration is in this context.
2307 bool containsDecl(Decl *D) const;
2308
2309 /// Checks whether a declaration is in this context.
2310 /// This also loads the Decls from the external source before the check.
2311 bool containsDeclAndLoad(Decl *D) const;
2312
2313 using lookup_result = DeclContextLookupResult;
2314 using lookup_iterator = lookup_result::iterator;
2315
2316 /// lookup - Find the declarations (if any) with the given Name in
2317 /// this context. Returns a range of iterators that contains all of
2318 /// the declarations with this name, with object, function, member,
2319 /// and enumerator names preceding any tag name. Note that this
2320 /// routine will not look into parent contexts.
2321 lookup_result lookup(DeclarationName Name) const;
2322
2323 /// Find the declarations with the given name that are visible
2324 /// within this context; don't attempt to retrieve anything from an
2325 /// external source.
2326 lookup_result noload_lookup(DeclarationName Name);
2327
2328 /// A simplistic name lookup mechanism that performs name lookup
2329 /// into this declaration context without consulting the external source.
2330 ///
2331 /// This function should almost never be used, because it subverts the
2332 /// usual relationship between a DeclContext and the external source.
2333 /// See the ASTImporter for the (few, but important) use cases.
2334 ///
2335 /// FIXME: This is very inefficient; replace uses of it with uses of
2336 /// noload_lookup.
2337 void localUncachedLookup(DeclarationName Name,
2338 SmallVectorImpl<NamedDecl *> &Results);
2339
2340 /// Makes a declaration visible within this context.
2341 ///
2342 /// This routine makes the declaration D visible to name lookup
2343 /// within this context and, if this is a transparent context,
2344 /// within its parent contexts up to the first enclosing
2345 /// non-transparent context. Making a declaration visible within a
2346 /// context does not transfer ownership of a declaration, and a
2347 /// declaration can be visible in many contexts that aren't its
2348 /// lexical context.
2349 ///
2350 /// If D is a redeclaration of an existing declaration that is
2351 /// visible from this context, as determined by
2352 /// NamedDecl::declarationReplaces, the previous declaration will be
2353 /// replaced with D.
2354 void makeDeclVisibleInContext(NamedDecl *D);
2355
2356 /// all_lookups_iterator - An iterator that provides a view over the results
2357 /// of looking up every possible name.
2358 class all_lookups_iterator;
2359
2360 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2361
2362 lookups_range lookups() const;
2363 // Like lookups(), but avoids loading external declarations.
2364 // If PreserveInternalState, avoids building lookup data structures too.
2365 lookups_range noload_lookups(bool PreserveInternalState) const;
2366
2367 /// Iterators over all possible lookups within this context.
2368 all_lookups_iterator lookups_begin() const;
2369 all_lookups_iterator lookups_end() const;
2370
2371 /// Iterators over all possible lookups within this context that are
2372 /// currently loaded; don't attempt to retrieve anything from an external
2373 /// source.
2374 all_lookups_iterator noload_lookups_begin() const;
2375 all_lookups_iterator noload_lookups_end() const;
2376
2377 struct udir_iterator;
2378
2379 using udir_iterator_base =
2380 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2381 typename lookup_iterator::iterator_category,
2382 UsingDirectiveDecl *>;
2383
2384 struct udir_iterator : udir_iterator_base {
2385 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2386
2387 UsingDirectiveDecl *operator*() const;
2388 };
2389
2390 using udir_range = llvm::iterator_range<udir_iterator>;
2391
2392 udir_range using_directives() const;
2393
2394 // These are all defined in DependentDiagnostic.h.
2395 class ddiag_iterator;
2396
2397 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2398
2399 inline ddiag_range ddiags() const;
2400
2401 // Low-level accessors
2402
2403 /// Mark that there are external lexical declarations that we need
2404 /// to include in our lookup table (and that are not available as external
2405 /// visible lookups). These extra lookup results will be found by walking
2406 /// the lexical declarations of this context. This should be used only if
2407 /// setHasExternalLexicalStorage() has been called on any decl context for
2408 /// which this is the primary context.
2409 void setMustBuildLookupTable() {
2410 assert(this == getPrimaryContext() &&((void)0)
2411 "should only be called on primary context")((void)0);
2412 DeclContextBits.HasLazyExternalLexicalLookups = true;
2413 }
2414
2415 /// Retrieve the internal representation of the lookup structure.
2416 /// This may omit some names if we are lazily building the structure.
2417 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2418
2419 /// Ensure the lookup structure is fully-built and return it.
2420 StoredDeclsMap *buildLookup();
2421
2422 /// Whether this DeclContext has external storage containing
2423 /// additional declarations that are lexically in this context.
2424 bool hasExternalLexicalStorage() const {
2425 return DeclContextBits.ExternalLexicalStorage;
2426 }
2427
2428 /// State whether this DeclContext has external storage for
2429 /// declarations lexically in this context.
2430 void setHasExternalLexicalStorage(bool ES = true) const {
2431 DeclContextBits.ExternalLexicalStorage = ES;
2432 }
2433
2434 /// Whether this DeclContext has external storage containing
2435 /// additional declarations that are visible in this context.
2436 bool hasExternalVisibleStorage() const {
2437 return DeclContextBits.ExternalVisibleStorage;
2438 }
2439
2440 /// State whether this DeclContext has external storage for
2441 /// declarations visible in this context.
2442 void setHasExternalVisibleStorage(bool ES = true) const {
2443 DeclContextBits.ExternalVisibleStorage = ES;
2444 if (ES && LookupPtr)
2445 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2446 }
2447
2448 /// Determine whether the given declaration is stored in the list of
2449 /// declarations lexically within this context.
2450 bool isDeclInLexicalTraversal(const Decl *D) const {
2451 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2452 D == LastDecl);
2453 }
2454
2455 bool setUseQualifiedLookup(bool use = true) const {
2456 bool old_value = DeclContextBits.UseQualifiedLookup;
2457 DeclContextBits.UseQualifiedLookup = use;
2458 return old_value;
2459 }
2460
2461 bool shouldUseQualifiedLookup() const {
2462 return DeclContextBits.UseQualifiedLookup;
2463 }
2464
2465 static bool classof(const Decl *D);
2466 static bool classof(const DeclContext *D) { return true; }
2467
2468 void dumpDeclContext() const;
2469 void dumpLookups() const;
2470 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2471 bool Deserialize = false) const;
2472
2473private:
2474 /// Whether this declaration context has had externally visible
2475 /// storage added since the last lookup. In this case, \c LookupPtr's
2476 /// invariant may not hold and needs to be fixed before we perform
2477 /// another lookup.
2478 bool hasNeedToReconcileExternalVisibleStorage() const {
2479 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2480 }
2481
2482 /// State that this declaration context has had externally visible
2483 /// storage added since the last lookup. In this case, \c LookupPtr's
2484 /// invariant may not hold and needs to be fixed before we perform
2485 /// another lookup.
2486 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2487 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2488 }
2489
2490 /// If \c true, this context may have local lexical declarations
2491 /// that are missing from the lookup table.
2492 bool hasLazyLocalLexicalLookups() const {
2493 return DeclContextBits.HasLazyLocalLexicalLookups;
2494 }
2495
2496 /// If \c true, this context may have local lexical declarations
2497 /// that are missing from the lookup table.
2498 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2499 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2500 }
2501
2502 /// If \c true, the external source may have lexical declarations
2503 /// that are missing from the lookup table.
2504 bool hasLazyExternalLexicalLookups() const {
2505 return DeclContextBits.HasLazyExternalLexicalLookups;
2506 }
2507
2508 /// If \c true, the external source may have lexical declarations
2509 /// that are missing from the lookup table.
2510 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2511 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2512 }
2513
2514 void reconcileExternalVisibleStorage() const;
2515 bool LoadLexicalDeclsFromExternalStorage() const;
2516
2517 /// Makes a declaration visible within this context, but
2518 /// suppresses searches for external declarations with the same
2519 /// name.
2520 ///
2521 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2522 /// use of addDeclInternal().
2523 void makeDeclVisibleInContextInternal(NamedDecl *D);
2524
2525 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2526
2527 void loadLazyLocalLexicalLookups();
2528 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2529 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2530 bool Rediscoverable);
2531 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2532};
2533
2534inline bool Decl::isTemplateParameter() const {
2535 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2536 getKind() == TemplateTemplateParm;
2537}
2538
2539// Specialization selected when ToTy is not a known subclass of DeclContext.
2540template <class ToTy,
2541 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2542struct cast_convert_decl_context {
2543 static const ToTy *doit(const DeclContext *Val) {
2544 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2545 }
2546
2547 static ToTy *doit(DeclContext *Val) {
2548 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2549 }
2550};
2551
2552// Specialization selected when ToTy is a known subclass of DeclContext.
2553template <class ToTy>
2554struct cast_convert_decl_context<ToTy, true> {
2555 static const ToTy *doit(const DeclContext *Val) {
2556 return static_cast<const ToTy*>(Val);
2557 }
2558
2559 static ToTy *doit(DeclContext *Val) {
2560 return static_cast<ToTy*>(Val);
2561 }
2562};
2563
2564} // namespace clang
2565
2566namespace llvm {
2567
2568/// isa<T>(DeclContext*)
2569template <typename To>
2570struct isa_impl<To, ::clang::DeclContext> {
2571 static bool doit(const ::clang::DeclContext &Val) {
2572 return To::classofKind(Val.getDeclKind());
2573 }
2574};
2575
2576/// cast<T>(DeclContext*)
2577template<class ToTy>
2578struct cast_convert_val<ToTy,
2579 const ::clang::DeclContext,const ::clang::DeclContext> {
2580 static const ToTy &doit(const ::clang::DeclContext &Val) {
2581 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2582 }
2583};
2584
2585template<class ToTy>
2586struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2587 static ToTy &doit(::clang::DeclContext &Val) {
2588 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2589 }
2590};
2591
2592template<class ToTy>
2593struct cast_convert_val<ToTy,
2594 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2595 static const ToTy *doit(const ::clang::DeclContext *Val) {
2596 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2597 }
2598};
2599
2600template<class ToTy>
2601struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2602 static ToTy *doit(::clang::DeclContext *Val) {
2603 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2604 }
2605};
2606
2607/// Implement cast_convert_val for Decl -> DeclContext conversions.
2608template<class FromTy>
2609struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2610 static ::clang::DeclContext &doit(const FromTy &Val) {
2611 return *FromTy::castToDeclContext(&Val);
2612 }
2613};
2614
2615template<class FromTy>
2616struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2617 static ::clang::DeclContext *doit(const FromTy *Val) {
2618 return FromTy::castToDeclContext(Val);
2619 }
2620};
2621
2622template<class FromTy>
2623struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2624 static const ::clang::DeclContext &doit(const FromTy &Val) {
2625 return *FromTy::castToDeclContext(&Val);
2626 }
2627};
2628
2629template<class FromTy>
2630struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2631 static const ::clang::DeclContext *doit(const FromTy *Val) {
2632 return FromTy::castToDeclContext(Val);
2633 }
2634};
2635
2636} // namespace llvm
2637
2638#endif // LLVM_CLANG_AST_DECLBASE_H

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/llvm/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
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//
9// This file defines the PointerUnion class, which is a discriminated union of
10// pointer types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERUNION_H
15#define LLVM_ADT_POINTERUNION_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include <cassert>
21#include <cstddef>
22#include <cstdint>
23
24namespace llvm {
25
26template <typename T> struct PointerUnionTypeSelectorReturn {
27 using Return = T;
28};
29
30/// Get a type based on whether two types are the same or not.
31///
32/// For:
33///
34/// \code
35/// using Ret = typename PointerUnionTypeSelector<T1, T2, EQ, NE>::Return;
36/// \endcode
37///
38/// Ret will be EQ type if T1 is same as T2 or NE type otherwise.
39template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
40struct PointerUnionTypeSelector {
41 using Return = typename PointerUnionTypeSelectorReturn<RET_NE>::Return;
42};
43
44template <typename T, typename RET_EQ, typename RET_NE>
45struct PointerUnionTypeSelector<T, T, RET_EQ, RET_NE> {
46 using Return = typename PointerUnionTypeSelectorReturn<RET_EQ>::Return;
47};
48
49template <typename T1, typename T2, typename RET_EQ, typename RET_NE>
50struct PointerUnionTypeSelectorReturn<
51 PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>> {
52 using Return =
53 typename PointerUnionTypeSelector<T1, T2, RET_EQ, RET_NE>::Return;
54};
55
56namespace pointer_union_detail {
57 /// Determine the number of bits required to store integers with values < n.
58 /// This is ceil(log2(n)).
59 constexpr int bitsRequired(unsigned n) {
60 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
61 }
62
63 template <typename... Ts> constexpr int lowBitsAvailable() {
64 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
65 }
66
67 /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
68 /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
69 /// list.
70 template <typename T, typename ...Us> struct TypeIndex;
71 template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> {
72 static constexpr int Index = 0;
73 };
74 template <typename T, typename U, typename... Us>
75 struct TypeIndex<T, U, Us...> {
76 static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
77 };
78 template <typename T> struct TypeIndex<T> {
79 static constexpr int Index = 0;
80 };
81
82 /// Find the first type in a list of types.
83 template <typename T, typename...> struct GetFirstType {
84 using type = T;
85 };
86
87 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
88 /// for the template arguments.
89 template <typename ...PTs> class PointerUnionUIntTraits {
90 public:
91 static inline void *getAsVoidPointer(void *P) { return P; }
92 static inline void *getFromVoidPointer(void *P) { return P; }
93 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
94 };
95
96 template <typename Derived, typename ValTy, int I, typename ...Types>
97 class PointerUnionMembers;
98
99 template <typename Derived, typename ValTy, int I>
100 class PointerUnionMembers<Derived, ValTy, I> {
101 protected:
102 ValTy Val;
103 PointerUnionMembers() = default;
104 PointerUnionMembers(ValTy Val) : Val(Val) {}
105
106 friend struct PointerLikeTypeTraits<Derived>;
107 };
108
109 template <typename Derived, typename ValTy, int I, typename Type,
110 typename ...Types>
111 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
112 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
113 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
114 public:
115 using Base::Base;
116 PointerUnionMembers() = default;
117 PointerUnionMembers(Type V)
118 : Base(ValTy(const_cast<void *>(
119 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
120 I)) {}
121
122 using Base::operator=;
123 Derived &operator=(Type V) {
124 this->Val = ValTy(
125 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
126 I);
127 return static_cast<Derived &>(*this);
128 };
129 };
130}
131
132/// A discriminated union of two or more pointer types, with the discriminator
133/// in the low bit of the pointer.
134///
135/// This implementation is extremely efficient in space due to leveraging the
136/// low bits of the pointer, while exposing a natural and type-safe API.
137///
138/// Common use patterns would be something like this:
139/// PointerUnion<int*, float*> P;
140/// P = (int*)0;
141/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
142/// X = P.get<int*>(); // ok.
143/// Y = P.get<float*>(); // runtime assertion failure.
144/// Z = P.get<double*>(); // compile time failure.
145/// P = (float*)0;
146/// Y = P.get<float*>(); // ok.
147/// X = P.get<int*>(); // runtime assertion failure.
148template <typename... PTs>
149class PointerUnion
150 : public pointer_union_detail::PointerUnionMembers<
151 PointerUnion<PTs...>,
152 PointerIntPair<
153 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
154 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
155 0, PTs...> {
156 // The first type is special because we want to directly cast a pointer to a
157 // default-initialized union to a pointer to the first type. But we don't
158 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
159 // because it's much more convenient to have a name for the whole pack. So
160 // split off the first type here.
161 using First = typename pointer_union_detail::GetFirstType<PTs...>::type;
162 using Base = typename PointerUnion::PointerUnionMembers;
163
164public:
165 PointerUnion() = default;
166
167 PointerUnion(std::nullptr_t) : PointerUnion() {}
168 using Base::Base;
169
170 /// Test if the pointer held in the union is null, regardless of
171 /// which type it is.
172 bool isNull() const { return !this->Val.getPointer(); }
173
174 explicit operator bool() const { return !isNull(); }
175
176 /// Test if the Union currently holds the type matching T.
177 template <typename T> bool is() const {
178 constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index;
179 static_assert(Index < sizeof...(PTs),
180 "PointerUnion::is<T> given type not in the union");
181 return this->Val.getInt() == Index;
4
Assuming the condition is false
5
Returning zero, which participates in a condition later
182 }
183
184 /// Returns the value of the specified pointer type.
185 ///
186 /// If the specified pointer type is incorrect, assert.
187 template <typename T> T get() const {
188 assert(is<T>() && "Invalid accessor called")((void)0);
189 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
190 }
191
192 /// Returns the current pointer if it is of the specified pointer type,
193 /// otherwise returns null.
194 template <typename T> T dyn_cast() const {
195 if (is<T>())
196 return get<T>();
197 return T();
198 }
199
200 /// If the union is set to the first pointer type get an address pointing to
201 /// it.
202 First const *getAddrOfPtr1() const {
203 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
204 }
205
206 /// If the union is set to the first pointer type get an address pointing to
207 /// it.
208 First *getAddrOfPtr1() {
209 assert(is<First>() && "Val is not the first pointer")((void)0);
210 assert(((void)0)
211 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==((void)0)
212 this->Val.getPointer() &&((void)0)
213 "Can't get the address because PointerLikeTypeTraits changes the ptr")((void)0);
214 return const_cast<First *>(
215 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
216 }
217
218 /// Assignment from nullptr which just clears the union.
219 const PointerUnion &operator=(std::nullptr_t) {
220 this->Val.initWithPointer(nullptr);
221 return *this;
222 }
223
224 /// Assignment from elements of the union.
225 using Base::operator=;
226
227 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
228 static inline PointerUnion getFromOpaqueValue(void *VP) {
229 PointerUnion V;
230 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
231 return V;
232 }
233};
234
235template <typename ...PTs>
236bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
237 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
238}
239
240template <typename ...PTs>
241bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
242 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
243}
244
245template <typename ...PTs>
246bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
247 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
248}
249
250// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
251// # low bits available = min(PT1bits,PT2bits)-1.
252template <typename ...PTs>
253struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
254 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
255 return P.getOpaqueValue();
256 }
257
258 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
259 return PointerUnion<PTs...>::getFromOpaqueValue(P);
260 }
261
262 // The number of bits available are the min of the pointer types minus the
263 // bits needed for the discriminator.
264 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
265 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
266};
267
268// Teach DenseMap how to use PointerUnions as keys.
269template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
270 using Union = PointerUnion<PTs...>;
271 using FirstInfo =
272 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
273
274 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
275
276 static inline Union getTombstoneKey() {
277 return Union(FirstInfo::getTombstoneKey());
278 }
279
280 static unsigned getHashValue(const Union &UnionVal) {
281 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
282 return DenseMapInfo<intptr_t>::getHashValue(key);
283 }
284
285 static bool isEqual(const Union &LHS, const Union &RHS) {
286 return LHS == RHS;
287 }
288};
289
290} // end namespace llvm
291
292#endif // LLVM_ADT_POINTERUNION_H