Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/lib/Sema/SemaLambda.cpp
Warning:line 1212, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaLambda.cpp -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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-29-125212-15910-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/lib/Sema/SemaLambda.cpp

/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/lib/Sema/SemaLambda.cpp

1//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
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 implements semantic analysis for C++ lambda expressions.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/Sema/DeclSpec.h"
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTLambda.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
19#include "clang/Sema/Scope.h"
20#include "clang/Sema/ScopeInfo.h"
21#include "clang/Sema/SemaInternal.h"
22#include "clang/Sema/SemaLambda.h"
23#include "llvm/ADT/STLExtras.h"
24using namespace clang;
25using namespace sema;
26
27/// Examines the FunctionScopeInfo stack to determine the nearest
28/// enclosing lambda (to the current lambda) that is 'capture-ready' for
29/// the variable referenced in the current lambda (i.e. \p VarToCapture).
30/// If successful, returns the index into Sema's FunctionScopeInfo stack
31/// of the capture-ready lambda's LambdaScopeInfo.
32///
33/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
34/// lambda - is on top) to determine the index of the nearest enclosing/outer
35/// lambda that is ready to capture the \p VarToCapture being referenced in
36/// the current lambda.
37/// As we climb down the stack, we want the index of the first such lambda -
38/// that is the lambda with the highest index that is 'capture-ready'.
39///
40/// A lambda 'L' is capture-ready for 'V' (var or this) if:
41/// - its enclosing context is non-dependent
42/// - and if the chain of lambdas between L and the lambda in which
43/// V is potentially used (i.e. the lambda at the top of the scope info
44/// stack), can all capture or have already captured V.
45/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
46///
47/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
48/// for whether it is 'capture-capable' (see
49/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
50/// capture.
51///
52/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
53/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
54/// is at the top of the stack and has the highest index.
55/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
56///
57/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
58/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
59/// which is capture-ready. If the return value evaluates to 'false' then
60/// no lambda is capture-ready for \p VarToCapture.
61
62static inline Optional<unsigned>
63getStackIndexOfNearestEnclosingCaptureReadyLambda(
64 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
65 VarDecl *VarToCapture) {
66 // Label failure to capture.
67 const Optional<unsigned> NoLambdaIsCaptureReady;
68
69 // Ignore all inner captured regions.
70 unsigned CurScopeIndex = FunctionScopes.size() - 1;
71 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
72 FunctionScopes[CurScopeIndex]))
73 --CurScopeIndex;
74 assert((static_cast <bool> (isa<clang::sema::LambdaScopeInfo
>(FunctionScopes[CurScopeIndex]) && "The function on the top of sema's function-info stack must be a lambda"
) ? void (0) : __assert_fail ("isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && \"The function on the top of sema's function-info stack must be a lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 76, __extension__ __PRETTY_FUNCTION__
))
75 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&(static_cast <bool> (isa<clang::sema::LambdaScopeInfo
>(FunctionScopes[CurScopeIndex]) && "The function on the top of sema's function-info stack must be a lambda"
) ? void (0) : __assert_fail ("isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && \"The function on the top of sema's function-info stack must be a lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 76, __extension__ __PRETTY_FUNCTION__
))
76 "The function on the top of sema's function-info stack must be a lambda")(static_cast <bool> (isa<clang::sema::LambdaScopeInfo
>(FunctionScopes[CurScopeIndex]) && "The function on the top of sema's function-info stack must be a lambda"
) ? void (0) : __assert_fail ("isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && \"The function on the top of sema's function-info stack must be a lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 76, __extension__ __PRETTY_FUNCTION__
))
;
77
78 // If VarToCapture is null, we are attempting to capture 'this'.
79 const bool IsCapturingThis = !VarToCapture;
80 const bool IsCapturingVariable = !IsCapturingThis;
81
82 // Start with the current lambda at the top of the stack (highest index).
83 DeclContext *EnclosingDC =
84 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
85
86 do {
87 const clang::sema::LambdaScopeInfo *LSI =
88 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
89 // IF we have climbed down to an intervening enclosing lambda that contains
90 // the variable declaration - it obviously can/must not capture the
91 // variable.
92 // Since its enclosing DC is dependent, all the lambdas between it and the
93 // innermost nested lambda are dependent (otherwise we wouldn't have
94 // arrived here) - so we don't yet have a lambda that can capture the
95 // variable.
96 if (IsCapturingVariable &&
97 VarToCapture->getDeclContext()->Equals(EnclosingDC))
98 return NoLambdaIsCaptureReady;
99
100 // For an enclosing lambda to be capture ready for an entity, all
101 // intervening lambda's have to be able to capture that entity. If even
102 // one of the intervening lambda's is not capable of capturing the entity
103 // then no enclosing lambda can ever capture that entity.
104 // For e.g.
105 // const int x = 10;
106 // [=](auto a) { #1
107 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
108 // [=](auto c) { #3
109 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
110 // }; }; };
111 // If they do not have a default implicit capture, check to see
112 // if the entity has already been explicitly captured.
113 // If even a single dependent enclosing lambda lacks the capability
114 // to ever capture this variable, there is no further enclosing
115 // non-dependent lambda that can capture this variable.
116 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
117 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
118 return NoLambdaIsCaptureReady;
119 if (IsCapturingThis && !LSI->isCXXThisCaptured())
120 return NoLambdaIsCaptureReady;
121 }
122 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
123
124 assert(CurScopeIndex)(static_cast <bool> (CurScopeIndex) ? void (0) : __assert_fail
("CurScopeIndex", "clang/lib/Sema/SemaLambda.cpp", 124, __extension__
__PRETTY_FUNCTION__))
;
125 --CurScopeIndex;
126 } while (!EnclosingDC->isTranslationUnit() &&
127 EnclosingDC->isDependentContext() &&
128 isLambdaCallOperator(EnclosingDC));
129
130 assert(CurScopeIndex < (FunctionScopes.size() - 1))(static_cast <bool> (CurScopeIndex < (FunctionScopes
.size() - 1)) ? void (0) : __assert_fail ("CurScopeIndex < (FunctionScopes.size() - 1)"
, "clang/lib/Sema/SemaLambda.cpp", 130, __extension__ __PRETTY_FUNCTION__
))
;
131 // If the enclosingDC is not dependent, then the immediately nested lambda
132 // (one index above) is capture-ready.
133 if (!EnclosingDC->isDependentContext())
134 return CurScopeIndex + 1;
135 return NoLambdaIsCaptureReady;
136}
137
138/// Examines the FunctionScopeInfo stack to determine the nearest
139/// enclosing lambda (to the current lambda) that is 'capture-capable' for
140/// the variable referenced in the current lambda (i.e. \p VarToCapture).
141/// If successful, returns the index into Sema's FunctionScopeInfo stack
142/// of the capture-capable lambda's LambdaScopeInfo.
143///
144/// Given the current stack of lambdas being processed by Sema and
145/// the variable of interest, to identify the nearest enclosing lambda (to the
146/// current lambda at the top of the stack) that can truly capture
147/// a variable, it has to have the following two properties:
148/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
149/// - climb down the stack (i.e. starting from the innermost and examining
150/// each outer lambda step by step) checking if each enclosing
151/// lambda can either implicitly or explicitly capture the variable.
152/// Record the first such lambda that is enclosed in a non-dependent
153/// context. If no such lambda currently exists return failure.
154/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
155/// capture the variable by checking all its enclosing lambdas:
156/// - check if all outer lambdas enclosing the 'capture-ready' lambda
157/// identified above in 'a' can also capture the variable (this is done
158/// via tryCaptureVariable for variables and CheckCXXThisCapture for
159/// 'this' by passing in the index of the Lambda identified in step 'a')
160///
161/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
162/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
163/// is at the top of the stack.
164///
165/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
166///
167///
168/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
169/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
170/// which is capture-capable. If the return value evaluates to 'false' then
171/// no lambda is capture-capable for \p VarToCapture.
172
173Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
174 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
175 VarDecl *VarToCapture, Sema &S) {
176
177 const Optional<unsigned> NoLambdaIsCaptureCapable;
178
179 const Optional<unsigned> OptionalStackIndex =
180 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
181 VarToCapture);
182 if (!OptionalStackIndex)
183 return NoLambdaIsCaptureCapable;
184
185 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
186 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||(static_cast <bool> (((IndexOfCaptureReadyLambda != (FunctionScopes
.size() - 1)) || S.getCurGenericLambda()) && "The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda") ? void (0) : __assert_fail
("((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || S.getCurGenericLambda()) && \"The capture ready lambda for a potential capture can only be the \" \"current lambda if it is a generic lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 189, __extension__ __PRETTY_FUNCTION__
))
187 S.getCurGenericLambda()) &&(static_cast <bool> (((IndexOfCaptureReadyLambda != (FunctionScopes
.size() - 1)) || S.getCurGenericLambda()) && "The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda") ? void (0) : __assert_fail
("((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || S.getCurGenericLambda()) && \"The capture ready lambda for a potential capture can only be the \" \"current lambda if it is a generic lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 189, __extension__ __PRETTY_FUNCTION__
))
188 "The capture ready lambda for a potential capture can only be the "(static_cast <bool> (((IndexOfCaptureReadyLambda != (FunctionScopes
.size() - 1)) || S.getCurGenericLambda()) && "The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda") ? void (0) : __assert_fail
("((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || S.getCurGenericLambda()) && \"The capture ready lambda for a potential capture can only be the \" \"current lambda if it is a generic lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 189, __extension__ __PRETTY_FUNCTION__
))
189 "current lambda if it is a generic lambda")(static_cast <bool> (((IndexOfCaptureReadyLambda != (FunctionScopes
.size() - 1)) || S.getCurGenericLambda()) && "The capture ready lambda for a potential capture can only be the "
"current lambda if it is a generic lambda") ? void (0) : __assert_fail
("((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || S.getCurGenericLambda()) && \"The capture ready lambda for a potential capture can only be the \" \"current lambda if it is a generic lambda\""
, "clang/lib/Sema/SemaLambda.cpp", 189, __extension__ __PRETTY_FUNCTION__
))
;
190
191 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
192 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
193
194 // If VarToCapture is null, we are attempting to capture 'this'
195 const bool IsCapturingThis = !VarToCapture;
196 const bool IsCapturingVariable = !IsCapturingThis;
197
198 if (IsCapturingVariable) {
199 // Check if the capture-ready lambda can truly capture the variable, by
200 // checking whether all enclosing lambdas of the capture-ready lambda allow
201 // the capture - i.e. make sure it is capture-capable.
202 QualType CaptureType, DeclRefType;
203 const bool CanCaptureVariable =
204 !S.tryCaptureVariable(VarToCapture,
205 /*ExprVarIsUsedInLoc*/ SourceLocation(),
206 clang::Sema::TryCapture_Implicit,
207 /*EllipsisLoc*/ SourceLocation(),
208 /*BuildAndDiagnose*/ false, CaptureType,
209 DeclRefType, &IndexOfCaptureReadyLambda);
210 if (!CanCaptureVariable)
211 return NoLambdaIsCaptureCapable;
212 } else {
213 // Check if the capture-ready lambda can truly capture 'this' by checking
214 // whether all enclosing lambdas of the capture-ready lambda can capture
215 // 'this'.
216 const bool CanCaptureThis =
217 !S.CheckCXXThisCapture(
218 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
219 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
220 &IndexOfCaptureReadyLambda);
221 if (!CanCaptureThis)
222 return NoLambdaIsCaptureCapable;
223 }
224 return IndexOfCaptureReadyLambda;
225}
226
227static inline TemplateParameterList *
228getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
229 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
230 LSI->GLTemplateParameterList = TemplateParameterList::Create(
231 SemaRef.Context,
232 /*Template kw loc*/ SourceLocation(),
233 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
234 LSI->TemplateParams,
235 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
236 LSI->RequiresClause.get());
237 }
238 return LSI->GLTemplateParameterList;
239}
240
241CXXRecordDecl *
242Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
243 unsigned LambdaDependencyKind,
244 LambdaCaptureDefault CaptureDefault) {
245 DeclContext *DC = CurContext;
246 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
247 DC = DC->getParent();
248 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
249 *this);
250 // Start constructing the lambda class.
251 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
252 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
253 IsGenericLambda, CaptureDefault);
254 DC->addDecl(Class);
255
256 return Class;
257}
258
259/// Determine whether the given context is or is enclosed in an inline
260/// function.
261static bool isInInlineFunction(const DeclContext *DC) {
262 while (!DC->isFileContext()) {
263 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
264 if (FD->isInlined())
265 return true;
266
267 DC = DC->getLexicalParent();
268 }
269
270 return false;
271}
272
273std::tuple<MangleNumberingContext *, Decl *>
274Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
275 // Compute the context for allocating mangling numbers in the current
276 // expression, if the ABI requires them.
277 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
278
279 enum ContextKind {
280 Normal,
281 DefaultArgument,
282 DataMember,
283 StaticDataMember,
284 InlineVariable,
285 VariableTemplate
286 } Kind = Normal;
287
288 // Default arguments of member function parameters that appear in a class
289 // definition, as well as the initializers of data members, receive special
290 // treatment. Identify them.
291 if (ManglingContextDecl) {
292 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
293 if (const DeclContext *LexicalDC
294 = Param->getDeclContext()->getLexicalParent())
295 if (LexicalDC->isRecord())
296 Kind = DefaultArgument;
297 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
298 if (Var->getDeclContext()->isRecord())
299 Kind = StaticDataMember;
300 else if (Var->getMostRecentDecl()->isInline())
301 Kind = InlineVariable;
302 else if (Var->getDescribedVarTemplate())
303 Kind = VariableTemplate;
304 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
305 if (!VTS->isExplicitSpecialization())
306 Kind = VariableTemplate;
307 }
308 } else if (isa<FieldDecl>(ManglingContextDecl)) {
309 Kind = DataMember;
310 }
311 }
312
313 // Itanium ABI [5.1.7]:
314 // In the following contexts [...] the one-definition rule requires closure
315 // types in different translation units to "correspond":
316 bool IsInNonspecializedTemplate =
317 inTemplateInstantiation() || CurContext->isDependentContext();
318 switch (Kind) {
319 case Normal: {
320 // -- the bodies of non-exported nonspecialized template functions
321 // -- the bodies of inline functions
322 if ((IsInNonspecializedTemplate &&
323 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
324 isInInlineFunction(CurContext)) {
325 while (auto *CD = dyn_cast<CapturedDecl>(DC))
326 DC = CD->getParent();
327 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
328 }
329
330 return std::make_tuple(nullptr, nullptr);
331 }
332
333 case StaticDataMember:
334 // -- the initializers of nonspecialized static members of template classes
335 if (!IsInNonspecializedTemplate)
336 return std::make_tuple(nullptr, ManglingContextDecl);
337 // Fall through to get the current context.
338 [[fallthrough]];
339
340 case DataMember:
341 // -- the in-class initializers of class members
342 case DefaultArgument:
343 // -- default arguments appearing in class definitions
344 case InlineVariable:
345 // -- the initializers of inline variables
346 case VariableTemplate:
347 // -- the initializers of templated variables
348 return std::make_tuple(
349 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
350 ManglingContextDecl),
351 ManglingContextDecl);
352 }
353
354 llvm_unreachable("unexpected context")::llvm::llvm_unreachable_internal("unexpected context", "clang/lib/Sema/SemaLambda.cpp"
, 354)
;
355}
356
357CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
358 SourceRange IntroducerRange,
359 TypeSourceInfo *MethodTypeInfo,
360 SourceLocation EndLoc,
361 ArrayRef<ParmVarDecl *> Params,
362 ConstexprSpecKind ConstexprKind,
363 Expr *TrailingRequiresClause) {
364 QualType MethodType = MethodTypeInfo->getType();
365 TemplateParameterList *TemplateParams =
366 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
367 // If a lambda appears in a dependent context or is a generic lambda (has
368 // template parameters) and has an 'auto' return type, deduce it to a
369 // dependent type.
370 if (Class->isDependentContext() || TemplateParams) {
371 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
372 QualType Result = FPT->getReturnType();
373 if (Result->isUndeducedType()) {
374 Result = SubstAutoTypeDependent(Result);
375 MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
376 FPT->getExtProtoInfo());
377 }
378 }
379
380 // C++11 [expr.prim.lambda]p5:
381 // The closure type for a lambda-expression has a public inline function
382 // call operator (13.5.4) whose parameters and return type are described by
383 // the lambda-expression's parameter-declaration-clause and
384 // trailing-return-type respectively.
385 DeclarationName MethodName
386 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
387 DeclarationNameLoc MethodNameLoc =
388 DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange);
389 CXXMethodDecl *Method = CXXMethodDecl::Create(
390 Context, Class, EndLoc,
391 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
392 MethodNameLoc),
393 MethodType, MethodTypeInfo, SC_None, getCurFPFeatures().isFPConstrained(),
394 /*isInline=*/true, ConstexprKind, EndLoc, TrailingRequiresClause);
395 Method->setAccess(AS_public);
396 if (!TemplateParams)
397 Class->addDecl(Method);
398
399 // Temporarily set the lexical declaration context to the current
400 // context, so that the Scope stack matches the lexical nesting.
401 Method->setLexicalDeclContext(CurContext);
402 // Create a function template if we have a template parameter list
403 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
404 FunctionTemplateDecl::Create(Context, Class,
405 Method->getLocation(), MethodName,
406 TemplateParams,
407 Method) : nullptr;
408 if (TemplateMethod) {
409 TemplateMethod->setAccess(AS_public);
410 Method->setDescribedFunctionTemplate(TemplateMethod);
411 Class->addDecl(TemplateMethod);
412 TemplateMethod->setLexicalDeclContext(CurContext);
413 }
414
415 // Add parameters.
416 if (!Params.empty()) {
417 Method->setParams(Params);
418 CheckParmsForFunctionDef(Params,
419 /*CheckParameterNames=*/false);
420
421 for (auto *P : Method->parameters())
422 P->setOwningFunction(Method);
423 }
424
425 return Method;
426}
427
428void Sema::handleLambdaNumbering(
429 CXXRecordDecl *Class, CXXMethodDecl *Method,
430 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) {
431 if (Mangling) {
432 bool HasKnownInternalLinkage;
433 unsigned ManglingNumber, DeviceManglingNumber;
434 Decl *ManglingContextDecl;
435 std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber,
436 ManglingContextDecl) = *Mangling;
437 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
438 HasKnownInternalLinkage);
439 Class->setDeviceLambdaManglingNumber(DeviceManglingNumber);
440 return;
441 }
442
443 auto getMangleNumberingContext =
444 [this](CXXRecordDecl *Class,
445 Decl *ManglingContextDecl) -> MangleNumberingContext * {
446 // Get mangle numbering context if there's any extra decl context.
447 if (ManglingContextDecl)
448 return &Context.getManglingNumberContext(
449 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
450 // Otherwise, from that lambda's decl context.
451 auto DC = Class->getDeclContext();
452 while (auto *CD = dyn_cast<CapturedDecl>(DC))
453 DC = CD->getParent();
454 return &Context.getManglingNumberContext(DC);
455 };
456
457 MangleNumberingContext *MCtx;
458 Decl *ManglingContextDecl;
459 std::tie(MCtx, ManglingContextDecl) =
460 getCurrentMangleNumberContext(Class->getDeclContext());
461 bool HasKnownInternalLinkage = false;
462 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
463 getLangOpts().SYCLIsHost)) {
464 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
465 // ODR. Both device- and host-compilation need to have a consistent naming
466 // on kernel functions. As lambdas are potential part of these `__global__`
467 // function names, they needs numbering following ODR.
468 // Also force for SYCL, since we need this for the
469 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
470 // mangling.
471 MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
472 assert(MCtx && "Retrieving mangle numbering context failed!")(static_cast <bool> (MCtx && "Retrieving mangle numbering context failed!"
) ? void (0) : __assert_fail ("MCtx && \"Retrieving mangle numbering context failed!\""
, "clang/lib/Sema/SemaLambda.cpp", 472, __extension__ __PRETTY_FUNCTION__
))
;
473 HasKnownInternalLinkage = true;
474 }
475 if (MCtx) {
476 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
477 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
478 HasKnownInternalLinkage);
479 Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method));
480 }
481}
482
483void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
484 CXXMethodDecl *CallOperator,
485 SourceRange IntroducerRange,
486 LambdaCaptureDefault CaptureDefault,
487 SourceLocation CaptureDefaultLoc,
488 bool ExplicitParams,
489 bool ExplicitResultType,
490 bool Mutable) {
491 LSI->CallOperator = CallOperator;
492 CXXRecordDecl *LambdaClass = CallOperator->getParent();
493 LSI->Lambda = LambdaClass;
494 if (CaptureDefault == LCD_ByCopy)
495 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
496 else if (CaptureDefault == LCD_ByRef)
497 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
498 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
499 LSI->IntroducerRange = IntroducerRange;
500 LSI->ExplicitParams = ExplicitParams;
501 LSI->Mutable = Mutable;
502
503 if (ExplicitResultType) {
504 LSI->ReturnType = CallOperator->getReturnType();
505
506 if (!LSI->ReturnType->isDependentType() &&
507 !LSI->ReturnType->isVoidType()) {
508 if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
509 diag::err_lambda_incomplete_result)) {
510 // Do nothing.
511 }
512 }
513 } else {
514 LSI->HasImplicitReturnType = true;
515 }
516}
517
518void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
519 LSI->finishedExplicitCaptures();
520}
521
522void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
523 ArrayRef<NamedDecl *> TParams,
524 SourceLocation RAngleLoc,
525 ExprResult RequiresClause) {
526 LambdaScopeInfo *LSI = getCurLambda();
527 assert(LSI && "Expected a lambda scope")(static_cast <bool> (LSI && "Expected a lambda scope"
) ? void (0) : __assert_fail ("LSI && \"Expected a lambda scope\""
, "clang/lib/Sema/SemaLambda.cpp", 527, __extension__ __PRETTY_FUNCTION__
))
;
528 assert(LSI->NumExplicitTemplateParams == 0 &&(static_cast <bool> (LSI->NumExplicitTemplateParams ==
0 && "Already acted on explicit template parameters"
) ? void (0) : __assert_fail ("LSI->NumExplicitTemplateParams == 0 && \"Already acted on explicit template parameters\""
, "clang/lib/Sema/SemaLambda.cpp", 529, __extension__ __PRETTY_FUNCTION__
))
529 "Already acted on explicit template parameters")(static_cast <bool> (LSI->NumExplicitTemplateParams ==
0 && "Already acted on explicit template parameters"
) ? void (0) : __assert_fail ("LSI->NumExplicitTemplateParams == 0 && \"Already acted on explicit template parameters\""
, "clang/lib/Sema/SemaLambda.cpp", 529, __extension__ __PRETTY_FUNCTION__
))
;
530 assert(LSI->TemplateParams.empty() &&(static_cast <bool> (LSI->TemplateParams.empty() &&
"Explicit template parameters should come " "before invented (auto) ones"
) ? void (0) : __assert_fail ("LSI->TemplateParams.empty() && \"Explicit template parameters should come \" \"before invented (auto) ones\""
, "clang/lib/Sema/SemaLambda.cpp", 532, __extension__ __PRETTY_FUNCTION__
))
531 "Explicit template parameters should come "(static_cast <bool> (LSI->TemplateParams.empty() &&
"Explicit template parameters should come " "before invented (auto) ones"
) ? void (0) : __assert_fail ("LSI->TemplateParams.empty() && \"Explicit template parameters should come \" \"before invented (auto) ones\""
, "clang/lib/Sema/SemaLambda.cpp", 532, __extension__ __PRETTY_FUNCTION__
))
532 "before invented (auto) ones")(static_cast <bool> (LSI->TemplateParams.empty() &&
"Explicit template parameters should come " "before invented (auto) ones"
) ? void (0) : __assert_fail ("LSI->TemplateParams.empty() && \"Explicit template parameters should come \" \"before invented (auto) ones\""
, "clang/lib/Sema/SemaLambda.cpp", 532, __extension__ __PRETTY_FUNCTION__
))
;
533 assert(!TParams.empty() &&(static_cast <bool> (!TParams.empty() && "No template parameters to act on"
) ? void (0) : __assert_fail ("!TParams.empty() && \"No template parameters to act on\""
, "clang/lib/Sema/SemaLambda.cpp", 534, __extension__ __PRETTY_FUNCTION__
))
534 "No template parameters to act on")(static_cast <bool> (!TParams.empty() && "No template parameters to act on"
) ? void (0) : __assert_fail ("!TParams.empty() && \"No template parameters to act on\""
, "clang/lib/Sema/SemaLambda.cpp", 534, __extension__ __PRETTY_FUNCTION__
))
;
535 LSI->TemplateParams.append(TParams.begin(), TParams.end());
536 LSI->NumExplicitTemplateParams = TParams.size();
537 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
538 LSI->RequiresClause = RequiresClause;
539}
540
541void Sema::addLambdaParameters(
542 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
543 CXXMethodDecl *CallOperator, Scope *CurScope) {
544 // Introduce our parameters into the function scope
545 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
546 p < NumParams; ++p) {
547 ParmVarDecl *Param = CallOperator->getParamDecl(p);
548
549 // If this has an identifier, add it to the scope stack.
550 if (CurScope && Param->getIdentifier()) {
551 bool Error = false;
552 // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
553 // retroactively apply it.
554 for (const auto &Capture : Captures) {
555 if (Capture.Id == Param->getIdentifier()) {
556 Error = true;
557 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
558 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
559 << Capture.Id << true;
560 }
561 }
562 if (!Error)
563 CheckShadow(CurScope, Param);
564
565 PushOnScopeChains(Param, CurScope);
566 }
567 }
568}
569
570/// If this expression is an enumerator-like expression of some type
571/// T, return the type T; otherwise, return null.
572///
573/// Pointer comparisons on the result here should always work because
574/// it's derived from either the parent of an EnumConstantDecl
575/// (i.e. the definition) or the declaration returned by
576/// EnumType::getDecl() (i.e. the definition).
577static EnumDecl *findEnumForBlockReturn(Expr *E) {
578 // An expression is an enumerator-like expression of type T if,
579 // ignoring parens and parens-like expressions:
580 E = E->IgnoreParens();
581
582 // - it is an enumerator whose enum type is T or
583 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
584 if (EnumConstantDecl *D
585 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
586 return cast<EnumDecl>(D->getDeclContext());
587 }
588 return nullptr;
589 }
590
591 // - it is a comma expression whose RHS is an enumerator-like
592 // expression of type T or
593 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
594 if (BO->getOpcode() == BO_Comma)
595 return findEnumForBlockReturn(BO->getRHS());
596 return nullptr;
597 }
598
599 // - it is a statement-expression whose value expression is an
600 // enumerator-like expression of type T or
601 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
602 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
603 return findEnumForBlockReturn(last);
604 return nullptr;
605 }
606
607 // - it is a ternary conditional operator (not the GNU ?:
608 // extension) whose second and third operands are
609 // enumerator-like expressions of type T or
610 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
611 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
612 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
613 return ED;
614 return nullptr;
615 }
616
617 // (implicitly:)
618 // - it is an implicit integral conversion applied to an
619 // enumerator-like expression of type T or
620 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
621 // We can sometimes see integral conversions in valid
622 // enumerator-like expressions.
623 if (ICE->getCastKind() == CK_IntegralCast)
624 return findEnumForBlockReturn(ICE->getSubExpr());
625
626 // Otherwise, just rely on the type.
627 }
628
629 // - it is an expression of that formal enum type.
630 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
631 return ET->getDecl();
632 }
633
634 // Otherwise, nope.
635 return nullptr;
636}
637
638/// Attempt to find a type T for which the returned expression of the
639/// given statement is an enumerator-like expression of that type.
640static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
641 if (Expr *retValue = ret->getRetValue())
642 return findEnumForBlockReturn(retValue);
643 return nullptr;
644}
645
646/// Attempt to find a common type T for which all of the returned
647/// expressions in a block are enumerator-like expressions of that
648/// type.
649static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
650 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
651
652 // Try to find one for the first return.
653 EnumDecl *ED = findEnumForBlockReturn(*i);
654 if (!ED) return nullptr;
655
656 // Check that the rest of the returns have the same enum.
657 for (++i; i != e; ++i) {
658 if (findEnumForBlockReturn(*i) != ED)
659 return nullptr;
660 }
661
662 // Never infer an anonymous enum type.
663 if (!ED->hasNameForLinkage()) return nullptr;
664
665 return ED;
666}
667
668/// Adjust the given return statements so that they formally return
669/// the given type. It should require, at most, an IntegralCast.
670static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
671 QualType returnType) {
672 for (ArrayRef<ReturnStmt*>::iterator
673 i = returns.begin(), e = returns.end(); i != e; ++i) {
674 ReturnStmt *ret = *i;
675 Expr *retValue = ret->getRetValue();
676 if (S.Context.hasSameType(retValue->getType(), returnType))
677 continue;
678
679 // Right now we only support integral fixup casts.
680 assert(returnType->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (returnType->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("returnType->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaLambda.cpp", 680, __extension__ __PRETTY_FUNCTION__
))
;
681 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType())(static_cast <bool> (retValue->getType()->isIntegralOrUnscopedEnumerationType
()) ? void (0) : __assert_fail ("retValue->getType()->isIntegralOrUnscopedEnumerationType()"
, "clang/lib/Sema/SemaLambda.cpp", 681, __extension__ __PRETTY_FUNCTION__
))
;
682
683 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
684
685 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
686 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
687 /*base path*/ nullptr, VK_PRValue,
688 FPOptionsOverride());
689 if (cleanups) {
690 cleanups->setSubExpr(E);
691 } else {
692 ret->setRetValue(E);
693 }
694 }
695}
696
697void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
698 assert(CSI.HasImplicitReturnType)(static_cast <bool> (CSI.HasImplicitReturnType) ? void (
0) : __assert_fail ("CSI.HasImplicitReturnType", "clang/lib/Sema/SemaLambda.cpp"
, 698, __extension__ __PRETTY_FUNCTION__))
;
699 // If it was ever a placeholder, it had to been deduced to DependentTy.
700 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType())(static_cast <bool> (CSI.ReturnType.isNull() || !CSI.ReturnType
->isUndeducedType()) ? void (0) : __assert_fail ("CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()"
, "clang/lib/Sema/SemaLambda.cpp", 700, __extension__ __PRETTY_FUNCTION__
))
;
701 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&(static_cast <bool> ((!isa<LambdaScopeInfo>(CSI) ||
!getLangOpts().CPlusPlus14) && "lambda expressions use auto deduction in C++14 onwards"
) ? void (0) : __assert_fail ("(!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && \"lambda expressions use auto deduction in C++14 onwards\""
, "clang/lib/Sema/SemaLambda.cpp", 702, __extension__ __PRETTY_FUNCTION__
))
702 "lambda expressions use auto deduction in C++14 onwards")(static_cast <bool> ((!isa<LambdaScopeInfo>(CSI) ||
!getLangOpts().CPlusPlus14) && "lambda expressions use auto deduction in C++14 onwards"
) ? void (0) : __assert_fail ("(!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && \"lambda expressions use auto deduction in C++14 onwards\""
, "clang/lib/Sema/SemaLambda.cpp", 702, __extension__ __PRETTY_FUNCTION__
))
;
703
704 // C++ core issue 975:
705 // If a lambda-expression does not include a trailing-return-type,
706 // it is as if the trailing-return-type denotes the following type:
707 // - if there are no return statements in the compound-statement,
708 // or all return statements return either an expression of type
709 // void or no expression or braced-init-list, the type void;
710 // - otherwise, if all return statements return an expression
711 // and the types of the returned expressions after
712 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
713 // array-to-pointer conversion (4.2 [conv.array]), and
714 // function-to-pointer conversion (4.3 [conv.func]) are the
715 // same, that common type;
716 // - otherwise, the program is ill-formed.
717 //
718 // C++ core issue 1048 additionally removes top-level cv-qualifiers
719 // from the types of returned expressions to match the C++14 auto
720 // deduction rules.
721 //
722 // In addition, in blocks in non-C++ modes, if all of the return
723 // statements are enumerator-like expressions of some type T, where
724 // T has a name for linkage, then we infer the return type of the
725 // block to be that type.
726
727 // First case: no return statements, implicit void return type.
728 ASTContext &Ctx = getASTContext();
729 if (CSI.Returns.empty()) {
730 // It's possible there were simply no /valid/ return statements.
731 // In this case, the first one we found may have at least given us a type.
732 if (CSI.ReturnType.isNull())
733 CSI.ReturnType = Ctx.VoidTy;
734 return;
735 }
736
737 // Second case: at least one return statement has dependent type.
738 // Delay type checking until instantiation.
739 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.")(static_cast <bool> (!CSI.ReturnType.isNull() &&
"We should have a tentative return type.") ? void (0) : __assert_fail
("!CSI.ReturnType.isNull() && \"We should have a tentative return type.\""
, "clang/lib/Sema/SemaLambda.cpp", 739, __extension__ __PRETTY_FUNCTION__
))
;
740 if (CSI.ReturnType->isDependentType())
741 return;
742
743 // Try to apply the enum-fuzz rule.
744 if (!getLangOpts().CPlusPlus) {
745 assert(isa<BlockScopeInfo>(CSI))(static_cast <bool> (isa<BlockScopeInfo>(CSI)) ? void
(0) : __assert_fail ("isa<BlockScopeInfo>(CSI)", "clang/lib/Sema/SemaLambda.cpp"
, 745, __extension__ __PRETTY_FUNCTION__))
;
746 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
747 if (ED) {
748 CSI.ReturnType = Context.getTypeDeclType(ED);
749 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
750 return;
751 }
752 }
753
754 // Third case: only one return statement. Don't bother doing extra work!
755 if (CSI.Returns.size() == 1)
756 return;
757
758 // General case: many return statements.
759 // Check that they all have compatible return types.
760
761 // We require the return types to strictly match here.
762 // Note that we've already done the required promotions as part of
763 // processing the return statement.
764 for (const ReturnStmt *RS : CSI.Returns) {
765 const Expr *RetE = RS->getRetValue();
766
767 QualType ReturnType =
768 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
769 if (Context.getCanonicalFunctionResultType(ReturnType) ==
770 Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
771 // Use the return type with the strictest possible nullability annotation.
772 auto RetTyNullability = ReturnType->getNullability(Ctx);
773 auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
774 if (BlockNullability &&
775 (!RetTyNullability ||
776 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
777 CSI.ReturnType = ReturnType;
778 continue;
779 }
780
781 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
782 // TODO: It's possible that the *first* return is the divergent one.
783 Diag(RS->getBeginLoc(),
784 diag::err_typecheck_missing_return_type_incompatible)
785 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
786 // Continue iterating so that we keep emitting diagnostics.
787 }
788}
789
790QualType Sema::buildLambdaInitCaptureInitialization(
791 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
792 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
793 Expr *&Init) {
794 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
795 // deduce against.
796 QualType DeductType = Context.getAutoDeductType();
797 TypeLocBuilder TLB;
798 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
799 TL.setNameLoc(Loc);
800 if (ByRef) {
801 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
802 assert(!DeductType.isNull() && "can't build reference to auto")(static_cast <bool> (!DeductType.isNull() && "can't build reference to auto"
) ? void (0) : __assert_fail ("!DeductType.isNull() && \"can't build reference to auto\""
, "clang/lib/Sema/SemaLambda.cpp", 802, __extension__ __PRETTY_FUNCTION__
))
;
803 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
804 }
805 if (EllipsisLoc.isValid()) {
806 if (Init->containsUnexpandedParameterPack()) {
807 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
808 ? diag::warn_cxx17_compat_init_capture_pack
809 : diag::ext_init_capture_pack);
810 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
811 /*ExpectPackInType=*/false);
812 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
813 } else {
814 // Just ignore the ellipsis for now and form a non-pack variable. We'll
815 // diagnose this later when we try to capture it.
816 }
817 }
818 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
819
820 // Deduce the type of the init capture.
821 QualType DeducedType = deduceVarTypeFromInitializer(
822 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
823 SourceRange(Loc, Loc), IsDirectInit, Init);
824 if (DeducedType.isNull())
825 return QualType();
826
827 // Are we a non-list direct initialization?
828 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
829
830 // Perform initialization analysis and ensure any implicit conversions
831 // (such as lvalue-to-rvalue) are enforced.
832 InitializedEntity Entity =
833 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
834 InitializationKind Kind =
835 IsDirectInit
836 ? (CXXDirectInit ? InitializationKind::CreateDirect(
837 Loc, Init->getBeginLoc(), Init->getEndLoc())
838 : InitializationKind::CreateDirectList(Loc))
839 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
840
841 MultiExprArg Args = Init;
842 if (CXXDirectInit)
843 Args =
844 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
845 QualType DclT;
846 InitializationSequence InitSeq(*this, Entity, Kind, Args);
847 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
848
849 if (Result.isInvalid())
850 return QualType();
851
852 Init = Result.getAs<Expr>();
853 return DeducedType;
854}
855
856VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
857 QualType InitCaptureType,
858 SourceLocation EllipsisLoc,
859 IdentifierInfo *Id,
860 unsigned InitStyle, Expr *Init) {
861 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
862 // rather than reconstructing it here.
863 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
864 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
865 PETL.setEllipsisLoc(EllipsisLoc);
866
867 // Create a dummy variable representing the init-capture. This is not actually
868 // used as a variable, and only exists as a way to name and refer to the
869 // init-capture.
870 // FIXME: Pass in separate source locations for '&' and identifier.
871 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
872 Loc, Id, InitCaptureType, TSI, SC_Auto);
873 NewVD->setInitCapture(true);
874 NewVD->setReferenced(true);
875 // FIXME: Pass in a VarDecl::InitializationStyle.
876 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
877 NewVD->markUsed(Context);
878 NewVD->setInit(Init);
879 if (NewVD->isParameterPack())
880 getCurLambda()->LocalPacks.push_back(NewVD);
881 return NewVD;
882}
883
884void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
885 assert(Var->isInitCapture() && "init capture flag should be set")(static_cast <bool> (Var->isInitCapture() &&
"init capture flag should be set") ? void (0) : __assert_fail
("Var->isInitCapture() && \"init capture flag should be set\""
, "clang/lib/Sema/SemaLambda.cpp", 885, __extension__ __PRETTY_FUNCTION__
))
;
886 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
887 /*isNested*/false, Var->getLocation(), SourceLocation(),
888 Var->getType(), /*Invalid*/false);
889}
890
891void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
892 Declarator &ParamInfo,
893 Scope *CurScope) {
894 LambdaScopeInfo *const LSI = getCurLambda();
895 assert(LSI && "LambdaScopeInfo should be on stack!")(static_cast <bool> (LSI && "LambdaScopeInfo should be on stack!"
) ? void (0) : __assert_fail ("LSI && \"LambdaScopeInfo should be on stack!\""
, "clang/lib/Sema/SemaLambda.cpp", 895, __extension__ __PRETTY_FUNCTION__
))
;
1
Assuming 'LSI' is non-null
2
'?' condition is true
896
897 // Determine if we're within a context where we know that the lambda will
898 // be dependent, because there are template parameters in scope.
899 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
900 CXXRecordDecl::LDK_Unknown;
901 if (LSI->NumExplicitTemplateParams > 0) {
3
Assuming field 'NumExplicitTemplateParams' is <= 0
4
Taking false branch
902 auto *TemplateParamScope = CurScope->getTemplateParamParent();
903 assert(TemplateParamScope &&(static_cast <bool> (TemplateParamScope && "Lambda with explicit template param list should establish a "
"template param scope") ? void (0) : __assert_fail ("TemplateParamScope && \"Lambda with explicit template param list should establish a \" \"template param scope\""
, "clang/lib/Sema/SemaLambda.cpp", 905, __extension__ __PRETTY_FUNCTION__
))
904 "Lambda with explicit template param list should establish a "(static_cast <bool> (TemplateParamScope && "Lambda with explicit template param list should establish a "
"template param scope") ? void (0) : __assert_fail ("TemplateParamScope && \"Lambda with explicit template param list should establish a \" \"template param scope\""
, "clang/lib/Sema/SemaLambda.cpp", 905, __extension__ __PRETTY_FUNCTION__
))
905 "template param scope")(static_cast <bool> (TemplateParamScope && "Lambda with explicit template param list should establish a "
"template param scope") ? void (0) : __assert_fail ("TemplateParamScope && \"Lambda with explicit template param list should establish a \" \"template param scope\""
, "clang/lib/Sema/SemaLambda.cpp", 905, __extension__ __PRETTY_FUNCTION__
))
;
906 assert(TemplateParamScope->getParent())(static_cast <bool> (TemplateParamScope->getParent()
) ? void (0) : __assert_fail ("TemplateParamScope->getParent()"
, "clang/lib/Sema/SemaLambda.cpp", 906, __extension__ __PRETTY_FUNCTION__
))
;
907 if (TemplateParamScope->getParent()->getTemplateParamParent() != nullptr)
908 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
909 } else if (CurScope->getTemplateParamParent() != nullptr) {
5
Assuming the condition is false
6
Taking false branch
910 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
911 }
912
913 // Determine the signature of the call operator.
914 TypeSourceInfo *MethodTyInfo;
915 bool ExplicitParams = true;
916 bool ExplicitResultType = true;
917 bool ContainsUnexpandedParameterPack = false;
918 SourceLocation EndLoc;
919 SmallVector<ParmVarDecl *, 8> Params;
920 if (ParamInfo.getNumTypeObjects() == 0) {
7
Assuming the condition is true
8
Taking true branch
921 // C++11 [expr.prim.lambda]p4:
922 // If a lambda-expression does not include a lambda-declarator, it is as
923 // if the lambda-declarator were ().
924 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
925 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
926 EPI.HasTrailingReturn = true;
927 EPI.TypeQuals.addConst();
928 LangAS AS = getDefaultCXXMethodAddrSpace();
929 if (AS != LangAS::Default)
9
Assuming 'AS' is equal to Default
930 EPI.TypeQuals.addAddressSpace(AS);
931
932 // C++1y [expr.prim.lambda]:
933 // The lambda return type is 'auto', which is replaced by the
934 // trailing-return type if provided and/or deduced from 'return'
935 // statements
936 // We don't do this before C++1y, because we don't support deduced return
937 // types there.
938 QualType DefaultTypeForNoTrailingReturn =
10
Taking false branch
939 getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
11
Assuming field 'CPlusPlus14' is 0
12
'?' condition is false
940 : Context.DependentTy;
941 QualType MethodTy =
942 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
943 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
944 ExplicitParams = false;
945 ExplicitResultType = false;
946 EndLoc = Intro.Range.getEnd();
947 } else {
948 assert(ParamInfo.isFunctionDeclarator() &&(static_cast <bool> (ParamInfo.isFunctionDeclarator() &&
"lambda-declarator is a function") ? void (0) : __assert_fail
("ParamInfo.isFunctionDeclarator() && \"lambda-declarator is a function\""
, "clang/lib/Sema/SemaLambda.cpp", 949, __extension__ __PRETTY_FUNCTION__
))
949 "lambda-declarator is a function")(static_cast <bool> (ParamInfo.isFunctionDeclarator() &&
"lambda-declarator is a function") ? void (0) : __assert_fail
("ParamInfo.isFunctionDeclarator() && \"lambda-declarator is a function\""
, "clang/lib/Sema/SemaLambda.cpp", 949, __extension__ __PRETTY_FUNCTION__
))
;
950 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
951
952 // C++11 [expr.prim.lambda]p5:
953 // This function call operator is declared const (9.3.1) if and only if
954 // the lambda-expression's parameter-declaration-clause is not followed
955 // by mutable. It is neither virtual nor declared volatile. [...]
956 if (!FTI.hasMutableQualifier()) {
957 FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
958 SourceLocation());
959 }
960
961 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
962 assert(MethodTyInfo && "no type from lambda-declarator")(static_cast <bool> (MethodTyInfo && "no type from lambda-declarator"
) ? void (0) : __assert_fail ("MethodTyInfo && \"no type from lambda-declarator\""
, "clang/lib/Sema/SemaLambda.cpp", 962, __extension__ __PRETTY_FUNCTION__
))
;
963 EndLoc = ParamInfo.getSourceRange().getEnd();
964
965 ExplicitResultType = FTI.hasTrailingReturnType();
966
967 if (FTIHasNonVoidParameters(FTI)) {
968 Params.reserve(FTI.NumParams);
969 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
970 Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
971 }
972
973 // Check for unexpanded parameter packs in the method type.
974 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
975 DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
976 UPPC_DeclarationType);
977 }
978
979 CXXRecordDecl *Class = createLambdaClosureType(
980 Intro.Range, MethodTyInfo, LambdaDependencyKind, Intro.Default);
981 CXXMethodDecl *Method =
982 startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
983 ParamInfo.getDeclSpec().getConstexprSpecifier(),
984 ParamInfo.getTrailingRequiresClause());
985 if (ExplicitParams
12.1
'ExplicitParams' is false
12.1
'ExplicitParams' is false
)
13
Taking false branch
986 CheckCXXDefaultArguments(Method);
987
988 // This represents the function body for the lambda function, check if we
989 // have to apply optnone due to a pragma.
990 AddRangeBasedOptnone(Method);
991
992 // code_seg attribute on lambda apply to the method.
993 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
14
Assuming 'A' is null
15
Taking false branch
994 Method->addAttr(A);
995
996 // Attributes on the lambda apply to the method.
997 ProcessDeclAttributes(CurScope, Method, ParamInfo);
998
999 // CUDA lambdas get implicit host and device attributes.
1000 if (getLangOpts().CUDA)
16
Assuming field 'CUDA' is 0
17
Taking false branch
1001 CUDASetLambdaAttrs(Method);
1002
1003 // OpenMP lambdas might get assumumption attributes.
1004 if (LangOpts.OpenMP)
18
Assuming field 'OpenMP' is 0
19
Taking false branch
1005 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
1006
1007 // Number the lambda for linkage purposes if necessary.
1008 handleLambdaNumbering(Class, Method);
1009
1010 // Introduce the function call operator as the current declaration context.
1011 PushDeclContext(CurScope, Method);
1012
1013 // Build the lambda scope.
1014 buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
1015 ExplicitParams, ExplicitResultType, !Method->isConst());
1016
1017 // C++11 [expr.prim.lambda]p9:
1018 // A lambda-expression whose smallest enclosing scope is a block scope is a
1019 // local lambda expression; any other lambda expression shall not have a
1020 // capture-default or simple-capture in its lambda-introducer.
1021 //
1022 // For simple-captures, this is covered by the check below that any named
1023 // entity is a variable that can be captured.
1024 //
1025 // For DR1632, we also allow a capture-default in any context where we can
1026 // odr-use 'this' (in particular, in a default initializer for a non-static
1027 // data member).
1028 if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
20
Assuming field 'Default' is equal to LCD_None
21
Taking false branch
1029 (getCurrentThisType().isNull() ||
1030 CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
1031 /*BuildAndDiagnose*/false)))
1032 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1033
1034 // Distinct capture names, for diagnostics.
1035 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
1036
1037 // Handle explicit captures.
1038 SourceLocation PrevCaptureLoc
1039 = Intro.Default
21.1
Field 'Default' is equal to LCD_None
21.1
Field 'Default' is equal to LCD_None
== LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
22
'?' condition is true
1040 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
23
Assuming 'C' is not equal to 'E'
1041 PrevCaptureLoc = C->Loc, ++C) {
1042 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
24
Assuming field 'Kind' is not equal to LCK_This
25
Assuming field 'Kind' is not equal to LCK_StarThis
1043 if (C->Kind == LCK_StarThis)
1044 Diag(C->Loc, !getLangOpts().CPlusPlus17
1045 ? diag::ext_star_this_lambda_capture_cxx17
1046 : diag::warn_cxx14_compat_star_this_lambda_capture);
1047
1048 // C++11 [expr.prim.lambda]p8:
1049 // An identifier or this shall not appear more than once in a
1050 // lambda-capture.
1051 if (LSI->isCXXThisCaptured()) {
1052 Diag(C->Loc, diag::err_capture_more_than_once)
1053 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1054 << FixItHint::CreateRemoval(
1055 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1056 continue;
1057 }
1058
1059 // C++2a [expr.prim.lambda]p8:
1060 // If a lambda-capture includes a capture-default that is =,
1061 // each simple-capture of that lambda-capture shall be of the form
1062 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1063 // redundant but accepted for compatibility with ISO C++14. --end note ]
1064 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1065 Diag(C->Loc, !getLangOpts().CPlusPlus20
1066 ? diag::ext_equals_this_lambda_capture_cxx20
1067 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1068
1069 // C++11 [expr.prim.lambda]p12:
1070 // If this is captured by a local lambda expression, its nearest
1071 // enclosing function shall be a non-static member function.
1072 QualType ThisCaptureType = getCurrentThisType();
1073 if (ThisCaptureType.isNull()) {
1074 Diag(C->Loc, diag::err_this_capture) << true;
1075 continue;
1076 }
1077
1078 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1079 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1080 C->Kind == LCK_StarThis);
1081 if (!LSI->Captures.empty())
1082 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1083 continue;
1084 }
1085
1086 assert(C->Id && "missing identifier for capture")(static_cast <bool> (C->Id && "missing identifier for capture"
) ? void (0) : __assert_fail ("C->Id && \"missing identifier for capture\""
, "clang/lib/Sema/SemaLambda.cpp", 1086, __extension__ __PRETTY_FUNCTION__
))
;
26
Taking false branch
27
Assuming field 'Id' is non-null
28
'?' condition is true
1087
1088 if (C->Init.isInvalid())
29
Assuming the condition is false
30
Taking false branch
1089 continue;
1090
1091 ValueDecl *Var = nullptr;
1092 if (C->Init.isUsable()) {
1093 Diag(C->Loc, getLangOpts().CPlusPlus14
1094 ? diag::warn_cxx11_compat_init_capture
1095 : diag::ext_init_capture);
1096
1097 // If the initializer expression is usable, but the InitCaptureType
1098 // is not, then an error has occurred - so ignore the capture for now.
1099 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1100 // FIXME: we should create the init capture variable and mark it invalid
1101 // in this case.
1102 if (C->InitCaptureType.get().isNull())
1103 continue;
1104
1105 if (C->Init.get()->containsUnexpandedParameterPack() &&
1106 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1107 DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
1108
1109 unsigned InitStyle;
1110 switch (C->InitKind) {
1111 case LambdaCaptureInitKind::NoInit:
1112 llvm_unreachable("not an init-capture?")::llvm::llvm_unreachable_internal("not an init-capture?", "clang/lib/Sema/SemaLambda.cpp"
, 1112)
;
1113 case LambdaCaptureInitKind::CopyInit:
1114 InitStyle = VarDecl::CInit;
1115 break;
1116 case LambdaCaptureInitKind::DirectInit:
1117 InitStyle = VarDecl::CallInit;
1118 break;
1119 case LambdaCaptureInitKind::ListInit:
1120 InitStyle = VarDecl::ListInit;
1121 break;
1122 }
1123 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1124 C->EllipsisLoc, C->Id, InitStyle,
1125 C->Init.get());
1126 // C++1y [expr.prim.lambda]p11:
1127 // An init-capture behaves as if it declares and explicitly
1128 // captures a variable [...] whose declarative region is the
1129 // lambda-expression's compound-statement
1130 if (Var)
1131 PushOnScopeChains(Var, CurScope, false);
1132 } else {
1133 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&(static_cast <bool> (C->InitKind == LambdaCaptureInitKind
::NoInit && "init capture has valid but null init?") ?
void (0) : __assert_fail ("C->InitKind == LambdaCaptureInitKind::NoInit && \"init capture has valid but null init?\""
, "clang/lib/Sema/SemaLambda.cpp", 1134, __extension__ __PRETTY_FUNCTION__
))
31
Taking false branch
32
Assuming field 'InitKind' is equal to NoInit
33
'?' condition is true
1134 "init capture has valid but null init?")(static_cast <bool> (C->InitKind == LambdaCaptureInitKind
::NoInit && "init capture has valid but null init?") ?
void (0) : __assert_fail ("C->InitKind == LambdaCaptureInitKind::NoInit && \"init capture has valid but null init?\""
, "clang/lib/Sema/SemaLambda.cpp", 1134, __extension__ __PRETTY_FUNCTION__
))
;
1135
1136 // C++11 [expr.prim.lambda]p8:
1137 // If a lambda-capture includes a capture-default that is &, the
1138 // identifiers in the lambda-capture shall not be preceded by &.
1139 // If a lambda-capture includes a capture-default that is =, [...]
1140 // each identifier it contains shall be preceded by &.
1141 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
34
Assuming field 'Kind' is not equal to LCK_ByRef
1142 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1143 << FixItHint::CreateRemoval(
1144 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1145 continue;
1146 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
35
Assuming field 'Kind' is not equal to LCK_ByCopy
1147 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1148 << FixItHint::CreateRemoval(
1149 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1150 continue;
1151 }
1152
1153 // C++11 [expr.prim.lambda]p10:
1154 // The identifiers in a capture-list are looked up using the usual
1155 // rules for unqualified name lookup (3.4.1)
1156 DeclarationNameInfo Name(C->Id, C->Loc);
1157 LookupResult R(*this, Name, LookupOrdinaryName);
1158 LookupName(R, CurScope);
1159 if (R.isAmbiguous())
36
Assuming the condition is false
37
Taking false branch
1160 continue;
1161 if (R.empty()) {
38
Assuming the condition is false
39
Taking false branch
1162 // FIXME: Disable corrections that would add qualification?
1163 CXXScopeSpec ScopeSpec;
1164 DeclFilterCCC<VarDecl> Validator{};
1165 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1166 continue;
1167 }
1168
1169 if (auto *BD = R.getAsSingle<BindingDecl>())
40
Assuming 'BD' is non-null
41
Taking true branch
1170 Var = BD;
1171 else
1172 Var = R.getAsSingle<VarDecl>();
1173 if (Var
41.1
'Var' is non-null
41.1
'Var' is non-null
&& DiagnoseUseOfDecl(Var, C->Loc))
42
Assuming the condition is false
43
Taking false branch
1174 continue;
1175 }
1176
1177 // C++11 [expr.prim.lambda]p8:
1178 // An identifier or this shall not appear more than once in a
1179 // lambda-capture.
1180 if (!CaptureNames.insert(C->Id).second) {
44
Assuming field 'second' is true
45
Taking false branch
1181 if (Var && LSI->isCaptured(Var)) {
1182 Diag(C->Loc, diag::err_capture_more_than_once)
1183 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1184 << FixItHint::CreateRemoval(
1185 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1186 } else
1187 // Previous capture captured something different (one or both was
1188 // an init-cpature): no fixit.
1189 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1190 continue;
1191 }
1192
1193 // C++11 [expr.prim.lambda]p10:
1194 // [...] each such lookup shall find a variable with automatic storage
1195 // duration declared in the reaching scope of the local lambda expression.
1196 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1197 if (!Var
45.1
'Var' is non-null
45.1
'Var' is non-null
) {
46
Taking false branch
1198 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1199 continue;
1200 }
1201
1202 // Ignore invalid decls; they'll just confuse the code later.
1203 if (Var->isInvalidDecl())
47
Assuming the condition is false
48
Taking false branch
1204 continue;
1205
1206 VarDecl *Underlying;
1207 if (auto *BD
49.1
'BD' is non-null
49.1
'BD' is non-null
= dyn_cast<BindingDecl>(Var))
49
Assuming 'Var' is a 'CastReturnType'
50
Taking true branch
1208 Underlying = dyn_cast<VarDecl>(BD->getDecomposedDecl());
51
Assuming the object is not a 'CastReturnType'
52
Null pointer value stored to 'Underlying'
1209 else
1210 Underlying = cast<VarDecl>(Var);
1211
1212 if (!Underlying->hasLocalStorage()) {
53
Called C++ object pointer is null
1213 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1214 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1215 continue;
1216 }
1217
1218 // C++11 [expr.prim.lambda]p23:
1219 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1220 SourceLocation EllipsisLoc;
1221 if (C->EllipsisLoc.isValid()) {
1222 if (Var->isParameterPack()) {
1223 EllipsisLoc = C->EllipsisLoc;
1224 } else {
1225 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1226 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1227 : SourceRange(C->Loc));
1228
1229 // Just ignore the ellipsis.
1230 }
1231 } else if (Var->isParameterPack()) {
1232 ContainsUnexpandedParameterPack = true;
1233 }
1234
1235 if (C->Init.isUsable()) {
1236 addInitCapture(LSI, cast<VarDecl>(Var));
1237 } else {
1238 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1239 TryCapture_ExplicitByVal;
1240 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1241 }
1242 if (!LSI->Captures.empty())
1243 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1244 }
1245 finishLambdaExplicitCaptures(LSI);
1246
1247 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1248
1249 // Add lambda parameters into scope.
1250 addLambdaParameters(Intro.Captures, Method, CurScope);
1251
1252 // Enter a new evaluation context to insulate the lambda from any
1253 // cleanups from the enclosing full-expression.
1254 PushExpressionEvaluationContext(
1255 LSI->CallOperator->isConsteval()
1256 ? ExpressionEvaluationContext::ImmediateFunctionContext
1257 : ExpressionEvaluationContext::PotentiallyEvaluated);
1258}
1259
1260void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1261 bool IsInstantiation) {
1262 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1263
1264 // Leave the expression-evaluation context.
1265 DiscardCleanupsInEvaluationContext();
1266 PopExpressionEvaluationContext();
1267
1268 // Leave the context of the lambda.
1269 if (!IsInstantiation)
1270 PopDeclContext();
1271
1272 // Finalize the lambda.
1273 CXXRecordDecl *Class = LSI->Lambda;
1274 Class->setInvalidDecl();
1275 SmallVector<Decl*, 4> Fields(Class->fields());
1276 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1277 SourceLocation(), ParsedAttributesView());
1278 CheckCompletedCXXClass(nullptr, Class);
1279
1280 PopFunctionScopeInfo();
1281}
1282
1283template <typename Func>
1284static void repeatForLambdaConversionFunctionCallingConvs(
1285 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1286 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1287 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1288 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1289 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1290 CallingConv CallOpCC = CallOpProto.getCallConv();
1291
1292 /// Implement emitting a version of the operator for many of the calling
1293 /// conventions for MSVC, as described here:
1294 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1295 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1296 /// vectorcall are generated by MSVC when it is supported by the target.
1297 /// Additionally, we are ensuring that the default-free/default-member and
1298 /// call-operator calling convention are generated as well.
1299 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1300 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1301 /// that someone who intentionally places 'thiscall' on the lambda call
1302 /// operator will still get that overload, since we don't have the a way of
1303 /// detecting the attribute by the time we get here.
1304 if (S.getLangOpts().MSVCCompat) {
1305 CallingConv Convs[] = {
1306 CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
1307 DefaultFree, DefaultMember, CallOpCC};
1308 llvm::sort(Convs);
1309 llvm::iterator_range<CallingConv *> Range(
1310 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1311 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1312
1313 for (CallingConv C : Range) {
1314 if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
1315 F(C);
1316 }
1317 return;
1318 }
1319
1320 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1321 F(DefaultFree);
1322 F(DefaultMember);
1323 } else {
1324 F(CallOpCC);
1325 }
1326}
1327
1328// Returns the 'standard' calling convention to be used for the lambda
1329// conversion function, that is, the 'free' function calling convention unless
1330// it is overridden by a non-default calling convention attribute.
1331static CallingConv
1332getLambdaConversionFunctionCallConv(Sema &S,
1333 const FunctionProtoType *CallOpProto) {
1334 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1335 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1336 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1337 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1338 CallingConv CallOpCC = CallOpProto->getCallConv();
1339
1340 // If the call-operator hasn't been changed, return both the 'free' and
1341 // 'member' function calling convention.
1342 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1343 return DefaultFree;
1344 return CallOpCC;
1345}
1346
1347QualType Sema::getLambdaConversionFunctionResultType(
1348 const FunctionProtoType *CallOpProto, CallingConv CC) {
1349 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1350 CallOpProto->getExtProtoInfo();
1351 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1352 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1353 InvokerExtInfo.TypeQuals = Qualifiers();
1354 assert(InvokerExtInfo.RefQualifier == RQ_None &&(static_cast <bool> (InvokerExtInfo.RefQualifier == RQ_None
&& "Lambda's call operator should not have a reference qualifier"
) ? void (0) : __assert_fail ("InvokerExtInfo.RefQualifier == RQ_None && \"Lambda's call operator should not have a reference qualifier\""
, "clang/lib/Sema/SemaLambda.cpp", 1355, __extension__ __PRETTY_FUNCTION__
))
1355 "Lambda's call operator should not have a reference qualifier")(static_cast <bool> (InvokerExtInfo.RefQualifier == RQ_None
&& "Lambda's call operator should not have a reference qualifier"
) ? void (0) : __assert_fail ("InvokerExtInfo.RefQualifier == RQ_None && \"Lambda's call operator should not have a reference qualifier\""
, "clang/lib/Sema/SemaLambda.cpp", 1355, __extension__ __PRETTY_FUNCTION__
))
;
1356 return Context.getFunctionType(CallOpProto->getReturnType(),
1357 CallOpProto->getParamTypes(), InvokerExtInfo);
1358}
1359
1360/// Add a lambda's conversion to function pointer, as described in
1361/// C++11 [expr.prim.lambda]p6.
1362static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1363 CXXRecordDecl *Class,
1364 CXXMethodDecl *CallOperator,
1365 QualType InvokerFunctionTy) {
1366 // This conversion is explicitly disabled if the lambda's function has
1367 // pass_object_size attributes on any of its parameters.
1368 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1369 return P->hasAttr<PassObjectSizeAttr>();
1370 };
1371 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1372 return;
1373
1374 // Add the conversion to function pointer.
1375 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1376
1377 // Create the type of the conversion function.
1378 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1379 S.Context.getDefaultCallingConvention(
1380 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1381 // The conversion function is always const and noexcept.
1382 ConvExtInfo.TypeQuals = Qualifiers();
1383 ConvExtInfo.TypeQuals.addConst();
1384 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1385 QualType ConvTy =
1386 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1387
1388 SourceLocation Loc = IntroducerRange.getBegin();
1389 DeclarationName ConversionName
1390 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1391 S.Context.getCanonicalType(PtrToFunctionTy));
1392 // Construct a TypeSourceInfo for the conversion function, and wire
1393 // all the parameters appropriately for the FunctionProtoTypeLoc
1394 // so that everything works during transformation/instantiation of
1395 // generic lambdas.
1396 // The main reason for wiring up the parameters of the conversion
1397 // function with that of the call operator is so that constructs
1398 // like the following work:
1399 // auto L = [](auto b) { <-- 1
1400 // return [](auto a) -> decltype(a) { <-- 2
1401 // return a;
1402 // };
1403 // };
1404 // int (*fp)(int) = L(5);
1405 // Because the trailing return type can contain DeclRefExprs that refer
1406 // to the original call operator's variables, we hijack the call
1407 // operators ParmVarDecls below.
1408 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1409 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1410 DeclarationNameLoc ConvNameLoc =
1411 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1412
1413 // The conversion function is a conversion to a pointer-to-function.
1414 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1415 FunctionProtoTypeLoc ConvTL =
1416 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1417 // Get the result of the conversion function which is a pointer-to-function.
1418 PointerTypeLoc PtrToFunctionTL =
1419 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1420 // Do the same for the TypeSourceInfo that is used to name the conversion
1421 // operator.
1422 PointerTypeLoc ConvNamePtrToFunctionTL =
1423 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1424
1425 // Get the underlying function types that the conversion function will
1426 // be converting to (should match the type of the call operator).
1427 FunctionProtoTypeLoc CallOpConvTL =
1428 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1429 FunctionProtoTypeLoc CallOpConvNameTL =
1430 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1431
1432 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1433 // These parameter's are essentially used to transform the name and
1434 // the type of the conversion operator. By using the same parameters
1435 // as the call operator's we don't have to fix any back references that
1436 // the trailing return type of the call operator's uses (such as
1437 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1438 // - we can simply use the return type of the call operator, and
1439 // everything should work.
1440 SmallVector<ParmVarDecl *, 4> InvokerParams;
1441 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1442 ParmVarDecl *From = CallOperator->getParamDecl(I);
1443
1444 InvokerParams.push_back(ParmVarDecl::Create(
1445 S.Context,
1446 // Temporarily add to the TU. This is set to the invoker below.
1447 S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
1448 From->getLocation(), From->getIdentifier(), From->getType(),
1449 From->getTypeSourceInfo(), From->getStorageClass(),
1450 /*DefArg=*/nullptr));
1451 CallOpConvTL.setParam(I, From);
1452 CallOpConvNameTL.setParam(I, From);
1453 }
1454
1455 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1456 S.Context, Class, Loc,
1457 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1458 S.getCurFPFeatures().isFPConstrained(),
1459 /*isInline=*/true, ExplicitSpecifier(),
1460 S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1461 : ConstexprSpecKind::Unspecified,
1462 CallOperator->getBody()->getEndLoc());
1463 Conversion->setAccess(AS_public);
1464 Conversion->setImplicit(true);
1465
1466 if (Class->isGenericLambda()) {
1467 // Create a template version of the conversion operator, using the template
1468 // parameter list of the function call operator.
1469 FunctionTemplateDecl *TemplateCallOperator =
1470 CallOperator->getDescribedFunctionTemplate();
1471 FunctionTemplateDecl *ConversionTemplate =
1472 FunctionTemplateDecl::Create(S.Context, Class,
1473 Loc, ConversionName,
1474 TemplateCallOperator->getTemplateParameters(),
1475 Conversion);
1476 ConversionTemplate->setAccess(AS_public);
1477 ConversionTemplate->setImplicit(true);
1478 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1479 Class->addDecl(ConversionTemplate);
1480 } else
1481 Class->addDecl(Conversion);
1482 // Add a non-static member function that will be the result of
1483 // the conversion with a certain unique ID.
1484 DeclarationName InvokerName = &S.Context.Idents.get(
1485 getLambdaStaticInvokerName());
1486 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1487 // we should get a prebuilt TrivialTypeSourceInfo from Context
1488 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1489 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1490 // loop below and then use its Params to set Invoke->setParams(...) below.
1491 // This would avoid the 'const' qualifier of the calloperator from
1492 // contaminating the type of the invoker, which is currently adjusted
1493 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1494 // trailing return type of the invoker would require a visitor to rebuild
1495 // the trailing return type and adjusting all back DeclRefExpr's to refer
1496 // to the new static invoker parameters - not the call operator's.
1497 CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1498 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1499 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1500 S.getCurFPFeatures().isFPConstrained(),
1501 /*isInline=*/true, ConstexprSpecKind::Unspecified,
1502 CallOperator->getBody()->getEndLoc());
1503 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1504 InvokerParams[I]->setOwningFunction(Invoke);
1505 Invoke->setParams(InvokerParams);
1506 Invoke->setAccess(AS_private);
1507 Invoke->setImplicit(true);
1508 if (Class->isGenericLambda()) {
1509 FunctionTemplateDecl *TemplateCallOperator =
1510 CallOperator->getDescribedFunctionTemplate();
1511 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1512 S.Context, Class, Loc, InvokerName,
1513 TemplateCallOperator->getTemplateParameters(),
1514 Invoke);
1515 StaticInvokerTemplate->setAccess(AS_private);
1516 StaticInvokerTemplate->setImplicit(true);
1517 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1518 Class->addDecl(StaticInvokerTemplate);
1519 } else
1520 Class->addDecl(Invoke);
1521}
1522
1523/// Add a lambda's conversion to function pointers, as described in
1524/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1525/// single pointer conversion. In the event that the default calling convention
1526/// for free and member functions is different, it will emit both conventions.
1527static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1528 CXXRecordDecl *Class,
1529 CXXMethodDecl *CallOperator) {
1530 const FunctionProtoType *CallOpProto =
1531 CallOperator->getType()->castAs<FunctionProtoType>();
1532
1533 repeatForLambdaConversionFunctionCallingConvs(
1534 S, *CallOpProto, [&](CallingConv CC) {
1535 QualType InvokerFunctionTy =
1536 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1537 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1538 InvokerFunctionTy);
1539 });
1540}
1541
1542/// Add a lambda's conversion to block pointer.
1543static void addBlockPointerConversion(Sema &S,
1544 SourceRange IntroducerRange,
1545 CXXRecordDecl *Class,
1546 CXXMethodDecl *CallOperator) {
1547 const FunctionProtoType *CallOpProto =
1548 CallOperator->getType()->castAs<FunctionProtoType>();
1549 QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1550 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1551 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1552
1553 FunctionProtoType::ExtProtoInfo ConversionEPI(
1554 S.Context.getDefaultCallingConvention(
1555 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1556 ConversionEPI.TypeQuals = Qualifiers();
1557 ConversionEPI.TypeQuals.addConst();
1558 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
1559
1560 SourceLocation Loc = IntroducerRange.getBegin();
1561 DeclarationName Name
1562 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1563 S.Context.getCanonicalType(BlockPtrTy));
1564 DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
1565 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1566 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1567 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1568 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1569 S.getCurFPFeatures().isFPConstrained(),
1570 /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
1571 CallOperator->getBody()->getEndLoc());
1572 Conversion->setAccess(AS_public);
1573 Conversion->setImplicit(true);
1574 Class->addDecl(Conversion);
1575}
1576
1577ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1578 SourceLocation ImplicitCaptureLoc,
1579 bool IsOpenMPMapping) {
1580 // VLA captures don't have a stored initialization expression.
1581 if (Cap.isVLATypeCapture())
1582 return ExprResult();
1583
1584 // An init-capture is initialized directly from its stored initializer.
1585 if (Cap.isInitCapture())
1586 return cast<VarDecl>(Cap.getVariable())->getInit();
1587
1588 // For anything else, build an initialization expression. For an implicit
1589 // capture, the capture notionally happens at the capture-default, so use
1590 // that location here.
1591 SourceLocation Loc =
1592 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1593
1594 // C++11 [expr.prim.lambda]p21:
1595 // When the lambda-expression is evaluated, the entities that
1596 // are captured by copy are used to direct-initialize each
1597 // corresponding non-static data member of the resulting closure
1598 // object. (For array members, the array elements are
1599 // direct-initialized in increasing subscript order.) These
1600 // initializations are performed in the (unspecified) order in
1601 // which the non-static data members are declared.
1602
1603 // C++ [expr.prim.lambda]p12:
1604 // An entity captured by a lambda-expression is odr-used (3.2) in
1605 // the scope containing the lambda-expression.
1606 ExprResult Init;
1607 IdentifierInfo *Name = nullptr;
1608 if (Cap.isThisCapture()) {
1609 QualType ThisTy = getCurrentThisType();
1610 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1611 if (Cap.isCopyCapture())
1612 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1613 else
1614 Init = This;
1615 } else {
1616 assert(Cap.isVariableCapture() && "unknown kind of capture")(static_cast <bool> (Cap.isVariableCapture() &&
"unknown kind of capture") ? void (0) : __assert_fail ("Cap.isVariableCapture() && \"unknown kind of capture\""
, "clang/lib/Sema/SemaLambda.cpp", 1616, __extension__ __PRETTY_FUNCTION__
))
;
1617 ValueDecl *Var = Cap.getVariable();
1618 Name = Var->getIdentifier();
1619 Init = BuildDeclarationNameExpr(
1620 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1621 }
1622
1623 // In OpenMP, the capture kind doesn't actually describe how to capture:
1624 // variables are "mapped" onto the device in a process that does not formally
1625 // make a copy, even for a "copy capture".
1626 if (IsOpenMPMapping)
1627 return Init;
1628
1629 if (Init.isInvalid())
1630 return ExprError();
1631
1632 Expr *InitExpr = Init.get();
1633 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1634 Name, Cap.getCaptureType(), Loc);
1635 InitializationKind InitKind =
1636 InitializationKind::CreateDirect(Loc, Loc, Loc);
1637 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1638 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1639}
1640
1641ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1642 Scope *CurScope) {
1643 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1644 ActOnFinishFunctionBody(LSI.CallOperator, Body);
1645 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1646}
1647
1648static LambdaCaptureDefault
1649mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1650 switch (ICS) {
1651 case CapturingScopeInfo::ImpCap_None:
1652 return LCD_None;
1653 case CapturingScopeInfo::ImpCap_LambdaByval:
1654 return LCD_ByCopy;
1655 case CapturingScopeInfo::ImpCap_CapturedRegion:
1656 case CapturingScopeInfo::ImpCap_LambdaByref:
1657 return LCD_ByRef;
1658 case CapturingScopeInfo::ImpCap_Block:
1659 llvm_unreachable("block capture in lambda")::llvm::llvm_unreachable_internal("block capture in lambda", "clang/lib/Sema/SemaLambda.cpp"
, 1659)
;
1660 }
1661 llvm_unreachable("Unknown implicit capture style")::llvm::llvm_unreachable_internal("Unknown implicit capture style"
, "clang/lib/Sema/SemaLambda.cpp", 1661)
;
1662}
1663
1664bool Sema::CaptureHasSideEffects(const Capture &From) {
1665 if (From.isInitCapture()) {
1666 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1667 if (Init && Init->HasSideEffects(Context))
1668 return true;
1669 }
1670
1671 if (!From.isCopyCapture())
1672 return false;
1673
1674 const QualType T = From.isThisCapture()
1675 ? getCurrentThisType()->getPointeeType()
1676 : From.getCaptureType();
1677
1678 if (T.isVolatileQualified())
1679 return true;
1680
1681 const Type *BaseT = T->getBaseElementTypeUnsafe();
1682 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1683 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1684 !RD->hasTrivialDestructor();
1685
1686 return false;
1687}
1688
1689bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
1690 const Capture &From) {
1691 if (CaptureHasSideEffects(From))
1692 return false;
1693
1694 if (From.isVLATypeCapture())
1695 return false;
1696
1697 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1698 if (From.isThisCapture())
1699 diag << "'this'";
1700 else
1701 diag << From.getVariable();
1702 diag << From.isNonODRUsed();
1703 diag << FixItHint::CreateRemoval(CaptureRange);
1704 return true;
1705}
1706
1707/// Create a field within the lambda class or captured statement record for the
1708/// given capture.
1709FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
1710 const sema::Capture &Capture) {
1711 SourceLocation Loc = Capture.getLocation();
1712 QualType FieldType = Capture.getCaptureType();
1713
1714 TypeSourceInfo *TSI = nullptr;
1715 if (Capture.isVariableCapture()) {
1716 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
1717 if (Var && Var->isInitCapture())
1718 TSI = Var->getTypeSourceInfo();
1719 }
1720
1721 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1722 // appropriate, at least for an implicit capture.
1723 if (!TSI)
1724 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1725
1726 // Build the non-static data member.
1727 FieldDecl *Field =
1728 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
1729 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
1730 /*Mutable=*/false, ICIS_NoInit);
1731 // If the variable being captured has an invalid type, mark the class as
1732 // invalid as well.
1733 if (!FieldType->isDependentType()) {
1734 if (RequireCompleteSizedType(Loc, FieldType,
1735 diag::err_field_incomplete_or_sizeless)) {
1736 RD->setInvalidDecl();
1737 Field->setInvalidDecl();
1738 } else {
1739 NamedDecl *Def;
1740 FieldType->isIncompleteType(&Def);
1741 if (Def && Def->isInvalidDecl()) {
1742 RD->setInvalidDecl();
1743 Field->setInvalidDecl();
1744 }
1745 }
1746 }
1747 Field->setImplicit(true);
1748 Field->setAccess(AS_private);
1749 RD->addDecl(Field);
1750
1751 if (Capture.isVLATypeCapture())
1752 Field->setCapturedVLAType(Capture.getCapturedVLAType());
1753
1754 return Field;
1755}
1756
1757ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1758 LambdaScopeInfo *LSI) {
1759 // Collect information from the lambda scope.
1760 SmallVector<LambdaCapture, 4> Captures;
1761 SmallVector<Expr *, 4> CaptureInits;
1762 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1763 LambdaCaptureDefault CaptureDefault =
1764 mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
1765 CXXRecordDecl *Class;
1766 CXXMethodDecl *CallOperator;
1767 SourceRange IntroducerRange;
1768 bool ExplicitParams;
1769 bool ExplicitResultType;
1770 CleanupInfo LambdaCleanup;
1771 bool ContainsUnexpandedParameterPack;
1772 bool IsGenericLambda;
1773 {
1774 CallOperator = LSI->CallOperator;
1775 Class = LSI->Lambda;
1776 IntroducerRange = LSI->IntroducerRange;
1777 ExplicitParams = LSI->ExplicitParams;
1778 ExplicitResultType = !LSI->HasImplicitReturnType;
1779 LambdaCleanup = LSI->Cleanup;
1780 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1781 IsGenericLambda = Class->isGenericLambda();
1782
1783 CallOperator->setLexicalDeclContext(Class);
1784 Decl *TemplateOrNonTemplateCallOperatorDecl =
1785 CallOperator->getDescribedFunctionTemplate()
1786 ? CallOperator->getDescribedFunctionTemplate()
1787 : cast<Decl>(CallOperator);
1788
1789 // FIXME: Is this really the best choice? Keeping the lexical decl context
1790 // set as CurContext seems more faithful to the source.
1791 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1792
1793 PopExpressionEvaluationContext();
1794
1795 // True if the current capture has a used capture or default before it.
1796 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
1797 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
1798 CaptureDefaultLoc : IntroducerRange.getBegin();
1799
1800 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1801 const Capture &From = LSI->Captures[I];
1802
1803 if (From.isInvalid())
1804 return ExprError();
1805
1806 assert(!From.isBlockCapture() && "Cannot capture __block variables")(static_cast <bool> (!From.isBlockCapture() && "Cannot capture __block variables"
) ? void (0) : __assert_fail ("!From.isBlockCapture() && \"Cannot capture __block variables\""
, "clang/lib/Sema/SemaLambda.cpp", 1806, __extension__ __PRETTY_FUNCTION__
))
;
1807 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1808 SourceLocation ImplicitCaptureLoc =
1809 IsImplicit ? CaptureDefaultLoc : SourceLocation();
1810
1811 // Use source ranges of explicit captures for fixits where available.
1812 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
1813
1814 // Warn about unused explicit captures.
1815 bool IsCaptureUsed = true;
1816 if (!CurContext->isDependentContext() && !IsImplicit &&
1817 !From.isODRUsed()) {
1818 // Initialized captures that are non-ODR used may not be eliminated.
1819 // FIXME: Where did the IsGenericLambda here come from?
1820 bool NonODRUsedInitCapture =
1821 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
1822 if (!NonODRUsedInitCapture) {
1823 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
1824 SourceRange FixItRange;
1825 if (CaptureRange.isValid()) {
1826 if (!CurHasPreviousCapture && !IsLast) {
1827 // If there are no captures preceding this capture, remove the
1828 // following comma.
1829 FixItRange = SourceRange(CaptureRange.getBegin(),
1830 getLocForEndOfToken(CaptureRange.getEnd()));
1831 } else {
1832 // Otherwise, remove the comma since the last used capture.
1833 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
1834 CaptureRange.getEnd());
1835 }
1836 }
1837
1838 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
1839 }
1840 }
1841
1842 if (CaptureRange.isValid()) {
1843 CurHasPreviousCapture |= IsCaptureUsed;
1844 PrevCaptureLoc = CaptureRange.getEnd();
1845 }
1846
1847 // Map the capture to our AST representation.
1848 LambdaCapture Capture = [&] {
1849 if (From.isThisCapture()) {
1850 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
1851 // because it results in a reference capture. Don't warn prior to
1852 // C++2a; there's nothing that can be done about it before then.
1853 if (getLangOpts().CPlusPlus20 && IsImplicit &&
1854 CaptureDefault == LCD_ByCopy) {
1855 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
1856 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
1857 << FixItHint::CreateInsertion(
1858 getLocForEndOfToken(CaptureDefaultLoc), ", this");
1859 }
1860 return LambdaCapture(From.getLocation(), IsImplicit,
1861 From.isCopyCapture() ? LCK_StarThis : LCK_This);
1862 } else if (From.isVLATypeCapture()) {
1863 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
1864 } else {
1865 assert(From.isVariableCapture() && "unknown kind of capture")(static_cast <bool> (From.isVariableCapture() &&
"unknown kind of capture") ? void (0) : __assert_fail ("From.isVariableCapture() && \"unknown kind of capture\""
, "clang/lib/Sema/SemaLambda.cpp", 1865, __extension__ __PRETTY_FUNCTION__
))
;
1866 ValueDecl *Var = From.getVariable();
1867 LambdaCaptureKind Kind =
1868 From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
1869 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
1870 From.getEllipsisLoc());
1871 }
1872 }();
1873
1874 // Form the initializer for the capture field.
1875 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
1876
1877 // FIXME: Skip this capture if the capture is not used, the initializer
1878 // has no side-effects, the type of the capture is trivial, and the
1879 // lambda is not externally visible.
1880
1881 // Add a FieldDecl for the capture and form its initializer.
1882 BuildCaptureField(Class, From);
1883 Captures.push_back(Capture);
1884 CaptureInits.push_back(Init.get());
1885
1886 if (LangOpts.CUDA)
1887 CUDACheckLambdaCapture(CallOperator, From);
1888 }
1889
1890 Class->setCaptures(Context, Captures);
1891
1892 // C++11 [expr.prim.lambda]p6:
1893 // The closure type for a lambda-expression with no lambda-capture
1894 // has a public non-virtual non-explicit const conversion function
1895 // to pointer to function having the same parameter and return
1896 // types as the closure type's function call operator.
1897 if (Captures.empty() && CaptureDefault == LCD_None)
1898 addFunctionPointerConversions(*this, IntroducerRange, Class,
1899 CallOperator);
1900
1901 // Objective-C++:
1902 // The closure type for a lambda-expression has a public non-virtual
1903 // non-explicit const conversion function to a block pointer having the
1904 // same parameter and return types as the closure type's function call
1905 // operator.
1906 // FIXME: Fix generic lambda to block conversions.
1907 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
1908 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1909
1910 // Finalize the lambda class.
1911 SmallVector<Decl*, 4> Fields(Class->fields());
1912 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1913 SourceLocation(), ParsedAttributesView());
1914 CheckCompletedCXXClass(nullptr, Class);
1915 }
1916
1917 Cleanup.mergeFrom(LambdaCleanup);
1918
1919 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1920 CaptureDefault, CaptureDefaultLoc,
1921 ExplicitParams, ExplicitResultType,
1922 CaptureInits, EndLoc,
1923 ContainsUnexpandedParameterPack);
1924 // If the lambda expression's call operator is not explicitly marked constexpr
1925 // and we are not in a dependent context, analyze the call operator to infer
1926 // its constexpr-ness, suppressing diagnostics while doing so.
1927 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
1928 !CallOperator->isConstexpr() &&
1929 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
1930 !Class->getDeclContext()->isDependentContext()) {
1931 CallOperator->setConstexprKind(
1932 CheckConstexprFunctionDefinition(CallOperator,
1933 CheckConstexprKind::CheckValid)
1934 ? ConstexprSpecKind::Constexpr
1935 : ConstexprSpecKind::Unspecified);
1936 }
1937
1938 // Emit delayed shadowing warnings now that the full capture list is known.
1939 DiagnoseShadowingLambdaDecls(LSI);
1940
1941 if (!CurContext->isDependentContext()) {
1942 switch (ExprEvalContexts.back().Context) {
1943 // C++11 [expr.prim.lambda]p2:
1944 // A lambda-expression shall not appear in an unevaluated operand
1945 // (Clause 5).
1946 case ExpressionEvaluationContext::Unevaluated:
1947 case ExpressionEvaluationContext::UnevaluatedList:
1948 case ExpressionEvaluationContext::UnevaluatedAbstract:
1949 // C++1y [expr.const]p2:
1950 // A conditional-expression e is a core constant expression unless the
1951 // evaluation of e, following the rules of the abstract machine, would
1952 // evaluate [...] a lambda-expression.
1953 //
1954 // This is technically incorrect, there are some constant evaluated contexts
1955 // where this should be allowed. We should probably fix this when DR1607 is
1956 // ratified, it lays out the exact set of conditions where we shouldn't
1957 // allow a lambda-expression.
1958 case ExpressionEvaluationContext::ConstantEvaluated:
1959 case ExpressionEvaluationContext::ImmediateFunctionContext:
1960 // We don't actually diagnose this case immediately, because we
1961 // could be within a context where we might find out later that
1962 // the expression is potentially evaluated (e.g., for typeid).
1963 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1964 break;
1965
1966 case ExpressionEvaluationContext::DiscardedStatement:
1967 case ExpressionEvaluationContext::PotentiallyEvaluated:
1968 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
1969 break;
1970 }
1971 }
1972
1973 return MaybeBindToTemporary(Lambda);
1974}
1975
1976ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1977 SourceLocation ConvLocation,
1978 CXXConversionDecl *Conv,
1979 Expr *Src) {
1980 // Make sure that the lambda call operator is marked used.
1981 CXXRecordDecl *Lambda = Conv->getParent();
1982 CXXMethodDecl *CallOperator
1983 = cast<CXXMethodDecl>(
1984 Lambda->lookup(
1985 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1986 CallOperator->setReferenced();
1987 CallOperator->markUsed(Context);
1988
1989 ExprResult Init = PerformCopyInitialization(
1990 InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType()),
1991 CurrentLocation, Src);
1992 if (!Init.isInvalid())
1993 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
1994
1995 if (Init.isInvalid())
1996 return ExprError();
1997
1998 // Create the new block to be returned.
1999 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
2000
2001 // Set the type information.
2002 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2003 Block->setIsVariadic(CallOperator->isVariadic());
2004 Block->setBlockMissingReturnType(false);
2005
2006 // Add parameters.
2007 SmallVector<ParmVarDecl *, 4> BlockParams;
2008 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2009 ParmVarDecl *From = CallOperator->getParamDecl(I);
2010 BlockParams.push_back(ParmVarDecl::Create(
2011 Context, Block, From->getBeginLoc(), From->getLocation(),
2012 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2013 From->getStorageClass(),
2014 /*DefArg=*/nullptr));
2015 }
2016 Block->setParams(BlockParams);
2017
2018 Block->setIsConversionFromLambda(true);
2019
2020 // Add capture. The capture uses a fake variable, which doesn't correspond
2021 // to any actual memory location. However, the initializer copy-initializes
2022 // the lambda object.
2023 TypeSourceInfo *CapVarTSI =
2024 Context.getTrivialTypeSourceInfo(Src->getType());
2025 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2026 ConvLocation, nullptr,
2027 Src->getType(), CapVarTSI,
2028 SC_None);
2029 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2030 /*nested=*/false, /*copy=*/Init.get());
2031 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2032
2033 // Add a fake function body to the block. IR generation is responsible
2034 // for filling in the actual body, which cannot be expressed as an AST.
2035 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2036
2037 // Create the block literal expression.
2038 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2039 ExprCleanupObjects.push_back(Block);
2040 Cleanup.setExprNeedsCleanups(true);
2041
2042 return BuildBlock;
2043}

