Bug Summary

File:clang/include/clang/AST/ExprCXX.h
Warning:line 4693, column 18
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaCoroutine.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -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-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaCoroutine.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaCoroutine.cpp

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

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/Sema/Sema.h

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