Bug Summary

File:clang/include/clang/AST/ExprCXX.h
Warning:line 4695, column 18
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 -disable-llvm-verifier -discard-value-names -main-file-name SemaCoroutine.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/llvm/include -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-13/lib/clang/13.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 -O2 -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-07-26-235520-9401-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp

/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp

1//===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//
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++ Coroutines.
10//
11// This file contains references to sections of the Coroutines TS, which
12// can be found at http://wg21.link/coroutines.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CoroutineStmtBuilder.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/StmtCXX.h"
21#include "clang/Basic/Builtins.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Overload.h"
25#include "clang/Sema/ScopeInfo.h"
26#include "clang/Sema/SemaInternal.h"
27#include "llvm/ADT/SmallSet.h"
28
29using namespace clang;
30using namespace sema;
31
32static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
33 SourceLocation Loc, bool &Res) {
34 DeclarationName DN = S.PP.getIdentifierInfo(Name);
35 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
36 // Suppress diagnostics when a private member is selected. The same warnings
37 // will be produced again when building the call.
38 LR.suppressDiagnostics();
39 Res = S.LookupQualifiedName(LR, RD);
40 return LR;
41}
42
43static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
44 SourceLocation Loc) {
45 bool Res;
46 lookupMember(S, Name, RD, Loc, Res);
47 return Res;
48}
49
50/// Look up the std::coroutine_traits<...>::promise_type for the given
51/// function type.
52static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
53 SourceLocation KwLoc) {
54 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
55 const SourceLocation FuncLoc = FD->getLocation();
56 // FIXME: Cache std::coroutine_traits once we've found it.
57 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
58 if (!StdExp) {
59 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
60 << "std::experimental::coroutine_traits";
61 return QualType();
62 }
63
64 ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
65 if (!CoroTraits) {
66 return QualType();
67 }
68
69 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
70 // to [dcl.fct.def.coroutine]3
71 TemplateArgumentListInfo Args(KwLoc, KwLoc);
72 auto AddArg = [&](QualType T) {
73 Args.addArgument(TemplateArgumentLoc(
74 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
75 };
76 AddArg(FnType->getReturnType());
77 // If the function is a non-static member function, add the type
78 // of the implicit object parameter before the formal parameters.
79 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
80 if (MD->isInstance()) {
81 // [over.match.funcs]4
82 // For non-static member functions, the type of the implicit object
83 // parameter is
84 // -- "lvalue reference to cv X" for functions declared without a
85 // ref-qualifier or with the & ref-qualifier
86 // -- "rvalue reference to cv X" for functions declared with the &&
87 // ref-qualifier
88 QualType T = MD->getThisType()->castAs<PointerType>()->getPointeeType();
89 T = FnType->getRefQualifier() == RQ_RValue
90 ? S.Context.getRValueReferenceType(T)
91 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
92 AddArg(T);
93 }
94 }
95 for (QualType T : FnType->getParamTypes())
96 AddArg(T);
97
98 // Build the template-id.
99 QualType CoroTrait =
100 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
101 if (CoroTrait.isNull())
102 return QualType();
103 if (S.RequireCompleteType(KwLoc, CoroTrait,
104 diag::err_coroutine_type_missing_specialization))
105 return QualType();
106
107 auto *RD = CoroTrait->getAsCXXRecordDecl();
108 assert(RD && "specialization of class template is not a class?")(static_cast <bool> (RD && "specialization of class template is not a class?"
) ? void (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 108, __extension__ __PRETTY_FUNCTION__))
;
109
110 // Look up the ::promise_type member.
111 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
112 Sema::LookupOrdinaryName);
113 S.LookupQualifiedName(R, RD);
114 auto *Promise = R.getAsSingle<TypeDecl>();
115 if (!Promise) {
116 S.Diag(FuncLoc,
117 diag::err_implied_std_coroutine_traits_promise_type_not_found)
118 << RD;
119 return QualType();
120 }
121 // The promise type is required to be a class type.
122 QualType PromiseType = S.Context.getTypeDeclType(Promise);
123
124 auto buildElaboratedType = [&]() {
125 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
126 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
127 CoroTrait.getTypePtr());
128 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
129 };
130
131 if (!PromiseType->getAsCXXRecordDecl()) {
132 S.Diag(FuncLoc,
133 diag::err_implied_std_coroutine_traits_promise_type_not_class)
134 << buildElaboratedType();
135 return QualType();
136 }
137 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
138 diag::err_coroutine_promise_type_incomplete))
139 return QualType();
140
141 return PromiseType;
142}
143
144/// Look up the std::experimental::coroutine_handle<PromiseType>.
145static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
146 SourceLocation Loc) {
147 if (PromiseType.isNull())
148 return QualType();
149
150 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
151 assert(StdExp && "Should already be diagnosed")(static_cast <bool> (StdExp && "Should already be diagnosed"
) ? void (0) : __assert_fail ("StdExp && \"Should already be diagnosed\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 151, __extension__ __PRETTY_FUNCTION__))
;
152
153 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
154 Loc, Sema::LookupOrdinaryName);
155 if (!S.LookupQualifiedName(Result, StdExp)) {
156 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
157 << "std::experimental::coroutine_handle";
158 return QualType();
159 }
160
161 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
162 if (!CoroHandle) {
163 Result.suppressDiagnostics();
164 // We found something weird. Complain about the first thing we found.
165 NamedDecl *Found = *Result.begin();
166 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
167 return QualType();
168 }
169
170 // Form template argument list for coroutine_handle<Promise>.
171 TemplateArgumentListInfo Args(Loc, Loc);
172 Args.addArgument(TemplateArgumentLoc(
173 TemplateArgument(PromiseType),
174 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
175
176 // Build the template-id.
177 QualType CoroHandleType =
178 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
179 if (CoroHandleType.isNull())
180 return QualType();
181 if (S.RequireCompleteType(Loc, CoroHandleType,
182 diag::err_coroutine_type_missing_specialization))
183 return QualType();
184
185 return CoroHandleType;
186}
187
188static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
189 StringRef Keyword) {
190 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
191 // a function body.
192 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
193 // appear in a default argument." But the diagnostic QoI here could be
194 // improved to inform the user that default arguments specifically are not
195 // allowed.
196 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
9
Assuming field 'CurContext' is a 'FunctionDecl'
197 if (!FD
9.1
'FD' is non-null
9.1
'FD' is non-null
9.1
'FD' is non-null
9.1
'FD' is non-null
) {
10
Taking false branch
198 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
199 ? diag::err_coroutine_objc_method
200 : diag::err_coroutine_outside_function) << Keyword;
201 return false;
202 }
203
204 // An enumeration for mapping the diagnostic type to the correct diagnostic
205 // selection index.
206 enum InvalidFuncDiag {
207 DiagCtor = 0,
208 DiagDtor,
209 DiagMain,
210 DiagConstexpr,
211 DiagAutoRet,
212 DiagVarargs,
213 DiagConsteval,
214 };
215 bool Diagnosed = false;
216 auto DiagInvalid = [&](InvalidFuncDiag ID) {
217 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
218 Diagnosed = true;
219 return false;
220 };
221
222 // Diagnose when a constructor, destructor
223 // or the function 'main' are declared as a coroutine.
224 auto *MD = dyn_cast<CXXMethodDecl>(FD);
11
Assuming 'FD' is not a 'CXXMethodDecl'
225 // [class.ctor]p11: "A constructor shall not be a coroutine."
226 if (MD
11.1
'MD' is null
11.1
'MD' is null
11.1
'MD' is null
11.1
'MD' is null
&& isa<CXXConstructorDecl>(MD))
227 return DiagInvalid(DiagCtor);
228 // [class.dtor]p17: "A destructor shall not be a coroutine."
229 else if (MD
11.2
'MD' is null
11.2
'MD' is null
11.2
'MD' is null
11.2
'MD' is null
&& isa<CXXDestructorDecl>(MD))
230 return DiagInvalid(DiagDtor);
231 // [basic.start.main]p3: "The function main shall not be a coroutine."
232 else if (FD->isMain())
12
Assuming the condition is false
13
Taking false branch
233 return DiagInvalid(DiagMain);
234
235 // Emit a diagnostics for each of the following conditions which is not met.
236 // [expr.const]p2: "An expression e is a core constant expression unless the
237 // evaluation of e [...] would evaluate one of the following expressions:
238 // [...] an await-expression [...] a yield-expression."
239 if (FD->isConstexpr())
14
Taking false branch
240 DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
241 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
242 // placeholder type shall not be a coroutine."
243 if (FD->getReturnType()->isUndeducedType())
15
Taking false branch
244 DiagInvalid(DiagAutoRet);
245 // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
246 // coroutine shall not terminate with an ellipsis that is not part of a
247 // parameter-declaration."
248 if (FD->isVariadic())
16
Assuming the condition is false
17
Taking false branch
249 DiagInvalid(DiagVarargs);
250
251 return !Diagnosed;
18
Returning the value 1, which participates in a condition later
252}
253
254static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
255 SourceLocation Loc) {
256 DeclarationName OpName =
257 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
258 LookupResult Operators(SemaRef, OpName, SourceLocation(),
259 Sema::LookupOperatorName);
260 SemaRef.LookupName(Operators, S);
261
262 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous")(static_cast <bool> (!Operators.isAmbiguous() &&
"Operator lookup cannot be ambiguous") ? void (0) : __assert_fail
("!Operators.isAmbiguous() && \"Operator lookup cannot be ambiguous\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 262, __extension__ __PRETTY_FUNCTION__))
;
263 const auto &Functions = Operators.asUnresolvedSet();
264 bool IsOverloaded =
265 Functions.size() > 1 ||
266 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
267 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
268 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
269 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
270 Functions.begin(), Functions.end());
271 assert(CoawaitOp)(static_cast <bool> (CoawaitOp) ? void (0) : __assert_fail
("CoawaitOp", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 271, __extension__ __PRETTY_FUNCTION__))
;
272 return CoawaitOp;
273}
274
275/// Build a call to 'operator co_await' if there is a suitable operator for
276/// the given expression.
277static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
278 Expr *E,
279 UnresolvedLookupExpr *Lookup) {
280 UnresolvedSet<16> Functions;
281 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
282 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
283}
284
285static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
286 SourceLocation Loc, Expr *E) {
287 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
288 if (R.isInvalid())
289 return ExprError();
290 return buildOperatorCoawaitCall(SemaRef, Loc, E,
291 cast<UnresolvedLookupExpr>(R.get()));
292}
293
294static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
295 SourceLocation Loc) {
296 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
297 if (CoroHandleType.isNull())
298 return ExprError();
299
300 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
301 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
302 Sema::LookupOrdinaryName);
303 if (!S.LookupQualifiedName(Found, LookupCtx)) {
304 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
305 << "from_address";
306 return ExprError();
307 }
308
309 Expr *FramePtr =
310 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
311
312 CXXScopeSpec SS;
313 ExprResult FromAddr =
314 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
315 if (FromAddr.isInvalid())
316 return ExprError();
317
318 return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
319}
320
321struct ReadySuspendResumeResult {
322 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
323 Expr *Results[3];
324 OpaqueValueExpr *OpaqueValue;
325 bool IsInvalid;
326};
327
328static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
329 StringRef Name, MultiExprArg Args) {
330 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
331
332 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
333 CXXScopeSpec SS;
334 ExprResult Result = S.BuildMemberReferenceExpr(
335 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
336 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
337 /*Scope=*/nullptr);
338 if (Result.isInvalid())
339 return ExprError();
340
341 // We meant exactly what we asked for. No need for typo correction.
342 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
343 S.clearDelayedTypo(TE);
344 S.Diag(Loc, diag::err_no_member)
345 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
346 << Base->getSourceRange();
347 return ExprError();
348 }
349
350 return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
351}
352
353// See if return type is coroutine-handle and if so, invoke builtin coro-resume
354// on its address. This is to enable experimental support for coroutine-handle
355// returning await_suspend that results in a guaranteed tail call to the target
356// coroutine.
357static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
358 SourceLocation Loc) {
359 if (RetType->isReferenceType())
360 return nullptr;
361 Type const *T = RetType.getTypePtr();
362 if (!T->isClassType() && !T->isStructureType())
363 return nullptr;
364
365 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
366 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
367 // a private function in SemaExprCXX.cpp
368
369 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
370 if (AddressExpr.isInvalid())
371 return nullptr;
372
373 Expr *JustAddress = AddressExpr.get();
374
375 // Check that the type of AddressExpr is void*
376 if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
377 S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),
378 diag::warn_coroutine_handle_address_invalid_return_type)
379 << JustAddress->getType();
380
381 // Clean up temporary objects so that they don't live across suspension points
382 // unnecessarily. We choose to clean up before the call to
383 // __builtin_coro_resume so that the cleanup code are not inserted in-between
384 // the resume call and return instruction, which would interfere with the
385 // musttail call contract.
386 JustAddress = S.MaybeCreateExprWithCleanups(JustAddress);
387 return S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_resume,
388 JustAddress);
389}
390
391/// Build calls to await_ready, await_suspend, and await_resume for a co_await
392/// expression.
393/// The generated AST tries to clean up temporary objects as early as
394/// possible so that they don't live across suspension points if possible.
395/// Having temporary objects living across suspension points unnecessarily can
396/// lead to large frame size, and also lead to memory corruptions if the
397/// coroutine frame is destroyed after coming back from suspension. This is done
398/// by wrapping both the await_ready call and the await_suspend call with
399/// ExprWithCleanups. In the end of this function, we also need to explicitly
400/// set cleanup state so that the CoawaitExpr is also wrapped with an
401/// ExprWithCleanups to clean up the awaiter associated with the co_await
402/// expression.
403static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
404 SourceLocation Loc, Expr *E) {
405 OpaqueValueExpr *Operand = new (S.Context)
406 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
407
408 // Assume valid until we see otherwise.
409 // Further operations are responsible for setting IsInalid to true.
410 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/false};
411
412 using ACT = ReadySuspendResumeResult::AwaitCallType;
413
414 auto BuildSubExpr = [&](ACT CallType, StringRef Func,
415 MultiExprArg Arg) -> Expr * {
416 ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);
417 if (Result.isInvalid()) {
418 Calls.IsInvalid = true;
419 return nullptr;
420 }
421 Calls.Results[CallType] = Result.get();
422 return Result.get();
423 };
424
425 CallExpr *AwaitReady =
426 cast_or_null<CallExpr>(BuildSubExpr(ACT::ACT_Ready, "await_ready", None));
57
Assuming null pointer is passed into cast
427 if (!AwaitReady
57.1
'AwaitReady' is null
57.1
'AwaitReady' is null
57.1
'AwaitReady' is null
57.1
'AwaitReady' is null
)
58
Taking true branch
428 return Calls;
59
The value 0 is assigned to 'RSS.IsInvalid', which participates in a condition later
60
Storing null pointer value
429 if (!AwaitReady->getType()->isDependentType()) {
430 // [expr.await]p3 [...]
431 // — await-ready is the expression e.await_ready(), contextually converted
432 // to bool.
433 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
434 if (Conv.isInvalid()) {
435 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
436 diag::note_await_ready_no_bool_conversion);
437 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
438 << AwaitReady->getDirectCallee() << E->getSourceRange();
439 Calls.IsInvalid = true;
440 } else
441 Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());
442 }
443
444 ExprResult CoroHandleRes =
445 buildCoroutineHandle(S, CoroPromise->getType(), Loc);
446 if (CoroHandleRes.isInvalid()) {
447 Calls.IsInvalid = true;
448 return Calls;
449 }
450 Expr *CoroHandle = CoroHandleRes.get();
451 CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
452 BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
453 if (!AwaitSuspend)
454 return Calls;
455 if (!AwaitSuspend->getType()->isDependentType()) {
456 // [expr.await]p3 [...]
457 // - await-suspend is the expression e.await_suspend(h), which shall be
458 // a prvalue of type void, bool, or std::coroutine_handle<Z> for some
459 // type Z.
460 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
461
462 // Experimental support for coroutine_handle returning await_suspend.
463 if (Expr *TailCallSuspend =
464 maybeTailCall(S, RetType, AwaitSuspend, Loc))
465 // Note that we don't wrap the expression with ExprWithCleanups here
466 // because that might interfere with tailcall contract (e.g. inserting
467 // clean up instructions in-between tailcall and return). Instead
468 // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
469 // call.
470 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
471 else {
472 // non-class prvalues always have cv-unqualified types
473 if (RetType->isReferenceType() ||
474 (!RetType->isBooleanType() && !RetType->isVoidType())) {
475 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
476 diag::err_await_suspend_invalid_return_type)
477 << RetType;
478 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
479 << AwaitSuspend->getDirectCallee();
480 Calls.IsInvalid = true;
481 } else
482 Calls.Results[ACT::ACT_Suspend] =
483 S.MaybeCreateExprWithCleanups(AwaitSuspend);
484 }
485 }
486
487 BuildSubExpr(ACT::ACT_Resume, "await_resume", None);
488
489 // Make sure the awaiter object gets a chance to be cleaned up.
490 S.Cleanup.setExprNeedsCleanups(true);
491
492 return Calls;
493}
494
495static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
496 SourceLocation Loc, StringRef Name,
497 MultiExprArg Args) {
498
499 // Form a reference to the promise.
500 ExprResult PromiseRef = S.BuildDeclRefExpr(
501 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
502 if (PromiseRef.isInvalid())
503 return ExprError();
504
505 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
506}
507
508VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
509 assert(isa<FunctionDecl>(CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(CurContext) && \"not in a function scope\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 509, __extension__ __PRETTY_FUNCTION__))
;
510 auto *FD = cast<FunctionDecl>(CurContext);
511 bool IsThisDependentType = [&] {
512 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
513 return MD->isInstance() && MD->getThisType()->isDependentType();
514 else
515 return false;
516 }();
517
518 QualType T = FD->getType()->isDependentType() || IsThisDependentType
519 ? Context.DependentTy
520 : lookupPromiseType(*this, FD, Loc);
521 if (T.isNull())
522 return nullptr;
523
524 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
525 &PP.getIdentifierTable().get("__promise"), T,
526 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
527 VD->setImplicit();
528 CheckVariableDeclarationType(VD);
529 if (VD->isInvalidDecl())
530 return nullptr;
531
532 auto *ScopeInfo = getCurFunction();
533
534 // Build a list of arguments, based on the coroutine function's arguments,
535 // that if present will be passed to the promise type's constructor.
536 llvm::SmallVector<Expr *, 4> CtorArgExprs;
537
538 // Add implicit object parameter.
539 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
540 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
541 ExprResult ThisExpr = ActOnCXXThis(Loc);
542 if (ThisExpr.isInvalid())
543 return nullptr;
544 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
545 if (ThisExpr.isInvalid())
546 return nullptr;
547 CtorArgExprs.push_back(ThisExpr.get());
548 }
549 }
550
551 // Add the coroutine function's parameters.
552 auto &Moves = ScopeInfo->CoroutineParameterMoves;
553 for (auto *PD : FD->parameters()) {
554 if (PD->getType()->isDependentType())
555 continue;
556
557 auto RefExpr = ExprEmpty();
558 auto Move = Moves.find(PD);
559 assert(Move != Moves.end() &&(static_cast <bool> (Move != Moves.end() && "Coroutine function parameter not inserted into move map"
) ? void (0) : __assert_fail ("Move != Moves.end() && \"Coroutine function parameter not inserted into move map\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 560, __extension__ __PRETTY_FUNCTION__))
560 "Coroutine function parameter not inserted into move map")(static_cast <bool> (Move != Moves.end() && "Coroutine function parameter not inserted into move map"
) ? void (0) : __assert_fail ("Move != Moves.end() && \"Coroutine function parameter not inserted into move map\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 560, __extension__ __PRETTY_FUNCTION__))
;
561 // If a reference to the function parameter exists in the coroutine
562 // frame, use that reference.
563 auto *MoveDecl =
564 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
565 RefExpr =
566 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
567 ExprValueKind::VK_LValue, FD->getLocation());
568 if (RefExpr.isInvalid())
569 return nullptr;
570 CtorArgExprs.push_back(RefExpr.get());
571 }
572
573 // If we have a non-zero number of constructor arguments, try to use them.
574 // Otherwise, fall back to the promise type's default constructor.
575 if (!CtorArgExprs.empty()) {
576 // Create an initialization sequence for the promise type using the
577 // constructor arguments, wrapped in a parenthesized list expression.
578 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
579 CtorArgExprs, FD->getLocation());
580 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
581 InitializationKind Kind = InitializationKind::CreateForInit(
582 VD->getLocation(), /*DirectInit=*/true, PLE);
583 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
584 /*TopLevelOfInitList=*/false,
585 /*TreatUnavailableAsInvalid=*/false);
586
587 // Attempt to initialize the promise type with the arguments.
588 // If that fails, fall back to the promise type's default constructor.
589 if (InitSeq) {
590 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
591 if (Result.isInvalid()) {
592 VD->setInvalidDecl();
593 } else if (Result.get()) {
594 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
595 VD->setInitStyle(VarDecl::CallInit);
596 CheckCompleteVariableDeclaration(VD);
597 }
598 } else
599 ActOnUninitializedDecl(VD);
600 } else
601 ActOnUninitializedDecl(VD);
602
603 FD->addDecl(VD);
604 return VD;
605}
606
607/// Check that this is a context in which a coroutine suspension can appear.
608static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
609 StringRef Keyword,
610 bool IsImplicit = false) {
611 if (!isValidCoroutineContext(S, Loc, Keyword))
8
Calling 'isValidCoroutineContext'
19
Returning from 'isValidCoroutineContext'
20
Taking false branch
612 return nullptr;
613
614 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(S.CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(S.CurContext) && \"not in a function scope\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 614, __extension__ __PRETTY_FUNCTION__))
;
21
Field 'CurContext' is a 'FunctionDecl'
22
'?' condition is true
615
616 auto *ScopeInfo = S.getCurFunction();
23
Calling 'Sema::getCurFunction'
26
Returning from 'Sema::getCurFunction'
617 assert(ScopeInfo && "missing function scope for function")(static_cast <bool> (ScopeInfo && "missing function scope for function"
) ? void (0) : __assert_fail ("ScopeInfo && \"missing function scope for function\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 617, __extension__ __PRETTY_FUNCTION__))
;
27
Assuming 'ScopeInfo' is non-null
28
'?' condition is true
618
619 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
620 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
621
622 if (ScopeInfo->CoroutinePromise)
29
Assuming field 'CoroutinePromise' is null
30
Taking false branch
623 return ScopeInfo;
624
625 if (!S.buildCoroutineParameterMoves(Loc))
31
Calling 'Sema::buildCoroutineParameterMoves'
39
Returning from 'Sema::buildCoroutineParameterMoves'
40
Taking false branch
626 return nullptr;
627
628 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
629 if (!ScopeInfo->CoroutinePromise)
41
Assuming field 'CoroutinePromise' is non-null
42
Taking false branch
630 return nullptr;
631
632 return ScopeInfo;
43
Returning pointer (loaded from 'ScopeInfo'), which participates in a condition later
633}
634
635/// Recursively check \p E and all its children to see if any call target
636/// (including constructor call) is declared noexcept. Also any value returned
637/// from the call has a noexcept destructor.
638static void checkNoThrow(Sema &S, const Stmt *E,
639 llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
640 auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
641 // In the case of dtor, the call to dtor is implicit and hence we should
642 // pass nullptr to canCalleeThrow.
643 if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {
644 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
645 // co_await promise.final_suspend() could end up calling
646 // __builtin_coro_resume for symmetric transfer if await_suspend()
647 // returns a handle. In that case, even __builtin_coro_resume is not
648 // declared as noexcept and may throw, it does not throw _into_ the
649 // coroutine that just suspended, but rather throws back out from
650 // whoever called coroutine_handle::resume(), hence we claim that
651 // logically it does not throw.
652 if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
653 return;
654 }
655 if (ThrowingDecls.empty()) {
656 // First time seeing an error, emit the error message.
657 S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),
658 diag::err_coroutine_promise_final_suspend_requires_nothrow);
659 }
660 ThrowingDecls.insert(D);
661 }
662 };
663 auto SC = E->getStmtClass();
664 if (SC == Expr::CXXConstructExprClass) {
665 auto const *Ctor = cast<CXXConstructExpr>(E)->getConstructor();
666 checkDeclNoexcept(Ctor);
667 // Check the corresponding destructor of the constructor.
668 checkDeclNoexcept(Ctor->getParent()->getDestructor(), true);
669 } else if (SC == Expr::CallExprClass || SC == Expr::CXXMemberCallExprClass ||
670 SC == Expr::CXXOperatorCallExprClass) {
671 if (!cast<CallExpr>(E)->isTypeDependent()) {
672 checkDeclNoexcept(cast<CallExpr>(E)->getCalleeDecl());
673 auto ReturnType = cast<CallExpr>(E)->getCallReturnType(S.getASTContext());
674 // Check the destructor of the call return type, if any.
675 if (ReturnType.isDestructedType() ==
676 QualType::DestructionKind::DK_cxx_destructor) {
677 const auto *T =
678 cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());
679 checkDeclNoexcept(
680 dyn_cast<CXXRecordDecl>(T->getDecl())->getDestructor(), true);
681 }
682 }
683 }
684 for (const auto *Child : E->children()) {
685 if (!Child)
686 continue;
687 checkNoThrow(S, Child, ThrowingDecls);
688 }
689}
690
691bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
692 llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
693 // We first collect all declarations that should not throw but not declared
694 // with noexcept. We then sort them based on the location before printing.
695 // This is to avoid emitting the same note multiple times on the same
696 // declaration, and also provide a deterministic order for the messages.
697 checkNoThrow(*this, FinalSuspend, ThrowingDecls);
698 auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
699 ThrowingDecls.end()};
700 sort(SortedDecls, [](const Decl *A, const Decl *B) {
701 return A->getEndLoc() < B->getEndLoc();
702 });
703 for (const auto *D : SortedDecls) {
704 Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);
705 }
706 return ThrowingDecls.empty();
707}
708
709bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
710 StringRef Keyword) {
711 if (!checkCoroutineContext(*this, KWLoc, Keyword))
712 return false;
713 auto *ScopeInfo = getCurFunction();
714 assert(ScopeInfo->CoroutinePromise)(static_cast <bool> (ScopeInfo->CoroutinePromise) ? void
(0) : __assert_fail ("ScopeInfo->CoroutinePromise", "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 714, __extension__ __PRETTY_FUNCTION__))
;
715
716 // If we have existing coroutine statements then we have already built
717 // the initial and final suspend points.
718 if (!ScopeInfo->NeedsCoroutineSuspends)
719 return true;
720
721 ScopeInfo->setNeedsCoroutineSuspends(false);
722
723 auto *Fn = cast<FunctionDecl>(CurContext);
724 SourceLocation Loc = Fn->getLocation();
725 // Build the initial suspend point
726 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
727 ExprResult Suspend =
728 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
729 if (Suspend.isInvalid())
730 return StmtError();
731 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
732 if (Suspend.isInvalid())
733 return StmtError();
734 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
735 /*IsImplicit*/ true);
736 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
737 if (Suspend.isInvalid()) {
738 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
739 << ((Name == "initial_suspend") ? 0 : 1);
740 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
741 return StmtError();
742 }
743 return cast<Stmt>(Suspend.get());
744 };
745
746 StmtResult InitSuspend = buildSuspends("initial_suspend");
747 if (InitSuspend.isInvalid())
748 return true;
749
750 StmtResult FinalSuspend = buildSuspends("final_suspend");
751 if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))
752 return true;
753
754 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
755
756 return true;
757}
758
759// Recursively walks up the scope hierarchy until either a 'catch' or a function
760// scope is found, whichever comes first.
761static bool isWithinCatchScope(Scope *S) {
762 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
763 // lambdas that use 'co_await' are allowed. The loop below ends when a
764 // function scope is found in order to ensure the following behavior:
765 //
766 // void foo() { // <- function scope
767 // try { //
768 // co_await x; // <- 'co_await' is OK within a function scope
769 // } catch { // <- catch scope
770 // co_await x; // <- 'co_await' is not OK within a catch scope
771 // []() { // <- function scope
772 // co_await x; // <- 'co_await' is OK within a function scope
773 // }();
774 // }
775 // }
776 while (S && !(S->getFlags() & Scope::FnScope)) {
777 if (S->getFlags() & Scope::CatchScope)
778 return true;
779 S = S->getParent();
780 }
781 return false;
782}
783
784// [expr.await]p2, emphasis added: "An await-expression shall appear only in
785// a *potentially evaluated* expression within the compound-statement of a
786// function-body *outside of a handler* [...] A context within a function
787// where an await-expression can appear is called a suspension context of the
788// function."
789static void checkSuspensionContext(Sema &S, SourceLocation Loc,
790 StringRef Keyword) {
791 // First emphasis of [expr.await]p2: must be a potentially evaluated context.
792 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
793 // \c sizeof.
794 if (S.isUnevaluatedContext())
795 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
796
797 // Second emphasis of [expr.await]p2: must be outside of an exception handler.
798 if (isWithinCatchScope(S.getCurScope()))
799 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
800}
801
802ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
803 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
804 CorrectDelayedTyposInExpr(E);
805 return ExprError();
806 }
807
808 checkSuspensionContext(*this, Loc, "co_await");
809
810 if (E->getType()->isPlaceholderType()) {
811 ExprResult R = CheckPlaceholderExpr(E);
812 if (R.isInvalid()) return ExprError();
813 E = R.get();
814 }
815 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
816 if (Lookup.isInvalid())
817 return ExprError();
818 return BuildUnresolvedCoawaitExpr(Loc, E,
819 cast<UnresolvedLookupExpr>(Lookup.get()));
820}
821
822ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E,
823 UnresolvedLookupExpr *Lookup) {
824 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
825 if (!FSI)
826 return ExprError();
827
828 if (E->getType()->isPlaceholderType()) {
829 ExprResult R = CheckPlaceholderExpr(E);
830 if (R.isInvalid())
831 return ExprError();
832 E = R.get();
833 }
834
835 auto *Promise = FSI->CoroutinePromise;
836 if (Promise->getType()->isDependentType()) {
837 Expr *Res =
838 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
839 return Res;
840 }
841
842 auto *RD = Promise->getType()->getAsCXXRecordDecl();
843 if (lookupMember(*this, "await_transform", RD, Loc)) {
844 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
845 if (R.isInvalid()) {
846 Diag(Loc,
847 diag::note_coroutine_promise_implicit_await_transform_required_here)
848 << E->getSourceRange();
849 return ExprError();
850 }
851 E = R.get();
852 }
853 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
854 if (Awaitable.isInvalid())
855 return ExprError();
856
857 return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
858}
859
860ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E,
861 bool IsImplicit) {
862 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
863 if (!Coroutine)
864 return ExprError();
865
866 if (E->getType()->isPlaceholderType()) {
867 ExprResult R = CheckPlaceholderExpr(E);
868 if (R.isInvalid()) return ExprError();
869 E = R.get();
870 }
871
872 if (E->getType()->isDependentType()) {
873 Expr *Res = new (Context)
874 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
875 return Res;
876 }
877
878 // If the expression is a temporary, materialize it as an lvalue so that we
879 // can use it multiple times.
880 if (E->getValueKind() == VK_PRValue)
881 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
882
883 // The location of the `co_await` token cannot be used when constructing
884 // the member call expressions since it's before the location of `Expr`, which
885 // is used as the start of the member call expression.
886 SourceLocation CallLoc = E->getExprLoc();
887
888 // Build the await_ready, await_suspend, await_resume calls.
889 ReadySuspendResumeResult RSS = buildCoawaitCalls(
890 *this, Coroutine->CoroutinePromise, CallLoc, E);
891 if (RSS.IsInvalid)
892 return ExprError();
893
894 Expr *Res =
895 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
896 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
897
898 return Res;
899}
900
901ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
902 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
1
Taking false branch
903 CorrectDelayedTyposInExpr(E);
904 return ExprError();
905 }
906
907 checkSuspensionContext(*this, Loc, "co_yield");
908
909 // Build yield_value call.
910 ExprResult Awaitable = buildPromiseCall(
911 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
912 if (Awaitable.isInvalid())
2
Assuming the condition is false
3
Taking false branch
913 return ExprError();
914
915 // Build 'operator co_await' call.
916 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
917 if (Awaitable.isInvalid())
4
Assuming the condition is false
5
Taking false branch
918 return ExprError();
919
920 return BuildCoyieldExpr(Loc, Awaitable.get());
6
Calling 'Sema::BuildCoyieldExpr'
921}
922ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
923 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
7
Calling 'checkCoroutineContext'
44
Returning from 'checkCoroutineContext'
924 if (!Coroutine
44.1
'Coroutine' is non-null
44.1
'Coroutine' is non-null
44.1
'Coroutine' is non-null
44.1
'Coroutine' is non-null
)
45
Taking false branch
925 return ExprError();
926
927 if (E->getType()->isPlaceholderType()) {
46
Calling 'Type::isPlaceholderType'
50
Returning from 'Type::isPlaceholderType'
51
Taking false branch
928 ExprResult R = CheckPlaceholderExpr(E);
929 if (R.isInvalid()) return ExprError();
930 E = R.get();
931 }
932
933 if (E->getType()->isDependentType()) {
52
Assuming the condition is false
53
Taking false branch
934 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
935 return Res;
936 }
937
938 // If the expression is a temporary, materialize it as an lvalue so that we
939 // can use it multiple times.
940 if (E->getValueKind() == VK_PRValue)
54
Assuming the condition is false
55
Taking false branch
941 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
942
943 // Build the await_ready, await_suspend, await_resume calls.
944 ReadySuspendResumeResult RSS = buildCoawaitCalls(
56
Calling 'buildCoawaitCalls'
61
Returning from 'buildCoawaitCalls'
945 *this, Coroutine->CoroutinePromise, Loc, E);
946 if (RSS.IsInvalid
61.1
Field 'IsInvalid' is false
61.1
Field 'IsInvalid' is false
61.1
Field 'IsInvalid' is false
61.1
Field 'IsInvalid' is false
)
62
Taking false branch
947 return ExprError();
948
949 Expr *Res =
950 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
64
Calling constructor for 'CoyieldExpr'
951 RSS.Results[2], RSS.OpaqueValue);
63
Passing null pointer value via 5th parameter 'Resume'
952
953 return Res;
954}
955
956StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
957 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
958 CorrectDelayedTyposInExpr(E);
959 return StmtError();
960 }
961 return BuildCoreturnStmt(Loc, E);
962}
963
964StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
965 bool IsImplicit) {
966 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
967 if (!FSI)
968 return StmtError();
969
970 if (E && E->getType()->isPlaceholderType() &&
971 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
972 ExprResult R = CheckPlaceholderExpr(E);
973 if (R.isInvalid()) return StmtError();
974 E = R.get();
975 }
976
977 VarDecl *Promise = FSI->CoroutinePromise;
978 ExprResult PC;
979 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
980 getNamedReturnInfo(E, /*ForceCXX2b=*/true);
981 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
982 } else {
983 E = MakeFullDiscardedValueExpr(E).get();
984 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
985 }
986 if (PC.isInvalid())
987 return StmtError();
988
989 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
990
991 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
992 return Res;
993}
994
995/// Look up the std::nothrow object.
996static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
997 NamespaceDecl *Std = S.getStdNamespace();
998 assert(Std && "Should already be diagnosed")(static_cast <bool> (Std && "Should already be diagnosed"
) ? void (0) : __assert_fail ("Std && \"Should already be diagnosed\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 998, __extension__ __PRETTY_FUNCTION__))
;
999
1000 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
1001 Sema::LookupOrdinaryName);
1002 if (!S.LookupQualifiedName(Result, Std)) {
1003 // FIXME: <experimental/coroutine> should have been included already.
1004 // If we require it to include <new> then this diagnostic is no longer
1005 // needed.
1006 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
1007 return nullptr;
1008 }
1009
1010 auto *VD = Result.getAsSingle<VarDecl>();
1011 if (!VD) {
1012 Result.suppressDiagnostics();
1013 // We found something weird. Complain about the first thing we found.
1014 NamedDecl *Found = *Result.begin();
1015 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
1016 return nullptr;
1017 }
1018
1019 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
1020 if (DR.isInvalid())
1021 return nullptr;
1022
1023 return DR.get();
1024}
1025
1026// Find an appropriate delete for the promise.
1027static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc,
1028 QualType PromiseType) {
1029 FunctionDecl *OperatorDelete = nullptr;
1030
1031 DeclarationName DeleteName =
1032 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1033
1034 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
1035 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type")(static_cast <bool> (PointeeRD && "PromiseType must be a CxxRecordDecl type"
) ? void (0) : __assert_fail ("PointeeRD && \"PromiseType must be a CxxRecordDecl type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1035, __extension__ __PRETTY_FUNCTION__))
;
1036
1037 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
1038 return nullptr;
1039
1040 if (!OperatorDelete) {
1041 // Look for a global declaration.
1042 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
1043 const bool Overaligned = false;
1044 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
1045 Overaligned, DeleteName);
1046 }
1047 S.MarkFunctionReferenced(Loc, OperatorDelete);
1048 return OperatorDelete;
1049}
1050
1051
1052void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
1053 FunctionScopeInfo *Fn = getCurFunction();
1054 assert(Fn && Fn->isCoroutine() && "not a coroutine")(static_cast <bool> (Fn && Fn->isCoroutine()
&& "not a coroutine") ? void (0) : __assert_fail ("Fn && Fn->isCoroutine() && \"not a coroutine\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1054, __extension__ __PRETTY_FUNCTION__))
;
1055 if (!Body) {
1056 assert(FD->isInvalidDecl() &&(static_cast <bool> (FD->isInvalidDecl() && "a null body is only allowed for invalid declarations"
) ? void (0) : __assert_fail ("FD->isInvalidDecl() && \"a null body is only allowed for invalid declarations\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1057, __extension__ __PRETTY_FUNCTION__))
1057 "a null body is only allowed for invalid declarations")(static_cast <bool> (FD->isInvalidDecl() && "a null body is only allowed for invalid declarations"
) ? void (0) : __assert_fail ("FD->isInvalidDecl() && \"a null body is only allowed for invalid declarations\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1057, __extension__ __PRETTY_FUNCTION__))
;
1058 return;
1059 }
1060 // We have a function that uses coroutine keywords, but we failed to build
1061 // the promise type.
1062 if (!Fn->CoroutinePromise)
1063 return FD->setInvalidDecl();
1064
1065 if (isa<CoroutineBodyStmt>(Body)) {
1066 // Nothing todo. the body is already a transformed coroutine body statement.
1067 return;
1068 }
1069
1070 // Coroutines [stmt.return]p1:
1071 // A return statement shall not appear in a coroutine.
1072 if (Fn->FirstReturnLoc.isValid()) {
1073 assert(Fn->FirstCoroutineStmtLoc.isValid() &&(static_cast <bool> (Fn->FirstCoroutineStmtLoc.isValid
() && "first coroutine location not set") ? void (0) :
__assert_fail ("Fn->FirstCoroutineStmtLoc.isValid() && \"first coroutine location not set\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1074, __extension__ __PRETTY_FUNCTION__))
1074 "first coroutine location not set")(static_cast <bool> (Fn->FirstCoroutineStmtLoc.isValid
() && "first coroutine location not set") ? void (0) :
__assert_fail ("Fn->FirstCoroutineStmtLoc.isValid() && \"first coroutine location not set\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1074, __extension__ __PRETTY_FUNCTION__))
;
1075 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
1076 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1077 << Fn->getFirstCoroutineStmtKeyword();
1078 }
1079 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
1080 if (Builder.isInvalid() || !Builder.buildStatements())
1081 return FD->setInvalidDecl();
1082
1083 // Build body for the coroutine wrapper statement.
1084 Body = CoroutineBodyStmt::Create(Context, Builder);
1085}
1086
1087CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
1088 sema::FunctionScopeInfo &Fn,
1089 Stmt *Body)
1090 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1091 IsPromiseDependentType(
1092 !Fn.CoroutinePromise ||
1093 Fn.CoroutinePromise->getType()->isDependentType()) {
1094 this->Body = Body;
1095
1096 for (auto KV : Fn.CoroutineParameterMoves)
1097 this->ParamMovesVector.push_back(KV.second);
1098 this->ParamMoves = this->ParamMovesVector;
1099
1100 if (!IsPromiseDependentType) {
1101 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1102 assert(PromiseRecordDecl && "Type should have already been checked")(static_cast <bool> (PromiseRecordDecl && "Type should have already been checked"
) ? void (0) : __assert_fail ("PromiseRecordDecl && \"Type should have already been checked\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1102, __extension__ __PRETTY_FUNCTION__))
;
1103 }
1104 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1105}
1106
1107bool CoroutineStmtBuilder::buildStatements() {
1108 assert(this->IsValid && "coroutine already invalid")(static_cast <bool> (this->IsValid && "coroutine already invalid"
) ? void (0) : __assert_fail ("this->IsValid && \"coroutine already invalid\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1108, __extension__ __PRETTY_FUNCTION__))
;
1109 this->IsValid = makeReturnObject();
1110 if (this->IsValid && !IsPromiseDependentType)
1111 buildDependentStatements();
1112 return this->IsValid;
1113}
1114
1115bool CoroutineStmtBuilder::buildDependentStatements() {
1116 assert(this->IsValid && "coroutine already invalid")(static_cast <bool> (this->IsValid && "coroutine already invalid"
) ? void (0) : __assert_fail ("this->IsValid && \"coroutine already invalid\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1116, __extension__ __PRETTY_FUNCTION__))
;
1117 assert(!this->IsPromiseDependentType &&(static_cast <bool> (!this->IsPromiseDependentType &&
"coroutine cannot have a dependent promise type") ? void (0)
: __assert_fail ("!this->IsPromiseDependentType && \"coroutine cannot have a dependent promise type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1118, __extension__ __PRETTY_FUNCTION__))
1118 "coroutine cannot have a dependent promise type")(static_cast <bool> (!this->IsPromiseDependentType &&
"coroutine cannot have a dependent promise type") ? void (0)
: __assert_fail ("!this->IsPromiseDependentType && \"coroutine cannot have a dependent promise type\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1118, __extension__ __PRETTY_FUNCTION__))
;
1119 this->IsValid = makeOnException() && makeOnFallthrough() &&
1120 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1121 makeNewAndDeleteExpr();
1122 return this->IsValid;
1123}
1124
1125bool CoroutineStmtBuilder::makePromiseStmt() {
1126 // Form a declaration statement for the promise declaration, so that AST
1127 // visitors can more easily find it.
1128 StmtResult PromiseStmt =
1129 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1130 if (PromiseStmt.isInvalid())
1131 return false;
1132
1133 this->Promise = PromiseStmt.get();
1134 return true;
1135}
1136
1137bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1138 if (Fn.hasInvalidCoroutineSuspends())
1139 return false;
1140 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1141 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1142 return true;
1143}
1144
1145static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1146 CXXRecordDecl *PromiseRecordDecl,
1147 FunctionScopeInfo &Fn) {
1148 auto Loc = E->getExprLoc();
1149 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1150 auto *Decl = DeclRef->getDecl();
1151 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1152 if (Method->isStatic())
1153 return true;
1154 else
1155 Loc = Decl->getLocation();
1156 }
1157 }
1158
1159 S.Diag(
1160 Loc,
1161 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1162 << PromiseRecordDecl;
1163 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1164 << Fn.getFirstCoroutineStmtKeyword();
1165 return false;
1166}
1167
1168bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1169 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1170, __extension__ __PRETTY_FUNCTION__))
1170 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1170, __extension__ __PRETTY_FUNCTION__))
;
1171
1172 // [dcl.fct.def.coroutine]/8
1173 // The unqualified-id get_return_object_on_allocation_failure is looked up in
1174 // the scope of class P by class member access lookup (3.4.5). ...
1175 // If an allocation function returns nullptr, ... the coroutine return value
1176 // is obtained by a call to ... get_return_object_on_allocation_failure().
1177
1178 DeclarationName DN =
1179 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1180 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1181 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1182 return true;
1183
1184 CXXScopeSpec SS;
1185 ExprResult DeclNameExpr =
1186 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1187 if (DeclNameExpr.isInvalid())
1188 return false;
1189
1190 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1191 return false;
1192
1193 ExprResult ReturnObjectOnAllocationFailure =
1194 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1195 if (ReturnObjectOnAllocationFailure.isInvalid())
1196 return false;
1197
1198 StmtResult ReturnStmt =
1199 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1200 if (ReturnStmt.isInvalid()) {
1201 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1202 << DN;
1203 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1204 << Fn.getFirstCoroutineStmtKeyword();
1205 return false;
1206 }
1207
1208 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1209 return true;
1210}
1211
1212bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1213 // Form and check allocation and deallocation calls.
1214 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1215, __extension__ __PRETTY_FUNCTION__))
1215 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1215, __extension__ __PRETTY_FUNCTION__))
;
1216 QualType PromiseType = Fn.CoroutinePromise->getType();
1217
1218 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1219 return false;
1220
1221 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1222
1223 // [dcl.fct.def.coroutine]/7
1224 // Lookup allocation functions using a parameter list composed of the
1225 // requested size of the coroutine state being allocated, followed by
1226 // the coroutine function's arguments. If a matching allocation function
1227 // exists, use it. Otherwise, use an allocation function that just takes
1228 // the requested size.
1229
1230 FunctionDecl *OperatorNew = nullptr;
1231 FunctionDecl *OperatorDelete = nullptr;
1232 FunctionDecl *UnusedResult = nullptr;
1233 bool PassAlignment = false;
1234 SmallVector<Expr *, 1> PlacementArgs;
1235
1236 // [dcl.fct.def.coroutine]/7
1237 // "The allocation function’s name is looked up in the scope of P.
1238 // [...] If the lookup finds an allocation function in the scope of P,
1239 // overload resolution is performed on a function call created by assembling
1240 // an argument list. The first argument is the amount of space requested,
1241 // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1242 // arguments."
1243 //
1244 // ...where "p1 ... pn" are defined earlier as:
1245 //
1246 // [dcl.fct.def.coroutine]/3
1247 // "For a coroutine f that is a non-static member function, let P1 denote the
1248 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1249 // of the function parameters; otherwise let P1 ... Pn be the types of the
1250 // function parameters. Let p1 ... pn be lvalues denoting those objects."
1251 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1252 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1253 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1254 if (ThisExpr.isInvalid())
1255 return false;
1256 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1257 if (ThisExpr.isInvalid())
1258 return false;
1259 PlacementArgs.push_back(ThisExpr.get());
1260 }
1261 }
1262 for (auto *PD : FD.parameters()) {
1263 if (PD->getType()->isDependentType())
1264 continue;
1265
1266 // Build a reference to the parameter.
1267 auto PDLoc = PD->getLocation();
1268 ExprResult PDRefExpr =
1269 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1270 ExprValueKind::VK_LValue, PDLoc);
1271 if (PDRefExpr.isInvalid())
1272 return false;
1273
1274 PlacementArgs.push_back(PDRefExpr.get());
1275 }
1276 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1277 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1278 /*isArray*/ false, PassAlignment, PlacementArgs,
1279 OperatorNew, UnusedResult, /*Diagnose*/ false);
1280
1281 // [dcl.fct.def.coroutine]/7
1282 // "If no matching function is found, overload resolution is performed again
1283 // on a function call created by passing just the amount of space required as
1284 // an argument of type std::size_t."
1285 if (!OperatorNew && !PlacementArgs.empty()) {
1286 PlacementArgs.clear();
1287 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1288 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1289 /*isArray*/ false, PassAlignment, PlacementArgs,
1290 OperatorNew, UnusedResult, /*Diagnose*/ false);
1291 }
1292
1293 // [dcl.fct.def.coroutine]/7
1294 // "The allocation function’s name is looked up in the scope of P. If this
1295 // lookup fails, the allocation function’s name is looked up in the global
1296 // scope."
1297 if (!OperatorNew) {
1298 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1299 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1300 /*isArray*/ false, PassAlignment, PlacementArgs,
1301 OperatorNew, UnusedResult);
1302 }
1303
1304 bool IsGlobalOverload =
1305 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1306 // If we didn't find a class-local new declaration and non-throwing new
1307 // was is required then we need to lookup the non-throwing global operator
1308 // instead.
1309 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1310 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1311 if (!StdNoThrow)
1312 return false;
1313 PlacementArgs = {StdNoThrow};
1314 OperatorNew = nullptr;
1315 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1316 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1317 /*isArray*/ false, PassAlignment, PlacementArgs,
1318 OperatorNew, UnusedResult);
1319 }
1320
1321 if (!OperatorNew)
1322 return false;
1323
1324 if (RequiresNoThrowAlloc) {
1325 const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
1326 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1327 S.Diag(OperatorNew->getLocation(),
1328 diag::err_coroutine_promise_new_requires_nothrow)
1329 << OperatorNew;
1330 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1331 << OperatorNew;
1332 return false;
1333 }
1334 }
1335
1336 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
1337 return false;
1338
1339 Expr *FramePtr =
1340 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
1341
1342 Expr *FrameSize =
1343 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_size, {});
1344
1345 // Make new call.
1346
1347 ExprResult NewRef =
1348 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1349 if (NewRef.isInvalid())
1350 return false;
1351
1352 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1353 for (auto Arg : PlacementArgs)
1354 NewArgs.push_back(Arg);
1355
1356 ExprResult NewExpr =
1357 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1358 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
1359 if (NewExpr.isInvalid())
1360 return false;
1361
1362 // Make delete call.
1363
1364 QualType OpDeleteQualType = OperatorDelete->getType();
1365
1366 ExprResult DeleteRef =
1367 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1368 if (DeleteRef.isInvalid())
1369 return false;
1370
1371 Expr *CoroFree =
1372 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1373
1374 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1375
1376 // Check if we need to pass the size.
1377 const auto *OpDeleteType =
1378 OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
1379 if (OpDeleteType->getNumParams() > 1)
1380 DeleteArgs.push_back(FrameSize);
1381
1382 ExprResult DeleteExpr =
1383 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1384 DeleteExpr =
1385 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
1386 if (DeleteExpr.isInvalid())
1387 return false;
1388
1389 this->Allocate = NewExpr.get();
1390 this->Deallocate = DeleteExpr.get();
1391
1392 return true;
1393}
1394
1395bool CoroutineStmtBuilder::makeOnFallthrough() {
1396 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1397, __extension__ __PRETTY_FUNCTION__))
1397 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1397, __extension__ __PRETTY_FUNCTION__))
;
1398
1399 // [dcl.fct.def.coroutine]/4
1400 // The unqualified-ids 'return_void' and 'return_value' are looked up in
1401 // the scope of class P. If both are found, the program is ill-formed.
1402 bool HasRVoid, HasRValue;
1403 LookupResult LRVoid =
1404 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1405 LookupResult LRValue =
1406 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1407
1408 StmtResult Fallthrough;
1409 if (HasRVoid && HasRValue) {
1410 // FIXME Improve this diagnostic
1411 S.Diag(FD.getLocation(),
1412 diag::err_coroutine_promise_incompatible_return_functions)
1413 << PromiseRecordDecl;
1414 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1415 diag::note_member_first_declared_here)
1416 << LRVoid.getLookupName();
1417 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1418 diag::note_member_first_declared_here)
1419 << LRValue.getLookupName();
1420 return false;
1421 } else if (!HasRVoid && !HasRValue) {
1422 // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1423 // However we still diagnose this as an error since until the PDTS is fixed.
1424 S.Diag(FD.getLocation(),
1425 diag::err_coroutine_promise_requires_return_function)
1426 << PromiseRecordDecl;
1427 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1428 << PromiseRecordDecl;
1429 return false;
1430 } else if (HasRVoid) {
1431 // If the unqualified-id return_void is found, flowing off the end of a
1432 // coroutine is equivalent to a co_return with no operand. Otherwise,
1433 // flowing off the end of a coroutine results in undefined behavior.
1434 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1435 /*IsImplicit*/false);
1436 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1437 if (Fallthrough.isInvalid())
1438 return false;
1439 }
1440
1441 this->OnFallthrough = Fallthrough.get();
1442 return true;
1443}
1444
1445bool CoroutineStmtBuilder::makeOnException() {
1446 // Try to form 'p.unhandled_exception();'
1447 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1448, __extension__ __PRETTY_FUNCTION__))
1448 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1448, __extension__ __PRETTY_FUNCTION__))
;
1449
1450 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1451
1452 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1453 auto DiagID =
1454 RequireUnhandledException
1455 ? diag::err_coroutine_promise_unhandled_exception_required
1456 : diag::
1457 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1458 S.Diag(Loc, DiagID) << PromiseRecordDecl;
1459 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1460 << PromiseRecordDecl;
1461 return !RequireUnhandledException;
1462 }
1463
1464 // If exceptions are disabled, don't try to build OnException.
1465 if (!S.getLangOpts().CXXExceptions)
1466 return true;
1467
1468 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1469 "unhandled_exception", None);
1470 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1471 /*DiscardedValue*/ false);
1472 if (UnhandledException.isInvalid())
1473 return false;
1474
1475 // Since the body of the coroutine will be wrapped in try-catch, it will
1476 // be incompatible with SEH __try if present in a function.
1477 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1478 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1479 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1480 << Fn.getFirstCoroutineStmtKeyword();
1481 return false;
1482 }
1483
1484 this->OnException = UnhandledException.get();
1485 return true;
1486}
1487
1488bool CoroutineStmtBuilder::makeReturnObject() {
1489 // Build implicit 'p.get_return_object()' expression and form initialization
1490 // of return type from it.
1491 ExprResult ReturnObject =
1492 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1493 if (ReturnObject.isInvalid())
1494 return false;
1495
1496 this->ReturnValue = ReturnObject.get();
1497 return true;
1498}
1499
1500static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1501 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1502 auto *MethodDecl = MbrRef->getMethodDecl();
1503 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1504 << MethodDecl;
1505 }
1506 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1507 << Fn.getFirstCoroutineStmtKeyword();
1508}
1509
1510bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1511 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1512, __extension__ __PRETTY_FUNCTION__))
1512 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1512, __extension__ __PRETTY_FUNCTION__))
;
1513 assert(this->ReturnValue && "ReturnValue must be already formed")(static_cast <bool> (this->ReturnValue && "ReturnValue must be already formed"
) ? void (0) : __assert_fail ("this->ReturnValue && \"ReturnValue must be already formed\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1513, __extension__ __PRETTY_FUNCTION__))
;
1514
1515 QualType const GroType = this->ReturnValue->getType();
1516 assert(!GroType->isDependentType() &&(static_cast <bool> (!GroType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!GroType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1517, __extension__ __PRETTY_FUNCTION__))
1517 "get_return_object type must no longer be dependent")(static_cast <bool> (!GroType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!GroType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1517, __extension__ __PRETTY_FUNCTION__))
;
1518
1519 QualType const FnRetType = FD.getReturnType();
1520 assert(!FnRetType->isDependentType() &&(static_cast <bool> (!FnRetType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!FnRetType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1521, __extension__ __PRETTY_FUNCTION__))
1521 "get_return_object type must no longer be dependent")(static_cast <bool> (!FnRetType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!FnRetType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1521, __extension__ __PRETTY_FUNCTION__))
;
1522
1523 if (FnRetType->isVoidType()) {
1524 ExprResult Res =
1525 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
1526 if (Res.isInvalid())
1527 return false;
1528
1529 this->ResultDecl = Res.get();
1530 return true;
1531 }
1532
1533 if (GroType->isVoidType()) {
1534 // Trigger a nice error message.
1535 InitializedEntity Entity =
1536 InitializedEntity::InitializeResult(Loc, FnRetType, false);
1537 S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
1538 noteMemberDeclaredHere(S, ReturnValue, Fn);
1539 return false;
1540 }
1541
1542 auto *GroDecl = VarDecl::Create(
1543 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1544 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1545 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1546 GroDecl->setImplicit();
1547
1548 S.CheckVariableDeclarationType(GroDecl);
1549 if (GroDecl->isInvalidDecl())
1550 return false;
1551
1552 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1553 ExprResult Res =
1554 S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
1555 if (Res.isInvalid())
1556 return false;
1557
1558 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
1559 if (Res.isInvalid())
1560 return false;
1561
1562 S.AddInitializerToDecl(GroDecl, Res.get(),
1563 /*DirectInit=*/false);
1564
1565 S.FinalizeDeclaration(GroDecl);
1566
1567 // Form a declaration statement for the return declaration, so that AST
1568 // visitors can more easily find it.
1569 StmtResult GroDeclStmt =
1570 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1571 if (GroDeclStmt.isInvalid())
1572 return false;
1573
1574 this->ResultDecl = GroDeclStmt.get();
1575
1576 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1577 if (declRef.isInvalid())
1578 return false;
1579
1580 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1581 if (ReturnStmt.isInvalid()) {
1582 noteMemberDeclaredHere(S, ReturnValue, Fn);
1583 return false;
1584 }
1585 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1586 GroDecl->setNRVOVariable(true);
1587
1588 this->ReturnStmt = ReturnStmt.get();
1589 return true;
1590}
1591
1592// Create a static_cast\<T&&>(expr).
1593static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1594 if (T.isNull())
1595 T = E->getType();
1596 QualType TargetType = S.BuildReferenceType(
1597 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1598 SourceLocation ExprLoc = E->getBeginLoc();
1599 TypeSourceInfo *TargetLoc =
1600 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1601
1602 return S
1603 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1604 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1605 .get();
1606}
1607
1608/// Build a variable declaration for move parameter.
1609static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1610 IdentifierInfo *II) {
1611 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1612 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1613 TInfo, SC_None);
1614 Decl->setImplicit();
1615 return Decl;
1616}
1617
1618// Build statements that move coroutine function parameters to the coroutine
1619// frame, and store them on the function scope info.
1620bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1621 assert(isa<FunctionDecl>(CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(CurContext) && \"not in a function scope\""
, "/build/llvm-toolchain-snapshot-13~++20210726100616+dead50d4427c/clang/lib/Sema/SemaCoroutine.cpp"
, 1621, __extension__ __PRETTY_FUNCTION__))
;
32
Field 'CurContext' is a 'FunctionDecl'
33
'?' condition is true
1622 auto *FD = cast<FunctionDecl>(CurContext);
34
Field 'CurContext' is a 'FunctionDecl'
1623
1624 auto *ScopeInfo = getCurFunction();
1625 if (!ScopeInfo->CoroutineParameterMoves.empty())
35
Assuming the condition is false
36
Taking false branch
1626 return false;
1627
1628 for (auto *PD : FD->parameters()) {
37
Assuming '__begin1' is equal to '__end1'
1629 if (PD->getType()->isDependentType())
1630 continue;
1631
1632 ExprResult PDRefExpr =
1633 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1634 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1635 if (PDRefExpr.isInvalid())
1636 return false;
1637
1638 Expr *CExpr = nullptr;
1639 if (PD->getType()->getAsCXXRecordDecl() ||
1640 PD->getType()->isRValueReferenceType())
1641 CExpr = castForMoving(*this, PDRefExpr.get());
1642 else
1643 CExpr = PDRefExpr.get();
1644
1645 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1646 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1647
1648 // Convert decl to a statement.
1649 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1650 if (Stmt.isInvalid())
1651 return false;
1652
1653 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1654 }
1655 return true;
38
Returning the value 1, which participates in a condition later
1656}
1657
1658StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1659 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1660 if (!Res)
1661 return StmtError();
1662 return Res;
1663}
1664
1665ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1666 SourceLocation FuncLoc) {
1667 if (!StdCoroutineTraitsCache) {
1668 if (auto StdExp = lookupStdExperimentalNamespace()) {
1669 LookupResult Result(*this,
1670 &PP.getIdentifierTable().get("coroutine_traits"),
1671 FuncLoc, LookupOrdinaryName);
1672 if (!LookupQualifiedName(Result, StdExp)) {
1673 Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1674 << "std::experimental::coroutine_traits";
1675 return nullptr;
1676 }
1677 if (!(StdCoroutineTraitsCache =
1678 Result.getAsSingle<ClassTemplateDecl>())) {
1679 Result.suppressDiagnostics();
1680 NamedDecl *Found = *Result.begin();
1681 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1682 return nullptr;
1683 }
1684 }
1685 }
1686 return StdCoroutineTraitsCache;
1687}

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