/build/llvm-toolchain-snapshot-16~++20220929111209+ac2e2d659819/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- 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 Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/TypeOrdering.h"
38#include "clang/Basic/BitmaskEnum.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/DarwinSDKInfo.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/OpenCLOptions.h"
44#include "clang/Basic/OpenMPKinds.h"
45#include "clang/Basic/PragmaKinds.h"
46#include "clang/Basic/Specifiers.h"
47#include "clang/Basic/TemplateKinds.h"
48#include "clang/Basic/TypeTraits.h"
49#include "clang/Sema/AnalysisBasedWarnings.h"
50#include "clang/Sema/CleanupInfo.h"
51#include "clang/Sema/DeclSpec.h"
52#include "clang/Sema/ExternalSemaSource.h"
53#include "clang/Sema/IdentifierResolver.h"
54#include "clang/Sema/ObjCMethodList.h"
55#include "clang/Sema/Ownership.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaConcept.h"
58#include "clang/Sema/TypoCorrection.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/Optional.h"
62#include "llvm/ADT/SetVector.h"
63#include "llvm/ADT/SmallBitVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/SmallSet.h"
66#include "llvm/ADT/SmallVector.h"
67#include "llvm/ADT/TinyPtrVector.h"
68#include "llvm/Frontend/OpenMP/OMPConstants.h"
69#include <deque>
70#include <memory>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
97 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
137 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
149 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
174 enum OverloadCandidateRewriteKind : unsigned;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class RISCVIntrinsicManager;
230 class SemaPPCallbacks;
231 class TemplateDeductionInfo;
232}
233
234namespace threadSafety {
235 class BeforeSet;
236 void threadSafetyCleanup(BeforeSet* Cache);
237}
238
239// FIXME: No way to easily map from TemplateTypeParmTypes to
240// TemplateTypeParmDecls, so we have this horrible PointerUnion.
241using UnexpandedParameterPack = std::pair<
242 llvm::PointerUnion<
243 const TemplateTypeParmType *, const SubstTemplateTypeParmPackType *,
244 const SubstNonTypeTemplateParmPackExpr *, const NamedDecl *>,
245 SourceLocation>;
246
247/// Describes whether we've seen any nullability information for the given
248/// file.
249struct FileNullability {
250 /// The first pointer declarator (of any pointer kind) in the file that does
251 /// not have a corresponding nullability annotation.
252 SourceLocation PointerLoc;
253
254 /// The end location for the first pointer declarator in the file. Used for
255 /// placing fix-its.
256 SourceLocation PointerEndLoc;
257
258 /// Which kind of pointer declarator we saw.
259 uint8_t PointerKind;
260
261 /// Whether we saw any type nullability annotations in the given file.
262 bool SawTypeNullability = false;
263};
264
265/// A mapping from file IDs to a record of whether we've seen nullability
266/// information in that file.
267class FileNullabilityMap {
268 /// A mapping from file IDs to the nullability information for each file ID.
269 llvm::DenseMap<FileID, FileNullability> Map;
270
271 /// A single-element cache based on the file ID.
272 struct {
273 FileID File;
274 FileNullability Nullability;
275 } Cache;
276
277public:
278 FileNullability &operator[](FileID file) {
279 // Check the single-element cache.
280 if (file == Cache.File)
281 return Cache.Nullability;
282
283 // It's not in the single-element cache; flush the cache if we have one.
284 if (!Cache.File.isInvalid()) {
285 Map[Cache.File] = Cache.Nullability;
286 }
287
288 // Pull this entry into the cache.
289 Cache.File = file;
290 Cache.Nullability = Map[file];
291 return Cache.Nullability;
292 }
293};
294
295/// Tracks expected type during expression parsing, for use in code completion.
296/// The type is tied to a particular token, all functions that update or consume
297/// the type take a start location of the token they are looking at as a
298/// parameter. This avoids updating the type on hot paths in the parser.
299class PreferredTypeBuilder {
300public:
301 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
302
303 void enterCondition(Sema &S, SourceLocation Tok);
304 void enterReturn(Sema &S, SourceLocation Tok);
305 void enterVariableInit(SourceLocation Tok, Decl *D);
306 /// Handles e.g. BaseType{ .D = Tok...
307 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
308 const Designation &D);
309 /// Computing a type for the function argument may require running
310 /// overloading, so we postpone its computation until it is actually needed.
311 ///
312 /// Clients should be very careful when using this function, as it stores a
313 /// function_ref, clients should make sure all calls to get() with the same
314 /// location happen while function_ref is alive.
315 ///
316 /// The callback should also emit signature help as a side-effect, but only
317 /// if the completion point has been reached.
318 void enterFunctionArgument(SourceLocation Tok,
319 llvm::function_ref<QualType()> ComputeType);
320
321 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
322 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
323 SourceLocation OpLoc);
324 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
325 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
326 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
327 /// Handles all type casts, including C-style cast, C++ casts, etc.
328 void enterTypeCast(SourceLocation Tok, QualType CastType);
329
330 /// Get the expected type associated with this location, if any.
331 ///
332 /// If the location is a function argument, determining the expected type
333 /// involves considering all function overloads and the arguments so far.
334 /// In this case, signature help for these function overloads will be reported
335 /// as a side-effect (only if the completion point has been reached).
336 QualType get(SourceLocation Tok) const {
337 if (!Enabled || Tok != ExpectedLoc)
338 return QualType();
339 if (!Type.isNull())
340 return Type;
341 if (ComputeType)
342 return ComputeType();
343 return QualType();
344 }
345
346private:
347 bool Enabled;
348 /// Start position of a token for which we store expected type.
349 SourceLocation ExpectedLoc;
350 /// Expected type for a token starting at ExpectedLoc.
351 QualType Type;
352 /// A function to compute expected type at ExpectedLoc. It is only considered
353 /// if Type is null.
354 llvm::function_ref<QualType()> ComputeType;
355};
356
357/// Sema - This implements semantic analysis and AST building for C.
358class Sema final {
359 Sema(const Sema &) = delete;
360 void operator=(const Sema &) = delete;
361
362 ///Source of additional semantic information.
363 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
364
365 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
366
367 /// Determine whether two declarations should be linked together, given that
368 /// the old declaration might not be visible and the new declaration might
369 /// not have external linkage.
370 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
371 const NamedDecl *New) {
372 if (isVisible(Old))
373 return true;
374 // See comment in below overload for why it's safe to compute the linkage
375 // of the new declaration here.
376 if (New->isExternallyDeclarable()) {
377 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 378, __extension__ __PRETTY_FUNCTION__
))
378 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 378, __extension__ __PRETTY_FUNCTION__
))
;
379 return true;
380 }
381 return false;
382 }
383 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
384
385 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
386 QualType ResultTy,
387 ArrayRef<QualType> Args);
388
389public:
390 /// The maximum alignment, same as in llvm::Value. We duplicate them here
391 /// because that allows us not to duplicate the constants in clang code,
392 /// which we must to since we can't directly use the llvm constants.
393 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
394 ///
395 /// This is the greatest alignment value supported by load, store, and alloca
396 /// instructions, and global values.
397 static const unsigned MaxAlignmentExponent = 32;
398 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
399
400 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
401 typedef OpaquePtr<TemplateName> TemplateTy;
402 typedef OpaquePtr<QualType> TypeTy;
403
404 OpenCLOptions OpenCLFeatures;
405 FPOptions CurFPFeatures;
406
407 const LangOptions &LangOpts;
408 Preprocessor &PP;
409 ASTContext &Context;
410 ASTConsumer &Consumer;
411 DiagnosticsEngine &Diags;
412 SourceManager &SourceMgr;
413
414 /// Flag indicating whether or not to collect detailed statistics.
415 bool CollectStats;
416
417 /// Code-completion consumer.
418 CodeCompleteConsumer *CodeCompleter;
419
420 /// CurContext - This is the current declaration context of parsing.
421 DeclContext *CurContext;
422
423 /// Generally null except when we temporarily switch decl contexts,
424 /// like in \see ActOnObjCTemporaryExitContainerContext.
425 DeclContext *OriginalLexicalContext;
426
427 /// VAListTagName - The declaration name corresponding to __va_list_tag.
428 /// This is used as part of a hack to omit that class from ADL results.
429 DeclarationName VAListTagName;
430
431 bool MSStructPragmaOn; // True when \#pragma ms_struct on
432
433 /// Controls member pointer representation format under the MS ABI.
434 LangOptions::PragmaMSPointersToMembersKind
435 MSPointerToMemberRepresentationMethod;
436
437 /// Stack of active SEH __finally scopes. Can be empty.
438 SmallVector<Scope*, 2> CurrentSEHFinally;
439
440 /// Source location for newly created implicit MSInheritanceAttrs
441 SourceLocation ImplicitMSInheritanceAttrLoc;
442
443 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
444 /// `TransformTypos` in order to keep track of any TypoExprs that are created
445 /// recursively during typo correction and wipe them away if the correction
446 /// fails.
447 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
448
449 /// pragma clang section kind
450 enum PragmaClangSectionKind {
451 PCSK_Invalid = 0,
452 PCSK_BSS = 1,
453 PCSK_Data = 2,
454 PCSK_Rodata = 3,
455 PCSK_Text = 4,
456 PCSK_Relro = 5
457 };
458
459 enum PragmaClangSectionAction {
460 PCSA_Set = 0,
461 PCSA_Clear = 1
462 };
463
464 struct PragmaClangSection {
465 std::string SectionName;
466 bool Valid = false;
467 SourceLocation PragmaLocation;
468 };
469
470 PragmaClangSection PragmaClangBSSSection;
471 PragmaClangSection PragmaClangDataSection;
472 PragmaClangSection PragmaClangRodataSection;
473 PragmaClangSection PragmaClangRelroSection;
474 PragmaClangSection PragmaClangTextSection;
475
476 enum PragmaMsStackAction {
477 PSK_Reset = 0x0, // #pragma ()
478 PSK_Set = 0x1, // #pragma (value)
479 PSK_Push = 0x2, // #pragma (push[, id])
480 PSK_Pop = 0x4, // #pragma (pop[, id])
481 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
482 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
483 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
484 };
485
486 // #pragma pack and align.
487 class AlignPackInfo {
488 public:
489 // `Native` represents default align mode, which may vary based on the
490 // platform.
491 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
492
493 // #pragma pack info constructor
494 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
495 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
496 assert(Num == PackNumber && "The pack number has been truncated.")(static_cast <bool> (Num == PackNumber && "The pack number has been truncated."
) ? void (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\""
, "clang/include/clang/Sema/Sema.h", 496, __extension__ __PRETTY_FUNCTION__
))
;
497 }
498
499 // #pragma align info constructor
500 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
501 : PackAttr(false), AlignMode(M),
502 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
503
504 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
505
506 AlignPackInfo() : AlignPackInfo(Native, false) {}
507
508 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
509 // integer encoding for it. This should only be passed to
510 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
511 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
512 std::uint32_t Encoding{};
513 if (Info.IsXLStack())
514 Encoding |= IsXLMask;
515
516 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
517
518 if (Info.IsPackAttr())
519 Encoding |= PackAttrMask;
520
521 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
522
523 return Encoding;
524 }
525
526 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
527 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
528 AlignPackInfo::Mode M =
529 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
530 int PackNumber = (Encoding & PackNumMask) >> 4;
531
532 if (Encoding & PackAttrMask)
533 return AlignPackInfo(M, PackNumber, IsXL);
534
535 return AlignPackInfo(M, IsXL);
536 }
537
538 bool IsPackAttr() const { return PackAttr; }
539
540 bool IsAlignAttr() const { return !PackAttr; }
541
542 Mode getAlignMode() const { return AlignMode; }
543
544 unsigned getPackNumber() const { return PackNumber; }
545
546 bool IsPackSet() const {
547 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
548 // attriute on a decl.
549 return PackNumber != UninitPackVal && PackNumber != 0;
550 }
551
552 bool IsXLStack() const { return XLStack; }
553
554 bool operator==(const AlignPackInfo &Info) const {
555 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
556 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
557 Info.XLStack);
558 }
559
560 bool operator!=(const AlignPackInfo &Info) const {
561 return !(*this == Info);
562 }
563
564 private:
565 /// \brief True if this is a pragma pack attribute,
566 /// not a pragma align attribute.
567 bool PackAttr;
568
569 /// \brief The alignment mode that is in effect.
570 Mode AlignMode;
571
572 /// \brief The pack number of the stack.
573 unsigned char PackNumber;
574
575 /// \brief True if it is a XL #pragma align/pack stack.
576 bool XLStack;
577
578 /// \brief Uninitialized pack value.
579 static constexpr unsigned char UninitPackVal = -1;
580
581 // Masks to encode and decode an AlignPackInfo.
582 static constexpr uint32_t IsXLMask{0x0000'0001};
583 static constexpr uint32_t AlignModeMask{0x0000'0006};
584 static constexpr uint32_t PackAttrMask{0x00000'0008};
585 static constexpr uint32_t PackNumMask{0x0000'01F0};
586 };
587
588 template<typename ValueType>
589 struct PragmaStack {
590 struct Slot {
591 llvm::StringRef StackSlotLabel;
592 ValueType Value;
593 SourceLocation PragmaLocation;
594 SourceLocation PragmaPushLocation;
595 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
596 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
597 : StackSlotLabel(StackSlotLabel), Value(Value),
598 PragmaLocation(PragmaLocation),
599 PragmaPushLocation(PragmaPushLocation) {}
600 };
601
602 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
603 llvm::StringRef StackSlotLabel, ValueType Value) {
604 if (Action == PSK_Reset) {
605 CurrentValue = DefaultValue;
606 CurrentPragmaLocation = PragmaLocation;
607 return;
608 }
609 if (Action & PSK_Push)
610 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
611 PragmaLocation);
612 else if (Action & PSK_Pop) {
613 if (!StackSlotLabel.empty()) {
614 // If we've got a label, try to find it and jump there.
615 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
616 return x.StackSlotLabel == StackSlotLabel;
617 });
618 // If we found the label so pop from there.
619 if (I != Stack.rend()) {
620 CurrentValue = I->Value;
621 CurrentPragmaLocation = I->PragmaLocation;
622 Stack.erase(std::prev(I.base()), Stack.end());
623 }
624 } else if (!Stack.empty()) {
625 // We do not have a label, just pop the last entry.
626 CurrentValue = Stack.back().Value;
627 CurrentPragmaLocation = Stack.back().PragmaLocation;
628 Stack.pop_back();
629 }
630 }
631 if (Action & PSK_Set) {
632 CurrentValue = Value;
633 CurrentPragmaLocation = PragmaLocation;
634 }
635 }
636
637 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
638 // method body to restore the stacks on exit, so it works like this:
639 //
640 // struct S {
641 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
642 // void Method {}
643 // #pragma <name>(pop, InternalPragmaSlot)
644 // };
645 //
646 // It works even with #pragma vtordisp, although MSVC doesn't support
647 // #pragma vtordisp(push [, id], n)
648 // syntax.
649 //
650 // Push / pop a named sentinel slot.
651 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
652 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 653, __extension__ __PRETTY_FUNCTION__
))
653 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 653, __extension__ __PRETTY_FUNCTION__
))
;
654 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
655 }
656
657 // Constructors.
658 explicit PragmaStack(const ValueType &Default)
659 : DefaultValue(Default), CurrentValue(Default) {}
660
661 bool hasValue() const { return CurrentValue != DefaultValue; }
662
663 SmallVector<Slot, 2> Stack;
664 ValueType DefaultValue; // Value used for PSK_Reset action.
665 ValueType CurrentValue;
666 SourceLocation CurrentPragmaLocation;
667 };
668 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
669 // we shouldn't do so if they're in a module).
670
671 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
672 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
673 ///
674 /// 0: Suppress all vtordisps
675 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
676 /// structors
677 /// 2: Always insert vtordisps to support RTTI on partially constructed
678 /// objects
679 PragmaStack<MSVtorDispMode> VtorDispStack;
680 PragmaStack<AlignPackInfo> AlignPackStack;
681 // The current #pragma align/pack values and locations at each #include.
682 struct AlignPackIncludeState {
683 AlignPackInfo CurrentValue;
684 SourceLocation CurrentPragmaLocation;
685 bool HasNonDefaultValue, ShouldWarnOnInclude;
686 };
687 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
688 // Segment #pragmas.
689 PragmaStack<StringLiteral *> DataSegStack;
690 PragmaStack<StringLiteral *> BSSSegStack;
691 PragmaStack<StringLiteral *> ConstSegStack;
692 PragmaStack<StringLiteral *> CodeSegStack;
693
694 // #pragma strict_gs_check.
695 PragmaStack<bool> StrictGuardStackCheckStack;
696
697 // This stack tracks the current state of Sema.CurFPFeatures.
698 PragmaStack<FPOptionsOverride> FpPragmaStack;
699 FPOptionsOverride CurFPFeatureOverrides() {
700 FPOptionsOverride result;
701 if (!FpPragmaStack.hasValue()) {
702 result = FPOptionsOverride();
703 } else {
704 result = FpPragmaStack.CurrentValue;
705 }
706 return result;
707 }
708
709 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
710 // Actions should be performed only if we enter / exit a C++ method body.
711 class PragmaStackSentinelRAII {
712 public:
713 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
714 ~PragmaStackSentinelRAII();
715
716 private:
717 Sema &S;
718 StringRef SlotLabel;
719 bool ShouldAct;
720 };
721
722 /// A mapping that describes the nullability we've seen in each header file.
723 FileNullabilityMap NullabilityMap;
724
725 /// Last section used with #pragma init_seg.
726 StringLiteral *CurInitSeg;
727 SourceLocation CurInitSegLoc;
728
729 /// Sections used with #pragma alloc_text.
730 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
731
732 /// VisContext - Manages the stack for \#pragma GCC visibility.
733 void *VisContext; // Really a "PragmaVisStack*"
734
735 /// This an attribute introduced by \#pragma clang attribute.
736 struct PragmaAttributeEntry {
737 SourceLocation Loc;
738 ParsedAttr *Attribute;
739 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
740 bool IsUsed;
741 };
742
743 /// A push'd group of PragmaAttributeEntries.
744 struct PragmaAttributeGroup {
745 /// The location of the push attribute.
746 SourceLocation Loc;
747 /// The namespace of this push group.
748 const IdentifierInfo *Namespace;
749 SmallVector<PragmaAttributeEntry, 2> Entries;
750 };
751
752 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
753
754 /// The declaration that is currently receiving an attribute from the
755 /// #pragma attribute stack.
756 const Decl *PragmaAttributeCurrentTargetDecl;
757
758 /// This represents the last location of a "#pragma clang optimize off"
759 /// directive if such a directive has not been closed by an "on" yet. If
760 /// optimizations are currently "on", this is set to an invalid location.
761 SourceLocation OptimizeOffPragmaLocation;
762
763 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
764 /// whether the optimizations in the list passed to the pragma should be
765 /// turned off or on. This boolean is true by default because command line
766 /// options are honored when `#pragma optimize("", on)`.
767 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
768 bool MSPragmaOptimizeIsOn = true;
769
770 /// Set of no-builtin functions listed by \#pragma function.
771 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
772
773 /// Flag indicating if Sema is building a recovery call expression.
774 ///
775 /// This flag is used to avoid building recovery call expressions
776 /// if Sema is already doing so, which would cause infinite recursions.
777 bool IsBuildingRecoveryCallExpr;
778
779 /// Used to control the generation of ExprWithCleanups.
780 CleanupInfo Cleanup;
781
782 /// ExprCleanupObjects - This is the stack of objects requiring
783 /// cleanup that are created by the current full expression.
784 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
785
786 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
787 /// to a variable (constant) that may or may not be odr-used in this Expr, and
788 /// we won't know until all lvalue-to-rvalue and discarded value conversions
789 /// have been applied to all subexpressions of the enclosing full expression.
790 /// This is cleared at the end of each full expression.
791 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
792 llvm::SmallPtrSet<Expr *, 4>>;
793 MaybeODRUseExprSet MaybeODRUseExprs;
794
795 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
796
797 /// Stack containing information about each of the nested
798 /// function, block, and method scopes that are currently active.
799 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
800
801 /// The index of the first FunctionScope that corresponds to the current
802 /// context.
803 unsigned FunctionScopesStart = 0;
804
805 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
806 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
807 FunctionScopes.end());
808 }
809
810 /// Stack containing information needed when in C++2a an 'auto' is encountered
811 /// in a function declaration parameter type specifier in order to invent a
812 /// corresponding template parameter in the enclosing abbreviated function
813 /// template. This information is also present in LambdaScopeInfo, stored in
814 /// the FunctionScopes stack.
815 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
816
817 /// The index of the first InventedParameterInfo that refers to the current
818 /// context.
819 unsigned InventedParameterInfosStart = 0;
820
821 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
822 return llvm::makeArrayRef(InventedParameterInfos.begin() +
823 InventedParameterInfosStart,
824 InventedParameterInfos.end());
825 }
826
827 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
828 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
829 ExtVectorDeclsType;
830
831 /// ExtVectorDecls - This is a list all the extended vector types. This allows
832 /// us to associate a raw vector type with one of the ext_vector type names.
833 /// This is only necessary for issuing pretty diagnostics.
834 ExtVectorDeclsType ExtVectorDecls;
835
836 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
837 std::unique_ptr<CXXFieldCollector> FieldCollector;
838
839 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
840
841 /// Set containing all declared private fields that are not used.
842 NamedDeclSetType UnusedPrivateFields;
843
844 /// Set containing all typedefs that are likely unused.
845 llvm::SmallSetVector<const TypedefNameDecl *, 4>
846 UnusedLocalTypedefNameCandidates;
847
848 /// Delete-expressions to be analyzed at the end of translation unit
849 ///
850 /// This list contains class members, and locations of delete-expressions
851 /// that could not be proven as to whether they mismatch with new-expression
852 /// used in initializer of the field.
853 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
854 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
855 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
856
857 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
858
859 /// PureVirtualClassDiagSet - a set of class declarations which we have
860 /// emitted a list of pure virtual functions. Used to prevent emitting the
861 /// same list more than once.
862 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
863
864 /// ParsingInitForAutoVars - a set of declarations with auto types for which
865 /// we are currently parsing the initializer.
866 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
867
868 /// Look for a locally scoped extern "C" declaration by the given name.
869 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
870
871 typedef LazyVector<VarDecl *, ExternalSemaSource,
872 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
873 TentativeDefinitionsType;
874
875 /// All the tentative definitions encountered in the TU.
876 TentativeDefinitionsType TentativeDefinitions;
877
878 /// All the external declarations encoutered and used in the TU.
879 SmallVector<VarDecl *, 4> ExternalDeclarations;
880
881 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
882 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
883 UnusedFileScopedDeclsType;
884
885 /// The set of file scoped decls seen so far that have not been used
886 /// and must warn if not used. Only contains the first declaration.
887 UnusedFileScopedDeclsType UnusedFileScopedDecls;
888
889 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
890 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
891 DelegatingCtorDeclsType;
892
893 /// All the delegating constructors seen so far in the file, used for
894 /// cycle detection at the end of the TU.
895 DelegatingCtorDeclsType DelegatingCtorDecls;
896
897 /// All the overriding functions seen during a class definition
898 /// that had their exception spec checks delayed, plus the overridden
899 /// function.
900 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
901 DelayedOverridingExceptionSpecChecks;
902
903 /// All the function redeclarations seen during a class definition that had
904 /// their exception spec checks delayed, plus the prior declaration they
905 /// should be checked against. Except during error recovery, the new decl
906 /// should always be a friend declaration, as that's the only valid way to
907 /// redeclare a special member before its class is complete.
908 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
909 DelayedEquivalentExceptionSpecChecks;
910
911 typedef llvm::MapVector<const FunctionDecl *,
912 std::unique_ptr<LateParsedTemplate>>
913 LateParsedTemplateMapT;
914 LateParsedTemplateMapT LateParsedTemplateMap;
915
916 /// Callback to the parser to parse templated functions when needed.
917 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
918 typedef void LateTemplateParserCleanupCB(void *P);
919 LateTemplateParserCB *LateTemplateParser;
920 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
921 void *OpaqueParser;
922
923 void SetLateTemplateParser(LateTemplateParserCB *LTP,
924 LateTemplateParserCleanupCB *LTPCleanup,
925 void *P) {
926 LateTemplateParser = LTP;
927 LateTemplateParserCleanup = LTPCleanup;
928 OpaqueParser = P;
929 }
930
931 class DelayedDiagnostics;
932
933 class DelayedDiagnosticsState {
934 sema::DelayedDiagnosticPool *SavedPool;
935 friend class Sema::DelayedDiagnostics;
936 };
937 typedef DelayedDiagnosticsState ParsingDeclState;
938 typedef DelayedDiagnosticsState ProcessingContextState;
939
940 /// A class which encapsulates the logic for delaying diagnostics
941 /// during parsing and other processing.
942 class DelayedDiagnostics {
943 /// The current pool of diagnostics into which delayed
944 /// diagnostics should go.
945 sema::DelayedDiagnosticPool *CurPool;
946
947 public:
948 DelayedDiagnostics() : CurPool(nullptr) {}
949
950 /// Adds a delayed diagnostic.
951 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
952
953 /// Determines whether diagnostics should be delayed.
954 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
955
956 /// Returns the current delayed-diagnostics pool.
957 sema::DelayedDiagnosticPool *getCurrentPool() const {
958 return CurPool;
959 }
960
961 /// Enter a new scope. Access and deprecation diagnostics will be
962 /// collected in this pool.
963 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
964 DelayedDiagnosticsState state;
965 state.SavedPool = CurPool;
966 CurPool = &pool;
967 return state;
968 }
969
970 /// Leave a delayed-diagnostic state that was previously pushed.
971 /// Do not emit any of the diagnostics. This is performed as part
972 /// of the bookkeeping of popping a pool "properly".
973 void popWithoutEmitting(DelayedDiagnosticsState state) {
974 CurPool = state.SavedPool;
975 }
976
977 /// Enter a new scope where access and deprecation diagnostics are
978 /// not delayed.
979 DelayedDiagnosticsState pushUndelayed() {
980 DelayedDiagnosticsState state;
981 state.SavedPool = CurPool;
982 CurPool = nullptr;
983 return state;
984 }
985
986 /// Undo a previous pushUndelayed().
987 void popUndelayed(DelayedDiagnosticsState state) {
988 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "clang/include/clang/Sema/Sema.h", 988
, __extension__ __PRETTY_FUNCTION__))
;
989 CurPool = state.SavedPool;
990 }
991 } DelayedDiagnostics;
992
993 /// A RAII object to temporarily push a declaration context.
994 class ContextRAII {
995 private:
996 Sema &S;
997 DeclContext *SavedContext;
998 ProcessingContextState SavedContextState;
999 QualType SavedCXXThisTypeOverride;
1000 unsigned SavedFunctionScopesStart;
1001 unsigned SavedInventedParameterInfosStart;
1002
1003 public:
1004 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1005 : S(S), SavedContext(S.CurContext),
1006 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1007 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1008 SavedFunctionScopesStart(S.FunctionScopesStart),
1009 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1010 {
1011 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "clang/include/clang/Sema/Sema.h", 1011, __extension__ __PRETTY_FUNCTION__
))
;
1012 S.CurContext = ContextToPush;
1013 if (NewThisContext)
1014 S.CXXThisTypeOverride = QualType();
1015 // Any saved FunctionScopes do not refer to this context.
1016 S.FunctionScopesStart = S.FunctionScopes.size();
1017 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1018 }
1019
1020 void pop() {
1021 if (!SavedContext) return;
1022 S.CurContext = SavedContext;
1023 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1024 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1025 S.FunctionScopesStart = SavedFunctionScopesStart;
1026 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1027 SavedContext = nullptr;
1028 }
1029
1030 ~ContextRAII() {
1031 pop();
1032 }
1033 };
1034
1035 /// Whether the AST is currently being rebuilt to correct immediate
1036 /// invocations. Immediate invocation candidates and references to consteval
1037 /// functions aren't tracked when this is set.
1038 bool RebuildingImmediateInvocation = false;
1039
1040 /// Used to change context to isConstantEvaluated without pushing a heavy
1041 /// ExpressionEvaluationContextRecord object.
1042 bool isConstantEvaluatedOverride;
1043
1044 bool isConstantEvaluated() {
1045 return ExprEvalContexts.back().isConstantEvaluated() ||
1046 isConstantEvaluatedOverride;
1047 }
1048
1049 /// RAII object to handle the state changes required to synthesize
1050 /// a function body.
1051 class SynthesizedFunctionScope {
1052 Sema &S;
1053 Sema::ContextRAII SavedContext;
1054 bool PushedCodeSynthesisContext = false;
1055
1056 public:
1057 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1058 : S(S), SavedContext(S, DC) {
1059 S.PushFunctionScope();
1060 S.PushExpressionEvaluationContext(
1061 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1062 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1063 FD->setWillHaveBody(true);
1064 else
1065 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "clang/include/clang/Sema/Sema.h"
, 1065, __extension__ __PRETTY_FUNCTION__))
;
1066 }
1067
1068 void addContextNote(SourceLocation UseLoc) {
1069 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "clang/include/clang/Sema/Sema.h"
, 1069, __extension__ __PRETTY_FUNCTION__))
;
1070
1071 Sema::CodeSynthesisContext Ctx;
1072 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1073 Ctx.PointOfInstantiation = UseLoc;
1074 Ctx.Entity = cast<Decl>(S.CurContext);
1075 S.pushCodeSynthesisContext(Ctx);
1076
1077 PushedCodeSynthesisContext = true;
1078 }
1079
1080 ~SynthesizedFunctionScope() {
1081 if (PushedCodeSynthesisContext)
1082 S.popCodeSynthesisContext();
1083 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1084 FD->setWillHaveBody(false);
1085 S.PopExpressionEvaluationContext();
1086 S.PopFunctionScopeInfo();
1087 }
1088 };
1089
1090 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1091 /// declared. Rare. May alias another identifier, declared or undeclared.
1092 ///
1093 /// For aliases, the target identifier is used as a key for eventual
1094 /// processing when the target is declared. For the single-identifier form,
1095 /// the sole identifier is used as the key. Each entry is a `SetVector`
1096 /// (ordered by parse order) of aliases (identified by the alias name) in case
1097 /// of multiple aliases to the same undeclared identifier.
1098 llvm::MapVector<
1099 IdentifierInfo *,
1100 llvm::SetVector<
1101 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1102 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1103 WeakUndeclaredIdentifiers;
1104
1105 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1106 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1107 /// to define functions that occur in multiple standards to call the version
1108 /// in the currently selected standard.
1109 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1110
1111
1112 /// Load weak undeclared identifiers from the external source.
1113 void LoadExternalWeakUndeclaredIdentifiers();
1114
1115 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1116 /// \#pragma weak during processing of other Decls.
1117 /// I couldn't figure out a clean way to generate these in-line, so
1118 /// we store them here and handle separately -- which is a hack.
1119 /// It would be best to refactor this.
1120 SmallVector<Decl*,2> WeakTopLevelDecl;
1121
1122 IdentifierResolver IdResolver;
1123
1124 /// Translation Unit Scope - useful to Objective-C actions that need
1125 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1126 /// For example, user-defined classes, built-in "id" type, etc.
1127 Scope *TUScope;
1128
1129 /// The C++ "std" namespace, where the standard library resides.
1130 LazyDeclPtr StdNamespace;
1131
1132 /// The C++ "std::bad_alloc" class, which is defined by the C++
1133 /// standard library.
1134 LazyDeclPtr StdBadAlloc;
1135
1136 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1137 /// standard library.
1138 LazyDeclPtr StdAlignValT;
1139
1140 /// The C++ "std::experimental" namespace, where the experimental parts
1141 /// of the standard library resides.
1142 NamespaceDecl *StdExperimentalNamespaceCache;
1143
1144 /// The C++ "std::initializer_list" template, which is defined in
1145 /// \<initializer_list>.
1146 ClassTemplateDecl *StdInitializerList;
1147
1148 /// The C++ "std::coroutine_traits" template, which is defined in
1149 /// \<coroutine_traits>
1150 ClassTemplateDecl *StdCoroutineTraitsCache;
1151 /// The namespace where coroutine components are defined. In standard,
1152 /// they are defined in std namespace. And in the previous implementation,
1153 /// they are defined in std::experimental namespace.
1154 NamespaceDecl *CoroTraitsNamespaceCache;
1155
1156 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1157 RecordDecl *CXXTypeInfoDecl;
1158
1159 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1160 RecordDecl *MSVCGuidDecl;
1161
1162 /// The C++ "std::source_location::__impl" struct, defined in
1163 /// \<source_location>.
1164 RecordDecl *StdSourceLocationImplDecl;
1165
1166 /// Caches identifiers/selectors for NSFoundation APIs.
1167 std::unique_ptr<NSAPI> NSAPIObj;
1168
1169 /// The declaration of the Objective-C NSNumber class.
1170 ObjCInterfaceDecl *NSNumberDecl;
1171
1172 /// The declaration of the Objective-C NSValue class.
1173 ObjCInterfaceDecl *NSValueDecl;
1174
1175 /// Pointer to NSNumber type (NSNumber *).
1176 QualType NSNumberPointer;
1177
1178 /// Pointer to NSValue type (NSValue *).
1179 QualType NSValuePointer;
1180
1181 /// The Objective-C NSNumber methods used to create NSNumber literals.
1182 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1183
1184 /// The declaration of the Objective-C NSString class.
1185 ObjCInterfaceDecl *NSStringDecl;
1186
1187 /// Pointer to NSString type (NSString *).
1188 QualType NSStringPointer;
1189
1190 /// The declaration of the stringWithUTF8String: method.
1191 ObjCMethodDecl *StringWithUTF8StringMethod;
1192
1193 /// The declaration of the valueWithBytes:objCType: method.
1194 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1195
1196 /// The declaration of the Objective-C NSArray class.
1197 ObjCInterfaceDecl *NSArrayDecl;
1198
1199 /// The declaration of the arrayWithObjects:count: method.
1200 ObjCMethodDecl *ArrayWithObjectsMethod;
1201
1202 /// The declaration of the Objective-C NSDictionary class.
1203 ObjCInterfaceDecl *NSDictionaryDecl;
1204
1205 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1206 ObjCMethodDecl *DictionaryWithObjectsMethod;
1207
1208 /// id<NSCopying> type.
1209 QualType QIDNSCopying;
1210
1211 /// will hold 'respondsToSelector:'
1212 Selector RespondsToSelectorSel;
1213
1214 /// A flag to remember whether the implicit forms of operator new and delete
1215 /// have been declared.
1216 bool GlobalNewDeleteDeclared;
1217
1218 /// Describes how the expressions currently being parsed are
1219 /// evaluated at run-time, if at all.
1220 enum class ExpressionEvaluationContext {
1221 /// The current expression and its subexpressions occur within an
1222 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1223 /// \c sizeof, where the type of the expression may be significant but
1224 /// no code will be generated to evaluate the value of the expression at
1225 /// run time.
1226 Unevaluated,
1227
1228 /// The current expression occurs within a braced-init-list within
1229 /// an unevaluated operand. This is mostly like a regular unevaluated
1230 /// context, except that we still instantiate constexpr functions that are
1231 /// referenced here so that we can perform narrowing checks correctly.
1232 UnevaluatedList,
1233
1234 /// The current expression occurs within a discarded statement.
1235 /// This behaves largely similarly to an unevaluated operand in preventing
1236 /// definitions from being required, but not in other ways.
1237 DiscardedStatement,
1238
1239 /// The current expression occurs within an unevaluated
1240 /// operand that unconditionally permits abstract references to
1241 /// fields, such as a SIZE operator in MS-style inline assembly.
1242 UnevaluatedAbstract,
1243
1244 /// The current context is "potentially evaluated" in C++11 terms,
1245 /// but the expression is evaluated at compile-time (like the values of
1246 /// cases in a switch statement).
1247 ConstantEvaluated,
1248
1249 /// In addition of being constant evaluated, the current expression
1250 /// occurs in an immediate function context - either a consteval function
1251 /// or a consteval if function.
1252 ImmediateFunctionContext,
1253
1254 /// The current expression is potentially evaluated at run time,
1255 /// which means that code may be generated to evaluate the value of the
1256 /// expression at run time.
1257 PotentiallyEvaluated,
1258
1259 /// The current expression is potentially evaluated, but any
1260 /// declarations referenced inside that expression are only used if
1261 /// in fact the current expression is used.
1262 ///
1263 /// This value is used when parsing default function arguments, for which
1264 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1265 /// through varargs) but do not want to mark declarations as "referenced"
1266 /// until the default argument is used.
1267 PotentiallyEvaluatedIfUsed
1268 };
1269
1270 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1271
1272 /// Data structure used to record current or nested
1273 /// expression evaluation contexts.
1274 struct ExpressionEvaluationContextRecord {
1275 /// The expression evaluation context.
1276 ExpressionEvaluationContext Context;
1277
1278 /// Whether the enclosing context needed a cleanup.
1279 CleanupInfo ParentCleanup;
1280
1281 /// The number of active cleanup objects when we entered
1282 /// this expression evaluation context.
1283 unsigned NumCleanupObjects;
1284
1285 /// The number of typos encountered during this expression evaluation
1286 /// context (i.e. the number of TypoExprs created).
1287 unsigned NumTypos;
1288
1289 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1290
1291 /// The lambdas that are present within this context, if it
1292 /// is indeed an unevaluated context.
1293 SmallVector<LambdaExpr *, 2> Lambdas;
1294
1295 /// The declaration that provides context for lambda expressions
1296 /// and block literals if the normal declaration context does not
1297 /// suffice, e.g., in a default function argument.
1298 Decl *ManglingContextDecl;
1299
1300 /// If we are processing a decltype type, a set of call expressions
1301 /// for which we have deferred checking the completeness of the return type.
1302 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1303
1304 /// If we are processing a decltype type, a set of temporary binding
1305 /// expressions for which we have deferred checking the destructor.
1306 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1307
1308 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1309
1310 /// Expressions appearing as the LHS of a volatile assignment in this
1311 /// context. We produce a warning for these when popping the context if
1312 /// they are not discarded-value expressions nor unevaluated operands.
1313 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1314
1315 /// Set of candidates for starting an immediate invocation.
1316 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1317
1318 /// Set of DeclRefExprs referencing a consteval function when used in a
1319 /// context not already known to be immediately invoked.
1320 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1321
1322 /// \brief Describes whether we are in an expression constext which we have
1323 /// to handle differently.
1324 enum ExpressionKind {
1325 EK_Decltype, EK_TemplateArgument, EK_Other
1326 } ExprContext;
1327
1328 // A context can be nested in both a discarded statement context and
1329 // an immediate function context, so they need to be tracked independently.
1330 bool InDiscardedStatement;
1331 bool InImmediateFunctionContext;
1332
1333 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1334 unsigned NumCleanupObjects,
1335 CleanupInfo ParentCleanup,
1336 Decl *ManglingContextDecl,
1337 ExpressionKind ExprContext)
1338 : Context(Context), ParentCleanup(ParentCleanup),
1339 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1340 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1341 InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1342
1343 bool isUnevaluated() const {
1344 return Context == ExpressionEvaluationContext::Unevaluated ||
1345 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1346 Context == ExpressionEvaluationContext::UnevaluatedList;
1347 }
1348
1349 bool isConstantEvaluated() const {
1350 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1351 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1352 }
1353
1354 bool isImmediateFunctionContext() const {
1355 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1356 (Context == ExpressionEvaluationContext::DiscardedStatement &&
1357 InImmediateFunctionContext) ||
1358 // C++2b [expr.const]p14:
1359 // An expression or conversion is in an immediate function
1360 // context if it is potentially evaluated and either:
1361 // * its innermost enclosing non-block scope is a function
1362 // parameter scope of an immediate function, or
1363 // * its enclosing statement is enclosed by the compound-
1364 // statement of a consteval if statement.
1365 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
1366 InImmediateFunctionContext);
1367 }
1368
1369 bool isDiscardedStatementContext() const {
1370 return Context == ExpressionEvaluationContext::DiscardedStatement ||
1371 (Context ==
1372 ExpressionEvaluationContext::ImmediateFunctionContext &&
1373 InDiscardedStatement);
1374 }
1375 };
1376
1377 /// A stack of expression evaluation contexts.
1378 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1379
1380 /// Emit a warning for all pending noderef expressions that we recorded.
1381 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1382
1383 /// Compute the mangling number context for a lambda expression or
1384 /// block literal. Also return the extra mangling decl if any.
1385 ///
1386 /// \param DC - The DeclContext containing the lambda expression or
1387 /// block literal.
1388 std::tuple<MangleNumberingContext *, Decl *>
1389 getCurrentMangleNumberContext(const DeclContext *DC);
1390
1391
1392 /// SpecialMemberOverloadResult - The overloading result for a special member
1393 /// function.
1394 ///
1395 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1396 /// integer are used to determine whether overload resolution succeeded.
1397 class SpecialMemberOverloadResult {
1398 public:
1399 enum Kind {
1400 NoMemberOrDeleted,
1401 Ambiguous,
1402 Success
1403 };
1404
1405 private:
1406 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1407
1408 public:
1409 SpecialMemberOverloadResult() {}
1410 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1411 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1412
1413 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1414 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1415
1416 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1417 void setKind(Kind K) { Pair.setInt(K); }
1418 };
1419
1420 class SpecialMemberOverloadResultEntry
1421 : public llvm::FastFoldingSetNode,
1422 public SpecialMemberOverloadResult {
1423 public:
1424 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1425 : FastFoldingSetNode(ID)
1426 {}
1427 };
1428
1429 /// A cache of special member function overload resolution results
1430 /// for C++ records.
1431 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1432
1433 /// A cache of the flags available in enumerations with the flag_bits
1434 /// attribute.
1435 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1436
1437 /// The kind of translation unit we are processing.
1438 ///
1439 /// When we're processing a complete translation unit, Sema will perform
1440 /// end-of-translation-unit semantic tasks (such as creating
1441 /// initializers for tentative definitions in C) once parsing has
1442 /// completed. Modules and precompiled headers perform different kinds of
1443 /// checks.
1444 const TranslationUnitKind TUKind;
1445
1446 llvm::BumpPtrAllocator BumpAlloc;
1447
1448 /// The number of SFINAE diagnostics that have been trapped.
1449 unsigned NumSFINAEErrors;
1450
1451 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1452 UnparsedDefaultArgInstantiationsMap;
1453
1454 /// A mapping from parameters with unparsed default arguments to the
1455 /// set of instantiations of each parameter.
1456 ///
1457 /// This mapping is a temporary data structure used when parsing
1458 /// nested class templates or nested classes of class templates,
1459 /// where we might end up instantiating an inner class before the
1460 /// default arguments of its methods have been parsed.
1461 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1462
1463 // Contains the locations of the beginning of unparsed default
1464 // argument locations.
1465 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1466
1467 /// UndefinedInternals - all the used, undefined objects which require a
1468 /// definition in this translation unit.
1469 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1470
1471 /// Determine if VD, which must be a variable or function, is an external
1472 /// symbol that nonetheless can't be referenced from outside this translation
1473 /// unit because its type has no linkage and it's not extern "C".
1474 bool isExternalWithNoLinkageType(ValueDecl *VD);
1475
1476 /// Obtain a sorted list of functions that are undefined but ODR-used.
1477 void getUndefinedButUsed(
1478 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1479
1480 /// Retrieves list of suspicious delete-expressions that will be checked at
1481 /// the end of translation unit.
1482 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1483 getMismatchingDeleteExpressions() const;
1484
1485 class GlobalMethodPool {
1486 public:
1487 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1488 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1489 iterator begin() { return Methods.begin(); }
1490 iterator end() { return Methods.end(); }
1491 iterator find(Selector Sel) { return Methods.find(Sel); }
1492 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1493 return Methods.insert(Val);
1494 }
1495 int count(Selector Sel) const { return Methods.count(Sel); }
1496 bool empty() const { return Methods.empty(); }
1497
1498 private:
1499 llvm::DenseMap<Selector, Lists> Methods;
1500 };
1501
1502 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1503 /// We need to maintain a list, since selectors can have differing signatures
1504 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1505 /// of selectors are "overloaded").
1506 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1507 /// methods inside categories with a particular selector.
1508 GlobalMethodPool MethodPool;
1509
1510 /// Method selectors used in a \@selector expression. Used for implementation
1511 /// of -Wselector.
1512 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1513
1514 /// List of SourceLocations where 'self' is implicitly retained inside a
1515 /// block.
1516 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1517 ImplicitlyRetainedSelfLocs;
1518
1519 /// Kinds of C++ special members.
1520 enum CXXSpecialMember {
1521 CXXDefaultConstructor,
1522 CXXCopyConstructor,
1523 CXXMoveConstructor,
1524 CXXCopyAssignment,
1525 CXXMoveAssignment,
1526 CXXDestructor,
1527 CXXInvalid
1528 };
1529
1530 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1531 SpecialMemberDecl;
1532
1533 /// The C++ special members which we are currently in the process of
1534 /// declaring. If this process recursively triggers the declaration of the
1535 /// same special member, we should act as if it is not yet declared.
1536 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1537
1538 /// Kinds of defaulted comparison operator functions.
1539 enum class DefaultedComparisonKind : unsigned char {
1540 /// This is not a defaultable comparison operator.
1541 None,
1542 /// This is an operator== that should be implemented as a series of
1543 /// subobject comparisons.
1544 Equal,
1545 /// This is an operator<=> that should be implemented as a series of
1546 /// subobject comparisons.
1547 ThreeWay,
1548 /// This is an operator!= that should be implemented as a rewrite in terms
1549 /// of a == comparison.
1550 NotEqual,
1551 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1552 /// terms of a <=> comparison.
1553 Relational,
1554 };
1555
1556 /// The function definitions which were renamed as part of typo-correction
1557 /// to match their respective declarations. We want to keep track of them
1558 /// to ensure that we don't emit a "redefinition" error if we encounter a
1559 /// correctly named definition after the renamed definition.
1560 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1561
1562 /// Stack of types that correspond to the parameter entities that are
1563 /// currently being copy-initialized. Can be empty.
1564 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1565
1566 void ReadMethodPool(Selector Sel);
1567 void updateOutOfDateSelector(Selector Sel);
1568
1569 /// Private Helper predicate to check for 'self'.
1570 bool isSelfExpr(Expr *RExpr);
1571 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1572
1573 /// Cause the active diagnostic on the DiagosticsEngine to be
1574 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1575 /// should not be used elsewhere.
1576 void EmitCurrentDiagnostic(unsigned DiagID);
1577
1578 /// Records and restores the CurFPFeatures state on entry/exit of compound
1579 /// statements.
1580 class FPFeaturesStateRAII {
1581 public:
1582 FPFeaturesStateRAII(Sema &S);
1583 ~FPFeaturesStateRAII();
1584 FPOptionsOverride getOverrides() { return OldOverrides; }
1585
1586 private:
1587 Sema& S;
1588 FPOptions OldFPFeaturesState;
1589 FPOptionsOverride OldOverrides;
1590 LangOptions::FPEvalMethodKind OldEvalMethod;
1591 SourceLocation OldFPPragmaLocation;
1592 };
1593
1594 void addImplicitTypedef(StringRef Name, QualType T);
1595
1596 bool WarnedStackExhausted = false;
1597
1598 /// Increment when we find a reference; decrement when we find an ignored
1599 /// assignment. Ultimately the value is 0 if every reference is an ignored
1600 /// assignment.
1601 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1602
1603 /// Indicate RISC-V vector builtin functions enabled or not.
1604 bool DeclareRISCVVBuiltins = false;
1605
1606private:
1607 std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1608
1609 Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1610
1611 bool WarnedDarwinSDKInfoMissing = false;
1612
1613public:
1614 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1615 TranslationUnitKind TUKind = TU_Complete,
1616 CodeCompleteConsumer *CompletionConsumer = nullptr);
1617 ~Sema();
1618
1619 /// Perform initialization that occurs after the parser has been
1620 /// initialized but before it parses anything.
1621 void Initialize();
1622
1623 /// This virtual key function only exists to limit the emission of debug info
1624 /// describing the Sema class. GCC and Clang only emit debug info for a class
1625 /// with a vtable when the vtable is emitted. Sema is final and not
1626 /// polymorphic, but the debug info size savings are so significant that it is
1627 /// worth adding a vtable just to take advantage of this optimization.
1628 virtual void anchor();
1629
1630 const LangOptions &getLangOpts() const { return LangOpts; }
1631 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1632 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1633
1634 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1635 SourceManager &getSourceManager() const { return SourceMgr; }
1636 Preprocessor &getPreprocessor() const { return PP; }
1637 ASTContext &getASTContext() const { return Context; }
1638 ASTConsumer &getASTConsumer() const { return Consumer; }
1639 ASTMutationListener *getASTMutationListener() const;
1640 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1641
1642 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1643 StringRef Platform);
1644 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1645
1646 ///Registers an external source. If an external source already exists,
1647 /// creates a multiplex external source and appends to it.
1648 ///
1649 ///\param[in] E - A non-null external sema source.
1650 ///
1651 void addExternalSource(ExternalSemaSource *E);
1652
1653 void PrintStats() const;
1654
1655 /// Warn that the stack is nearly exhausted.
1656 void warnStackExhausted(SourceLocation Loc);
1657
1658 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1659 /// guaranteed). Produces a warning if we're low on stack space and allocates
1660 /// more in that case. Use this in code that may recurse deeply (for example,
1661 /// in template instantiation) to avoid stack overflow.
1662 void runWithSufficientStackSpace(SourceLocation Loc,
1663 llvm::function_ref<void()> Fn);
1664
1665 /// Helper class that creates diagnostics with optional
1666 /// template instantiation stacks.
1667 ///
1668 /// This class provides a wrapper around the basic DiagnosticBuilder
1669 /// class that emits diagnostics. ImmediateDiagBuilder is
1670 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1671 /// does) and, if the diagnostic comes from inside a template
1672 /// instantiation, printing the template instantiation stack as
1673 /// well.
1674 class ImmediateDiagBuilder : public DiagnosticBuilder {
1675 Sema &SemaRef;
1676 unsigned DiagID;
1677
1678 public:
1679 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1680 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1681 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1682 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1683
1684 // This is a cunning lie. DiagnosticBuilder actually performs move
1685 // construction in its copy constructor (but due to varied uses, it's not
1686 // possible to conveniently express this as actual move construction). So
1687 // the default copy ctor here is fine, because the base class disables the
1688 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1689 // in that case anwyay.
1690 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1691
1692 ~ImmediateDiagBuilder() {
1693 // If we aren't active, there is nothing to do.
1694 if (!isActive()) return;
1695
1696 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1697 // builder itself so it won't emit the diagnostic in its own destructor.
1698 //
1699 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1700 // do its own needless checks to see if the diagnostic needs to be
1701 // emitted. However, because we take care to ensure that the builder
1702 // objects never escape, a sufficiently smart compiler will be able to
1703 // eliminate that code.
1704 Clear();
1705
1706 // Dispatch to Sema to emit the diagnostic.
1707 SemaRef.EmitCurrentDiagnostic(DiagID);
1708 }
1709
1710 /// Teach operator<< to produce an object of the correct type.
1711 template <typename T>
1712 friend const ImmediateDiagBuilder &
1713 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1714 const DiagnosticBuilder &BaseDiag = Diag;
1715 BaseDiag << Value;
1716 return Diag;
1717 }
1718
1719 // It is necessary to limit this to rvalue reference to avoid calling this
1720 // function with a bitfield lvalue argument since non-const reference to
1721 // bitfield is not allowed.
1722 template <typename T, typename = typename std::enable_if<
1723 !std::is_lvalue_reference<T>::value>::type>
1724 const ImmediateDiagBuilder &operator<<(T &&V) const {
1725 const DiagnosticBuilder &BaseDiag = *this;
1726 BaseDiag << std::move(V);
1727 return *this;
1728 }
1729 };
1730
1731 /// A generic diagnostic builder for errors which may or may not be deferred.
1732 ///
1733 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1734 /// which are not allowed to appear inside __device__ functions and are
1735 /// allowed to appear in __host__ __device__ functions only if the host+device
1736 /// function is never codegen'ed.
1737 ///
1738 /// To handle this, we use the notion of "deferred diagnostics", where we
1739 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1740 ///
1741 /// This class lets you emit either a regular diagnostic, a deferred
1742 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1743 /// its constructor, thus simplifying the process of creating these "maybe
1744 /// deferred" diagnostics.
1745 class SemaDiagnosticBuilder {
1746 public:
1747 enum Kind {
1748 /// Emit no diagnostics.
1749 K_Nop,
1750 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1751 K_Immediate,
1752 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1753 /// emit a call stack showing how this function can be reached by an a
1754 /// priori known-emitted function.
1755 K_ImmediateWithCallStack,
1756 /// Create a deferred diagnostic, which is emitted only if the function
1757 /// it's attached to is codegen'ed. Also emit a call stack as with
1758 /// K_ImmediateWithCallStack.
1759 K_Deferred
1760 };
1761
1762 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1763 FunctionDecl *Fn, Sema &S);
1764 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1765 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1766 ~SemaDiagnosticBuilder();
1767
1768 bool isImmediate() const { return ImmediateDiag.has_value(); }
1769
1770 /// Convertible to bool: True if we immediately emitted an error, false if
1771 /// we didn't emit an error or we created a deferred error.
1772 ///
1773 /// Example usage:
1774 ///
1775 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1776 /// return ExprError();
1777 ///
1778 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1779 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1780 operator bool() const { return isImmediate(); }
1781
1782 template <typename T>
1783 friend const SemaDiagnosticBuilder &
1784 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1785 if (Diag.ImmediateDiag)
1786 *Diag.ImmediateDiag << Value;
1787 else if (Diag.PartialDiagId)
1788 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1789 << Value;
1790 return Diag;
1791 }
1792
1793 // It is necessary to limit this to rvalue reference to avoid calling this
1794 // function with a bitfield lvalue argument since non-const reference to
1795 // bitfield is not allowed.
1796 template <typename T, typename = typename std::enable_if<
1797 !std::is_lvalue_reference<T>::value>::type>
1798 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1799 if (ImmediateDiag)
1800 *ImmediateDiag << std::move(V);
1801 else if (PartialDiagId)
1802 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1803 return *this;
1804 }
1805
1806 friend const SemaDiagnosticBuilder &
1807 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1808 if (Diag.ImmediateDiag)
1809 PD.Emit(*Diag.ImmediateDiag);
1810 else if (Diag.PartialDiagId)
1811 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1812 return Diag;
1813 }
1814
1815 void AddFixItHint(const FixItHint &Hint) const {
1816 if (ImmediateDiag)
1817 ImmediateDiag->AddFixItHint(Hint);
1818 else if (PartialDiagId)
1819 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1820 }
1821
1822 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1823 return ExprError();
1824 }
1825 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1826 return StmtError();
1827 }
1828 operator ExprResult() const { return ExprError(); }
1829 operator StmtResult() const { return StmtError(); }
1830 operator TypeResult() const { return TypeError(); }
1831 operator DeclResult() const { return DeclResult(true); }
1832 operator MemInitResult() const { return MemInitResult(true); }
1833
1834 private:
1835 Sema &S;
1836 SourceLocation Loc;
1837 unsigned DiagID;
1838 FunctionDecl *Fn;
1839 bool ShowCallStack;
1840
1841 // Invariant: At most one of these Optionals has a value.
1842 // FIXME: Switch these to a Variant once that exists.
1843 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1844 llvm::Optional<unsigned> PartialDiagId;
1845 };
1846
1847 /// Is the last error level diagnostic immediate. This is used to determined
1848 /// whether the next info diagnostic should be immediate.
1849 bool IsLastErrorImmediate = true;
1850
1851 /// Emit a diagnostic.
1852 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1853 bool DeferHint = false);
1854
1855 /// Emit a partial diagnostic.
1856 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1857 bool DeferHint = false);
1858
1859 /// Build a partial diagnostic.
1860 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1861
1862 /// Whether deferrable diagnostics should be deferred.
1863 bool DeferDiags = false;
1864
1865 /// RAII class to control scope of DeferDiags.
1866 class DeferDiagsRAII {
1867 Sema &S;
1868 bool SavedDeferDiags = false;
1869
1870 public:
1871 DeferDiagsRAII(Sema &S, bool DeferDiags)
1872 : S(S), SavedDeferDiags(S.DeferDiags) {
1873 S.DeferDiags = DeferDiags;
1874 }
1875 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1876 };
1877
1878 /// Whether uncompilable error has occurred. This includes error happens
1879 /// in deferred diagnostics.
1880 bool hasUncompilableErrorOccurred() const;
1881
1882 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1883
1884 /// Get a string to suggest for zero-initialization of a type.
1885 std::string
1886 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1887 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1888
1889 /// Calls \c Lexer::getLocForEndOfToken()
1890 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1891
1892 /// Retrieve the module loader associated with the preprocessor.
1893 ModuleLoader &getModuleLoader() const;
1894
1895 /// Invent a new identifier for parameters of abbreviated templates.
1896 IdentifierInfo *
1897 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1898 unsigned Index);
1899
1900 void emitAndClearUnusedLocalTypedefWarnings();
1901
1902 private:
1903 /// Function or variable declarations to be checked for whether the deferred
1904 /// diagnostics should be emitted.
1905 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1906
1907 public:
1908 // Emit all deferred diagnostics.
1909 void emitDeferredDiags();
1910
1911 enum TUFragmentKind {
1912 /// The global module fragment, between 'module;' and a module-declaration.
1913 Global,
1914 /// A normal translation unit fragment. For a non-module unit, this is the
1915 /// entire translation unit. Otherwise, it runs from the module-declaration
1916 /// to the private-module-fragment (if any) or the end of the TU (if not).
1917 Normal,
1918 /// The private module fragment, between 'module :private;' and the end of
1919 /// the translation unit.
1920 Private
1921 };
1922
1923 void ActOnStartOfTranslationUnit();
1924 void ActOnEndOfTranslationUnit();
1925 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1926
1927 void CheckDelegatingCtorCycles();
1928
1929 Scope *getScopeForContext(DeclContext *Ctx);
1930
1931 void PushFunctionScope();
1932 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1933 sema::LambdaScopeInfo *PushLambdaScope();
1934
1935 /// This is used to inform Sema what the current TemplateParameterDepth
1936 /// is during Parsing. Currently it is used to pass on the depth
1937 /// when parsing generic lambda 'auto' parameters.
1938 void RecordParsingTemplateParameterDepth(unsigned Depth);
1939
1940 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1941 RecordDecl *RD, CapturedRegionKind K,
1942 unsigned OpenMPCaptureLevel = 0);
1943
1944 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1945 /// time after they've been popped.
1946 class PoppedFunctionScopeDeleter {
1947 Sema *Self;
1948
1949 public:
1950 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1951 void operator()(sema::FunctionScopeInfo *Scope) const;
1952 };
1953
1954 using PoppedFunctionScopePtr =
1955 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1956
1957 PoppedFunctionScopePtr
1958 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1959 const Decl *D = nullptr,
1960 QualType BlockType = QualType());
1961
1962 sema::FunctionScopeInfo *getCurFunction() const {
1963 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
1964 }
1965
1966 sema::FunctionScopeInfo *getEnclosingFunction() const;
1967
1968 void setFunctionHasBranchIntoScope();
1969 void setFunctionHasBranchProtectedScope();
1970 void setFunctionHasIndirectGoto();
1971 void setFunctionHasMustTail();
1972
1973 void PushCompoundScope(bool IsStmtExpr);
1974 void PopCompoundScope();
1975
1976 sema::CompoundScopeInfo &getCurCompoundScope() const;
1977
1978 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1979
1980 /// Retrieve the current block, if any.
1981 sema::BlockScopeInfo *getCurBlock();
1982
1983 /// Get the innermost lambda enclosing the current location, if any. This
1984 /// looks through intervening non-lambda scopes such as local functions and
1985 /// blocks.
1986 sema::LambdaScopeInfo *getEnclosingLambda() const;
1987
1988 /// Retrieve the current lambda scope info, if any.
1989 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1990 /// lambda scope info ignoring all inner capturing scopes that are not
1991 /// lambda scopes.
1992 sema::LambdaScopeInfo *
1993 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1994
1995 /// Retrieve the current generic lambda info, if any.
1996 sema::LambdaScopeInfo *getCurGenericLambda();
1997
1998 /// Retrieve the current captured region, if any.
1999 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
2000
2001 /// Retrieve the current function, if any, that should be analyzed for
2002 /// potential availability violations.
2003 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2004
2005 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2006 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
2007
2008 /// Called before parsing a function declarator belonging to a function
2009 /// declaration.
2010 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
2011 unsigned TemplateParameterDepth);
2012
2013 /// Called after parsing a function declarator belonging to a function
2014 /// declaration.
2015 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2016
2017 void ActOnComment(SourceRange Comment);
2018
2019 //===--------------------------------------------------------------------===//
2020 // Type Analysis / Processing: SemaType.cpp.
2021 //
2022
2023 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2024 const DeclSpec *DS = nullptr);
2025 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2026 const DeclSpec *DS = nullptr);
2027 QualType BuildPointerType(QualType T,
2028 SourceLocation Loc, DeclarationName Entity);
2029 QualType BuildReferenceType(QualType T, bool LValueRef,
2030 SourceLocation Loc, DeclarationName Entity);
2031 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2032 Expr *ArraySize, unsigned Quals,
2033 SourceRange Brackets, DeclarationName Entity);
2034 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2035 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2036 SourceLocation AttrLoc);
2037 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2038 SourceLocation AttrLoc);
2039
2040 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2041 SourceLocation AttrLoc);
2042
2043 /// Same as above, but constructs the AddressSpace index if not provided.
2044 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2045 SourceLocation AttrLoc);
2046
2047 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2048
2049 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2050
2051 /// Build a function type.
2052 ///
2053 /// This routine checks the function type according to C++ rules and
2054 /// under the assumption that the result type and parameter types have
2055 /// just been instantiated from a template. It therefore duplicates
2056 /// some of the behavior of GetTypeForDeclarator, but in a much
2057 /// simpler form that is only suitable for this narrow use case.
2058 ///
2059 /// \param T The return type of the function.
2060 ///
2061 /// \param ParamTypes The parameter types of the function. This array
2062 /// will be modified to account for adjustments to the types of the
2063 /// function parameters.
2064 ///
2065 /// \param Loc The location of the entity whose type involves this
2066 /// function type or, if there is no such entity, the location of the
2067 /// type that will have function type.
2068 ///
2069 /// \param Entity The name of the entity that involves the function
2070 /// type, if known.
2071 ///
2072 /// \param EPI Extra information about the function type. Usually this will
2073 /// be taken from an existing function with the same prototype.
2074 ///
2075 /// \returns A suitable function type, if there are no errors. The
2076 /// unqualified type will always be a FunctionProtoType.
2077 /// Otherwise, returns a NULL type.
2078 QualType BuildFunctionType(QualType T,
2079 MutableArrayRef<QualType> ParamTypes,
2080 SourceLocation Loc, DeclarationName Entity,
2081 const FunctionProtoType::ExtProtoInfo &EPI);
2082
2083 QualType BuildMemberPointerType(QualType T, QualType Class,
2084 SourceLocation Loc,
2085 DeclarationName Entity);
2086 QualType BuildBlockPointerType(QualType T,
2087 SourceLocation Loc, DeclarationName Entity);
2088 QualType BuildParenType(QualType T);
2089 QualType BuildAtomicType(QualType T, SourceLocation Loc);
2090 QualType BuildReadPipeType(QualType T,
2091 SourceLocation Loc);
2092 QualType BuildWritePipeType(QualType T,
2093 SourceLocation Loc);
2094 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2095
2096 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2097 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2098
2099 /// Package the given type and TSI into a ParsedType.
2100 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2101 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2102 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2103 static QualType GetTypeFromParser(ParsedType Ty,
2104 TypeSourceInfo **TInfo = nullptr);
2105 CanThrowResult canThrow(const Stmt *E);
2106 /// Determine whether the callee of a particular function call can throw.
2107 /// E, D and Loc are all optional.
2108 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2109 SourceLocation Loc = SourceLocation());
2110 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2111 const FunctionProtoType *FPT);
2112 void UpdateExceptionSpec(FunctionDecl *FD,
2113 const FunctionProtoType::ExceptionSpecInfo &ESI);
2114 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2115 bool CheckDistantExceptionSpec(QualType T);
2116 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2117 bool CheckEquivalentExceptionSpec(
2118 const FunctionProtoType *Old, SourceLocation OldLoc,
2119 const FunctionProtoType *New, SourceLocation NewLoc);
2120 bool CheckEquivalentExceptionSpec(
2121 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2122 const FunctionProtoType *Old, SourceLocation OldLoc,
2123 const FunctionProtoType *New, SourceLocation NewLoc);
2124 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2125 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2126 const PartialDiagnostic &NestedDiagID,
2127 const PartialDiagnostic &NoteID,
2128 const PartialDiagnostic &NoThrowDiagID,
2129 const FunctionProtoType *Superset,
2130 SourceLocation SuperLoc,
2131 const FunctionProtoType *Subset,
2132 SourceLocation SubLoc);
2133 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2134 const PartialDiagnostic &NoteID,
2135 const FunctionProtoType *Target,
2136 SourceLocation TargetLoc,
2137 const FunctionProtoType *Source,
2138 SourceLocation SourceLoc);
2139
2140 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2141
2142 /// The parser has parsed the context-sensitive type 'instancetype'
2143 /// in an Objective-C message declaration. Return the appropriate type.
2144 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2145
2146 /// Abstract class used to diagnose incomplete types.
2147 struct TypeDiagnoser {
2148 TypeDiagnoser() {}
2149
2150 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2151 virtual ~TypeDiagnoser() {}
2152 };
2153
2154 static int getPrintable(int I) { return I; }
2155 static unsigned getPrintable(unsigned I) { return I; }
2156 static bool getPrintable(bool B) { return B; }
2157 static const char * getPrintable(const char *S) { return S; }
2158 static StringRef getPrintable(StringRef S) { return S; }
2159 static const std::string &getPrintable(const std::string &S) { return S; }
2160 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2161 return II;
2162 }
2163 static DeclarationName getPrintable(DeclarationName N) { return N; }
2164 static QualType getPrintable(QualType T) { return T; }
2165 static SourceRange getPrintable(SourceRange R) { return R; }
2166 static SourceRange getPrintable(SourceLocation L) { return L; }
2167 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2168 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2169
2170 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2171 protected:
2172 unsigned DiagID;
2173 std::tuple<const Ts &...> Args;
2174
2175 template <std::size_t... Is>
2176 void emit(const SemaDiagnosticBuilder &DB,
2177 std::index_sequence<Is...>) const {
2178 // Apply all tuple elements to the builder in order.
2179 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2180 (void)Dummy;
2181 }
2182
2183 public:
2184 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2185 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2186 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "clang/include/clang/Sema/Sema.h", 2186, __extension__ __PRETTY_FUNCTION__
))
;
2187 }
2188
2189 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2190 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2191 emit(DB, std::index_sequence_for<Ts...>());
2192 DB << T;
2193 }
2194 };
2195
2196 /// Do a check to make sure \p Name looks like a legal argument for the
2197 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2198 /// is invalid for the given declaration.
2199 ///
2200 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2201 ///
2202 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2203 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2204 const ParsedAttr &AL, bool IsAsync);
2205
2206 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2207 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2208 /// For example, a diagnostic with no other parameters would generally have
2209 /// the form "...%select{incomplete|sizeless}0 type %1...".
2210 template <typename... Ts>
2211 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2212 public:
2213 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2214 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2215
2216 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2217 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2218 this->emit(DB, std::index_sequence_for<Ts...>());
2219 DB << T->isSizelessType() << T;
2220 }
2221 };
2222
2223 enum class CompleteTypeKind {
2224 /// Apply the normal rules for complete types. In particular,
2225 /// treat all sizeless types as incomplete.
2226 Normal,
2227
2228 /// Relax the normal rules for complete types so that they include
2229 /// sizeless built-in types.
2230 AcceptSizeless,
2231
2232 // FIXME: Eventually we should flip the default to Normal and opt in
2233 // to AcceptSizeless rather than opt out of it.
2234 Default = AcceptSizeless
2235 };
2236
2237 enum class AcceptableKind { Visible, Reachable };
2238
2239private:
2240 /// Methods for marking which expressions involve dereferencing a pointer
2241 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2242 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2243 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2244 /// `*p`, but need to check that `address of` is called on it. This requires
2245 /// keeping a container of all pending expressions and checking if the address
2246 /// of them are eventually taken.
2247 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2248 void CheckAddressOfNoDeref(const Expr *E);
2249 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2250
2251 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2252 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2253
2254 struct ModuleScope {
2255 SourceLocation BeginLoc;
2256 clang::Module *Module = nullptr;
2257 bool ModuleInterface = false;
2258 bool IsPartition = false;
2259 bool ImplicitGlobalModuleFragment = false;
2260 VisibleModuleSet OuterVisibleModules;
2261 };
2262 /// The modules we're currently parsing.
2263 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2264 /// The global module fragment of the current translation unit.
2265 clang::Module *GlobalModuleFragment = nullptr;
2266
2267 /// The modules we imported directly.
2268 llvm::SmallPtrSet<clang::Module *, 8> DirectModuleImports;
2269
2270 /// Namespace definitions that we will export when they finish.
2271 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2272
2273 /// In a C++ standard module, inline declarations require a definition to be
2274 /// present at the end of a definition domain. This set holds the decls to
2275 /// be checked at the end of the TU.
2276 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2277
2278 /// Helper function to judge if we are in module purview.
2279 /// Return false if we are not in a module.
2280 bool isCurrentModulePurview() const {
2281 return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2282 }
2283
2284 /// Enter the scope of the global module.
2285 Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2286 /// Leave the scope of the global module.
2287 void PopGlobalModuleFragment();
2288
2289 VisibleModuleSet VisibleModules;
2290
2291 /// Cache for module units which is usable for current module.
2292 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2293
2294 bool isUsableModule(const Module *M);
2295
2296 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2297
2298public:
2299 /// Get the module unit whose scope we are currently within.
2300 Module *getCurrentModule() const {
2301 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2302 }
2303
2304 /// Is the module scope we are an interface?
2305 bool currentModuleIsInterface() const {
2306 return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2307 }
2308
2309 /// Get the module owning an entity.
2310 Module *getOwningModule(const Decl *Entity) {
2311 return Entity->getOwningModule();
2312 }
2313
2314 bool isModuleDirectlyImported(const Module *M) {
2315 return DirectModuleImports.contains(M);
2316 }
2317
2318 // Determine whether the module M belongs to the current TU.
2319 bool isModuleUnitOfCurrentTU(const Module *M) const;
2320
2321 /// Make a merged definition of an existing hidden definition \p ND
2322 /// visible at the specified location.
2323 void makeMergedDefinitionVisible(NamedDecl *ND);
2324
2325 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2326
2327 // When loading a non-modular PCH files, this is used to restore module
2328 // visibility.
2329 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2330 VisibleModules.setVisible(Mod, ImportLoc);
2331 }
2332
2333 /// Determine whether a declaration is visible to name lookup.
2334 bool isVisible(const NamedDecl *D) {
2335 return D->isUnconditionallyVisible() ||
2336 isAcceptableSlow(D, AcceptableKind::Visible);
2337 }
2338
2339 /// Determine whether a declaration is reachable.
2340 bool isReachable(const NamedDecl *D) {
2341 // All visible declarations are reachable.
2342 return D->isUnconditionallyVisible() ||
2343 isAcceptableSlow(D, AcceptableKind::Reachable);
2344 }
2345
2346 /// Determine whether a declaration is acceptable (visible/reachable).
2347 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
2348 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2349 }
2350
2351 /// Determine whether any declaration of an entity is visible.
2352 bool
2353 hasVisibleDeclaration(const NamedDecl *D,
2354 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2355 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2356 }
2357
2358 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2359 llvm::SmallVectorImpl<Module *> *Modules);
2360 /// Determine whether any declaration of an entity is reachable.
2361 bool
2362 hasReachableDeclaration(const NamedDecl *D,
2363 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2364 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2365 }
2366 bool hasReachableDeclarationSlow(
2367 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2368
2369 bool hasVisibleMergedDefinition(NamedDecl *Def);
2370 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2371
2372 /// Determine if \p D and \p Suggested have a structurally compatible
2373 /// layout as described in C11 6.2.7/1.
2374 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2375
2376 /// Determine if \p D has a visible definition. If not, suggest a declaration
2377 /// that should be made visible to expose the definition.
2378 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2379 bool OnlyNeedComplete = false);
2380 bool hasVisibleDefinition(const NamedDecl *D) {
2381 NamedDecl *Hidden;
2382 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2383 }
2384
2385 /// Determine if \p D has a reachable definition. If not, suggest a
2386 /// declaration that should be made reachable to expose the definition.
2387 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2388 bool OnlyNeedComplete = false);
2389 bool hasReachableDefinition(NamedDecl *D) {
2390 NamedDecl *Hidden;
2391 return hasReachableDefinition(D, &Hidden);
2392 }
2393
2394 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2395 AcceptableKind Kind,
2396 bool OnlyNeedComplete = false);
2397 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
2398 NamedDecl *Hidden;
2399 return hasAcceptableDefinition(D, &Hidden, Kind);
2400 }
2401
2402 /// Determine if the template parameter \p D has a visible default argument.
2403 bool
2404 hasVisibleDefaultArgument(const NamedDecl *D,
2405 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2406 /// Determine if the template parameter \p D has a reachable default argument.
2407 bool hasReachableDefaultArgument(
2408 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2409 /// Determine if the template parameter \p D has a reachable default argument.
2410 bool hasAcceptableDefaultArgument(const NamedDecl *D,
2411 llvm::SmallVectorImpl<Module *> *Modules,
2412 Sema::AcceptableKind Kind);
2413
2414 /// Determine if there is a visible declaration of \p D that is an explicit
2415 /// specialization declaration for a specialization of a template. (For a
2416 /// member specialization, use hasVisibleMemberSpecialization.)
2417 bool hasVisibleExplicitSpecialization(
2418 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2419 /// Determine if there is a reachable declaration of \p D that is an explicit
2420 /// specialization declaration for a specialization of a template. (For a
2421 /// member specialization, use hasReachableMemberSpecialization.)
2422 bool hasReachableExplicitSpecialization(
2423 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2424
2425 /// Determine if there is a visible declaration of \p D that is a member
2426 /// specialization declaration (as opposed to an instantiated declaration).
2427 bool hasVisibleMemberSpecialization(
2428 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2429 /// Determine if there is a reachable declaration of \p D that is a member
2430 /// specialization declaration (as opposed to an instantiated declaration).
2431 bool hasReachableMemberSpecialization(
2432 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2433
2434 /// Determine if \p A and \p B are equivalent internal linkage declarations
2435 /// from different modules, and thus an ambiguity error can be downgraded to
2436 /// an extension warning.
2437 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2438 const NamedDecl *B);
2439 void diagnoseEquivalentInternalLinkageDeclarations(
2440 SourceLocation Loc, const NamedDecl *D,
2441 ArrayRef<const NamedDecl *> Equiv);
2442
2443 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2444
2445 // Check whether the size of array element of type \p EltTy is a multiple of
2446 // its alignment and return false if it isn't.
2447 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
2448
2449 bool isCompleteType(SourceLocation Loc, QualType T,
2450 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2451 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2452 }
2453 bool RequireCompleteType(SourceLocation Loc, QualType T,
2454 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2455 bool RequireCompleteType(SourceLocation Loc, QualType T,
2456 CompleteTypeKind Kind, unsigned DiagID);
2457
2458 bool RequireCompleteType(SourceLocation Loc, QualType T,
2459 TypeDiagnoser &Diagnoser) {
2460 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2461 }
2462 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2463 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2464 }
2465
2466 template <typename... Ts>
2467 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2468 const Ts &...Args) {
2469 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2470 return RequireCompleteType(Loc, T, Diagnoser);
2471 }
2472
2473 template <typename... Ts>
2474 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2475 const Ts &... Args) {
2476 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2477 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2478 }
2479
2480 /// Get the type of expression E, triggering instantiation to complete the
2481 /// type if necessary -- that is, if the expression refers to a templated
2482 /// static data member of incomplete array type.
2483 ///
2484 /// May still return an incomplete type if instantiation was not possible or
2485 /// if the type is incomplete for a different reason. Use
2486 /// RequireCompleteExprType instead if a diagnostic is expected for an
2487 /// incomplete expression type.
2488 QualType getCompletedType(Expr *E);
2489
2490 void completeExprArrayBound(Expr *E);
2491 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2492 TypeDiagnoser &Diagnoser);
2493 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2494
2495 template <typename... Ts>
2496 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2497 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2498 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2499 }
2500
2501 template <typename... Ts>
2502 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2503 const Ts &... Args) {
2504 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2505 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2506 }
2507
2508 bool RequireLiteralType(SourceLocation Loc, QualType T,
2509 TypeDiagnoser &Diagnoser);
2510 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2511
2512 template <typename... Ts>
2513 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2514 const Ts &...Args) {
2515 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2516 return RequireLiteralType(Loc, T, Diagnoser);
2517 }
2518
2519 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2520 const CXXScopeSpec &SS, QualType T,
2521 TagDecl *OwnedTagDecl = nullptr);
2522
2523 // Returns the underlying type of a decltype with the given expression.
2524 QualType getDecltypeForExpr(Expr *E);
2525
2526 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
2527 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2528 /// context, such as when building a type for decltype(auto).
2529 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2530
2531 using UTTKind = UnaryTransformType::UTTKind;
2532 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
2533 SourceLocation Loc);
2534 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
2535 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
2536 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
2537 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
2538 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
2539 SourceLocation Loc);
2540 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
2541 SourceLocation Loc);
2542 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
2543 SourceLocation Loc);
2544 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
2545 SourceLocation Loc);
2546 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
2547 SourceLocation Loc);
2548
2549 //===--------------------------------------------------------------------===//
2550 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2551 //
2552
2553 struct SkipBodyInfo {
2554 SkipBodyInfo()
2555 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2556 New(nullptr) {}
2557 bool ShouldSkip;
2558 bool CheckSameAsPrevious;
2559 NamedDecl *Previous;
2560 NamedDecl *New;
2561 };
2562
2563 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2564
2565 void DiagnoseUseOfUnimplementedSelectors();
2566
2567 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2568
2569 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2570 Scope *S, CXXScopeSpec *SS = nullptr,
2571 bool isClassName = false, bool HasTrailingDot = false,
2572 ParsedType ObjectType = nullptr,
2573 bool IsCtorOrDtorName = false,
2574 bool WantNontrivialTypeSourceInfo = false,
2575 bool IsClassTemplateDeductionContext = true,
2576 ImplicitTypenameContext AllowImplicitTypename =
2577 ImplicitTypenameContext::No,
2578 IdentifierInfo **CorrectedII = nullptr);
2579 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2580 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2581 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2582 SourceLocation IILoc,
2583 Scope *S,
2584 CXXScopeSpec *SS,
2585 ParsedType &SuggestedType,
2586 bool IsTemplateName = false);
2587
2588 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2589 /// type name has failed in a dependent context. In these situations, we
2590 /// automatically form a DependentTypeName that will retry lookup in a related
2591 /// scope during instantiation.
2592 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2593 SourceLocation NameLoc,
2594 bool IsTemplateTypeArg);
2595
2596 /// Describes the result of the name lookup and resolution performed
2597 /// by \c ClassifyName().
2598 enum NameClassificationKind {
2599 /// This name is not a type or template in this context, but might be
2600 /// something else.
2601 NC_Unknown,
2602 /// Classification failed; an error has been produced.
2603 NC_Error,
2604 /// The name has been typo-corrected to a keyword.
2605 NC_Keyword,
2606 /// The name was classified as a type.
2607 NC_Type,
2608 /// The name was classified as a specific non-type, non-template
2609 /// declaration. ActOnNameClassifiedAsNonType should be called to
2610 /// convert the declaration to an expression.
2611 NC_NonType,
2612 /// The name was classified as an ADL-only function name.
2613 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2614 /// result to an expression.
2615 NC_UndeclaredNonType,
2616 /// The name denotes a member of a dependent type that could not be
2617 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2618 /// convert the result to an expression.
2619 NC_DependentNonType,
2620 /// The name was classified as an overload set, and an expression
2621 /// representing that overload set has been formed.
2622 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2623 /// expression referencing the overload set.
2624 NC_OverloadSet,
2625 /// The name was classified as a template whose specializations are types.
2626 NC_TypeTemplate,
2627 /// The name was classified as a variable template name.
2628 NC_VarTemplate,
2629 /// The name was classified as a function template name.
2630 NC_FunctionTemplate,
2631 /// The name was classified as an ADL-only function template name.
2632 NC_UndeclaredTemplate,
2633 /// The name was classified as a concept name.
2634 NC_Concept,
2635 };
2636
2637 class NameClassification {
2638 NameClassificationKind Kind;
2639 union {
2640 ExprResult Expr;
2641 NamedDecl *NonTypeDecl;
2642 TemplateName Template;
2643 ParsedType Type;
2644 };
2645
2646 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2647
2648 public:
2649 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2650
2651 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2652
2653 static NameClassification Error() {
2654 return NameClassification(NC_Error);
2655 }
2656
2657 static NameClassification Unknown() {
2658 return NameClassification(NC_Unknown);
2659 }
2660
2661 static NameClassification OverloadSet(ExprResult E) {
2662 NameClassification Result(NC_OverloadSet);
2663 Result.Expr = E;
2664 return Result;
2665 }
2666
2667 static NameClassification NonType(NamedDecl *D) {
2668 NameClassification Result(NC_NonType);
2669 Result.NonTypeDecl = D;
2670 return Result;
2671 }
2672
2673 static NameClassification UndeclaredNonType() {
2674 return NameClassification(NC_UndeclaredNonType);
2675 }
2676
2677 static NameClassification DependentNonType() {
2678 return NameClassification(NC_DependentNonType);
2679 }
2680
2681 static NameClassification TypeTemplate(TemplateName Name) {
2682 NameClassification Result(NC_TypeTemplate);
2683 Result.Template = Name;
2684 return Result;
2685 }
2686
2687 static NameClassification VarTemplate(TemplateName Name) {
2688 NameClassification Result(NC_VarTemplate);
2689 Result.Template = Name;
2690 return Result;
2691 }
2692
2693 static NameClassification FunctionTemplate(TemplateName Name) {
2694 NameClassification Result(NC_FunctionTemplate);
2695 Result.Template = Name;
2696 return Result;
2697 }
2698
2699 static NameClassification Concept(TemplateName Name) {
2700 NameClassification Result(NC_Concept);
2701 Result.Template = Name;
2702 return Result;
2703 }
2704
2705 static NameClassification UndeclaredTemplate(TemplateName Name) {
2706 NameClassification Result(NC_UndeclaredTemplate);
2707 Result.Template = Name;
2708 return Result;
2709 }
2710
2711 NameClassificationKind getKind() const { return Kind; }
2712
2713 ExprResult getExpression() const {
2714 assert(Kind == NC_OverloadSet)(static_cast <bool> (Kind == NC_OverloadSet) ? void (0)
: __assert_fail ("Kind == NC_OverloadSet", "clang/include/clang/Sema/Sema.h"
, 2714, __extension__ __PRETTY_FUNCTION__))
;
2715 return Expr;
2716 }
2717
2718 ParsedType getType() const {
2719 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "clang/include/clang/Sema/Sema.h", 2719,
__extension__ __PRETTY_FUNCTION__))
;
2720 return Type;
2721 }
2722
2723 NamedDecl *getNonTypeDecl() const {
2724 assert(Kind == NC_NonType)(static_cast <bool> (Kind == NC_NonType) ? void (0) : __assert_fail
("Kind == NC_NonType", "clang/include/clang/Sema/Sema.h", 2724
, __extension__ __PRETTY_FUNCTION__))
;
2725 return NonTypeDecl;
2726 }
2727
2728 TemplateName getTemplateName() const {
2729 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2731, __extension__ __PRETTY_FUNCTION__
))
2730 Kind == NC_VarTemplate || Kind == NC_Concept ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2731, __extension__ __PRETTY_FUNCTION__
))
2731 Kind == NC_UndeclaredTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2731, __extension__ __PRETTY_FUNCTION__
))
;
2732 return Template;
2733 }
2734
2735 TemplateNameKind getTemplateNameKind() const {
2736 switch (Kind) {
2737 case NC_TypeTemplate:
2738 return TNK_Type_template;
2739 case NC_FunctionTemplate:
2740 return TNK_Function_template;
2741 case NC_VarTemplate:
2742 return TNK_Var_template;
2743 case NC_Concept:
2744 return TNK_Concept_template;
2745 case NC_UndeclaredTemplate:
2746 return TNK_Undeclared_template;
2747 default:
2748 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "clang/include/clang/Sema/Sema.h", 2748)
;
2749 }
2750 }
2751 };
2752
2753 /// Perform name lookup on the given name, classifying it based on
2754 /// the results of name lookup and the following token.
2755 ///
2756 /// This routine is used by the parser to resolve identifiers and help direct
2757 /// parsing. When the identifier cannot be found, this routine will attempt
2758 /// to correct the typo and classify based on the resulting name.
2759 ///
2760 /// \param S The scope in which we're performing name lookup.
2761 ///
2762 /// \param SS The nested-name-specifier that precedes the name.
2763 ///
2764 /// \param Name The identifier. If typo correction finds an alternative name,
2765 /// this pointer parameter will be updated accordingly.
2766 ///
2767 /// \param NameLoc The location of the identifier.
2768 ///
2769 /// \param NextToken The token following the identifier. Used to help
2770 /// disambiguate the name.
2771 ///
2772 /// \param CCC The correction callback, if typo correction is desired.
2773 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2774 IdentifierInfo *&Name, SourceLocation NameLoc,
2775 const Token &NextToken,
2776 CorrectionCandidateCallback *CCC = nullptr);
2777
2778 /// Act on the result of classifying a name as an undeclared (ADL-only)
2779 /// non-type declaration.
2780 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2781 SourceLocation NameLoc);
2782 /// Act on the result of classifying a name as an undeclared member of a
2783 /// dependent base class.
2784 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2785 IdentifierInfo *Name,
2786 SourceLocation NameLoc,
2787 bool IsAddressOfOperand);
2788 /// Act on the result of classifying a name as a specific non-type
2789 /// declaration.
2790 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2791 NamedDecl *Found,
2792 SourceLocation NameLoc,
2793 const Token &NextToken);
2794 /// Act on the result of classifying a name as an overload set.
2795 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2796
2797 /// Describes the detailed kind of a template name. Used in diagnostics.
2798 enum class TemplateNameKindForDiagnostics {
2799 ClassTemplate,
2800 FunctionTemplate,
2801 VarTemplate,
2802 AliasTemplate,
2803 TemplateTemplateParam,
2804 Concept,
2805 DependentTemplate
2806 };
2807 TemplateNameKindForDiagnostics
2808 getTemplateNameKindForDiagnostics(TemplateName Name);
2809
2810 /// Determine whether it's plausible that E was intended to be a
2811 /// template-name.
2812 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2813 if (!getLangOpts().CPlusPlus || E.isInvalid())
2814 return false;
2815 Dependent = false;
2816 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2817 return !DRE->hasExplicitTemplateArgs();
2818 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2819 return !ME->hasExplicitTemplateArgs();
2820 Dependent = true;
2821 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2822 return !DSDRE->hasExplicitTemplateArgs();
2823 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2824 return !DSME->hasExplicitTemplateArgs();
2825 // Any additional cases recognized here should also be handled by
2826 // diagnoseExprIntendedAsTemplateName.
2827 return false;
2828 }
2829 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2830 SourceLocation Less,
2831 SourceLocation Greater);
2832
2833 void warnOnReservedIdentifier(const NamedDecl *D);
2834
2835 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2836
2837 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2838 MultiTemplateParamsArg TemplateParameterLists);
2839 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2840 QualType &T, SourceLocation Loc,
2841 unsigned FailedFoldDiagID);
2842 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2843 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2844 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2845 DeclarationName Name, SourceLocation Loc,
2846 bool IsTemplateId);
2847 void
2848 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2849 SourceLocation FallbackLoc,
2850 SourceLocation ConstQualLoc = SourceLocation(),
2851 SourceLocation VolatileQualLoc = SourceLocation(),
2852 SourceLocation RestrictQualLoc = SourceLocation(),
2853 SourceLocation AtomicQualLoc = SourceLocation(),
2854 SourceLocation UnalignedQualLoc = SourceLocation());
2855
2856 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2857 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2858 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2859 const LookupResult &R);
2860 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2861 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2862 const LookupResult &R);
2863 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2864 const LookupResult &R);
2865 void CheckShadow(Scope *S, VarDecl *D);
2866
2867 /// Warn if 'E', which is an expression that is about to be modified, refers
2868 /// to a shadowing declaration.
2869 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2870
2871 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2872
2873private:
2874 /// Map of current shadowing declarations to shadowed declarations. Warn if
2875 /// it looks like the user is trying to modify the shadowing declaration.
2876 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2877
2878public:
2879 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2880 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2881 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2882 TypedefNameDecl *NewTD);
2883 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2884 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2885 TypeSourceInfo *TInfo,
2886 LookupResult &Previous);
2887 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2888 LookupResult &Previous, bool &Redeclaration);
2889 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2890 TypeSourceInfo *TInfo,
2891 LookupResult &Previous,
2892 MultiTemplateParamsArg TemplateParamLists,
2893 bool &AddToScope,
2894 ArrayRef<BindingDecl *> Bindings = None);
2895 NamedDecl *
2896 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2897 MultiTemplateParamsArg TemplateParamLists);
2898 // Returns true if the variable declaration is a redeclaration
2899 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2900 void CheckVariableDeclarationType(VarDecl *NewVD);
2901 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2902 Expr *Init);
2903 void CheckCompleteVariableDeclaration(VarDecl *VD);
2904 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2905 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2906
2907 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2908 TypeSourceInfo *TInfo,
2909 LookupResult &Previous,
2910 MultiTemplateParamsArg TemplateParamLists,
2911 bool &AddToScope);
2912 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2913
2914 enum class CheckConstexprKind {
2915 /// Diagnose issues that are non-constant or that are extensions.
2916 Diagnose,
2917 /// Identify whether this function satisfies the formal rules for constexpr
2918 /// functions in the current lanugage mode (with no extensions).
2919 CheckValid
2920 };
2921
2922 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2923 CheckConstexprKind Kind);
2924
2925 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2926 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2927 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2928 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2929 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2930 // Returns true if the function declaration is a redeclaration
2931 bool CheckFunctionDeclaration(Scope *S,
2932 FunctionDecl *NewFD, LookupResult &Previous,
2933 bool IsMemberSpecialization, bool DeclIsDefn);
2934 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2935 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2936 QualType NewT, QualType OldT);
2937 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2938 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2939 void CheckHLSLEntryPoint(FunctionDecl *FD);
2940 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2941 bool IsDefinition);
2942 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2943 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2944 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2945 SourceLocation Loc,
2946 QualType T);
2947 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2948 SourceLocation NameLoc, IdentifierInfo *Name,
2949 QualType T, TypeSourceInfo *TSInfo,
2950 StorageClass SC);
2951 void ActOnParamDefaultArgument(Decl *param,
2952 SourceLocation EqualLoc,
2953 Expr *defarg);
2954 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2955 SourceLocation ArgLoc);
2956 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2957 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2958 SourceLocation EqualLoc);
2959 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2960 SourceLocation EqualLoc);
2961
2962 // Contexts where using non-trivial C union types can be disallowed. This is
2963 // passed to err_non_trivial_c_union_in_invalid_context.
2964 enum NonTrivialCUnionContext {
2965 // Function parameter.
2966 NTCUC_FunctionParam,
2967 // Function return.
2968 NTCUC_FunctionReturn,
2969 // Default-initialized object.
2970 NTCUC_DefaultInitializedObject,
2971 // Variable with automatic storage duration.
2972 NTCUC_AutoVar,
2973 // Initializer expression that might copy from another object.
2974 NTCUC_CopyInit,
2975 // Assignment.
2976 NTCUC_Assignment,
2977 // Compound literal.
2978 NTCUC_CompoundLiteral,
2979 // Block capture.
2980 NTCUC_BlockCapture,
2981 // lvalue-to-rvalue conversion of volatile type.
2982 NTCUC_LValueToRValueVolatile,
2983 };
2984
2985 /// Emit diagnostics if the initializer or any of its explicit or
2986 /// implicitly-generated subexpressions require copying or
2987 /// default-initializing a type that is or contains a C union type that is
2988 /// non-trivial to copy or default-initialize.
2989 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2990
2991 // These flags are passed to checkNonTrivialCUnion.
2992 enum NonTrivialCUnionKind {
2993 NTCUK_Init = 0x1,
2994 NTCUK_Destruct = 0x2,
2995 NTCUK_Copy = 0x4,
2996 };
2997
2998 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2999 /// a non-trivial C union is used in an invalid context.
3000 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
3001 NonTrivialCUnionContext UseContext,
3002 unsigned NonTrivialKind);
3003
3004 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3005 void ActOnUninitializedDecl(Decl *dcl);
3006 void ActOnInitializerError(Decl *Dcl);
3007
3008 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3009 void ActOnCXXForRangeDecl(Decl *D);
3010 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
3011 IdentifierInfo *Ident,
3012 ParsedAttributes &Attrs);
3013 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3014 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3015 void CheckStaticLocalForDllExport(VarDecl *VD);
3016 void FinalizeDeclaration(Decl *D);
3017 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3018 ArrayRef<Decl *> Group);
3019 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
3020
3021 /// Should be called on all declarations that might have attached
3022 /// documentation comments.
3023 void ActOnDocumentableDecl(Decl *D);
3024 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
3025
3026 enum class FnBodyKind {
3027 /// C++ [dcl.fct.def.general]p1
3028 /// function-body:
3029 /// ctor-initializer[opt] compound-statement
3030 /// function-try-block
3031 Other,
3032 /// = default ;
3033 Default,
3034 /// = delete ;
3035 Delete
3036 };
3037
3038 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3039 SourceLocation LocAfterDecls);
3040 void CheckForFunctionRedefinition(
3041 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3042 SkipBodyInfo *SkipBody = nullptr);
3043 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
3044 MultiTemplateParamsArg TemplateParamLists,
3045 SkipBodyInfo *SkipBody = nullptr,
3046 FnBodyKind BodyKind = FnBodyKind::Other);
3047 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
3048 SkipBodyInfo *SkipBody = nullptr,
3049 FnBodyKind BodyKind = FnBodyKind::Other);
3050 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3051 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
3052 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
3053 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3054 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3055 bool isObjCMethodDecl(Decl *D) {
3056 return D && isa<ObjCMethodDecl>(D);
3057 }
3058
3059 /// Determine whether we can delay parsing the body of a function or
3060 /// function template until it is used, assuming we don't care about emitting
3061 /// code for that function.
3062 ///
3063 /// This will be \c false if we may need the body of the function in the
3064 /// middle of parsing an expression (where it's impractical to switch to
3065 /// parsing a different function), for instance, if it's constexpr in C++11
3066 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3067 bool canDelayFunctionBody(const Declarator &D);
3068
3069 /// Determine whether we can skip parsing the body of a function
3070 /// definition, assuming we don't care about analyzing its body or emitting
3071 /// code for that function.
3072 ///
3073 /// This will be \c false only if we may need the body of the function in
3074 /// order to parse the rest of the program (for instance, if it is
3075 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3076 bool canSkipFunctionBody(Decl *D);
3077
3078 /// Determine whether \param D is function like (function or function
3079 /// template) for parsing.
3080 bool isDeclaratorFunctionLike(Declarator &D);
3081
3082 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
3083 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
3084 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3085 Decl *ActOnSkippedFunctionBody(Decl *Decl);
3086 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
3087
3088 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3089 /// attribute for which parsing is delayed.
3090 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
3091
3092 /// Diagnose any unused parameters in the given sequence of
3093 /// ParmVarDecl pointers.
3094 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
3095
3096 /// Diagnose whether the size of parameters or return value of a
3097 /// function or obj-c method definition is pass-by-value and larger than a
3098 /// specified threshold.
3099 void
3100 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
3101 QualType ReturnTy, NamedDecl *D);
3102
3103 void DiagnoseInvalidJumps(Stmt *Body);
3104 Decl *ActOnFileScopeAsmDecl(Expr *expr,
3105 SourceLocation AsmLoc,
3106 SourceLocation RParenLoc);
3107
3108 /// Handle a C++11 empty-declaration and attribute-declaration.
3109 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
3110 SourceLocation SemiLoc);
3111
3112 enum class ModuleDeclKind {
3113 Interface, ///< 'export module X;'
3114 Implementation, ///< 'module X;'
3115 PartitionInterface, ///< 'export module X:Y;'
3116 PartitionImplementation, ///< 'module X:Y;'
3117 };
3118
3119 /// An enumeration to represent the transition of states in parsing module
3120 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3121 /// an error in state transition, the state is set to NotACXX20Module.
3122 enum class ModuleImportState {
3123 FirstDecl, ///< Parsing the first decl in a TU.
3124 GlobalFragment, ///< after 'module;' but before 'module X;'
3125 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3126 ImportFinished, ///< after any non-import decl.
3127 PrivateFragment, ///< after 'module :private;'.
3128 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3129 };
3130
3131private:
3132 /// The parser has begun a translation unit to be compiled as a C++20
3133 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3134 void HandleStartOfHeaderUnit();
3135
3136public:
3137 /// The parser has processed a module-declaration that begins the definition
3138 /// of a module interface or implementation.
3139 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3140 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3141 ModuleIdPath Path, ModuleIdPath Partition,
3142 ModuleImportState &ImportState);
3143
3144 /// The parser has processed a global-module-fragment declaration that begins
3145 /// the definition of the global module fragment of the current module unit.
3146 /// \param ModuleLoc The location of the 'module' keyword.
3147 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3148
3149 /// The parser has processed a private-module-fragment declaration that begins
3150 /// the definition of the private module fragment of the current module unit.
3151 /// \param ModuleLoc The location of the 'module' keyword.
3152 /// \param PrivateLoc The location of the 'private' keyword.
3153 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3154 SourceLocation PrivateLoc);
3155
3156 /// The parser has processed a module import declaration.
3157 ///
3158 /// \param StartLoc The location of the first token in the declaration. This
3159 /// could be the location of an '@', 'export', or 'import'.
3160 /// \param ExportLoc The location of the 'export' keyword, if any.
3161 /// \param ImportLoc The location of the 'import' keyword.
3162 /// \param Path The module toplevel name as an access path.
3163 /// \param IsPartition If the name is for a partition.
3164 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3165 SourceLocation ExportLoc,
3166 SourceLocation ImportLoc, ModuleIdPath Path,
3167 bool IsPartition = false);
3168 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3169 SourceLocation ExportLoc,
3170 SourceLocation ImportLoc, Module *M,
3171 ModuleIdPath Path = {});
3172
3173 /// The parser has processed a module import translated from a
3174 /// #include or similar preprocessing directive.
3175 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3176 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3177
3178 /// The parsed has entered a submodule.
3179 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3180 /// The parser has left a submodule.
3181 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3182
3183 /// Create an implicit import of the given module at the given
3184 /// source location, for error recovery, if possible.
3185 ///
3186 /// This routine is typically used when an entity found by name lookup
3187 /// is actually hidden within a module that we know about but the user
3188 /// has forgotten to import.
3189 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3190 Module *Mod);
3191
3192 /// Kinds of missing import. Note, the values of these enumerators correspond
3193 /// to %select values in diagnostics.
3194 enum class MissingImportKind {
3195 Declaration,
3196 Definition,
3197 DefaultArgument,
3198 ExplicitSpecialization,
3199 PartialSpecialization
3200 };
3201
3202 /// Diagnose that the specified declaration needs to be visible but
3203 /// isn't, and suggest a module import that would resolve the problem.
3204 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3205 MissingImportKind MIK, bool Recover = true);
3206 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3207 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3208 MissingImportKind MIK, bool Recover);
3209
3210 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3211 SourceLocation LBraceLoc);
3212 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3213 SourceLocation RBraceLoc);
3214
3215 /// We've found a use of a templated declaration that would trigger an
3216 /// implicit instantiation. Check that any relevant explicit specializations
3217 /// and partial specializations are visible/reachable, and diagnose if not.
3218 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3219 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
3220
3221 /// Retrieve a suitable printing policy for diagnostics.
3222 PrintingPolicy getPrintingPolicy() const {
3223 return getPrintingPolicy(Context, PP);
3224 }
3225
3226 /// Retrieve a suitable printing policy for diagnostics.
3227 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3228 const Preprocessor &PP);
3229
3230 /// Scope actions.
3231 void ActOnPopScope(SourceLocation Loc, Scope *S);
3232 void ActOnTranslationUnitScope(Scope *S);
3233
3234 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3235 const ParsedAttributesView &DeclAttrs,
3236 RecordDecl *&AnonRecord);
3237 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3238 const ParsedAttributesView &DeclAttrs,
3239 MultiTemplateParamsArg TemplateParams,
3240 bool IsExplicitInstantiation,
3241 RecordDecl *&AnonRecord);
3242
3243 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3244 AccessSpecifier AS,
3245 RecordDecl *Record,
3246 const PrintingPolicy &Policy);
3247
3248 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3249 RecordDecl *Record);
3250
3251 /// Common ways to introduce type names without a tag for use in diagnostics.
3252 /// Keep in sync with err_tag_reference_non_tag.
3253 enum NonTagKind {
3254 NTK_NonStruct,
3255 NTK_NonClass,
3256 NTK_NonUnion,
3257 NTK_NonEnum,
3258 NTK_Typedef,
3259 NTK_TypeAlias,
3260 NTK_Template,
3261 NTK_TypeAliasTemplate,
3262 NTK_TemplateTemplateArgument,
3263 };
3264
3265 /// Given a non-tag type declaration, returns an enum useful for indicating
3266 /// what kind of non-tag type this is.
3267 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3268
3269 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3270 TagTypeKind NewTag, bool isDefinition,
3271 SourceLocation NewTagLoc,
3272 const IdentifierInfo *Name);
3273
3274 enum TagUseKind {
3275 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3276 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3277 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3278 TUK_Friend // Friend declaration: 'friend struct foo;'
3279 };
3280
3281 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3282 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3283 SourceLocation NameLoc, const ParsedAttributesView &Attr,
3284 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3285 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3286 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3287 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3288 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3289 SkipBodyInfo *SkipBody = nullptr);
3290
3291 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3292 unsigned TagSpec, SourceLocation TagLoc,
3293 CXXScopeSpec &SS, IdentifierInfo *Name,
3294 SourceLocation NameLoc,
3295 const ParsedAttributesView &Attr,
3296 MultiTemplateParamsArg TempParamLists);
3297
3298 TypeResult ActOnDependentTag(Scope *S,
3299 unsigned TagSpec,
3300 TagUseKind TUK,
3301 const CXXScopeSpec &SS,
3302 IdentifierInfo *Name,
3303 SourceLocation TagLoc,
3304 SourceLocation NameLoc);
3305
3306 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3307 IdentifierInfo *ClassName,
3308 SmallVectorImpl<Decl *> &Decls);
3309 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3310 Declarator &D, Expr *BitfieldWidth);
3311
3312 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3313 Declarator &D, Expr *BitfieldWidth,
3314 InClassInitStyle InitStyle,
3315 AccessSpecifier AS);
3316 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3317 SourceLocation DeclStart, Declarator &D,
3318 Expr *BitfieldWidth,
3319 InClassInitStyle InitStyle,
3320 AccessSpecifier AS,
3321 const ParsedAttr &MSPropertyAttr);
3322
3323 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3324 TypeSourceInfo *TInfo,
3325 RecordDecl *Record, SourceLocation Loc,
3326 bool Mutable, Expr *BitfieldWidth,
3327 InClassInitStyle InitStyle,
3328 SourceLocation TSSL,
3329 AccessSpecifier AS, NamedDecl *PrevDecl,
3330 Declarator *D = nullptr);
3331
3332 bool CheckNontrivialField(FieldDecl *FD);
3333 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3334
3335 enum TrivialABIHandling {
3336 /// The triviality of a method unaffected by "trivial_abi".
3337 TAH_IgnoreTrivialABI,
3338
3339 /// The triviality of a method affected by "trivial_abi".
3340 TAH_ConsiderTrivialABI
3341 };
3342
3343 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3344 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3345 bool Diagnose = false);
3346
3347 /// For a defaulted function, the kind of defaulted function that it is.
3348 class DefaultedFunctionKind {
3349 CXXSpecialMember SpecialMember : 8;
3350 DefaultedComparisonKind Comparison : 8;
3351
3352 public:
3353 DefaultedFunctionKind()
3354 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3355 }
3356 DefaultedFunctionKind(CXXSpecialMember CSM)
3357 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3358 DefaultedFunctionKind(DefaultedComparisonKind Comp)
3359 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3360
3361 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3362 bool isComparison() const {
3363 return Comparison != DefaultedComparisonKind::None;
3364 }
3365
3366 explicit operator bool() const {
3367 return isSpecialMember() || isComparison();
3368 }
3369
3370 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3371 DefaultedComparisonKind asComparison() const { return Comparison; }
3372
3373 /// Get the index of this function kind for use in diagnostics.
3374 unsigned getDiagnosticIndex() const {
3375 static_assert(CXXInvalid > CXXDestructor,
3376 "invalid should have highest index");
3377 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3378 "none should be equal to zero");
3379 return SpecialMember + (unsigned)Comparison;
3380 }
3381 };
3382
3383 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3384
3385 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3386 return getDefaultedFunctionKind(MD).asSpecialMember();
3387 }
3388 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3389 return getDefaultedFunctionKind(FD).asComparison();
3390 }
3391
3392 void ActOnLastBitfield(SourceLocation DeclStart,
3393 SmallVectorImpl<Decl *> &AllIvarDecls);
3394 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3395 Declarator &D, Expr *BitfieldWidth,
3396 tok::ObjCKeywordKind visibility);
3397
3398 // This is used for both record definitions and ObjC interface declarations.
3399 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3400 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3401 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3402
3403 /// ActOnTagStartDefinition - Invoked when we have entered the
3404 /// scope of a tag's definition (e.g., for an enumeration, class,
3405 /// struct, or union).
3406 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3407
3408 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3409 /// Differently from C++, actually parse the body and reject / error out
3410 /// in case of a structural mismatch.
3411 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3412
3413 typedef void *SkippedDefinitionContext;
3414
3415 /// Invoked when we enter a tag definition that we're skipping.
3416 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3417
3418 void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
3419
3420 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3421 /// C++ record definition's base-specifiers clause and are starting its
3422 /// member declarations.
3423 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3424 SourceLocation FinalLoc,
3425 bool IsFinalSpelledSealed,
3426 bool IsAbstract,
3427 SourceLocation LBraceLoc);
3428
3429 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3430 /// the definition of a tag (enumeration, class, struct, or union).
3431 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3432 SourceRange BraceRange);
3433
3434 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3435
3436 void ActOnObjCContainerFinishDefinition();
3437
3438 /// Invoked when we must temporarily exit the objective-c container
3439 /// scope for parsing/looking-up C constructs.
3440 ///
3441 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3442 void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
3443 void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
3444
3445 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3446 /// error parsing the definition of a tag.
3447 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3448
3449 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3450 EnumConstantDecl *LastEnumConst,
3451 SourceLocation IdLoc,
3452 IdentifierInfo *Id,
3453 Expr *val);
3454 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3455 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3456 QualType EnumUnderlyingTy, bool IsFixed,
3457 const EnumDecl *Prev);
3458
3459 /// Determine whether the body of an anonymous enumeration should be skipped.
3460 /// \param II The name of the first enumerator.
3461 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3462 SourceLocation IILoc);
3463
3464 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3465 SourceLocation IdLoc, IdentifierInfo *Id,
3466 const ParsedAttributesView &Attrs,
3467 SourceLocation EqualLoc, Expr *Val);
3468 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3469 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3470 const ParsedAttributesView &Attr);
3471
3472 /// Set the current declaration context until it gets popped.
3473 void PushDeclContext(Scope *S, DeclContext *DC);
3474 void PopDeclContext();
3475
3476 /// EnterDeclaratorContext - Used when we must lookup names in the context
3477 /// of a declarator's nested name specifier.
3478 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3479 void ExitDeclaratorContext(Scope *S);
3480
3481 /// Enter a template parameter scope, after it's been associated with a particular
3482 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3483 /// in the correct order.
3484 void EnterTemplatedContext(Scope *S, DeclContext *DC);
3485
3486 /// Push the parameters of D, which must be a function, into scope.
3487 void ActOnReenterFunctionContext(Scope* S, Decl* D);
3488 void ActOnExitFunctionContext();
3489
3490 /// If \p AllowLambda is true, treat lambda as function.
3491 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false);
3492
3493 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3494 /// current context is not inside a function. If \p AllowLambda is true,
3495 /// this can return the call operator of an enclosing lambda, otherwise
3496 /// lambdas are skipped when looking for an enclosing function.
3497 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false);
3498
3499 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3500 /// the method decl for the method being parsed. If we're currently
3501 /// in a 'block', this returns the containing context.
3502 ObjCMethodDecl *getCurMethodDecl();
3503
3504 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3505 /// or C function we're in, otherwise return null. If we're currently
3506 /// in a 'block', this returns the containing context.
3507 NamedDecl *getCurFunctionOrMethodDecl();
3508
3509 /// Add this decl to the scope shadowed decl chains.
3510 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3511
3512 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3513 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3514 /// true if 'D' belongs to the given declaration context.
3515 ///
3516 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3517 /// enclosing namespace set of the context, rather than contained
3518 /// directly within it.
3519 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3520 bool AllowInlineNamespace = false);
3521
3522 /// Finds the scope corresponding to the given decl context, if it
3523 /// happens to be an enclosing scope. Otherwise return NULL.
3524 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3525
3526 /// Subroutines of ActOnDeclarator().
3527 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3528 TypeSourceInfo *TInfo);
3529 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3530
3531 /// Describes the kind of merge to perform for availability
3532 /// attributes (including "deprecated", "unavailable", and "availability").
3533 enum AvailabilityMergeKind {
3534 /// Don't merge availability attributes at all.
3535 AMK_None,
3536 /// Merge availability attributes for a redeclaration, which requires
3537 /// an exact match.
3538 AMK_Redeclaration,
3539 /// Merge availability attributes for an override, which requires
3540 /// an exact match or a weakening of constraints.
3541 AMK_Override,
3542 /// Merge availability attributes for an implementation of
3543 /// a protocol requirement.
3544 AMK_ProtocolImplementation,
3545 /// Merge availability attributes for an implementation of
3546 /// an optional protocol requirement.
3547 AMK_OptionalProtocolImplementation
3548 };
3549
3550 /// Describes the kind of priority given to an availability attribute.
3551 ///
3552 /// The sum of priorities deteremines the final priority of the attribute.
3553 /// The final priority determines how the attribute will be merged.
3554 /// An attribute with a lower priority will always remove higher priority
3555 /// attributes for the specified platform when it is being applied. An
3556 /// attribute with a higher priority will not be applied if the declaration
3557 /// already has an availability attribute with a lower priority for the
3558 /// specified platform. The final prirority values are not expected to match
3559 /// the values in this enumeration, but instead should be treated as a plain
3560 /// integer value. This enumeration just names the priority weights that are
3561 /// used to calculate that final vaue.
3562 enum AvailabilityPriority : int {
3563 /// The availability attribute was specified explicitly next to the
3564 /// declaration.
3565 AP_Explicit = 0,
3566
3567 /// The availability attribute was applied using '#pragma clang attribute'.
3568 AP_PragmaClangAttribute = 1,
3569
3570 /// The availability attribute for a specific platform was inferred from
3571 /// an availability attribute for another platform.
3572 AP_InferredFromOtherPlatform = 2
3573 };
3574
3575 /// Attribute merging methods. Return true if a new attribute was added.
3576 AvailabilityAttr *
3577 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3578 IdentifierInfo *Platform, bool Implicit,
3579 VersionTuple Introduced, VersionTuple Deprecated,
3580 VersionTuple Obsoleted, bool IsUnavailable,
3581 StringRef Message, bool IsStrict, StringRef Replacement,
3582 AvailabilityMergeKind AMK, int Priority);
3583 TypeVisibilityAttr *
3584 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3585 TypeVisibilityAttr::VisibilityType Vis);
3586 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3587 VisibilityAttr::VisibilityType Vis);
3588 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3589 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3590 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3591 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3592 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3593 const AttributeCommonInfo &CI,
3594 bool BestCase,
3595 MSInheritanceModel Model);
3596 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3597 StringRef NewUserDiagnostic);
3598 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3599 IdentifierInfo *Format, int FormatIdx,
3600 int FirstArg);
3601 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3602 StringRef Name);
3603 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3604 StringRef Name);
3605 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3606 const AttributeCommonInfo &CI,
3607 const IdentifierInfo *Ident);
3608 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3609 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3610 StringRef Name);
3611 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3612 const AttributeCommonInfo &CI);
3613 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3614 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3615 const InternalLinkageAttr &AL);
3616 WebAssemblyImportNameAttr *mergeImportNameAttr(
3617 Decl *D, const WebAssemblyImportNameAttr &AL);
3618 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3619 Decl *D, const WebAssemblyImportModuleAttr &AL);
3620