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 -fhalf-no-semantic-interposition -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~++20210413100635+64c24f493e5f/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~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/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/6.3.0/../../../../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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f=. -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-04-14-063029-18377-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210413100635+64c24f493e5f/clang/lib/Sema/SemaCoroutine.cpp

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

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