Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include/clang/AST/ExprCXX.h
Warning:line 4710, 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 -clear-ast-before-backend -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 -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-15/lib/clang/15.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/Sema/SemaCoroutine.cpp

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

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/TypeOrdering.h"
38#include "clang/Basic/BitmaskEnum.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/DarwinSDKInfo.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/OpenCLOptions.h"
44#include "clang/Basic/OpenMPKinds.h"
45#include "clang/Basic/PragmaKinds.h"
46#include "clang/Basic/Specifiers.h"
47#include "clang/Basic/TemplateKinds.h"
48#include "clang/Basic/TypeTraits.h"
49#include "clang/Sema/AnalysisBasedWarnings.h"
50#include "clang/Sema/CleanupInfo.h"
51#include "clang/Sema/DeclSpec.h"
52#include "clang/Sema/ExternalSemaSource.h"
53#include "clang/Sema/IdentifierResolver.h"
54#include "clang/Sema/ObjCMethodList.h"
55#include "clang/Sema/Ownership.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaConcept.h"
58#include "clang/Sema/TypoCorrection.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/Optional.h"
62#include "llvm/ADT/SetVector.h"
63#include "llvm/ADT/SmallBitVector.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/SmallSet.h"
66#include "llvm/ADT/SmallVector.h"
67#include "llvm/ADT/TinyPtrVector.h"
68#include "llvm/Frontend/OpenMP/OMPConstants.h"
69#include <deque>
70#include <memory>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
97 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
137 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
149 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
174 enum OverloadCandidateRewriteKind : unsigned;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class SemaPPCallbacks;
230 class TemplateDeductionInfo;
231}
232
233namespace threadSafety {
234 class BeforeSet;
235 void threadSafetyCleanup(BeforeSet* Cache);
236}
237
238// FIXME: No way to easily map from TemplateTypeParmTypes to
239// TemplateTypeParmDecls, so we have this horrible PointerUnion.
240typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>,
241 SourceLocation> UnexpandedParameterPack;
242
243/// Describes whether we've seen any nullability information for the given
244/// file.
245struct FileNullability {
246 /// The first pointer declarator (of any pointer kind) in the file that does
247 /// not have a corresponding nullability annotation.
248 SourceLocation PointerLoc;
249
250 /// The end location for the first pointer declarator in the file. Used for
251 /// placing fix-its.
252 SourceLocation PointerEndLoc;
253
254 /// Which kind of pointer declarator we saw.
255 uint8_t PointerKind;
256
257 /// Whether we saw any type nullability annotations in the given file.
258 bool SawTypeNullability = false;
259};
260
261/// A mapping from file IDs to a record of whether we've seen nullability
262/// information in that file.
263class FileNullabilityMap {
264 /// A mapping from file IDs to the nullability information for each file ID.
265 llvm::DenseMap<FileID, FileNullability> Map;
266
267 /// A single-element cache based on the file ID.
268 struct {
269 FileID File;
270 FileNullability Nullability;
271 } Cache;
272
273public:
274 FileNullability &operator[](FileID file) {
275 // Check the single-element cache.
276 if (file == Cache.File)
277 return Cache.Nullability;
278
279 // It's not in the single-element cache; flush the cache if we have one.
280 if (!Cache.File.isInvalid()) {
281 Map[Cache.File] = Cache.Nullability;
282 }
283
284 // Pull this entry into the cache.
285 Cache.File = file;
286 Cache.Nullability = Map[file];
287 return Cache.Nullability;
288 }
289};
290
291/// Tracks expected type during expression parsing, for use in code completion.
292/// The type is tied to a particular token, all functions that update or consume
293/// the type take a start location of the token they are looking at as a
294/// parameter. This avoids updating the type on hot paths in the parser.
295class PreferredTypeBuilder {
296public:
297 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
298
299 void enterCondition(Sema &S, SourceLocation Tok);
300 void enterReturn(Sema &S, SourceLocation Tok);
301 void enterVariableInit(SourceLocation Tok, Decl *D);
302 /// Handles e.g. BaseType{ .D = Tok...
303 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
304 const Designation &D);
305 /// Computing a type for the function argument may require running
306 /// overloading, so we postpone its computation until it is actually needed.
307 ///
308 /// Clients should be very careful when using this funciton, as it stores a
309 /// function_ref, clients should make sure all calls to get() with the same
310 /// location happen while function_ref is alive.
311 ///
312 /// The callback should also emit signature help as a side-effect, but only
313 /// if the completion point has been reached.
314 void enterFunctionArgument(SourceLocation Tok,
315 llvm::function_ref<QualType()> ComputeType);
316
317 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
318 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
319 SourceLocation OpLoc);
320 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
321 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
322 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
323 /// Handles all type casts, including C-style cast, C++ casts, etc.
324 void enterTypeCast(SourceLocation Tok, QualType CastType);
325
326 /// Get the expected type associated with this location, if any.
327 ///
328 /// If the location is a function argument, determining the expected type
329 /// involves considering all function overloads and the arguments so far.
330 /// In this case, signature help for these function overloads will be reported
331 /// as a side-effect (only if the completion point has been reached).
332 QualType get(SourceLocation Tok) const {
333 if (!Enabled || Tok != ExpectedLoc)
334 return QualType();
335 if (!Type.isNull())
336 return Type;
337 if (ComputeType)
338 return ComputeType();
339 return QualType();
340 }
341
342private:
343 bool Enabled;
344 /// Start position of a token for which we store expected type.
345 SourceLocation ExpectedLoc;
346 /// Expected type for a token starting at ExpectedLoc.
347 QualType Type;
348 /// A function to compute expected type at ExpectedLoc. It is only considered
349 /// if Type is null.
350 llvm::function_ref<QualType()> ComputeType;
351};
352
353/// Sema - This implements semantic analysis and AST building for C.
354class Sema final {
355 Sema(const Sema &) = delete;
356 void operator=(const Sema &) = delete;
357
358 ///Source of additional semantic information.
359 ExternalSemaSource *ExternalSource;
360
361 ///Whether Sema has generated a multiplexer and has to delete it.
362 bool isMultiplexExternalSource;
363
364 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
365
366 bool isVisibleSlow(const NamedDecl *D);
367
368 /// Determine whether two declarations should be linked together, given that
369 /// the old declaration might not be visible and the new declaration might
370 /// not have external linkage.
371 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
372 const NamedDecl *New) {
373 if (isVisible(Old))
374 return true;
375 // See comment in below overload for why it's safe to compute the linkage
376 // of the new declaration here.
377 if (New->isExternallyDeclarable()) {
378 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 379, __extension__ __PRETTY_FUNCTION__
))
379 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 379, __extension__ __PRETTY_FUNCTION__
))
;
380 return true;
381 }
382 return false;
383 }
384 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
385
386 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
387 QualType ResultTy,
388 ArrayRef<QualType> Args);
389
390public:
391 /// The maximum alignment, same as in llvm::Value. We duplicate them here
392 /// because that allows us not to duplicate the constants in clang code,
393 /// which we must to since we can't directly use the llvm constants.
394 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
395 ///
396 /// This is the greatest alignment value supported by load, store, and alloca
397 /// instructions, and global values.
398 static const unsigned MaxAlignmentExponent = 32;
399 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
400
401 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
402 typedef OpaquePtr<TemplateName> TemplateTy;
403 typedef OpaquePtr<QualType> TypeTy;
404
405 OpenCLOptions OpenCLFeatures;
406 FPOptions CurFPFeatures;
407
408 const LangOptions &LangOpts;
409 Preprocessor &PP;
410 ASTContext &Context;
411 ASTConsumer &Consumer;
412 DiagnosticsEngine &Diags;
413 SourceManager &SourceMgr;
414
415 /// Flag indicating whether or not to collect detailed statistics.
416 bool CollectStats;
417
418 /// Code-completion consumer.
419 CodeCompleteConsumer *CodeCompleter;
420
421 /// CurContext - This is the current declaration context of parsing.
422 DeclContext *CurContext;
423
424 /// Generally null except when we temporarily switch decl contexts,
425 /// like in \see ActOnObjCTemporaryExitContainerContext.
426 DeclContext *OriginalLexicalContext;
427
428 /// VAListTagName - The declaration name corresponding to __va_list_tag.
429 /// This is used as part of a hack to omit that class from ADL results.
430 DeclarationName VAListTagName;
431
432 bool MSStructPragmaOn; // True when \#pragma ms_struct on
433
434 /// Controls member pointer representation format under the MS ABI.
435 LangOptions::PragmaMSPointersToMembersKind
436 MSPointerToMemberRepresentationMethod;
437
438 /// Stack of active SEH __finally scopes. Can be empty.
439 SmallVector<Scope*, 2> CurrentSEHFinally;
440
441 /// Source location for newly created implicit MSInheritanceAttrs
442 SourceLocation ImplicitMSInheritanceAttrLoc;
443
444 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
445 /// `TransformTypos` in order to keep track of any TypoExprs that are created
446 /// recursively during typo correction and wipe them away if the correction
447 /// fails.
448 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
449
450 /// pragma clang section kind
451 enum PragmaClangSectionKind {
452 PCSK_Invalid = 0,
453 PCSK_BSS = 1,
454 PCSK_Data = 2,
455 PCSK_Rodata = 3,
456 PCSK_Text = 4,
457 PCSK_Relro = 5
458 };
459
460 enum PragmaClangSectionAction {
461 PCSA_Set = 0,
462 PCSA_Clear = 1
463 };
464
465 struct PragmaClangSection {
466 std::string SectionName;
467 bool Valid = false;
468 SourceLocation PragmaLocation;
469 };
470
471 PragmaClangSection PragmaClangBSSSection;
472 PragmaClangSection PragmaClangDataSection;
473 PragmaClangSection PragmaClangRodataSection;
474 PragmaClangSection PragmaClangRelroSection;
475 PragmaClangSection PragmaClangTextSection;
476
477 enum PragmaMsStackAction {
478 PSK_Reset = 0x0, // #pragma ()
479 PSK_Set = 0x1, // #pragma (value)
480 PSK_Push = 0x2, // #pragma (push[, id])
481 PSK_Pop = 0x4, // #pragma (pop[, id])
482 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
483 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
484 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
485 };
486
487 // #pragma pack and align.
488 class AlignPackInfo {
489 public:
490 // `Native` represents default align mode, which may vary based on the
491 // platform.
492 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
493
494 // #pragma pack info constructor
495 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
496 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
497 assert(Num == PackNumber && "The pack number has been truncated.")(static_cast <bool> (Num == PackNumber && "The pack number has been truncated."
) ? void (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\""
, "clang/include/clang/Sema/Sema.h", 497, __extension__ __PRETTY_FUNCTION__
))
;
498 }
499
500 // #pragma align info constructor
501 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
502 : PackAttr(false), AlignMode(M),
503 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
504
505 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
506
507 AlignPackInfo() : AlignPackInfo(Native, false) {}
508
509 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
510 // integer encoding for it. This should only be passed to
511 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
512 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
513 std::uint32_t Encoding{};
514 if (Info.IsXLStack())
515 Encoding |= IsXLMask;
516
517 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
518
519 if (Info.IsPackAttr())
520 Encoding |= PackAttrMask;
521
522 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
523
524 return Encoding;
525 }
526
527 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
528 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
529 AlignPackInfo::Mode M =
530 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
531 int PackNumber = (Encoding & PackNumMask) >> 4;
532
533 if (Encoding & PackAttrMask)
534 return AlignPackInfo(M, PackNumber, IsXL);
535
536 return AlignPackInfo(M, IsXL);
537 }
538
539 bool IsPackAttr() const { return PackAttr; }
540
541 bool IsAlignAttr() const { return !PackAttr; }
542
543 Mode getAlignMode() const { return AlignMode; }
544
545 unsigned getPackNumber() const { return PackNumber; }
546
547 bool IsPackSet() const {
548 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
549 // attriute on a decl.
550 return PackNumber != UninitPackVal && PackNumber != 0;
551 }
552
553 bool IsXLStack() const { return XLStack; }
554
555 bool operator==(const AlignPackInfo &Info) const {
556 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
557 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
558 Info.XLStack);
559 }
560
561 bool operator!=(const AlignPackInfo &Info) const {
562 return !(*this == Info);
563 }
564
565 private:
566 /// \brief True if this is a pragma pack attribute,
567 /// not a pragma align attribute.
568 bool PackAttr;
569
570 /// \brief The alignment mode that is in effect.
571 Mode AlignMode;
572
573 /// \brief The pack number of the stack.
574 unsigned char PackNumber;
575
576 /// \brief True if it is a XL #pragma align/pack stack.
577 bool XLStack;
578
579 /// \brief Uninitialized pack value.
580 static constexpr unsigned char UninitPackVal = -1;
581
582 // Masks to encode and decode an AlignPackInfo.
583 static constexpr uint32_t IsXLMask{0x0000'0001};
584 static constexpr uint32_t AlignModeMask{0x0000'0006};
585 static constexpr uint32_t PackAttrMask{0x00000'0008};
586 static constexpr uint32_t PackNumMask{0x0000'01F0};
587 };
588
589 template<typename ValueType>
590 struct PragmaStack {
591 struct Slot {
592 llvm::StringRef StackSlotLabel;
593 ValueType Value;
594 SourceLocation PragmaLocation;
595 SourceLocation PragmaPushLocation;
596 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
597 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
598 : StackSlotLabel(StackSlotLabel), Value(Value),
599 PragmaLocation(PragmaLocation),
600 PragmaPushLocation(PragmaPushLocation) {}
601 };
602
603 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
604 llvm::StringRef StackSlotLabel, ValueType Value) {
605 if (Action == PSK_Reset) {
606 CurrentValue = DefaultValue;
607 CurrentPragmaLocation = PragmaLocation;
608 return;
609 }
610 if (Action & PSK_Push)
611 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
612 PragmaLocation);
613 else if (Action & PSK_Pop) {
614 if (!StackSlotLabel.empty()) {
615 // If we've got a label, try to find it and jump there.
616 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
617 return x.StackSlotLabel == StackSlotLabel;
618 });
619 // If we found the label so pop from there.
620 if (I != Stack.rend()) {
621 CurrentValue = I->Value;
622 CurrentPragmaLocation = I->PragmaLocation;
623 Stack.erase(std::prev(I.base()), Stack.end());
624 }
625 } else if (!Stack.empty()) {
626 // We do not have a label, just pop the last entry.
627 CurrentValue = Stack.back().Value;
628 CurrentPragmaLocation = Stack.back().PragmaLocation;
629 Stack.pop_back();
630 }
631 }
632 if (Action & PSK_Set) {
633 CurrentValue = Value;
634 CurrentPragmaLocation = PragmaLocation;
635 }
636 }
637
638 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
639 // method body to restore the stacks on exit, so it works like this:
640 //
641 // struct S {
642 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
643 // void Method {}
644 // #pragma <name>(pop, InternalPragmaSlot)
645 // };
646 //
647 // It works even with #pragma vtordisp, although MSVC doesn't support
648 // #pragma vtordisp(push [, id], n)
649 // syntax.
650 //
651 // Push / pop a named sentinel slot.
652 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
653 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 654, __extension__ __PRETTY_FUNCTION__
))
654 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 654, __extension__ __PRETTY_FUNCTION__
))
;
655 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
656 }
657
658 // Constructors.
659 explicit PragmaStack(const ValueType &Default)
660 : DefaultValue(Default), CurrentValue(Default) {}
661
662 bool hasValue() const { return CurrentValue != DefaultValue; }
663
664 SmallVector<Slot, 2> Stack;
665 ValueType DefaultValue; // Value used for PSK_Reset action.
666 ValueType CurrentValue;
667 SourceLocation CurrentPragmaLocation;
668 };
669 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
670 // we shouldn't do so if they're in a module).
671
672 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
673 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
674 ///
675 /// 0: Suppress all vtordisps
676 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
677 /// structors
678 /// 2: Always insert vtordisps to support RTTI on partially constructed
679 /// objects
680 PragmaStack<MSVtorDispMode> VtorDispStack;
681 PragmaStack<AlignPackInfo> AlignPackStack;
682 // The current #pragma align/pack values and locations at each #include.
683 struct AlignPackIncludeState {
684 AlignPackInfo CurrentValue;
685 SourceLocation CurrentPragmaLocation;
686 bool HasNonDefaultValue, ShouldWarnOnInclude;
687 };
688 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
689 // Segment #pragmas.
690 PragmaStack<StringLiteral *> DataSegStack;
691 PragmaStack<StringLiteral *> BSSSegStack;
692 PragmaStack<StringLiteral *> ConstSegStack;
693 PragmaStack<StringLiteral *> CodeSegStack;
694
695 // This stack tracks the current state of Sema.CurFPFeatures.
696 PragmaStack<FPOptionsOverride> FpPragmaStack;
697 FPOptionsOverride CurFPFeatureOverrides() {
698 FPOptionsOverride result;
699 if (!FpPragmaStack.hasValue()) {
700 result = FPOptionsOverride();
701 } else {
702 result = FpPragmaStack.CurrentValue;
703 }
704 return result;
705 }
706
707 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
708 // Actions should be performed only if we enter / exit a C++ method body.
709 class PragmaStackSentinelRAII {
710 public:
711 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
712 ~PragmaStackSentinelRAII();
713
714 private:
715 Sema &S;
716 StringRef SlotLabel;
717 bool ShouldAct;
718 };
719
720 /// A mapping that describes the nullability we've seen in each header file.
721 FileNullabilityMap NullabilityMap;
722
723 /// Last section used with #pragma init_seg.
724 StringLiteral *CurInitSeg;
725 SourceLocation CurInitSegLoc;
726
727 /// VisContext - Manages the stack for \#pragma GCC visibility.
728 void *VisContext; // Really a "PragmaVisStack*"
729
730 /// This an attribute introduced by \#pragma clang attribute.
731 struct PragmaAttributeEntry {
732 SourceLocation Loc;
733 ParsedAttr *Attribute;
734 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
735 bool IsUsed;
736 };
737
738 /// A push'd group of PragmaAttributeEntries.
739 struct PragmaAttributeGroup {
740 /// The location of the push attribute.
741 SourceLocation Loc;
742 /// The namespace of this push group.
743 const IdentifierInfo *Namespace;
744 SmallVector<PragmaAttributeEntry, 2> Entries;
745 };
746
747 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
748
749 /// The declaration that is currently receiving an attribute from the
750 /// #pragma attribute stack.
751 const Decl *PragmaAttributeCurrentTargetDecl;
752
753 /// This represents the last location of a "#pragma clang optimize off"
754 /// directive if such a directive has not been closed by an "on" yet. If
755 /// optimizations are currently "on", this is set to an invalid location.
756 SourceLocation OptimizeOffPragmaLocation;
757
758 /// Flag indicating if Sema is building a recovery call expression.
759 ///
760 /// This flag is used to avoid building recovery call expressions
761 /// if Sema is already doing so, which would cause infinite recursions.
762 bool IsBuildingRecoveryCallExpr;
763
764 /// Used to control the generation of ExprWithCleanups.
765 CleanupInfo Cleanup;
766
767 /// ExprCleanupObjects - This is the stack of objects requiring
768 /// cleanup that are created by the current full expression.
769 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
770
771 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
772 /// to a variable (constant) that may or may not be odr-used in this Expr, and
773 /// we won't know until all lvalue-to-rvalue and discarded value conversions
774 /// have been applied to all subexpressions of the enclosing full expression.
775 /// This is cleared at the end of each full expression.
776 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
777 llvm::SmallPtrSet<Expr *, 4>>;
778 MaybeODRUseExprSet MaybeODRUseExprs;
779
780 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
781
782 /// Stack containing information about each of the nested
783 /// function, block, and method scopes that are currently active.
784 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
785
786 /// The index of the first FunctionScope that corresponds to the current
787 /// context.
788 unsigned FunctionScopesStart = 0;
789
790 /// Whether we are currently in the context of a mutable agnostic identifier
791 /// as described by CWG2569.
792 /// We are handling the unqualified-id of a decltype or noexcept expression.
793 bool InMutableAgnosticContext = false;
794
795 /// RAII object used to change the value of \c InMutableAgnosticContext
796 /// within a \c Sema object.
797 class MutableAgnosticContextRAII {
798 Sema &SemaRef;
799
800 public:
801 MutableAgnosticContextRAII(Sema &S) : SemaRef(S) {
802 SemaRef.InMutableAgnosticContext = true;
803 }
804 ~MutableAgnosticContextRAII() { SemaRef.InMutableAgnosticContext = false; }
805 };
806
807 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
808 return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart,
809 FunctionScopes.end());
810 }
811
812 /// Stack containing information needed when in C++2a an 'auto' is encountered
813 /// in a function declaration parameter type specifier in order to invent a
814 /// corresponding template parameter in the enclosing abbreviated function
815 /// template. This information is also present in LambdaScopeInfo, stored in
816 /// the FunctionScopes stack.
817 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
818
819 /// The index of the first InventedParameterInfo that refers to the current
820 /// context.
821 unsigned InventedParameterInfosStart = 0;
822
823 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
824 return llvm::makeArrayRef(InventedParameterInfos.begin() +
825 InventedParameterInfosStart,
826 InventedParameterInfos.end());
827 }
828
829 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
830 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
831 ExtVectorDeclsType;
832
833 /// ExtVectorDecls - This is a list all the extended vector types. This allows
834 /// us to associate a raw vector type with one of the ext_vector type names.
835 /// This is only necessary for issuing pretty diagnostics.
836 ExtVectorDeclsType ExtVectorDecls;
837
838 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
839 std::unique_ptr<CXXFieldCollector> FieldCollector;
840
841 typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType;
842
843 /// Set containing all declared private fields that are not used.
844 NamedDeclSetType UnusedPrivateFields;
845
846 /// Set containing all typedefs that are likely unused.
847 llvm::SmallSetVector<const TypedefNameDecl *, 4>
848 UnusedLocalTypedefNameCandidates;
849
850 /// Delete-expressions to be analyzed at the end of translation unit
851 ///
852 /// This list contains class members, and locations of delete-expressions
853 /// that could not be proven as to whether they mismatch with new-expression
854 /// used in initializer of the field.
855 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
856 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
857 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
858
859 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
860
861 /// PureVirtualClassDiagSet - a set of class declarations which we have
862 /// emitted a list of pure virtual functions. Used to prevent emitting the
863 /// same list more than once.
864 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
865
866 /// ParsingInitForAutoVars - a set of declarations with auto types for which
867 /// we are currently parsing the initializer.
868 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
869
870 /// Look for a locally scoped extern "C" declaration by the given name.
871 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
872
873 typedef LazyVector<VarDecl *, ExternalSemaSource,
874 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
875 TentativeDefinitionsType;
876
877 /// All the tentative definitions encountered in the TU.
878 TentativeDefinitionsType TentativeDefinitions;
879
880 /// All the external declarations encoutered and used in the TU.
881 SmallVector<VarDecl *, 4> ExternalDeclarations;
882
883 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
884 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
885 UnusedFileScopedDeclsType;
886
887 /// The set of file scoped decls seen so far that have not been used
888 /// and must warn if not used. Only contains the first declaration.
889 UnusedFileScopedDeclsType UnusedFileScopedDecls;
890
891 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
892 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
893 DelegatingCtorDeclsType;
894
895 /// All the delegating constructors seen so far in the file, used for
896 /// cycle detection at the end of the TU.
897 DelegatingCtorDeclsType DelegatingCtorDecls;
898
899 /// All the overriding functions seen during a class definition
900 /// that had their exception spec checks delayed, plus the overridden
901 /// function.
902 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
903 DelayedOverridingExceptionSpecChecks;
904
905 /// All the function redeclarations seen during a class definition that had
906 /// their exception spec checks delayed, plus the prior declaration they
907 /// should be checked against. Except during error recovery, the new decl
908 /// should always be a friend declaration, as that's the only valid way to
909 /// redeclare a special member before its class is complete.
910 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
911 DelayedEquivalentExceptionSpecChecks;
912
913 typedef llvm::MapVector<const FunctionDecl *,
914 std::unique_ptr<LateParsedTemplate>>
915 LateParsedTemplateMapT;
916 LateParsedTemplateMapT LateParsedTemplateMap;
917
918 /// Callback to the parser to parse templated functions when needed.
919 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
920 typedef void LateTemplateParserCleanupCB(void *P);
921 LateTemplateParserCB *LateTemplateParser;
922 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
923 void *OpaqueParser;
924
925 void SetLateTemplateParser(LateTemplateParserCB *LTP,
926 LateTemplateParserCleanupCB *LTPCleanup,
927 void *P) {
928 LateTemplateParser = LTP;
929 LateTemplateParserCleanup = LTPCleanup;
930 OpaqueParser = P;
931 }
932
933 class DelayedDiagnostics;
934
935 class DelayedDiagnosticsState {
936 sema::DelayedDiagnosticPool *SavedPool;
937 friend class Sema::DelayedDiagnostics;
938 };
939 typedef DelayedDiagnosticsState ParsingDeclState;
940 typedef DelayedDiagnosticsState ProcessingContextState;
941
942 /// A class which encapsulates the logic for delaying diagnostics
943 /// during parsing and other processing.
944 class DelayedDiagnostics {
945 /// The current pool of diagnostics into which delayed
946 /// diagnostics should go.
947 sema::DelayedDiagnosticPool *CurPool;
948
949 public:
950 DelayedDiagnostics() : CurPool(nullptr) {}
951
952 /// Adds a delayed diagnostic.
953 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
954
955 /// Determines whether diagnostics should be delayed.
956 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
957
958 /// Returns the current delayed-diagnostics pool.
959 sema::DelayedDiagnosticPool *getCurrentPool() const {
960 return CurPool;
961 }
962
963 /// Enter a new scope. Access and deprecation diagnostics will be
964 /// collected in this pool.
965 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
966 DelayedDiagnosticsState state;
967 state.SavedPool = CurPool;
968 CurPool = &pool;
969 return state;
970 }
971
972 /// Leave a delayed-diagnostic state that was previously pushed.
973 /// Do not emit any of the diagnostics. This is performed as part
974 /// of the bookkeeping of popping a pool "properly".
975 void popWithoutEmitting(DelayedDiagnosticsState state) {
976 CurPool = state.SavedPool;
977 }
978
979 /// Enter a new scope where access and deprecation diagnostics are
980 /// not delayed.
981 DelayedDiagnosticsState pushUndelayed() {
982 DelayedDiagnosticsState state;
983 state.SavedPool = CurPool;
984 CurPool = nullptr;
985 return state;
986 }
987
988 /// Undo a previous pushUndelayed().
989 void popUndelayed(DelayedDiagnosticsState state) {
990 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "clang/include/clang/Sema/Sema.h", 990
, __extension__ __PRETTY_FUNCTION__))
;
991 CurPool = state.SavedPool;
992 }
993 } DelayedDiagnostics;
994
995 /// A RAII object to temporarily push a declaration context.
996 class ContextRAII {
997 private:
998 Sema &S;
999 DeclContext *SavedContext;
1000 ProcessingContextState SavedContextState;
1001 QualType SavedCXXThisTypeOverride;
1002 unsigned SavedFunctionScopesStart;
1003 unsigned SavedInventedParameterInfosStart;
1004
1005 public:
1006 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1007 : S(S), SavedContext(S.CurContext),
1008 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1009 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1010 SavedFunctionScopesStart(S.FunctionScopesStart),
1011 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1012 {
1013 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "clang/include/clang/Sema/Sema.h", 1013, __extension__ __PRETTY_FUNCTION__
))
;
1014 S.CurContext = ContextToPush;
1015 if (NewThisContext)
1016 S.CXXThisTypeOverride = QualType();
1017 // Any saved FunctionScopes do not refer to this context.
1018 S.FunctionScopesStart = S.FunctionScopes.size();
1019 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1020 }
1021
1022 void pop() {
1023 if (!SavedContext) return;
1024 S.CurContext = SavedContext;
1025 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1026 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1027 S.FunctionScopesStart = SavedFunctionScopesStart;
1028 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1029 SavedContext = nullptr;
1030 }
1031
1032 ~ContextRAII() {
1033 pop();
1034 }
1035 };
1036
1037 /// Whether the AST is currently being rebuilt to correct immediate
1038 /// invocations. Immediate invocation candidates and references to consteval
1039 /// functions aren't tracked when this is set.
1040 bool RebuildingImmediateInvocation = false;
1041
1042 /// Used to change context to isConstantEvaluated without pushing a heavy
1043 /// ExpressionEvaluationContextRecord object.
1044 bool isConstantEvaluatedOverride;
1045
1046 bool isConstantEvaluated() {
1047 return ExprEvalContexts.back().isConstantEvaluated() ||
1048 isConstantEvaluatedOverride;
1049 }
1050
1051 /// RAII object to handle the state changes required to synthesize
1052 /// a function body.
1053 class SynthesizedFunctionScope {
1054 Sema &S;
1055 Sema::ContextRAII SavedContext;
1056 bool PushedCodeSynthesisContext = false;
1057
1058 public:
1059 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1060 : S(S), SavedContext(S, DC) {
1061 S.PushFunctionScope();
1062 S.PushExpressionEvaluationContext(
1063 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1064 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1065 FD->setWillHaveBody(true);
1066 else
1067 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "clang/include/clang/Sema/Sema.h"
, 1067, __extension__ __PRETTY_FUNCTION__))
;
1068 }
1069
1070 void addContextNote(SourceLocation UseLoc) {
1071 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "clang/include/clang/Sema/Sema.h"
, 1071, __extension__ __PRETTY_FUNCTION__))
;
1072
1073 Sema::CodeSynthesisContext Ctx;
1074 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1075 Ctx.PointOfInstantiation = UseLoc;
1076 Ctx.Entity = cast<Decl>(S.CurContext);
1077 S.pushCodeSynthesisContext(Ctx);
1078
1079 PushedCodeSynthesisContext = true;
1080 }
1081
1082 ~SynthesizedFunctionScope() {
1083 if (PushedCodeSynthesisContext)
1084 S.popCodeSynthesisContext();
1085 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1086 FD->setWillHaveBody(false);
1087 S.PopExpressionEvaluationContext();
1088 S.PopFunctionScopeInfo();
1089 }
1090 };
1091
1092 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1093 /// declared. Rare. May alias another identifier, declared or undeclared.
1094 ///
1095 /// For aliases, the target identifier is used as a key for eventual
1096 /// processing when the target is declared. For the single-identifier form,
1097 /// the sole identifier is used as the key. Each entry is a `SetVector`
1098 /// (ordered by parse order) of aliases (identified by the alias name) in case
1099 /// of multiple aliases to the same undeclared identifier.
1100 llvm::MapVector<
1101 IdentifierInfo *,
1102 llvm::SetVector<
1103 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1104 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1105 WeakUndeclaredIdentifiers;
1106
1107 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1108 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1109 /// to define functions that occur in multiple standards to call the version
1110 /// in the currently selected standard.
1111 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1112
1113
1114 /// Load weak undeclared identifiers from the external source.
1115 void LoadExternalWeakUndeclaredIdentifiers();
1116
1117 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1118 /// \#pragma weak during processing of other Decls.
1119 /// I couldn't figure out a clean way to generate these in-line, so
1120 /// we store them here and handle separately -- which is a hack.
1121 /// It would be best to refactor this.
1122 SmallVector<Decl*,2> WeakTopLevelDecl;
1123
1124 IdentifierResolver IdResolver;
1125
1126 /// Translation Unit Scope - useful to Objective-C actions that need
1127 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1128 /// For example, user-defined classes, built-in "id" type, etc.
1129 Scope *TUScope;
1130
1131 /// The C++ "std" namespace, where the standard library resides.
1132 LazyDeclPtr StdNamespace;
1133
1134 /// The C++ "std::bad_alloc" class, which is defined by the C++
1135 /// standard library.
1136 LazyDeclPtr StdBadAlloc;
1137
1138 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1139 /// standard library.
1140 LazyDeclPtr StdAlignValT;
1141
1142 /// The C++ "std::experimental" namespace, where the experimental parts
1143 /// of the standard library resides.
1144 NamespaceDecl *StdExperimentalNamespaceCache;
1145
1146 /// The C++ "std::initializer_list" template, which is defined in
1147 /// \<initializer_list>.
1148 ClassTemplateDecl *StdInitializerList;
1149
1150 /// The C++ "std::coroutine_traits" template, which is defined in
1151 /// \<coroutine_traits>
1152 ClassTemplateDecl *StdCoroutineTraitsCache;
1153 /// The namespace where coroutine components are defined. In standard,
1154 /// they are defined in std namespace. And in the previous implementation,
1155 /// they are defined in std::experimental namespace.
1156 NamespaceDecl *CoroTraitsNamespaceCache;
1157
1158 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1159 RecordDecl *CXXTypeInfoDecl;
1160
1161 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1162 RecordDecl *MSVCGuidDecl;
1163
1164 /// The C++ "std::source_location::__impl" struct, defined in
1165 /// \<source_location>.
1166 RecordDecl *StdSourceLocationImplDecl;
1167
1168 /// Caches identifiers/selectors for NSFoundation APIs.
1169 std::unique_ptr<NSAPI> NSAPIObj;
1170
1171 /// The declaration of the Objective-C NSNumber class.
1172 ObjCInterfaceDecl *NSNumberDecl;
1173
1174 /// The declaration of the Objective-C NSValue class.
1175 ObjCInterfaceDecl *NSValueDecl;
1176
1177 /// Pointer to NSNumber type (NSNumber *).
1178 QualType NSNumberPointer;
1179
1180 /// Pointer to NSValue type (NSValue *).
1181 QualType NSValuePointer;
1182
1183 /// The Objective-C NSNumber methods used to create NSNumber literals.
1184 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1185
1186 /// The declaration of the Objective-C NSString class.
1187 ObjCInterfaceDecl *NSStringDecl;
1188
1189 /// Pointer to NSString type (NSString *).
1190 QualType NSStringPointer;
1191
1192 /// The declaration of the stringWithUTF8String: method.
1193 ObjCMethodDecl *StringWithUTF8StringMethod;
1194
1195 /// The declaration of the valueWithBytes:objCType: method.
1196 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1197
1198 /// The declaration of the Objective-C NSArray class.
1199 ObjCInterfaceDecl *NSArrayDecl;
1200
1201 /// The declaration of the arrayWithObjects:count: method.
1202 ObjCMethodDecl *ArrayWithObjectsMethod;
1203
1204 /// The declaration of the Objective-C NSDictionary class.
1205 ObjCInterfaceDecl *NSDictionaryDecl;
1206
1207 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1208 ObjCMethodDecl *DictionaryWithObjectsMethod;
1209
1210 /// id<NSCopying> type.
1211 QualType QIDNSCopying;
1212
1213 /// will hold 'respondsToSelector:'
1214 Selector RespondsToSelectorSel;
1215
1216 /// A flag to remember whether the implicit forms of operator new and delete
1217 /// have been declared.
1218 bool GlobalNewDeleteDeclared;
1219
1220 /// Describes how the expressions currently being parsed are
1221 /// evaluated at run-time, if at all.
1222 enum class ExpressionEvaluationContext {
1223 /// The current expression and its subexpressions occur within an
1224 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1225 /// \c sizeof, where the type of the expression may be significant but
1226 /// no code will be generated to evaluate the value of the expression at
1227 /// run time.
1228 Unevaluated,
1229
1230 /// The current expression occurs within a braced-init-list within
1231 /// an unevaluated operand. This is mostly like a regular unevaluated
1232 /// context, except that we still instantiate constexpr functions that are
1233 /// referenced here so that we can perform narrowing checks correctly.
1234 UnevaluatedList,
1235
1236 /// The current expression occurs within a discarded statement.
1237 /// This behaves largely similarly to an unevaluated operand in preventing
1238 /// definitions from being required, but not in other ways.
1239 DiscardedStatement,
1240
1241 /// The current expression occurs within an unevaluated
1242 /// operand that unconditionally permits abstract references to
1243 /// fields, such as a SIZE operator in MS-style inline assembly.
1244 UnevaluatedAbstract,
1245
1246 /// The current context is "potentially evaluated" in C++11 terms,
1247 /// but the expression is evaluated at compile-time (like the values of
1248 /// cases in a switch statement).
1249 ConstantEvaluated,
1250
1251 /// In addition of being constant evaluated, the current expression
1252 /// occurs in an immediate function context - either a consteval function
1253 /// or a consteval if function.
1254 ImmediateFunctionContext,
1255
1256 /// The current expression is potentially evaluated at run time,
1257 /// which means that code may be generated to evaluate the value of the
1258 /// expression at run time.
1259 PotentiallyEvaluated,
1260
1261 /// The current expression is potentially evaluated, but any
1262 /// declarations referenced inside that expression are only used if
1263 /// in fact the current expression is used.
1264 ///
1265 /// This value is used when parsing default function arguments, for which
1266 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1267 /// through varargs) but do not want to mark declarations as "referenced"
1268 /// until the default argument is used.
1269 PotentiallyEvaluatedIfUsed
1270 };
1271
1272 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1273
1274 /// Data structure used to record current or nested
1275 /// expression evaluation contexts.
1276 struct ExpressionEvaluationContextRecord {
1277 /// The expression evaluation context.
1278 ExpressionEvaluationContext Context;
1279
1280 /// Whether the enclosing context needed a cleanup.
1281 CleanupInfo ParentCleanup;
1282
1283 /// The number of active cleanup objects when we entered
1284 /// this expression evaluation context.
1285 unsigned NumCleanupObjects;
1286
1287 /// The number of typos encountered during this expression evaluation
1288 /// context (i.e. the number of TypoExprs created).
1289 unsigned NumTypos;
1290
1291 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1292
1293 /// The lambdas that are present within this context, if it
1294 /// is indeed an unevaluated context.
1295 SmallVector<LambdaExpr *, 2> Lambdas;
1296
1297 /// The declaration that provides context for lambda expressions
1298 /// and block literals if the normal declaration context does not
1299 /// suffice, e.g., in a default function argument.
1300 Decl *ManglingContextDecl;
1301
1302 /// If we are processing a decltype type, a set of call expressions
1303 /// for which we have deferred checking the completeness of the return type.
1304 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1305
1306 /// If we are processing a decltype type, a set of temporary binding
1307 /// expressions for which we have deferred checking the destructor.
1308 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1309
1310 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1311
1312 /// Expressions appearing as the LHS of a volatile assignment in this
1313 /// context. We produce a warning for these when popping the context if
1314 /// they are not discarded-value expressions nor unevaluated operands.
1315 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1316
1317 /// Set of candidates for starting an immediate invocation.
1318 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1319
1320 /// Set of DeclRefExprs referencing a consteval function when used in a
1321 /// context not already known to be immediately invoked.
1322 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1323
1324 /// \brief Describes whether we are in an expression constext which we have
1325 /// to handle differently.
1326 enum ExpressionKind {
1327 EK_Decltype, EK_TemplateArgument, EK_Other
1328 } ExprContext;
1329
1330 // A context can be nested in both a discarded statement context and
1331 // an immediate function context, so they need to be tracked independently.
1332 bool InDiscardedStatement;
1333 bool InImmediateFunctionContext;
1334
1335 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1336 unsigned NumCleanupObjects,
1337 CleanupInfo ParentCleanup,
1338 Decl *ManglingContextDecl,
1339 ExpressionKind ExprContext)
1340 : Context(Context), ParentCleanup(ParentCleanup),
1341 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1342 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1343 InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1344
1345 bool isUnevaluated() const {
1346 return Context == ExpressionEvaluationContext::Unevaluated ||
1347 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1348 Context == ExpressionEvaluationContext::UnevaluatedList;
1349 }
1350
1351 bool isConstantEvaluated() const {
1352 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1353 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1354 }
1355
1356 bool isImmediateFunctionContext() const {
1357 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1358 (Context == ExpressionEvaluationContext::DiscardedStatement &&
1359 InImmediateFunctionContext);
1360 }
1361
1362 bool isDiscardedStatementContext() const {
1363 return Context == ExpressionEvaluationContext::DiscardedStatement ||
1364 (Context ==
1365 ExpressionEvaluationContext::ImmediateFunctionContext &&
1366 InDiscardedStatement);
1367 }
1368 };
1369
1370 /// A stack of expression evaluation contexts.
1371 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1372
1373 /// Emit a warning for all pending noderef expressions that we recorded.
1374 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1375
1376 /// Compute the mangling number context for a lambda expression or
1377 /// block literal. Also return the extra mangling decl if any.
1378 ///
1379 /// \param DC - The DeclContext containing the lambda expression or
1380 /// block literal.
1381 std::tuple<MangleNumberingContext *, Decl *>
1382 getCurrentMangleNumberContext(const DeclContext *DC);
1383
1384
1385 /// SpecialMemberOverloadResult - The overloading result for a special member
1386 /// function.
1387 ///
1388 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1389 /// integer are used to determine whether overload resolution succeeded.
1390 class SpecialMemberOverloadResult {
1391 public:
1392 enum Kind {
1393 NoMemberOrDeleted,
1394 Ambiguous,
1395 Success
1396 };
1397
1398 private:
1399 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1400
1401 public:
1402 SpecialMemberOverloadResult() {}
1403 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1404 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1405
1406 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1407 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1408
1409 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1410 void setKind(Kind K) { Pair.setInt(K); }
1411 };
1412
1413 class SpecialMemberOverloadResultEntry
1414 : public llvm::FastFoldingSetNode,
1415 public SpecialMemberOverloadResult {
1416 public:
1417 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1418 : FastFoldingSetNode(ID)
1419 {}
1420 };
1421
1422 /// A cache of special member function overload resolution results
1423 /// for C++ records.
1424 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1425
1426 /// A cache of the flags available in enumerations with the flag_bits
1427 /// attribute.
1428 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1429
1430 /// The kind of translation unit we are processing.
1431 ///
1432 /// When we're processing a complete translation unit, Sema will perform
1433 /// end-of-translation-unit semantic tasks (such as creating
1434 /// initializers for tentative definitions in C) once parsing has
1435 /// completed. Modules and precompiled headers perform different kinds of
1436 /// checks.
1437 const TranslationUnitKind TUKind;
1438
1439 llvm::BumpPtrAllocator BumpAlloc;
1440
1441 /// The number of SFINAE diagnostics that have been trapped.
1442 unsigned NumSFINAEErrors;
1443
1444 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1445 UnparsedDefaultArgInstantiationsMap;
1446
1447 /// A mapping from parameters with unparsed default arguments to the
1448 /// set of instantiations of each parameter.
1449 ///
1450 /// This mapping is a temporary data structure used when parsing
1451 /// nested class templates or nested classes of class templates,
1452 /// where we might end up instantiating an inner class before the
1453 /// default arguments of its methods have been parsed.
1454 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1455
1456 // Contains the locations of the beginning of unparsed default
1457 // argument locations.
1458 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1459
1460 /// UndefinedInternals - all the used, undefined objects which require a
1461 /// definition in this translation unit.
1462 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1463
1464 /// Determine if VD, which must be a variable or function, is an external
1465 /// symbol that nonetheless can't be referenced from outside this translation
1466 /// unit because its type has no linkage and it's not extern "C".
1467 bool isExternalWithNoLinkageType(ValueDecl *VD);
1468
1469 /// Obtain a sorted list of functions that are undefined but ODR-used.
1470 void getUndefinedButUsed(
1471 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1472
1473 /// Retrieves list of suspicious delete-expressions that will be checked at
1474 /// the end of translation unit.
1475 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1476 getMismatchingDeleteExpressions() const;
1477
1478 class GlobalMethodPool {
1479 public:
1480 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1481 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1482 iterator begin() { return Methods.begin(); }
1483 iterator end() { return Methods.end(); }
1484 iterator find(Selector Sel) { return Methods.find(Sel); }
1485 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1486 return Methods.insert(Val);
1487 }
1488 int count(Selector Sel) const { return Methods.count(Sel); }
1489 bool empty() const { return Methods.empty(); }
1490
1491 private:
1492 llvm::DenseMap<Selector, Lists> Methods;
1493 };
1494
1495 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1496 /// We need to maintain a list, since selectors can have differing signatures
1497 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1498 /// of selectors are "overloaded").
1499 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1500 /// methods inside categories with a particular selector.
1501 GlobalMethodPool MethodPool;
1502
1503 /// Method selectors used in a \@selector expression. Used for implementation
1504 /// of -Wselector.
1505 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1506
1507 /// List of SourceLocations where 'self' is implicitly retained inside a
1508 /// block.
1509 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1510 ImplicitlyRetainedSelfLocs;
1511
1512 /// Kinds of C++ special members.
1513 enum CXXSpecialMember {
1514 CXXDefaultConstructor,
1515 CXXCopyConstructor,
1516 CXXMoveConstructor,
1517 CXXCopyAssignment,
1518 CXXMoveAssignment,
1519 CXXDestructor,
1520 CXXInvalid
1521 };
1522
1523 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1524 SpecialMemberDecl;
1525
1526 /// The C++ special members which we are currently in the process of
1527 /// declaring. If this process recursively triggers the declaration of the
1528 /// same special member, we should act as if it is not yet declared.
1529 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1530
1531 /// Kinds of defaulted comparison operator functions.
1532 enum class DefaultedComparisonKind : unsigned char {
1533 /// This is not a defaultable comparison operator.
1534 None,
1535 /// This is an operator== that should be implemented as a series of
1536 /// subobject comparisons.
1537 Equal,
1538 /// This is an operator<=> that should be implemented as a series of
1539 /// subobject comparisons.
1540 ThreeWay,
1541 /// This is an operator!= that should be implemented as a rewrite in terms
1542 /// of a == comparison.
1543 NotEqual,
1544 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1545 /// terms of a <=> comparison.
1546 Relational,
1547 };
1548
1549 /// The function definitions which were renamed as part of typo-correction
1550 /// to match their respective declarations. We want to keep track of them
1551 /// to ensure that we don't emit a "redefinition" error if we encounter a
1552 /// correctly named definition after the renamed definition.
1553 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1554
1555 /// Stack of types that correspond to the parameter entities that are
1556 /// currently being copy-initialized. Can be empty.
1557 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1558
1559 void ReadMethodPool(Selector Sel);
1560 void updateOutOfDateSelector(Selector Sel);
1561
1562 /// Private Helper predicate to check for 'self'.
1563 bool isSelfExpr(Expr *RExpr);
1564 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1565
1566 /// Cause the active diagnostic on the DiagosticsEngine to be
1567 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1568 /// should not be used elsewhere.
1569 void EmitCurrentDiagnostic(unsigned DiagID);
1570
1571 /// Records and restores the CurFPFeatures state on entry/exit of compound
1572 /// statements.
1573 class FPFeaturesStateRAII {
1574 public:
1575 FPFeaturesStateRAII(Sema &S);
1576 ~FPFeaturesStateRAII();
1577 FPOptionsOverride getOverrides() { return OldOverrides; }
1578
1579 private:
1580 Sema& S;
1581 FPOptions OldFPFeaturesState;
1582 FPOptionsOverride OldOverrides;
1583 LangOptions::FPEvalMethodKind OldEvalMethod;
1584 SourceLocation OldFPPragmaLocation;
1585 };
1586
1587 void addImplicitTypedef(StringRef Name, QualType T);
1588
1589 bool WarnedStackExhausted = false;
1590
1591 /// Increment when we find a reference; decrement when we find an ignored
1592 /// assignment. Ultimately the value is 0 if every reference is an ignored
1593 /// assignment.
1594 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1595
1596private:
1597 Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1598
1599 bool WarnedDarwinSDKInfoMissing = false;
1600
1601public:
1602 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1603 TranslationUnitKind TUKind = TU_Complete,
1604 CodeCompleteConsumer *CompletionConsumer = nullptr);
1605 ~Sema();
1606
1607 /// Perform initialization that occurs after the parser has been
1608 /// initialized but before it parses anything.
1609 void Initialize();
1610
1611 /// This virtual key function only exists to limit the emission of debug info
1612 /// describing the Sema class. GCC and Clang only emit debug info for a class
1613 /// with a vtable when the vtable is emitted. Sema is final and not
1614 /// polymorphic, but the debug info size savings are so significant that it is
1615 /// worth adding a vtable just to take advantage of this optimization.
1616 virtual void anchor();
1617
1618 const LangOptions &getLangOpts() const { return LangOpts; }
1619 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1620 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1621
1622 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1623 SourceManager &getSourceManager() const { return SourceMgr; }
1624 Preprocessor &getPreprocessor() const { return PP; }
1625 ASTContext &getASTContext() const { return Context; }
1626 ASTConsumer &getASTConsumer() const { return Consumer; }
1627 ASTMutationListener *getASTMutationListener() const;
1628 ExternalSemaSource* getExternalSource() const { return ExternalSource; }
1629
1630 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1631 StringRef Platform);
1632 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1633
1634 ///Registers an external source. If an external source already exists,
1635 /// creates a multiplex external source and appends to it.
1636 ///
1637 ///\param[in] E - A non-null external sema source.
1638 ///
1639 void addExternalSource(ExternalSemaSource *E);
1640
1641 void PrintStats() const;
1642
1643 /// Warn that the stack is nearly exhausted.
1644 void warnStackExhausted(SourceLocation Loc);
1645
1646 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1647 /// guaranteed). Produces a warning if we're low on stack space and allocates
1648 /// more in that case. Use this in code that may recurse deeply (for example,
1649 /// in template instantiation) to avoid stack overflow.
1650 void runWithSufficientStackSpace(SourceLocation Loc,
1651 llvm::function_ref<void()> Fn);
1652
1653 /// Helper class that creates diagnostics with optional
1654 /// template instantiation stacks.
1655 ///
1656 /// This class provides a wrapper around the basic DiagnosticBuilder
1657 /// class that emits diagnostics. ImmediateDiagBuilder is
1658 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1659 /// does) and, if the diagnostic comes from inside a template
1660 /// instantiation, printing the template instantiation stack as
1661 /// well.
1662 class ImmediateDiagBuilder : public DiagnosticBuilder {
1663 Sema &SemaRef;
1664 unsigned DiagID;
1665
1666 public:
1667 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1668 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1669 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1670 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1671
1672 // This is a cunning lie. DiagnosticBuilder actually performs move
1673 // construction in its copy constructor (but due to varied uses, it's not
1674 // possible to conveniently express this as actual move construction). So
1675 // the default copy ctor here is fine, because the base class disables the
1676 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1677 // in that case anwyay.
1678 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1679
1680 ~ImmediateDiagBuilder() {
1681 // If we aren't active, there is nothing to do.
1682 if (!isActive()) return;
1683
1684 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1685 // builder itself so it won't emit the diagnostic in its own destructor.
1686 //
1687 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1688 // do its own needless checks to see if the diagnostic needs to be
1689 // emitted. However, because we take care to ensure that the builder
1690 // objects never escape, a sufficiently smart compiler will be able to
1691 // eliminate that code.
1692 Clear();
1693
1694 // Dispatch to Sema to emit the diagnostic.
1695 SemaRef.EmitCurrentDiagnostic(DiagID);
1696 }
1697
1698 /// Teach operator<< to produce an object of the correct type.
1699 template <typename T>
1700 friend const ImmediateDiagBuilder &
1701 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1702 const DiagnosticBuilder &BaseDiag = Diag;
1703 BaseDiag << Value;
1704 return Diag;
1705 }
1706
1707 // It is necessary to limit this to rvalue reference to avoid calling this
1708 // function with a bitfield lvalue argument since non-const reference to
1709 // bitfield is not allowed.
1710 template <typename T, typename = typename std::enable_if<
1711 !std::is_lvalue_reference<T>::value>::type>
1712 const ImmediateDiagBuilder &operator<<(T &&V) const {
1713 const DiagnosticBuilder &BaseDiag = *this;
1714 BaseDiag << std::move(V);
1715 return *this;
1716 }
1717 };
1718
1719 /// A generic diagnostic builder for errors which may or may not be deferred.
1720 ///
1721 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1722 /// which are not allowed to appear inside __device__ functions and are
1723 /// allowed to appear in __host__ __device__ functions only if the host+device
1724 /// function is never codegen'ed.
1725 ///
1726 /// To handle this, we use the notion of "deferred diagnostics", where we
1727 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1728 ///
1729 /// This class lets you emit either a regular diagnostic, a deferred
1730 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1731 /// its constructor, thus simplifying the process of creating these "maybe
1732 /// deferred" diagnostics.
1733 class SemaDiagnosticBuilder {
1734 public:
1735 enum Kind {
1736 /// Emit no diagnostics.
1737 K_Nop,
1738 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1739 K_Immediate,
1740 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1741 /// emit a call stack showing how this function can be reached by an a
1742 /// priori known-emitted function.
1743 K_ImmediateWithCallStack,
1744 /// Create a deferred diagnostic, which is emitted only if the function
1745 /// it's attached to is codegen'ed. Also emit a call stack as with
1746 /// K_ImmediateWithCallStack.
1747 K_Deferred
1748 };
1749
1750 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1751 FunctionDecl *Fn, Sema &S);
1752 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1753 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1754 ~SemaDiagnosticBuilder();
1755
1756 bool isImmediate() const { return ImmediateDiag.hasValue(); }
1757
1758 /// Convertible to bool: True if we immediately emitted an error, false if
1759 /// we didn't emit an error or we created a deferred error.
1760 ///
1761 /// Example usage:
1762 ///
1763 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1764 /// return ExprError();
1765 ///
1766 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1767 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1768 operator bool() const { return isImmediate(); }
1769
1770 template <typename T>
1771 friend const SemaDiagnosticBuilder &
1772 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1773 if (Diag.ImmediateDiag.hasValue())
1774 *Diag.ImmediateDiag << Value;
1775 else if (Diag.PartialDiagId.hasValue())
1776 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1777 << Value;
1778 return Diag;
1779 }
1780
1781 // It is necessary to limit this to rvalue reference to avoid calling this
1782 // function with a bitfield lvalue argument since non-const reference to
1783 // bitfield is not allowed.
1784 template <typename T, typename = typename std::enable_if<
1785 !std::is_lvalue_reference<T>::value>::type>
1786 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1787 if (ImmediateDiag.hasValue())
1788 *ImmediateDiag << std::move(V);
1789 else if (PartialDiagId.hasValue())
1790 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1791 return *this;
1792 }
1793
1794 friend const SemaDiagnosticBuilder &
1795 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1796 if (Diag.ImmediateDiag.hasValue())
1797 PD.Emit(*Diag.ImmediateDiag);
1798 else if (Diag.PartialDiagId.hasValue())
1799 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1800 return Diag;
1801 }
1802
1803 void AddFixItHint(const FixItHint &Hint) const {
1804 if (ImmediateDiag.hasValue())
1805 ImmediateDiag->AddFixItHint(Hint);
1806 else if (PartialDiagId.hasValue())
1807 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1808 }
1809
1810 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1811 return ExprError();
1812 }
1813 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1814 return StmtError();
1815 }
1816 operator ExprResult() const { return ExprError(); }
1817 operator StmtResult() const { return StmtError(); }
1818 operator TypeResult() const { return TypeError(); }
1819 operator DeclResult() const { return DeclResult(true); }
1820 operator MemInitResult() const { return MemInitResult(true); }
1821
1822 private:
1823 Sema &S;
1824 SourceLocation Loc;
1825 unsigned DiagID;
1826 FunctionDecl *Fn;
1827 bool ShowCallStack;
1828
1829 // Invariant: At most one of these Optionals has a value.
1830 // FIXME: Switch these to a Variant once that exists.
1831 llvm::Optional<ImmediateDiagBuilder> ImmediateDiag;
1832 llvm::Optional<unsigned> PartialDiagId;
1833 };
1834
1835 /// Is the last error level diagnostic immediate. This is used to determined
1836 /// whether the next info diagnostic should be immediate.
1837 bool IsLastErrorImmediate = true;
1838
1839 /// Emit a diagnostic.
1840 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1841 bool DeferHint = false);
1842
1843 /// Emit a partial diagnostic.
1844 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1845 bool DeferHint = false);
1846
1847 /// Build a partial diagnostic.
1848 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1849
1850 /// Whether deferrable diagnostics should be deferred.
1851 bool DeferDiags = false;
1852
1853 /// RAII class to control scope of DeferDiags.
1854 class DeferDiagsRAII {
1855 Sema &S;
1856 bool SavedDeferDiags = false;
1857
1858 public:
1859 DeferDiagsRAII(Sema &S, bool DeferDiags)
1860 : S(S), SavedDeferDiags(S.DeferDiags) {
1861 S.DeferDiags = DeferDiags;
1862 }
1863 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1864 };
1865
1866 /// Whether uncompilable error has occurred. This includes error happens
1867 /// in deferred diagnostics.
1868 bool hasUncompilableErrorOccurred() const;
1869
1870 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1871
1872 /// Get a string to suggest for zero-initialization of a type.
1873 std::string
1874 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1875 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1876
1877 /// Calls \c Lexer::getLocForEndOfToken()
1878 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1879
1880 /// Retrieve the module loader associated with the preprocessor.
1881 ModuleLoader &getModuleLoader() const;
1882
1883 /// Invent a new identifier for parameters of abbreviated templates.
1884 IdentifierInfo *
1885 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1886 unsigned Index);
1887
1888 void emitAndClearUnusedLocalTypedefWarnings();
1889
1890 private:
1891 /// Function or variable declarations to be checked for whether the deferred
1892 /// diagnostics should be emitted.
1893 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1894
1895 public:
1896 // Emit all deferred diagnostics.
1897 void emitDeferredDiags();
1898
1899 enum TUFragmentKind {
1900 /// The global module fragment, between 'module;' and a module-declaration.
1901 Global,
1902 /// A normal translation unit fragment. For a non-module unit, this is the
1903 /// entire translation unit. Otherwise, it runs from the module-declaration
1904 /// to the private-module-fragment (if any) or the end of the TU (if not).
1905 Normal,
1906 /// The private module fragment, between 'module :private;' and the end of
1907 /// the translation unit.
1908 Private
1909 };
1910
1911 void ActOnStartOfTranslationUnit();
1912 void ActOnEndOfTranslationUnit();
1913 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1914
1915 void CheckDelegatingCtorCycles();
1916
1917 Scope *getScopeForContext(DeclContext *Ctx);
1918
1919 void PushFunctionScope();
1920 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1921 sema::LambdaScopeInfo *PushLambdaScope();
1922
1923 /// This is used to inform Sema what the current TemplateParameterDepth
1924 /// is during Parsing. Currently it is used to pass on the depth
1925 /// when parsing generic lambda 'auto' parameters.
1926 void RecordParsingTemplateParameterDepth(unsigned Depth);
1927
1928 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1929 RecordDecl *RD, CapturedRegionKind K,
1930 unsigned OpenMPCaptureLevel = 0);
1931
1932 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1933 /// time after they've been popped.
1934 class PoppedFunctionScopeDeleter {
1935 Sema *Self;
1936
1937 public:
1938 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1939 void operator()(sema::FunctionScopeInfo *Scope) const;
1940 };
1941
1942 using PoppedFunctionScopePtr =
1943 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1944
1945 PoppedFunctionScopePtr
1946 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1947 const Decl *D = nullptr,
1948 QualType BlockType = QualType());
1949
1950 sema::FunctionScopeInfo *getCurFunction() const {
1951 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
12
'?' condition is false
13
Returning pointer, which participates in a condition later
1952 }
1953
1954 sema::FunctionScopeInfo *getEnclosingFunction() const;
1955
1956 void setFunctionHasBranchIntoScope();
1957 void setFunctionHasBranchProtectedScope();
1958 void setFunctionHasIndirectGoto();
1959 void setFunctionHasMustTail();
1960
1961 void PushCompoundScope(bool IsStmtExpr);
1962 void PopCompoundScope();
1963
1964 sema::CompoundScopeInfo &getCurCompoundScope() const;
1965
1966 bool hasAnyUnrecoverableErrorsInThisFunction() const;
1967
1968 /// Retrieve the current block, if any.
1969 sema::BlockScopeInfo *getCurBlock();
1970
1971 /// Get the innermost lambda enclosing the current location, if any. This
1972 /// looks through intervening non-lambda scopes such as local functions and
1973 /// blocks.
1974 sema::LambdaScopeInfo *getEnclosingLambda() const;
1975
1976 /// Retrieve the current lambda scope info, if any.
1977 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
1978 /// lambda scope info ignoring all inner capturing scopes that are not
1979 /// lambda scopes.
1980 sema::LambdaScopeInfo *
1981 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
1982
1983 /// Retrieve the current generic lambda info, if any.
1984 sema::LambdaScopeInfo *getCurGenericLambda();
1985
1986 /// Retrieve the current captured region, if any.
1987 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
1988
1989 /// Retrieve the current function, if any, that should be analyzed for
1990 /// potential availability violations.
1991 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
1992
1993 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
1994 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
1995
1996 /// Called before parsing a function declarator belonging to a function
1997 /// declaration.
1998 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
1999 unsigned TemplateParameterDepth);
2000
2001 /// Called after parsing a function declarator belonging to a function
2002 /// declaration.
2003 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2004
2005 void ActOnComment(SourceRange Comment);
2006
2007 //===--------------------------------------------------------------------===//
2008 // Type Analysis / Processing: SemaType.cpp.
2009 //
2010
2011 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2012 const DeclSpec *DS = nullptr);
2013 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2014 const DeclSpec *DS = nullptr);
2015 QualType BuildPointerType(QualType T,
2016 SourceLocation Loc, DeclarationName Entity);
2017 QualType BuildReferenceType(QualType T, bool LValueRef,
2018 SourceLocation Loc, DeclarationName Entity);
2019 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2020 Expr *ArraySize, unsigned Quals,
2021 SourceRange Brackets, DeclarationName Entity);
2022 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2023 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2024 SourceLocation AttrLoc);
2025 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2026 SourceLocation AttrLoc);
2027
2028 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2029 SourceLocation AttrLoc);
2030
2031 /// Same as above, but constructs the AddressSpace index if not provided.
2032 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2033 SourceLocation AttrLoc);
2034
2035 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2036
2037 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2038
2039 /// Build a function type.
2040 ///
2041 /// This routine checks the function type according to C++ rules and
2042 /// under the assumption that the result type and parameter types have
2043 /// just been instantiated from a template. It therefore duplicates
2044 /// some of the behavior of GetTypeForDeclarator, but in a much
2045 /// simpler form that is only suitable for this narrow use case.
2046 ///
2047 /// \param T The return type of the function.
2048 ///
2049 /// \param ParamTypes The parameter types of the function. This array
2050 /// will be modified to account for adjustments to the types of the
2051 /// function parameters.
2052 ///
2053 /// \param Loc The location of the entity whose type involves this
2054 /// function type or, if there is no such entity, the location of the
2055 /// type that will have function type.
2056 ///
2057 /// \param Entity The name of the entity that involves the function
2058 /// type, if known.
2059 ///
2060 /// \param EPI Extra information about the function type. Usually this will
2061 /// be taken from an existing function with the same prototype.
2062 ///
2063 /// \returns A suitable function type, if there are no errors. The
2064 /// unqualified type will always be a FunctionProtoType.
2065 /// Otherwise, returns a NULL type.
2066 QualType BuildFunctionType(QualType T,
2067 MutableArrayRef<QualType> ParamTypes,
2068 SourceLocation Loc, DeclarationName Entity,
2069 const FunctionProtoType::ExtProtoInfo &EPI);
2070
2071 QualType BuildMemberPointerType(QualType T, QualType Class,
2072 SourceLocation Loc,
2073 DeclarationName Entity);
2074 QualType BuildBlockPointerType(QualType T,
2075 SourceLocation Loc, DeclarationName Entity);
2076 QualType BuildParenType(QualType T);
2077 QualType BuildAtomicType(QualType T, SourceLocation Loc);
2078 QualType BuildReadPipeType(QualType T,
2079 SourceLocation Loc);
2080 QualType BuildWritePipeType(QualType T,
2081 SourceLocation Loc);
2082 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2083
2084 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2085 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2086
2087 /// Package the given type and TSI into a ParsedType.
2088 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2089 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2090 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2091 static QualType GetTypeFromParser(ParsedType Ty,
2092 TypeSourceInfo **TInfo = nullptr);
2093 CanThrowResult canThrow(const Stmt *E);
2094 /// Determine whether the callee of a particular function call can throw.
2095 /// E, D and Loc are all optional.
2096 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2097 SourceLocation Loc = SourceLocation());
2098 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2099 const FunctionProtoType *FPT);
2100 void UpdateExceptionSpec(FunctionDecl *FD,
2101 const FunctionProtoType::ExceptionSpecInfo &ESI);
2102 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2103 bool CheckDistantExceptionSpec(QualType T);
2104 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2105 bool CheckEquivalentExceptionSpec(
2106 const FunctionProtoType *Old, SourceLocation OldLoc,
2107 const FunctionProtoType *New, SourceLocation NewLoc);
2108 bool CheckEquivalentExceptionSpec(
2109 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2110 const FunctionProtoType *Old, SourceLocation OldLoc,
2111 const FunctionProtoType *New, SourceLocation NewLoc);
2112 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2113 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2114 const PartialDiagnostic &NestedDiagID,
2115 const PartialDiagnostic &NoteID,
2116 const PartialDiagnostic &NoThrowDiagID,
2117 const FunctionProtoType *Superset,
2118 SourceLocation SuperLoc,
2119 const FunctionProtoType *Subset,
2120 SourceLocation SubLoc);
2121 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2122 const PartialDiagnostic &NoteID,
2123 const FunctionProtoType *Target,
2124 SourceLocation TargetLoc,
2125 const FunctionProtoType *Source,
2126 SourceLocation SourceLoc);
2127
2128 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2129
2130 /// The parser has parsed the context-sensitive type 'instancetype'
2131 /// in an Objective-C message declaration. Return the appropriate type.
2132 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2133
2134 /// Abstract class used to diagnose incomplete types.
2135 struct TypeDiagnoser {
2136 TypeDiagnoser() {}
2137
2138 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2139 virtual ~TypeDiagnoser() {}
2140 };
2141
2142 static int getPrintable(int I) { return I; }
2143 static unsigned getPrintable(unsigned I) { return I; }
2144 static bool getPrintable(bool B) { return B; }
2145 static const char * getPrintable(const char *S) { return S; }
2146 static StringRef getPrintable(StringRef S) { return S; }
2147 static const std::string &getPrintable(const std::string &S) { return S; }
2148 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2149 return II;
2150 }
2151 static DeclarationName getPrintable(DeclarationName N) { return N; }
2152 static QualType getPrintable(QualType T) { return T; }
2153 static SourceRange getPrintable(SourceRange R) { return R; }
2154 static SourceRange getPrintable(SourceLocation L) { return L; }
2155 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2156 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2157
2158 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2159 protected:
2160 unsigned DiagID;
2161 std::tuple<const Ts &...> Args;
2162
2163 template <std::size_t... Is>
2164 void emit(const SemaDiagnosticBuilder &DB,
2165 std::index_sequence<Is...>) const {
2166 // Apply all tuple elements to the builder in order.
2167 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2168 (void)Dummy;
2169 }
2170
2171 public:
2172 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2173 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2174 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "clang/include/clang/Sema/Sema.h", 2174, __extension__ __PRETTY_FUNCTION__
))
;
2175 }
2176
2177 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2178 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2179 emit(DB, std::index_sequence_for<Ts...>());
2180 DB << T;
2181 }
2182 };
2183
2184 /// Do a check to make sure \p Name looks like a legal argument for the
2185 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2186 /// is invalid for the given declaration.
2187 ///
2188 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2189 ///
2190 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2191 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2192 const ParsedAttr &AL, bool IsAsync);
2193
2194 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2195 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2196 /// For example, a diagnostic with no other parameters would generally have
2197 /// the form "...%select{incomplete|sizeless}0 type %1...".
2198 template <typename... Ts>
2199 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2200 public:
2201 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2202 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2203
2204 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2205 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2206 this->emit(DB, std::index_sequence_for<Ts...>());
2207 DB << T->isSizelessType() << T;
2208 }
2209 };
2210
2211 enum class CompleteTypeKind {
2212 /// Apply the normal rules for complete types. In particular,
2213 /// treat all sizeless types as incomplete.
2214 Normal,
2215
2216 /// Relax the normal rules for complete types so that they include
2217 /// sizeless built-in types.
2218 AcceptSizeless,
2219
2220 // FIXME: Eventually we should flip the default to Normal and opt in
2221 // to AcceptSizeless rather than opt out of it.
2222 Default = AcceptSizeless
2223 };
2224
2225private:
2226 /// Methods for marking which expressions involve dereferencing a pointer
2227 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2228 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2229 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2230 /// `*p`, but need to check that `address of` is called on it. This requires
2231 /// keeping a container of all pending expressions and checking if the address
2232 /// of them are eventually taken.
2233 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2234 void CheckAddressOfNoDeref(const Expr *E);
2235 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2236
2237 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2238 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2239
2240 struct ModuleScope {
2241 SourceLocation BeginLoc;
2242 clang::Module *Module = nullptr;
2243 bool ModuleInterface = false;
2244 bool IsPartition = false;
2245 bool ImplicitGlobalModuleFragment = false;
2246 VisibleModuleSet OuterVisibleModules;
2247 };
2248 /// The modules we're currently parsing.
2249 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2250 /// The global module fragment of the current translation unit.
2251 clang::Module *GlobalModuleFragment = nullptr;
2252
2253 /// The modules we imported directly.
2254 llvm::SmallPtrSet<clang::Module *, 8> DirectModuleImports;
2255
2256 /// Namespace definitions that we will export when they finish.
2257 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2258
2259 /// Get the module whose scope we are currently within.
2260 Module *getCurrentModule() const {
2261 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2262 }
2263
2264 /// Helper function to judge if we are in module purview.
2265 /// Return false if we are not in a module.
2266 bool isCurrentModulePurview() const {
2267 return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2268 }
2269
2270 /// Enter the scope of the global module.
2271 Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit);
2272 /// Leave the scope of the global module.
2273 void PopGlobalModuleFragment();
2274
2275 VisibleModuleSet VisibleModules;
2276
2277public:
2278 /// Get the module owning an entity.
2279 Module *getOwningModule(const Decl *Entity) {
2280 return Entity->getOwningModule();
2281 }
2282
2283 bool isModuleDirectlyImported(const Module *M) {
2284 return DirectModuleImports.contains(M);
2285 }
2286
2287 /// Make a merged definition of an existing hidden definition \p ND
2288 /// visible at the specified location.
2289 void makeMergedDefinitionVisible(NamedDecl *ND);
2290
2291 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2292
2293 // When loading a non-modular PCH files, this is used to restore module
2294 // visibility.
2295 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2296 VisibleModules.setVisible(Mod, ImportLoc);
2297 }
2298
2299 /// Determine whether a declaration is visible to name lookup.
2300 bool isVisible(const NamedDecl *D) {
2301 return D->isUnconditionallyVisible() || isVisibleSlow(D);
2302 }
2303
2304 /// Determine whether any declaration of an entity is visible.
2305 bool
2306 hasVisibleDeclaration(const NamedDecl *D,
2307 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2308 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2309 }
2310 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2311 llvm::SmallVectorImpl<Module *> *Modules);
2312
2313 bool hasVisibleMergedDefinition(NamedDecl *Def);
2314 bool hasMergedDefinitionInCurrentModule(NamedDecl *Def);
2315
2316 /// Determine if \p D and \p Suggested have a structurally compatible
2317 /// layout as described in C11 6.2.7/1.
2318 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2319
2320 /// Determine if \p D has a visible definition. If not, suggest a declaration
2321 /// that should be made visible to expose the definition.
2322 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2323 bool OnlyNeedComplete = false);
2324 bool hasVisibleDefinition(const NamedDecl *D) {
2325 NamedDecl *Hidden;
2326 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2327 }
2328
2329 /// Determine if the template parameter \p D has a visible default argument.
2330 bool
2331 hasVisibleDefaultArgument(const NamedDecl *D,
2332 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2333
2334 /// Determine if there is a visible declaration of \p D that is an explicit
2335 /// specialization declaration for a specialization of a template. (For a
2336 /// member specialization, use hasVisibleMemberSpecialization.)
2337 bool hasVisibleExplicitSpecialization(
2338 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2339
2340 /// Determine if there is a visible declaration of \p D that is a member
2341 /// specialization declaration (as opposed to an instantiated declaration).
2342 bool hasVisibleMemberSpecialization(
2343 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2344
2345 /// Determine if \p A and \p B are equivalent internal linkage declarations
2346 /// from different modules, and thus an ambiguity error can be downgraded to
2347 /// an extension warning.
2348 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2349 const NamedDecl *B);
2350 void diagnoseEquivalentInternalLinkageDeclarations(
2351 SourceLocation Loc, const NamedDecl *D,
2352 ArrayRef<const NamedDecl *> Equiv);
2353
2354 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2355
2356 bool isCompleteType(SourceLocation Loc, QualType T,
2357 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2358 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2359 }
2360 bool RequireCompleteType(SourceLocation Loc, QualType T,
2361 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2362 bool RequireCompleteType(SourceLocation Loc, QualType T,
2363 CompleteTypeKind Kind, unsigned DiagID);
2364
2365 bool RequireCompleteType(SourceLocation Loc, QualType T,
2366 TypeDiagnoser &Diagnoser) {
2367 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2368 }
2369 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2370 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2371 }
2372
2373 template <typename... Ts>
2374 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2375 const Ts &...Args) {
2376 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2377 return RequireCompleteType(Loc, T, Diagnoser);
2378 }
2379
2380 template <typename... Ts>
2381 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2382 const Ts &... Args) {
2383 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2384 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2385 }
2386
2387 /// Get the type of expression E, triggering instantiation to complete the
2388 /// type if necessary -- that is, if the expression refers to a templated
2389 /// static data member of incomplete array type.
2390 ///
2391 /// May still return an incomplete type if instantiation was not possible or
2392 /// if the type is incomplete for a different reason. Use
2393 /// RequireCompleteExprType instead if a diagnostic is expected for an
2394 /// incomplete expression type.
2395 QualType getCompletedType(Expr *E);
2396
2397 void completeExprArrayBound(Expr *E);
2398 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2399 TypeDiagnoser &Diagnoser);
2400 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2401
2402 template <typename... Ts>
2403 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2404 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2405 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2406 }
2407
2408 template <typename... Ts>
2409 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2410 const Ts &... Args) {
2411 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2412 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2413 }
2414
2415 bool RequireLiteralType(SourceLocation Loc, QualType T,
2416 TypeDiagnoser &Diagnoser);
2417 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2418
2419 template <typename... Ts>
2420 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2421 const Ts &...Args) {
2422 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2423 return RequireLiteralType(Loc, T, Diagnoser);
2424 }
2425
2426 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2427 const CXXScopeSpec &SS, QualType T,
2428 TagDecl *OwnedTagDecl = nullptr);
2429
2430 // Returns the underlying type of a decltype with the given expression.
2431 QualType getDecltypeForExpr(Expr *E);
2432
2433 QualType BuildTypeofExprType(Expr *E);
2434 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2435 /// context, such as when building a type for decltype(auto).
2436 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2437 QualType BuildUnaryTransformType(QualType BaseType,
2438 UnaryTransformType::UTTKind UKind,
2439 SourceLocation Loc);
2440
2441 //===--------------------------------------------------------------------===//
2442 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2443 //
2444
2445 struct SkipBodyInfo {
2446 SkipBodyInfo()
2447 : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr),
2448 New(nullptr) {}
2449 bool ShouldSkip;
2450 bool CheckSameAsPrevious;
2451 NamedDecl *Previous;
2452 NamedDecl *New;
2453 };
2454
2455 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2456
2457 void DiagnoseUseOfUnimplementedSelectors();
2458
2459 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2460
2461 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2462 Scope *S, CXXScopeSpec *SS = nullptr,
2463 bool isClassName = false, bool HasTrailingDot = false,
2464 ParsedType ObjectType = nullptr,
2465 bool IsCtorOrDtorName = false,
2466 bool WantNontrivialTypeSourceInfo = false,
2467 bool IsClassTemplateDeductionContext = true,
2468 IdentifierInfo **CorrectedII = nullptr);
2469 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2470 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2471 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2472 SourceLocation IILoc,
2473 Scope *S,
2474 CXXScopeSpec *SS,
2475 ParsedType &SuggestedType,
2476 bool IsTemplateName = false);
2477
2478 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2479 /// type name has failed in a dependent context. In these situations, we
2480 /// automatically form a DependentTypeName that will retry lookup in a related
2481 /// scope during instantiation.
2482 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2483 SourceLocation NameLoc,
2484 bool IsTemplateTypeArg);
2485
2486 /// Describes the result of the name lookup and resolution performed
2487 /// by \c ClassifyName().
2488 enum NameClassificationKind {
2489 /// This name is not a type or template in this context, but might be
2490 /// something else.
2491 NC_Unknown,
2492 /// Classification failed; an error has been produced.
2493 NC_Error,
2494 /// The name has been typo-corrected to a keyword.
2495 NC_Keyword,
2496 /// The name was classified as a type.
2497 NC_Type,
2498 /// The name was classified as a specific non-type, non-template
2499 /// declaration. ActOnNameClassifiedAsNonType should be called to
2500 /// convert the declaration to an expression.
2501 NC_NonType,
2502 /// The name was classified as an ADL-only function name.
2503 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2504 /// result to an expression.
2505 NC_UndeclaredNonType,
2506 /// The name denotes a member of a dependent type that could not be
2507 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2508 /// convert the result to an expression.
2509 NC_DependentNonType,
2510 /// The name was classified as an overload set, and an expression
2511 /// representing that overload set has been formed.
2512 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2513 /// expression referencing the overload set.
2514 NC_OverloadSet,
2515 /// The name was classified as a template whose specializations are types.
2516 NC_TypeTemplate,
2517 /// The name was classified as a variable template name.
2518 NC_VarTemplate,
2519 /// The name was classified as a function template name.
2520 NC_FunctionTemplate,
2521 /// The name was classified as an ADL-only function template name.
2522 NC_UndeclaredTemplate,
2523 /// The name was classified as a concept name.
2524 NC_Concept,
2525 };
2526
2527 class NameClassification {
2528 NameClassificationKind Kind;
2529 union {
2530 ExprResult Expr;
2531 NamedDecl *NonTypeDecl;
2532 TemplateName Template;
2533 ParsedType Type;
2534 };
2535
2536 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2537
2538 public:
2539 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2540
2541 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2542
2543 static NameClassification Error() {
2544 return NameClassification(NC_Error);
2545 }
2546
2547 static NameClassification Unknown() {
2548 return NameClassification(NC_Unknown);
2549 }
2550
2551 static NameClassification OverloadSet(ExprResult E) {
2552 NameClassification Result(NC_OverloadSet);
2553 Result.Expr = E;
2554 return Result;
2555 }
2556
2557 static NameClassification NonType(NamedDecl *D) {
2558 NameClassification Result(NC_NonType);
2559 Result.NonTypeDecl = D;
2560 return Result;
2561 }
2562
2563 static NameClassification UndeclaredNonType() {
2564 return NameClassification(NC_UndeclaredNonType);
2565 }
2566
2567 static NameClassification DependentNonType() {
2568 return NameClassification(NC_DependentNonType);
2569 }
2570
2571 static NameClassification TypeTemplate(TemplateName Name) {
2572 NameClassification Result(NC_TypeTemplate);
2573 Result.Template = Name;
2574 return Result;
2575 }
2576
2577 static NameClassification VarTemplate(TemplateName Name) {
2578 NameClassification Result(NC_VarTemplate);
2579 Result.Template = Name;
2580 return Result;
2581 }
2582
2583 static NameClassification FunctionTemplate(TemplateName Name) {
2584 NameClassification Result(NC_FunctionTemplate);
2585 Result.Template = Name;
2586 return Result;
2587 }
2588
2589 static NameClassification Concept(TemplateName Name) {
2590 NameClassification Result(NC_Concept);
2591 Result.Template = Name;
2592 return Result;
2593 }
2594
2595 static NameClassification UndeclaredTemplate(TemplateName Name) {
2596 NameClassification Result(NC_UndeclaredTemplate);
2597 Result.Template = Name;
2598 return Result;
2599 }
2600
2601 NameClassificationKind getKind() const { return Kind; }
2602
2603 ExprResult getExpression() const {
2604 assert(Kind == NC_OverloadSet)(static_cast <bool> (Kind == NC_OverloadSet) ? void (0)
: __assert_fail ("Kind == NC_OverloadSet", "clang/include/clang/Sema/Sema.h"
, 2604, __extension__ __PRETTY_FUNCTION__))
;
2605 return Expr;
2606 }
2607
2608 ParsedType getType() const {
2609 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "clang/include/clang/Sema/Sema.h", 2609,
__extension__ __PRETTY_FUNCTION__))
;
2610 return Type;
2611 }
2612
2613 NamedDecl *getNonTypeDecl() const {
2614 assert(Kind == NC_NonType)(static_cast <bool> (Kind == NC_NonType) ? void (0) : __assert_fail
("Kind == NC_NonType", "clang/include/clang/Sema/Sema.h", 2614
, __extension__ __PRETTY_FUNCTION__))
;
2615 return NonTypeDecl;
2616 }
2617
2618 TemplateName getTemplateName() const {
2619 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2621, __extension__ __PRETTY_FUNCTION__
))
2620 Kind == NC_VarTemplate || Kind == NC_Concept ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2621, __extension__ __PRETTY_FUNCTION__
))
2621 Kind == NC_UndeclaredTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2621, __extension__ __PRETTY_FUNCTION__
))
;
2622 return Template;
2623 }
2624
2625 TemplateNameKind getTemplateNameKind() const {
2626 switch (Kind) {
2627 case NC_TypeTemplate:
2628 return TNK_Type_template;
2629 case NC_FunctionTemplate:
2630 return TNK_Function_template;
2631 case NC_VarTemplate:
2632 return TNK_Var_template;
2633 case NC_Concept:
2634 return TNK_Concept_template;
2635 case NC_UndeclaredTemplate:
2636 return TNK_Undeclared_template;
2637 default:
2638 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "clang/include/clang/Sema/Sema.h", 2638)
;
2639 }
2640 }
2641 };
2642
2643 /// Perform name lookup on the given name, classifying it based on
2644 /// the results of name lookup and the following token.
2645 ///
2646 /// This routine is used by the parser to resolve identifiers and help direct
2647 /// parsing. When the identifier cannot be found, this routine will attempt
2648 /// to correct the typo and classify based on the resulting name.
2649 ///
2650 /// \param S The scope in which we're performing name lookup.
2651 ///
2652 /// \param SS The nested-name-specifier that precedes the name.
2653 ///
2654 /// \param Name The identifier. If typo correction finds an alternative name,
2655 /// this pointer parameter will be updated accordingly.
2656 ///
2657 /// \param NameLoc The location of the identifier.
2658 ///
2659 /// \param NextToken The token following the identifier. Used to help
2660 /// disambiguate the name.
2661 ///
2662 /// \param CCC The correction callback, if typo correction is desired.
2663 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2664 IdentifierInfo *&Name, SourceLocation NameLoc,
2665 const Token &NextToken,
2666 CorrectionCandidateCallback *CCC = nullptr);
2667
2668 /// Act on the result of classifying a name as an undeclared (ADL-only)
2669 /// non-type declaration.
2670 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2671 SourceLocation NameLoc);
2672 /// Act on the result of classifying a name as an undeclared member of a
2673 /// dependent base class.
2674 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2675 IdentifierInfo *Name,
2676 SourceLocation NameLoc,
2677 bool IsAddressOfOperand);
2678 /// Act on the result of classifying a name as a specific non-type
2679 /// declaration.
2680 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2681 NamedDecl *Found,
2682 SourceLocation NameLoc,
2683 const Token &NextToken);
2684 /// Act on the result of classifying a name as an overload set.
2685 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2686
2687 /// Describes the detailed kind of a template name. Used in diagnostics.
2688 enum class TemplateNameKindForDiagnostics {
2689 ClassTemplate,
2690 FunctionTemplate,
2691 VarTemplate,
2692 AliasTemplate,
2693 TemplateTemplateParam,
2694 Concept,
2695 DependentTemplate
2696 };
2697 TemplateNameKindForDiagnostics
2698 getTemplateNameKindForDiagnostics(TemplateName Name);
2699
2700 /// Determine whether it's plausible that E was intended to be a
2701 /// template-name.
2702 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2703 if (!getLangOpts().CPlusPlus || E.isInvalid())
2704 return false;
2705 Dependent = false;
2706 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2707 return !DRE->hasExplicitTemplateArgs();
2708 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2709 return !ME->hasExplicitTemplateArgs();
2710 Dependent = true;
2711 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2712 return !DSDRE->hasExplicitTemplateArgs();
2713 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2714 return !DSME->hasExplicitTemplateArgs();
2715 // Any additional cases recognized here should also be handled by
2716 // diagnoseExprIntendedAsTemplateName.
2717 return false;
2718 }
2719 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2720 SourceLocation Less,
2721 SourceLocation Greater);
2722
2723 void warnOnReservedIdentifier(const NamedDecl *D);
2724
2725 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2726
2727 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2728 MultiTemplateParamsArg TemplateParameterLists);
2729 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2730 QualType &T, SourceLocation Loc,
2731 unsigned FailedFoldDiagID);
2732 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2733 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2734 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2735 DeclarationName Name, SourceLocation Loc,
2736 bool IsTemplateId);
2737 void
2738 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2739 SourceLocation FallbackLoc,
2740 SourceLocation ConstQualLoc = SourceLocation(),
2741 SourceLocation VolatileQualLoc = SourceLocation(),
2742 SourceLocation RestrictQualLoc = SourceLocation(),
2743 SourceLocation AtomicQualLoc = SourceLocation(),
2744 SourceLocation UnalignedQualLoc = SourceLocation());
2745
2746 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2747 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2748 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2749 const LookupResult &R);
2750 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2751 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2752 const LookupResult &R);
2753 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2754 const LookupResult &R);
2755 void CheckShadow(Scope *S, VarDecl *D);
2756
2757 /// Warn if 'E', which is an expression that is about to be modified, refers
2758 /// to a shadowing declaration.
2759 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2760
2761 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2762
2763private:
2764 /// Map of current shadowing declarations to shadowed declarations. Warn if
2765 /// it looks like the user is trying to modify the shadowing declaration.
2766 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2767
2768public:
2769 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2770 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2771 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2772 TypedefNameDecl *NewTD);
2773 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2774 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2775 TypeSourceInfo *TInfo,
2776 LookupResult &Previous);
2777 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2778 LookupResult &Previous, bool &Redeclaration);
2779 NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
2780 TypeSourceInfo *TInfo,
2781 LookupResult &Previous,
2782 MultiTemplateParamsArg TemplateParamLists,
2783 bool &AddToScope,
2784 ArrayRef<BindingDecl *> Bindings = None);
2785 NamedDecl *
2786 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2787 MultiTemplateParamsArg TemplateParamLists);
2788 // Returns true if the variable declaration is a redeclaration
2789 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2790 void CheckVariableDeclarationType(VarDecl *NewVD);
2791 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2792 Expr *Init);
2793 void CheckCompleteVariableDeclaration(VarDecl *VD);
2794 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2795 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2796
2797 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2798 TypeSourceInfo *TInfo,
2799 LookupResult &Previous,
2800 MultiTemplateParamsArg TemplateParamLists,
2801 bool &AddToScope);
2802 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2803
2804 enum class CheckConstexprKind {
2805 /// Diagnose issues that are non-constant or that are extensions.
2806 Diagnose,
2807 /// Identify whether this function satisfies the formal rules for constexpr
2808 /// functions in the current lanugage mode (with no extensions).
2809 CheckValid
2810 };
2811
2812 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2813 CheckConstexprKind Kind);
2814
2815 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2816 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2817 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2818 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2819 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2820 // Returns true if the function declaration is a redeclaration
2821 bool CheckFunctionDeclaration(Scope *S,
2822 FunctionDecl *NewFD, LookupResult &Previous,
2823 bool IsMemberSpecialization, bool DeclIsDefn);
2824 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2825 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2826 QualType NewT, QualType OldT);
2827 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2828 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2829 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2830 bool IsDefinition);
2831 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2832 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2833 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2834 SourceLocation Loc,
2835 QualType T);
2836 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2837 SourceLocation NameLoc, IdentifierInfo *Name,
2838 QualType T, TypeSourceInfo *TSInfo,
2839 StorageClass SC);
2840 void ActOnParamDefaultArgument(Decl *param,
2841 SourceLocation EqualLoc,
2842 Expr *defarg);
2843 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2844 SourceLocation ArgLoc);
2845 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2846 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2847 SourceLocation EqualLoc);
2848 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2849 SourceLocation EqualLoc);
2850
2851 // Contexts where using non-trivial C union types can be disallowed. This is
2852 // passed to err_non_trivial_c_union_in_invalid_context.
2853 enum NonTrivialCUnionContext {
2854 // Function parameter.
2855 NTCUC_FunctionParam,
2856 // Function return.
2857 NTCUC_FunctionReturn,
2858 // Default-initialized object.
2859 NTCUC_DefaultInitializedObject,
2860 // Variable with automatic storage duration.
2861 NTCUC_AutoVar,
2862 // Initializer expression that might copy from another object.
2863 NTCUC_CopyInit,
2864 // Assignment.
2865 NTCUC_Assignment,
2866 // Compound literal.
2867 NTCUC_CompoundLiteral,
2868 // Block capture.
2869 NTCUC_BlockCapture,
2870 // lvalue-to-rvalue conversion of volatile type.
2871 NTCUC_LValueToRValueVolatile,
2872 };
2873
2874 /// Emit diagnostics if the initializer or any of its explicit or
2875 /// implicitly-generated subexpressions require copying or
2876 /// default-initializing a type that is or contains a C union type that is
2877 /// non-trivial to copy or default-initialize.
2878 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
2879
2880 // These flags are passed to checkNonTrivialCUnion.
2881 enum NonTrivialCUnionKind {
2882 NTCUK_Init = 0x1,
2883 NTCUK_Destruct = 0x2,
2884 NTCUK_Copy = 0x4,
2885 };
2886
2887 /// Emit diagnostics if a non-trivial C union type or a struct that contains
2888 /// a non-trivial C union is used in an invalid context.
2889 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
2890 NonTrivialCUnionContext UseContext,
2891 unsigned NonTrivialKind);
2892
2893 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
2894 void ActOnUninitializedDecl(Decl *dcl);
2895 void ActOnInitializerError(Decl *Dcl);
2896
2897 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
2898 void ActOnCXXForRangeDecl(Decl *D);
2899 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
2900 IdentifierInfo *Ident,
2901 ParsedAttributes &Attrs);
2902 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
2903 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
2904 void CheckStaticLocalForDllExport(VarDecl *VD);
2905 void FinalizeDeclaration(Decl *D);
2906 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
2907 ArrayRef<Decl *> Group);
2908 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
2909
2910 /// Should be called on all declarations that might have attached
2911 /// documentation comments.
2912 void ActOnDocumentableDecl(Decl *D);
2913 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
2914
2915 enum class FnBodyKind {
2916 /// C++ [dcl.fct.def.general]p1
2917 /// function-body:
2918 /// ctor-initializer[opt] compound-statement
2919 /// function-try-block
2920 Other,
2921 /// = default ;
2922 Default,
2923 /// = delete ;
2924 Delete
2925 };
2926
2927 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
2928 SourceLocation LocAfterDecls);
2929 void CheckForFunctionRedefinition(
2930 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
2931 SkipBodyInfo *SkipBody = nullptr);
2932 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
2933 MultiTemplateParamsArg TemplateParamLists,
2934 SkipBodyInfo *SkipBody = nullptr,
2935 FnBodyKind BodyKind = FnBodyKind::Other);
2936 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
2937 SkipBodyInfo *SkipBody = nullptr,
2938 FnBodyKind BodyKind = FnBodyKind::Other);
2939 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
2940 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
2941 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
2942 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
2943 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
2944 bool isObjCMethodDecl(Decl *D) {
2945 return D && isa<ObjCMethodDecl>(D);
2946 }
2947
2948 /// Determine whether we can delay parsing the body of a function or
2949 /// function template until it is used, assuming we don't care about emitting
2950 /// code for that function.
2951 ///
2952 /// This will be \c false if we may need the body of the function in the
2953 /// middle of parsing an expression (where it's impractical to switch to
2954 /// parsing a different function), for instance, if it's constexpr in C++11
2955 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
2956 bool canDelayFunctionBody(const Declarator &D);
2957
2958 /// Determine whether we can skip parsing the body of a function
2959 /// definition, assuming we don't care about analyzing its body or emitting
2960 /// code for that function.
2961 ///
2962 /// This will be \c false only if we may need the body of the function in
2963 /// order to parse the rest of the program (for instance, if it is
2964 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
2965 bool canSkipFunctionBody(Decl *D);
2966
2967 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
2968 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
2969 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
2970 Decl *ActOnSkippedFunctionBody(Decl *Decl);
2971 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
2972
2973 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
2974 /// attribute for which parsing is delayed.
2975 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
2976
2977 /// Diagnose any unused parameters in the given sequence of
2978 /// ParmVarDecl pointers.
2979 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
2980
2981 /// Diagnose whether the size of parameters or return value of a
2982 /// function or obj-c method definition is pass-by-value and larger than a
2983 /// specified threshold.
2984 void
2985 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
2986 QualType ReturnTy, NamedDecl *D);
2987
2988 void DiagnoseInvalidJumps(Stmt *Body);
2989 Decl *ActOnFileScopeAsmDecl(Expr *expr,
2990 SourceLocation AsmLoc,
2991 SourceLocation RParenLoc);
2992
2993 /// Handle a C++11 empty-declaration and attribute-declaration.
2994 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
2995 SourceLocation SemiLoc);
2996
2997 enum class ModuleDeclKind {
2998 Interface, ///< 'export module X;'
2999 Implementation, ///< 'module X;'
3000 PartitionInterface, ///< 'export module X:Y;'
3001 PartitionImplementation, ///< 'module X:Y;'
3002 };
3003
3004 /// An enumeration to represent the transition of states in parsing module
3005 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3006 /// an error in state transition, the state is set to NotACXX20Module.
3007 enum class ModuleImportState {
3008 FirstDecl, ///< Parsing the first decl in a TU.
3009 GlobalFragment, ///< after 'module;' but before 'module X;'
3010 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3011 ImportFinished, ///< after any non-import decl.
3012 PrivateFragment, ///< after 'module :private;'.
3013 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3014 };
3015
3016private:
3017 /// The parser has begun a translation unit to be compiled as a C++20
3018 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3019 void HandleStartOfHeaderUnit();
3020
3021public:
3022 /// The parser has processed a module-declaration that begins the definition
3023 /// of a module interface or implementation.
3024 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3025 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3026 ModuleIdPath Path, ModuleIdPath Partition,
3027 ModuleImportState &ImportState);
3028
3029 /// The parser has processed a global-module-fragment declaration that begins
3030 /// the definition of the global module fragment of the current module unit.
3031 /// \param ModuleLoc The location of the 'module' keyword.
3032 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3033
3034 /// The parser has processed a private-module-fragment declaration that begins
3035 /// the definition of the private module fragment of the current module unit.
3036 /// \param ModuleLoc The location of the 'module' keyword.
3037 /// \param PrivateLoc The location of the 'private' keyword.
3038 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3039 SourceLocation PrivateLoc);
3040
3041 /// The parser has processed a module import declaration.
3042 ///
3043 /// \param StartLoc The location of the first token in the declaration. This
3044 /// could be the location of an '@', 'export', or 'import'.
3045 /// \param ExportLoc The location of the 'export' keyword, if any.
3046 /// \param ImportLoc The location of the 'import' keyword.
3047 /// \param Path The module toplevel name as an access path.
3048 /// \param IsPartition If the name is for a partition.
3049 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3050 SourceLocation ExportLoc,
3051 SourceLocation ImportLoc, ModuleIdPath Path,
3052 bool IsPartition = false);
3053 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3054 SourceLocation ExportLoc,
3055 SourceLocation ImportLoc, Module *M,
3056 ModuleIdPath Path = {});
3057
3058 /// The parser has processed a module import translated from a
3059 /// #include or similar preprocessing directive.
3060 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3061 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3062
3063 /// The parsed has entered a submodule.
3064 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3065 /// The parser has left a submodule.
3066 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3067
3068 /// Create an implicit import of the given module at the given
3069 /// source location, for error recovery, if possible.
3070 ///
3071 /// This routine is typically used when an entity found by name lookup
3072 /// is actually hidden within a module that we know about but the user
3073 /// has forgotten to import.
3074 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3075 Module *Mod);
3076
3077 /// Kinds of missing import. Note, the values of these enumerators correspond
3078 /// to %select values in diagnostics.
3079 enum class MissingImportKind {
3080 Declaration,
3081 Definition,
3082 DefaultArgument,
3083 ExplicitSpecialization,
3084 PartialSpecialization
3085 };
3086
3087 /// Diagnose that the specified declaration needs to be visible but
3088 /// isn't, and suggest a module import that would resolve the problem.
3089 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3090 MissingImportKind MIK, bool Recover = true);
3091 void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
3092 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3093 MissingImportKind MIK, bool Recover);
3094
3095 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3096 SourceLocation LBraceLoc);
3097 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3098 SourceLocation RBraceLoc);
3099
3100 /// We've found a use of a templated declaration that would trigger an
3101 /// implicit instantiation. Check that any relevant explicit specializations
3102 /// and partial specializations are visible, and diagnose if not.
3103 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3104
3105 /// Retrieve a suitable printing policy for diagnostics.
3106 PrintingPolicy getPrintingPolicy() const {
3107 return getPrintingPolicy(Context, PP);
3108 }
3109
3110 /// Retrieve a suitable printing policy for diagnostics.
3111 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3112 const Preprocessor &PP);
3113
3114 /// Scope actions.
3115 void ActOnPopScope(SourceLocation Loc, Scope *S);
3116 void ActOnTranslationUnitScope(Scope *S);
3117
3118 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3119 RecordDecl *&AnonRecord);
3120 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3121 MultiTemplateParamsArg TemplateParams,
3122 bool IsExplicitInstantiation,
3123 RecordDecl *&AnonRecord);
3124
3125 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3126 AccessSpecifier AS,
3127 RecordDecl *Record,
3128 const PrintingPolicy &Policy);
3129
3130 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3131 RecordDecl *Record);
3132
3133 /// Common ways to introduce type names without a tag for use in diagnostics.
3134 /// Keep in sync with err_tag_reference_non_tag.
3135 enum NonTagKind {
3136 NTK_NonStruct,
3137 NTK_NonClass,
3138 NTK_NonUnion,
3139 NTK_NonEnum,
3140 NTK_Typedef,
3141 NTK_TypeAlias,
3142 NTK_Template,
3143 NTK_TypeAliasTemplate,
3144 NTK_TemplateTemplateArgument,
3145 };
3146
3147 /// Given a non-tag type declaration, returns an enum useful for indicating
3148 /// what kind of non-tag type this is.
3149 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3150
3151 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3152 TagTypeKind NewTag, bool isDefinition,
3153 SourceLocation NewTagLoc,
3154 const IdentifierInfo *Name);
3155
3156 enum TagUseKind {
3157 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3158 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3159 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3160 TUK_Friend // Friend declaration: 'friend struct foo;'
3161 };
3162
3163 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3164 SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name,
3165 SourceLocation NameLoc, const ParsedAttributesView &Attr,
3166 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
3167 MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl,
3168 bool &IsDependent, SourceLocation ScopedEnumKWLoc,
3169 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3170 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3171 SkipBodyInfo *SkipBody = nullptr);
3172
3173 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3174 unsigned TagSpec, SourceLocation TagLoc,
3175 CXXScopeSpec &SS, IdentifierInfo *Name,
3176 SourceLocation NameLoc,
3177 const ParsedAttributesView &Attr,
3178 MultiTemplateParamsArg TempParamLists);
3179
3180 TypeResult ActOnDependentTag(Scope *S,
3181 unsigned TagSpec,
3182 TagUseKind TUK,
3183 const CXXScopeSpec &SS,
3184 IdentifierInfo *Name,
3185 SourceLocation TagLoc,
3186 SourceLocation NameLoc);
3187
3188 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3189 IdentifierInfo *ClassName,
3190 SmallVectorImpl<Decl *> &Decls);
3191 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3192 Declarator &D, Expr *BitfieldWidth);
3193
3194 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3195 Declarator &D, Expr *BitfieldWidth,
3196 InClassInitStyle InitStyle,
3197 AccessSpecifier AS);
3198 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3199 SourceLocation DeclStart, Declarator &D,
3200 Expr *BitfieldWidth,
3201 InClassInitStyle InitStyle,
3202 AccessSpecifier AS,
3203 const ParsedAttr &MSPropertyAttr);
3204
3205 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3206 TypeSourceInfo *TInfo,
3207 RecordDecl *Record, SourceLocation Loc,
3208 bool Mutable, Expr *BitfieldWidth,
3209 InClassInitStyle InitStyle,
3210 SourceLocation TSSL,
3211 AccessSpecifier AS, NamedDecl *PrevDecl,
3212 Declarator *D = nullptr);
3213
3214 bool CheckNontrivialField(FieldDecl *FD);
3215 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3216
3217 enum TrivialABIHandling {
3218 /// The triviality of a method unaffected by "trivial_abi".
3219 TAH_IgnoreTrivialABI,
3220
3221 /// The triviality of a method affected by "trivial_abi".
3222 TAH_ConsiderTrivialABI
3223 };
3224
3225 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3226 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3227 bool Diagnose = false);
3228
3229 /// For a defaulted function, the kind of defaulted function that it is.
3230 class DefaultedFunctionKind {
3231 CXXSpecialMember SpecialMember : 8;
3232 DefaultedComparisonKind Comparison : 8;
3233
3234 public:
3235 DefaultedFunctionKind()
3236 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3237 }
3238 DefaultedFunctionKind(CXXSpecialMember CSM)
3239 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3240 DefaultedFunctionKind(DefaultedComparisonKind Comp)
3241 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3242
3243 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3244 bool isComparison() const {
3245 return Comparison != DefaultedComparisonKind::None;
3246 }
3247
3248 explicit operator bool() const {
3249 return isSpecialMember() || isComparison();
3250 }
3251
3252 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3253 DefaultedComparisonKind asComparison() const { return Comparison; }
3254
3255 /// Get the index of this function kind for use in diagnostics.
3256 unsigned getDiagnosticIndex() const {
3257 static_assert(CXXInvalid > CXXDestructor,
3258 "invalid should have highest index");
3259 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3260 "none should be equal to zero");
3261 return SpecialMember + (unsigned)Comparison;
3262 }
3263 };
3264
3265 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3266
3267 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3268 return getDefaultedFunctionKind(MD).asSpecialMember();
3269 }
3270 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3271 return getDefaultedFunctionKind(FD).asComparison();
3272 }
3273
3274 void ActOnLastBitfield(SourceLocation DeclStart,
3275 SmallVectorImpl<Decl *> &AllIvarDecls);
3276 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3277 Declarator &D, Expr *BitfieldWidth,
3278 tok::ObjCKeywordKind visibility);
3279
3280 // This is used for both record definitions and ObjC interface declarations.
3281 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3282 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3283 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3284
3285 /// ActOnTagStartDefinition - Invoked when we have entered the
3286 /// scope of a tag's definition (e.g., for an enumeration, class,
3287 /// struct, or union).
3288 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3289
3290 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3291 /// Differently from C++, actually parse the body and reject / error out
3292 /// in case of a structural mismatch.
3293 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3294
3295 typedef void *SkippedDefinitionContext;
3296
3297 /// Invoked when we enter a tag definition that we're skipping.
3298 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3299
3300 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl);
3301
3302 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3303 /// C++ record definition's base-specifiers clause and are starting its
3304 /// member declarations.
3305 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3306 SourceLocation FinalLoc,
3307 bool IsFinalSpelledSealed,
3308 bool IsAbstract,
3309 SourceLocation LBraceLoc);
3310
3311 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3312 /// the definition of a tag (enumeration, class, struct, or union).
3313 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3314 SourceRange BraceRange);
3315
3316 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3317
3318 void ActOnObjCContainerFinishDefinition();
3319
3320 /// Invoked when we must temporarily exit the objective-c container
3321 /// scope for parsing/looking-up C constructs.
3322 ///
3323 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3324 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC);
3325 void ActOnObjCReenterContainerContext(DeclContext *DC);
3326
3327 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3328 /// error parsing the definition of a tag.
3329 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3330
3331 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3332 EnumConstantDecl *LastEnumConst,
3333 SourceLocation IdLoc,
3334 IdentifierInfo *Id,
3335 Expr *val);
3336 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3337 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3338 QualType EnumUnderlyingTy, bool IsFixed,
3339 const EnumDecl *Prev);
3340
3341 /// Determine whether the body of an anonymous enumeration should be skipped.
3342 /// \param II The name of the first enumerator.
3343 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3344 SourceLocation IILoc);
3345
3346 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3347 SourceLocation IdLoc, IdentifierInfo *Id,
3348 const ParsedAttributesView &Attrs,
3349 SourceLocation EqualLoc, Expr *Val);
3350 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3351 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3352 const ParsedAttributesView &Attr);
3353
3354 /// Set the current declaration context until it gets popped.
3355 void PushDeclContext(Scope *S, DeclContext *DC);
3356 void PopDeclContext();
3357
3358 /// EnterDeclaratorContext - Used when we must lookup names in the context
3359 /// of a declarator's nested name specifier.
3360 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3361 void ExitDeclaratorContext(Scope *S);
3362
3363 /// Enter a template parameter scope, after it's been associated with a particular
3364 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3365 /// in the correct order.
3366 void EnterTemplatedContext(Scope *S, DeclContext *DC);
3367
3368 /// Push the parameters of D, which must be a function, into scope.
3369 void ActOnReenterFunctionContext(Scope* S, Decl* D);
3370 void ActOnExitFunctionContext();
3371
3372 /// If \p AllowLambda is true, treat lambda as function.
3373 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false);
3374
3375 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3376 /// current context is not inside a function. If \p AllowLambda is true,
3377 /// this can return the call operator of an enclosing lambda, otherwise
3378 /// lambdas are skipped when looking for an enclosing function.
3379 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false);
3380
3381 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3382 /// the method decl for the method being parsed. If we're currently
3383 /// in a 'block', this returns the containing context.
3384 ObjCMethodDecl *getCurMethodDecl();
3385
3386 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3387 /// or C function we're in, otherwise return null. If we're currently
3388 /// in a 'block', this returns the containing context.
3389 NamedDecl *getCurFunctionOrMethodDecl();
3390
3391 /// Add this decl to the scope shadowed decl chains.
3392 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3393
3394 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3395 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3396 /// true if 'D' belongs to the given declaration context.
3397 ///
3398 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3399 /// enclosing namespace set of the context, rather than contained
3400 /// directly within it.
3401 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3402 bool AllowInlineNamespace = false);
3403
3404 /// Finds the scope corresponding to the given decl context, if it
3405 /// happens to be an enclosing scope. Otherwise return NULL.
3406 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3407
3408 /// Subroutines of ActOnDeclarator().
3409 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3410 TypeSourceInfo *TInfo);
3411 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3412
3413 /// Describes the kind of merge to perform for availability
3414 /// attributes (including "deprecated", "unavailable", and "availability").
3415 enum AvailabilityMergeKind {
3416 /// Don't merge availability attributes at all.
3417 AMK_None,
3418 /// Merge availability attributes for a redeclaration, which requires
3419 /// an exact match.
3420 AMK_Redeclaration,
3421 /// Merge availability attributes for an override, which requires
3422 /// an exact match or a weakening of constraints.
3423 AMK_Override,
3424 /// Merge availability attributes for an implementation of
3425 /// a protocol requirement.
3426 AMK_ProtocolImplementation,
3427 /// Merge availability attributes for an implementation of
3428 /// an optional protocol requirement.
3429 AMK_OptionalProtocolImplementation
3430 };
3431
3432 /// Describes the kind of priority given to an availability attribute.
3433 ///
3434 /// The sum of priorities deteremines the final priority of the attribute.
3435 /// The final priority determines how the attribute will be merged.
3436 /// An attribute with a lower priority will always remove higher priority
3437 /// attributes for the specified platform when it is being applied. An
3438 /// attribute with a higher priority will not be applied if the declaration
3439 /// already has an availability attribute with a lower priority for the
3440 /// specified platform. The final prirority values are not expected to match
3441 /// the values in this enumeration, but instead should be treated as a plain
3442 /// integer value. This enumeration just names the priority weights that are
3443 /// used to calculate that final vaue.
3444 enum AvailabilityPriority : int {
3445 /// The availability attribute was specified explicitly next to the
3446 /// declaration.
3447 AP_Explicit = 0,
3448
3449 /// The availability attribute was applied using '#pragma clang attribute'.
3450 AP_PragmaClangAttribute = 1,
3451
3452 /// The availability attribute for a specific platform was inferred from
3453 /// an availability attribute for another platform.
3454 AP_InferredFromOtherPlatform = 2
3455 };
3456
3457 /// Attribute merging methods. Return true if a new attribute was added.
3458 AvailabilityAttr *
3459 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3460 IdentifierInfo *Platform, bool Implicit,
3461 VersionTuple Introduced, VersionTuple Deprecated,
3462 VersionTuple Obsoleted, bool IsUnavailable,
3463 StringRef Message, bool IsStrict, StringRef Replacement,
3464 AvailabilityMergeKind AMK, int Priority);
3465 TypeVisibilityAttr *
3466 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3467 TypeVisibilityAttr::VisibilityType Vis);
3468 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3469 VisibilityAttr::VisibilityType Vis);
3470 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3471 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3472 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3473 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3474 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3475 const AttributeCommonInfo &CI,
3476 bool BestCase,
3477 MSInheritanceModel Model);
3478 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3479 StringRef NewUserDiagnostic);
3480 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3481 IdentifierInfo *Format, int FormatIdx,
3482 int FirstArg);
3483 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3484 StringRef Name);
3485 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3486 StringRef Name);
3487 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3488 const AttributeCommonInfo &CI,
3489 const IdentifierInfo *Ident);
3490 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3491 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3492 StringRef Name);
3493 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3494 const AttributeCommonInfo &CI);
3495 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3496 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3497 const InternalLinkageAttr &AL);
3498 WebAssemblyImportNameAttr *mergeImportNameAttr(
3499 Decl *D, const WebAssemblyImportNameAttr &AL);
3500 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3501 Decl *D, const WebAssemblyImportModuleAttr &AL);
3502 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3503 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3504 const EnforceTCBLeafAttr &AL);
3505 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3506 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3507 const AttributeCommonInfo &AL,
3508 int X, int Y, int Z);
3509
3510 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3511 AvailabilityMergeKind AMK = AMK_Redeclaration);
3512 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3513 LookupResult &OldDecls);
3514 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3515 bool MergeTypeWithOld, bool NewDeclIsDefn);
3516 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3517 Scope *S, bool MergeTypeWithOld);
3518 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3519 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3520 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3521 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3522 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3523 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3524 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3525
3526 // AssignmentAction - This is used by all the assignment diagnostic functions
3527 // to represent what is actually causing the operation
3528 enum AssignmentAction {
3529 AA_Assigning,
3530 AA_Passing,
3531 AA_Returning,
3532 AA_Converting,
3533 AA_Initializing,
3534 AA_Sending,
3535 AA_Casting,
3536 AA_Passing_CFAudited
3537 };
3538
3539 /// C++ Overloading.
3540 enum OverloadKind {
3541 /// This is a legitimate overload: the existing declarations are
3542 /// functions or function templates with different signatures.
3543 Ovl_Overload,
3544
3545 /// This is not an overload because the signature exactly matches
3546 /// an existing declaration.
3547 Ovl_Match,
3548
3549 /// This is not an overload because the lookup results contain a
3550 /// non-function.
3551 Ovl_NonFunction
3552 };
3553 OverloadKind CheckOverload(Scope *S,
3554 FunctionDecl *New,
3555 const LookupResult &OldDecls,
3556 NamedDecl *&OldDecl,
3557 bool IsForUsingDecl);
3558 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl,
3559 bool ConsiderCudaAttrs = true,
3560 bool ConsiderRequiresClauses = true);
3561
3562 enum class AllowedExplicit {
3563 /// Allow no explicit functions to be used.
3564 None,
3565 /// Allow explicit conversion functions but not explicit constructors.
3566 Conversions,
3567 /// Allow both explicit conversion functions and explicit constructors.
3568 All
3569 };
3570
3571 ImplicitConversionSequence
3572 TryImplicitConversion(Expr *From, QualType ToType,
3573 bool SuppressUserConversions,
3574 AllowedExplicit AllowExplicit,
3575 bool InOverloadResolution,
3576 bool CStyle,
3577 bool AllowObjCWritebackConversion);
3578
3579 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3580 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3581 bool IsComplexPromotion(QualType FromType, QualType ToType);
3582 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3583 bool InOverloadResolution,
3584 QualType& ConvertedType, bool &IncompatibleObjC);
3585 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3586 QualType& ConvertedType, bool &IncompatibleObjC);
3587 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3588 QualType &ConvertedType);
3589 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3590 QualType& ConvertedType);
3591 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3592 const FunctionProtoType *NewType,
3593 unsigned *ArgPos = nullptr);
3594 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
3595 QualType FromType, QualType ToType);
3596
3597 void maybeExtendBlockObject(ExprResult &E);
3598 CastKind PrepareCastToObjCObjectPointer(ExprResult &E);
3599 bool CheckPointerConversion(Expr *From, QualType ToType,
3600 CastKind &Kind,
3601 CXXCastPath& BasePath,
3602 bool IgnoreBaseAccess,
3603 bool Diagnose = true);
3604 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType,
3605 bool InOverloadResolution,
3606 QualType &ConvertedType);
3607 bool CheckMemberPointerConversion(Expr *From, QualType ToType,
3608 CastKind &Kind,
3609 CXXCastPath &BasePath,
3610 bool IgnoreBaseAccess);
3611 bool IsQualificationConversion(QualType FromType, QualType ToType,
3612 bool CStyle, bool &ObjCLifetimeConversion);
3613 bool IsFunctionConversion(QualType FromType, QualType ToType,
3614 QualType &ResultTy);
3615 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType);
3616 bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg);
3617
3618 bool CanPerformAggregateInitializationForOverloadResolution(
3619 const InitializedEntity &Entity, InitListExpr *From);
3620
3621 bool IsStringInit(Expr *Init, const ArrayType *AT);
3622
3623 bool CanPerformCopyInitialization(const InitializedEntity &Entity,
3624 ExprResult Init);
3625 ExprResult PerformCopyInitialization(const InitializedEntity &Entity,
3626 SourceLocation EqualLoc,
3627 ExprResult Init,
3628 bool TopLevelOfInitList = false,
3629 bool AllowExplicit = false);
3630 ExprResult PerformObjectArgumentInitialization(Expr *From,
3631 NestedNameSpecifier *Qualifier,
3632 NamedDecl *FoundDecl,
3633 CXXMethodDecl *Method);
3634
3635 /// Check that the lifetime of the initializer (and its subobjects) is
3636 /// sufficient for initializing the entity, and perform lifetime extension
3637 /// (when permitted) if not.
3638 void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init);
3639
3640 ExprResult PerformContextuallyConvertToBool(Expr *From);
3641 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From);
3642
3643 /// Contexts in which a converted constant expression is required.
3644 enum CCEKind {
3645 CCEK_CaseValue, ///< Expression in a case label.
3646 CCEK_Enumerator, ///< Enumerator value with fixed underlying type.
3647 CCEK_TemplateArg, ///< Value of a non-type template parameter.
3648 CCEK_ArrayBound, ///< Array bound in array declarator or new-expression.
3649 CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier.
3650 CCEK_Noexcept ///< Condition in a noexcept(bool) specifier.
3651 };
3652 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3653 llvm::APSInt &Value, CCEKind CCE);
3654 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T,
3655 APValue &Value, CCEKind CCE,
3656 NamedDecl *Dest = nullptr);
3657
3658 /// Abstract base class used to perform a contextual implicit
3659 /// conversion from an expression to any type passing a filter.
3660 class ContextualImplicitConverter {
3661 public:
3662 bool Suppress;
3663 bool SuppressConversion;
3664
3665 ContextualImplicitConverter(bool Suppress = false,
3666 bool SuppressConversion = false)
3667 : Suppress(Suppress), SuppressConversion(SuppressConversion) {}
3668
3669 /// Determine whether the specified type is a valid destination type
3670 /// for this conversion.
3671 virtual bool match(QualType T) = 0;
3672
3673 /// Emits a diagnostic complaining that the expression does not have
3674 /// integral or enumeration type.
3675 virtual SemaDiagnosticBuilder
3676 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0;
3677
3678 /// Emits a diagnostic when the expression has incomplete class type.
3679 virtual SemaDiagnosticBuilder
3680 diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0;
3681
3682 /// Emits a diagnostic when the only matching conversion function
3683 /// is explicit.
3684 virtual SemaDiagnosticBuilder diagnoseExplicitConv(
3685 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3686
3687 /// Emits a note for the explicit conversion function.
3688 virtual SemaDiagnosticBuilder
3689 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3690
3691 /// Emits a diagnostic when there are multiple possible conversion
3692 /// functions.
3693 virtual SemaDiagnosticBuilder
3694 diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0;
3695
3696 /// Emits a note for one of the candidate conversions.
3697 virtual SemaDiagnosticBuilder
3698 noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0;
3699
3700 /// Emits a diagnostic when we picked a conversion function
3701 /// (for cases when we are not allowed to pick a conversion function).
3702 virtual SemaDiagnosticBuilder diagnoseConversion(
3703 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0;
3704
3705 virtual ~ContextualImplicitConverter() {}
3706 };
3707
3708 class ICEConvertDiagnoser : public ContextualImplicitConverter {
3709 bool AllowScopedEnumerations;
3710
3711 public:
3712 ICEConvertDiagnoser(bool AllowScopedEnumerations,
3713 bool Suppress, bool SuppressConversion)
3714 : ContextualImplicitConverter(Suppress, SuppressConversion),
3715 AllowScopedEnumerations(AllowScopedEnumerations) {}
3716
3717 /// Match an integral or (possibly scoped) enumeration type.
3718 bool match(QualType T) override;
3719
3720 SemaDiagnosticBuilder
3721 diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override {
3722 return diagnoseNotInt(S, Loc, T);
3723 }
3724
3725 /// Emits a diagnostic complaining that the expression does not have
3726 /// integral or enumeration type.
3727 virtual SemaDiagnosticBuilder
3728 diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0;
3729 };
3730
3731 /// Perform a contextual implicit conversion.
3732 ExprResult PerformContextualImplicitConversion(
3733 SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter);
3734
3735
3736 enum ObjCSubscriptKind {
3737 OS_Array,
3738 OS_Dictionary,
3739 OS_Error
3740 };
3741 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE);
3742
3743 // Note that LK_String is intentionally after the other literals, as
3744 // this is used for diagnostics logic.
3745 enum ObjCLiteralKind {
3746 LK_Array,
3747 LK_Dictionary,
3748 LK_Numeric,
3749 LK_Boxed,
3750 LK_String,
3751 LK_Block,
3752 LK_None
3753 };
3754 ObjCLiteralKind CheckLiteralKind(Expr *FromE);
3755
3756 ExprResult PerformObjectMemberConversion(Expr *From,
3757 NestedNameSpecifier *Qualifier,
3758 NamedDecl *FoundDecl,
3759 NamedDecl *Member);
3760
3761 // Members have to be NamespaceDecl* or TranslationUnitDecl*.
3762 // TODO: make this is a typesafe union.
3763 typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet;
3764 typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet;
3765
3766 using ADLCallKind = CallExpr::ADLCallKind;
3767
3768 void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl,
3769 ArrayRef<Expr *> Args,
3770 OverloadCandidateSet &CandidateSet,
3771 bool SuppressUserConversions = false,
3772 bool PartialOverloading = false,
3773 bool AllowExplicit = true,
3774 bool AllowExplicitConversion = false,
3775 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3776 ConversionSequenceList EarlyConversions = None,
3777 OverloadCandidateParamOrder PO = {});
3778 void AddFunctionCandidates(const UnresolvedSetImpl &Functions,
3779 ArrayRef<Expr *> Args,
3780 OverloadCandidateSet &CandidateSet,
3781 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
3782 bool SuppressUserConversions = false,
3783 bool PartialOverloading = false,
3784 bool FirstArgumentIsBase = false);
3785 void AddMethodCandidate(DeclAccessPair FoundDecl,
3786 QualType ObjectType,
3787 Expr::Classification ObjectClassification,
3788 ArrayRef<Expr *> Args,
3789 OverloadCandidateSet& CandidateSet,
3790 bool SuppressUserConversion = false,
3791 OverloadCandidateParamOrder PO = {});
3792 void AddMethodCandidate(CXXMethodDecl *Method,
3793 DeclAccessPair FoundDecl,
3794 CXXRecordDecl *ActingContext, QualType ObjectType,
3795 Expr::Classification ObjectClassification,
3796 ArrayRef<Expr *> Args,
3797 OverloadCandidateSet& CandidateSet,
3798 bool SuppressUserConversions = false,
3799 bool PartialOverloading = false,
3800 ConversionSequenceList EarlyConversions = None,
3801 OverloadCandidateParamOrder PO = {});
3802 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3803 DeclAccessPair FoundDecl,
3804 CXXRecordDecl *ActingContext,
3805 TemplateArgumentListInfo *ExplicitTemplateArgs,
3806 QualType ObjectType,
3807 Expr::Classification ObjectClassification,
3808 ArrayRef<Expr *> Args,
3809 OverloadCandidateSet& CandidateSet,
3810 bool SuppressUserConversions = false,
3811 bool PartialOverloading = false,
3812 OverloadCandidateParamOrder PO = {});
3813 void AddTemplateOverloadCandidate(
3814 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3815 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
3816 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false,
3817 bool PartialOverloading = false, bool AllowExplicit = true,
3818 ADLCallKind IsADLCandidate = ADLCallKind::NotADL,
3819 OverloadCandidateParamOrder PO = {});
3820 bool CheckNonDependentConversions(
3821 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
3822 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
3823 ConversionSequenceList &Conversions, bool SuppressUserConversions,
3824 CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(),
3825 Expr::Classification ObjectClassification = {},
3826 OverloadCandidateParamOrder PO = {});
3827 void AddConversionCandidate(
3828 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
3829 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3830 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3831 bool AllowExplicit, bool AllowResultConversion = true);
3832 void AddTemplateConversionCandidate(
3833 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
3834 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
3835 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
3836 bool AllowExplicit, bool AllowResultConversion = true);
3837 void AddSurrogateCandidate(CXXConversionDecl *Conversion,
3838 DeclAccessPair FoundDecl,
3839 CXXRecordDecl *ActingContext,
3840 const FunctionProtoType *Proto,
3841 Expr *Object, ArrayRef<Expr *> Args,
3842 OverloadCandidateSet& CandidateSet);
3843 void AddNonMemberOperatorCandidates(
3844 const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args,
3845 OverloadCandidateSet &CandidateSet,
3846 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
3847 void AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3848 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3849 OverloadCandidateSet &CandidateSet,
3850 OverloadCandidateParamOrder PO = {});
3851 void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
3852 OverloadCandidateSet& CandidateSet,
3853 bool IsAssignmentOperator = false,
3854 unsigned NumContextualBoolArguments = 0);
3855 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3856 SourceLocation OpLoc, ArrayRef<Expr *> Args,
3857 OverloadCandidateSet& CandidateSet);
3858 void AddArgumentDependentLookupCandidates(DeclarationName Name,
3859 SourceLocation Loc,
3860 ArrayRef<Expr *> Args,
3861 TemplateArgumentListInfo *ExplicitTemplateArgs,
3862 OverloadCandidateSet& CandidateSet,
3863 bool PartialOverloading = false);
3864
3865 // Emit as a 'note' the specific overload candidate
3866 void NoteOverloadCandidate(
3867 NamedDecl *Found, FunctionDecl *Fn,
3868 OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(),
3869 QualType DestType = QualType(), bool TakingAddress = false);
3870
3871 // Emit as a series of 'note's all template and non-templates identified by
3872 // the expression Expr
3873 void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(),
3874 bool TakingAddress = false);
3875
3876 /// Check the enable_if expressions on the given function. Returns the first
3877 /// failing attribute, or NULL if they were all successful.
3878 EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc,
3879 ArrayRef<Expr *> Args,
3880 bool MissingImplicitThis = false);
3881
3882 /// Find the failed Boolean condition within a given Boolean
3883 /// constant expression, and describe it with a string.
3884 std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond);
3885
3886 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3887 /// non-ArgDependent DiagnoseIfAttrs.
3888 ///
3889 /// Argument-dependent diagnose_if attributes should be checked each time a
3890 /// function is used as a direct callee of a function call.
3891 ///
3892 /// Returns true if any errors were emitted.
3893 bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
3894 const Expr *ThisArg,
3895 ArrayRef<const Expr *> Args,
3896 SourceLocation Loc);
3897
3898 /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any
3899 /// ArgDependent DiagnoseIfAttrs.
3900 ///
3901 /// Argument-independent diagnose_if attributes should be checked on every use
3902 /// of a function.
3903 ///
3904 /// Returns true if any errors were emitted.
3905 bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
3906 SourceLocation Loc);
3907
3908 /// Returns whether the given function's address can be taken or not,
3909 /// optionally emitting a diagnostic if the address can't be taken.
3910 ///
3911 /// Returns false if taking the address of the function is illegal.
3912 bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
3913 bool Complain = false,
3914 SourceLocation Loc = SourceLocation());
3915
3916 // [PossiblyAFunctionType] --> [Return]
3917 // NonFunctionType --> NonFunctionType
3918 // R (A) --> R(A)
3919 // R (*)(A) --> R (A)
3920 // R (&)(A) --> R (A)
3921 // R (S::*)(A) --> R (A)
3922 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType);
3923
3924 FunctionDecl *
3925 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
3926 QualType TargetType,
3927 bool Complain,
3928 DeclAccessPair &Found,
3929 bool *pHadMultipleCandidates = nullptr);
3930
3931 FunctionDecl *
3932 resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult);
3933
3934 bool resolveAndFixAddressOfSingleOverloadCandidate(
3935 ExprResult &SrcExpr, bool DoFunctionPointerConversion = false);
3936
3937 FunctionDecl *
3938 ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
3939 bool Complain = false,
3940 DeclAccessPair *Found = nullptr);
3941
3942 bool ResolveAndFixSingleFunctionTemplateSpecialization(
3943 ExprResult &SrcExpr,
3944 bool DoFunctionPointerConverion = false,
3945 bool Complain = false,
3946 SourceRange OpRangeForComplaining = SourceRange(),
3947 QualType DestTypeForComplaining = QualType(),
3948 unsigned DiagIDForComplaining = 0);
3949
3950
3951 Expr *FixOverloadedFunctionReference(Expr *E,
3952 DeclAccessPair FoundDecl,
3953 FunctionDecl *Fn);
3954 ExprResult FixOverloadedFunctionReference(ExprResult,
3955 DeclAccessPair FoundDecl,
3956 FunctionDecl *Fn);
3957
3958 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
3959 ArrayRef<Expr *> Args,
3960 OverloadCandidateSet &CandidateSet,
3961 bool PartialOverloading = false);
3962 void AddOverloadedCallCandidates(
3963 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
3964 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet);
3965
3966 // An enum used to represent the different possible results of building a
3967 // range-based for loop.
3968 enum ForRangeStatus {
3969 FRS_Success,
3970 FRS_NoViableFunction,
3971 FRS_DiagnosticIssued
3972 };
3973
3974 ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc,
3975 SourceLocation RangeLoc,
3976 const DeclarationNameInfo &NameInfo,
3977 LookupResult &MemberLookup,
3978 OverloadCandidateSet *CandidateSet,
3979 Expr *Range, ExprResult *CallExpr);
3980
3981 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn,
3982 UnresolvedLookupExpr *ULE,
3983 SourceLocation LParenLoc,
3984 MultiExprArg Args,
3985 SourceLocation RParenLoc,
3986 Expr *ExecConfig,
3987 bool AllowTypoCorrection=true,
3988 bool CalleesAddressIsTaken=false);
3989
3990 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
3991 MultiExprArg Args, SourceLocation RParenLoc,
3992 OverloadCandidateSet *CandidateSet,
3993 ExprResult *Result);
3994
3995 ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass,
3996 NestedNameSpecifierLoc NNSLoc,
3997 DeclarationNameInfo DNI,
3998 const UnresolvedSetImpl &Fns,
3999 bool PerformADL = true);
4000
4001 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc,
4002 UnaryOperatorKind Opc,
4003 const UnresolvedSetImpl &Fns,
4004 Expr *input, bool RequiresADL = true);
4005
4006 void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
4007 OverloadedOperatorKind Op,
4008 const UnresolvedSetImpl &Fns,
4009 ArrayRef<Expr *> Args, bool RequiresADL = true);
4010 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc,
4011 BinaryOperatorKind Opc,
4012 const UnresolvedSetImpl &Fns,
4013 Expr *LHS, Expr *RHS,
4014 bool RequiresADL = true,
4015 bool AllowRewrittenCandidates = true,
4016 FunctionDecl *DefaultedFn = nullptr);
4017 ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc,
4018 const UnresolvedSetImpl &Fns,
4019 Expr *LHS, Expr *RHS,
4020 FunctionDecl *DefaultedFn);
4021
4022 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4023 SourceLocation RLoc, Expr *Base,
4024 MultiExprArg Args);
4025
4026 ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr,
4027 SourceLocation LParenLoc,
4028 MultiExprArg Args,
4029 SourceLocation RParenLoc,
4030 Expr *ExecConfig = nullptr,
4031 bool IsExecConfig = false,
4032 bool AllowRecovery = false);
4033 ExprResult
4034 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc,
4035 MultiExprArg Args,
4036 SourceLocation RParenLoc);
4037
4038 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base,
4039 SourceLocation OpLoc,
4040 bool *NoArrowOperatorFound = nullptr);
4041
4042 /// CheckCallReturnType - Checks that a call expression's return type is
4043 /// complete. Returns true on failure. The location passed in is the location
4044 /// that best represents the call.
4045 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
4046 CallExpr *CE, FunctionDecl *FD);
4047
4048 /// Helpers for dealing with blocks and functions.
4049 bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
4050 bool CheckParameterNames);
4051 void CheckCXXDefaultArguments(FunctionDecl *FD);
4052 void CheckExtraCXXDefaultArguments(Declarator &D);
4053 Scope *getNonFieldDeclScope(Scope *S);
4054
4055 /// \name Name lookup
4056 ///
4057 /// These routines provide name lookup that is used during semantic
4058 /// analysis to resolve the various kinds of names (identifiers,
4059 /// overloaded operator names, constructor names, etc.) into zero or
4060 /// more declarations within a particular scope. The major entry
4061 /// points are LookupName, which performs unqualified name lookup,
4062 /// and LookupQualifiedName, which performs qualified name lookup.
4063 ///
4064 /// All name lookup is performed based on some specific criteria,
4065 /// which specify what names will be visible to name lookup and how
4066 /// far name lookup should work. These criteria are important both
4067 /// for capturing language semantics (certain lookups will ignore
4068 /// certain names, for example) and for performance, since name
4069 /// lookup is often a bottleneck in the compilation of C++. Name
4070 /// lookup criteria is specified via the LookupCriteria enumeration.
4071 ///
4072 /// The results of name lookup can vary based on the kind of name
4073 /// lookup performed, the current language, and the translation
4074 /// unit. In C, for example, name lookup will either return nothing
4075 /// (no entity found) or a single declaration. In C++, name lookup
4076 /// can additionally refer to a set of overloaded functions or
4077 /// result in an ambiguity. All of the possible results of name
4078 /// lookup are captured by the LookupResult class, which provides
4079 /// the ability to distinguish among them.
4080 //@{
4081
4082 /// Describes the kind of name lookup to perform.
4083 enum LookupNameKind {
4084 /// Ordinary name lookup, which finds ordinary names (functions,
4085 /// variables, typedefs, etc.) in C and most kinds of names
4086 /// (functions, variables, members, types, etc.) in C++.
4087 LookupOrdinaryName = 0,
4088 /// Tag name lookup, which finds the names of enums, classes,
4089 /// structs, and unions.
4090 LookupTagName,
4091 /// Label name lookup.
4092 LookupLabel,
4093 /// Member name lookup, which finds the names of
4094 /// class/struct/union members.
4095 LookupMemberName,
4096 /// Look up of an operator name (e.g., operator+) for use with
4097 /// operator overloading. This lookup is similar to ordinary name
4098 /// lookup, but will ignore any declarations that are class members.
4099 LookupOperatorName,
4100 /// Look up a name following ~ in a destructor name. This is an ordinary
4101 /// lookup, but prefers tags to typedefs.
4102 LookupDestructorName,
4103 /// Look up of a name that precedes the '::' scope resolution
4104 /// operator in C++. This lookup completely ignores operator, object,
4105 /// function, and enumerator names (C++ [basic.lookup.qual]p1).
4106 LookupNestedNameSpecifierName,
4107 /// Look up a namespace name within a C++ using directive or
4108 /// namespace alias definition, ignoring non-namespace names (C++
4109 /// [basic.lookup.udir]p1).
4110 LookupNamespaceName,
4111 /// Look up all declarations in a scope with the given name,
4112 /// including resolved using declarations. This is appropriate
4113 /// for checking redeclarations for a using declaration.
4114 LookupUsingDeclName,
4115 /// Look up an ordinary name that is going to be redeclared as a
4116 /// name with linkage. This lookup ignores any declarations that
4117 /// are outside of the current scope unless they have linkage. See
4118 /// C99 6.2.2p4-5 and C++ [basic.link]p6.
4119 LookupRedeclarationWithLinkage,
4120 /// Look up a friend of a local class. This lookup does not look
4121 /// outside the innermost non-class scope. See C++11 [class.friend]p11.
4122 LookupLocalFriendName,
4123 /// Look up the name of an Objective-C protocol.
4124 LookupObjCProtocolName,
4125 /// Look up implicit 'self' parameter of an objective-c method.
4126 LookupObjCImplicitSelfParam,
4127 /// Look up the name of an OpenMP user-defined reduction operation.
4128 LookupOMPReductionName,
4129 /// Look up the name of an OpenMP user-defined mapper.
4130 LookupOMPMapperName,
4131 /// Look up any declaration with any name.
4132 LookupAnyName
4133 };
4134
4135 /// Specifies whether (or how) name lookup is being performed for a
4136 /// redeclaration (vs. a reference).
4137 enum RedeclarationKind {
4138 /// The lookup is a reference to this name that is not for the
4139 /// purpose of redeclaring the name.
4140 NotForRedeclaration = 0,
4141 /// The lookup results will be used for redeclaration of a name,
4142 /// if an entity by that name already exists and is visible.
4143 ForVisibleRedeclaration,
4144 /// The lookup results will be used for redeclaration of a name
4145 /// with external linkage; non-visible lookup results with external linkage
4146 /// may also be found.
4147 ForExternalRedeclaration
4148 };
4149
4150 RedeclarationKind forRedeclarationInCurContext() {
4151 // A declaration with an owning module for linkage can never link against
4152 // anything that is not visible. We don't need to check linkage here; if
4153 // the context has internal linkage, redeclaration lookup won't find things
4154 // from other TUs, and we can't safely compute linkage yet in general.
4155 if (cast<Decl>(CurContext)
4156 ->getOwningModuleForLinkage(/*IgnoreLinkage*/true))
4157 return ForVisibleRedeclaration;
4158 return ForExternalRedeclaration;
4159 }
4160
4161 /// The possible outcomes of name lookup for a literal operator.
4162 enum LiteralOperatorLookupResult {
4163 /// The lookup resulted in an error.
4164 LOLR_Error,
4165 /// The lookup found no match but no diagnostic was issued.
4166 LOLR_ErrorNoDiagnostic,
4167 /// The lookup found a single 'cooked' literal operator, which
4168 /// expects a normal literal to be built and passed to it.
4169 LOLR_Cooked,
4170 /// The lookup found a single 'raw' literal operator, which expects
4171 /// a string literal containing the spelling of the literal token.
4172 LOLR_Raw,
4173 /// The lookup found an overload set of literal operator templates,
4174 /// which expect the characters of the spelling of the literal token to be
4175 /// passed as a non-type template argument pack.
4176 LOLR_Template,
4177 /// The lookup found an overload set of literal operator templates,
4178 /// which expect the character type and characters of the spelling of the
4179 /// string literal token to be passed as template arguments.
4180 LOLR_StringTemplatePack,
4181 };
4182
4183 SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D,
4184 CXXSpecialMember SM,
4185 bool ConstArg,
4186 bool VolatileArg,
4187 bool RValueThis,
4188 bool ConstThis,
4189 bool VolatileThis);
4190
4191 typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator;
4192 typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)>
4193 TypoRecoveryCallback;
4194
4195private:
4196 bool CppLookupName(LookupResult &R, Scope *S);
4197
4198 struct TypoExprState {
4199 std::unique_ptr<TypoCorrectionConsumer> Consumer;
4200 TypoDiagnosticGenerator DiagHandler;
4201 TypoRecoveryCallback RecoveryHandler;
4202 TypoExprState();
4203 TypoExprState(TypoExprState &&other) noexcept;
4204 TypoExprState &operator=(TypoExprState &&other) noexcept;
4205 };
4206
4207 /// The set of unhandled TypoExprs and their associated state.
4208 llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos;
4209
4210 /// Creates a new TypoExpr AST node.
4211 TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
4212 TypoDiagnosticGenerator TDG,
4213 TypoRecoveryCallback TRC, SourceLocation TypoLoc);
4214
4215 // The set of known/encountered (unique, canonicalized) NamespaceDecls.
4216 //
4217 // The boolean value will be true to indicate that the namespace was loaded
4218 // from an AST/PCH file, or false otherwise.
4219 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces;
4220
4221 /// Whether we have already loaded known namespaces from an extenal
4222 /// source.
4223 bool LoadedExternalKnownNamespaces;
4224
4225 /// Helper for CorrectTypo and CorrectTypoDelayed used to create and
4226 /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction
4227 /// should be skipped entirely.
4228 std::unique_ptr<TypoCorrectionConsumer>
4229 makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo,
4230 Sema::LookupNameKind LookupKind, Scope *S,
4231 CXXScopeSpec *SS,
4232 CorrectionCandidateCallback &CCC,
4233 DeclContext *MemberContext, bool EnteringContext,
4234 const ObjCObjectPointerType *OPT,
4235 bool ErrorRecovery);
4236
4237public:
4238 const TypoExprState &getTypoExprState(TypoExpr *TE) const;
4239
4240 /// Clears the state of the given TypoExpr.
4241 void clearDelayedTypo(TypoExpr *TE);
4242
4243 /// Look up a name, looking for a single declaration. Return
4244 /// null if the results were absent, ambiguous, or overloaded.
4245 ///
4246 /// It is preferable to use the elaborated form and explicitly handle
4247 /// ambiguity and overloaded.
4248 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name,
4249 SourceLocation Loc,
4250 LookupNameKind NameKind,
4251 RedeclarationKind Redecl
4252 = NotForRedeclaration);
4253 bool LookupBuiltin(LookupResult &R);
4254 void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID);
4255 bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false,
4256 bool ForceNoCPlusPlus = false);
4257 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4258 bool InUnqualifiedLookup = false);
4259 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
4260 CXXScopeSpec &SS);
4261 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
4262 bool AllowBuiltinCreation = false,
4263 bool EnteringContext = false);
4264 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc,
4265 RedeclarationKind Redecl
4266 = NotForRedeclaration);
4267 bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class);
4268
4269 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
4270 UnresolvedSetImpl &Functions);
4271
4272 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc,
4273 SourceLocation GnuLabelLoc = SourceLocation());
4274
4275 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class);
4276 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class);
4277 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class,
4278 unsigned Quals);
4279 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals,
4280 bool RValueThis, unsigned ThisQuals);
4281 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class,
4282 unsigned Quals);
4283 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals,
4284 bool RValueThis, unsigned ThisQuals);
4285 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class);
4286
4287 bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id,
4288 bool IsUDSuffix);
4289 LiteralOperatorLookupResult
4290 LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys,
4291 bool AllowRaw, bool AllowTemplate,
4292 bool AllowStringTemplate, bool DiagnoseMissing,
4293 StringLiteral *StringLit = nullptr);
4294 bool isKnownName(StringRef name);
4295
4296 /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
4297 enum class FunctionEmissionStatus {
4298 Emitted,
4299 CUDADiscarded, // Discarded due to CUDA/HIP hostness
4300 OMPDiscarded, // Discarded due to OpenMP hostness
4301 TemplateDiscarded, // Discarded due to uninstantiated templates
4302 Unknown,
4303 };
4304 FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl,
4305 bool Final = false);
4306
4307 // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
4308 bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
4309
4310 void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
4311 ArrayRef<Expr *> Args, ADLResult &Functions);
4312
4313 void LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4314 VisibleDeclConsumer &Consumer,
4315 bool IncludeGlobalScope = true,
4316 bool LoadExternal = true);
4317 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4318 VisibleDeclConsumer &Consumer,
4319 bool IncludeGlobalScope = true,
4320 bool IncludeDependentBases = false,
4321 bool LoadExternal = true);
4322
4323 enum CorrectTypoKind {
4324 CTK_NonError, // CorrectTypo used in a non error recovery situation.
4325 CTK_ErrorRecovery // CorrectTypo used in normal error recovery.
4326 };
4327
4328 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo,
4329 Sema::LookupNameKind LookupKind,
4330 Scope *S, CXXScopeSpec *SS,
4331 CorrectionCandidateCallback &CCC,
4332 CorrectTypoKind Mode,
4333 DeclContext *MemberContext = nullptr,
4334 bool EnteringContext = false,
4335 const ObjCObjectPointerType *OPT = nullptr,
4336 bool RecordFailure = true);
4337
4338 TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo,
4339 Sema::LookupNameKind LookupKind, Scope *S,
4340 CXXScopeSpec *SS,
4341 CorrectionCandidateCallback &CCC,
4342 TypoDiagnosticGenerator TDG,
4343 TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4344 DeclContext *MemberContext = nullptr,
4345 bool EnteringContext = false,
4346 const ObjCObjectPointerType *OPT = nullptr);
4347
4348 /// Process any TypoExprs in the given Expr and its children,
4349 /// generating diagnostics as appropriate and returning a new Expr if there
4350 /// were typos that were all successfully corrected and ExprError if one or
4351 /// more typos could not be corrected.
4352 ///
4353 /// \param E The Expr to check for TypoExprs.
4354 ///
4355 /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its
4356 /// initializer.
4357 ///
4358 /// \param RecoverUncorrectedTypos If true, when typo correction fails, it
4359 /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs.
4360 ///
4361 /// \param Filter A function applied to a newly rebuilt Expr to determine if
4362 /// it is an acceptable/usable result from a single combination of typo
4363 /// corrections. As long as the filter returns ExprError, different
4364 /// combinations of corrections will be tried until all are exhausted.
4365 ExprResult CorrectDelayedTyposInExpr(
4366 Expr *E, VarDecl *InitDecl = nullptr,
4367 bool RecoverUncorrectedTypos = false,
4368 llvm::function_ref<ExprResult(Expr *)> Filter =
4369 [](Expr *E) -> ExprResult { return E; });
4370
4371 ExprResult CorrectDelayedTyposInExpr(
4372 ExprResult ER, VarDecl *InitDecl = nullptr,
4373 bool RecoverUncorrectedTypos = false,
4374 llvm::function_ref<ExprResult(Expr *)> Filter =
4375 [](Expr *E) -> ExprResult { return E; }) {
4376 return ER.isInvalid()
4377 ? ER
4378 : CorrectDelayedTyposInExpr(ER.get(), InitDecl,
4379 RecoverUncorrectedTypos, Filter);
4380 }
4381
4382 void diagnoseTypo(const TypoCorrection &Correction,
4383 const PartialDiagnostic &TypoDiag,
4384 bool ErrorRecovery = true);
4385
4386 void diagnoseTypo(const TypoCorrection &Correction,
4387 const PartialDiagnostic &TypoDiag,
4388 const PartialDiagnostic &PrevNote,
4389 bool ErrorRecovery = true);
4390
4391 void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F);
4392
4393 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,
4394 ArrayRef<Expr *> Args,
4395 AssociatedNamespaceSet &AssociatedNamespaces,
4396 AssociatedClassSet &AssociatedClasses);
4397
4398 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
4399 bool ConsiderLinkage, bool AllowInlineNamespace);
4400
4401 bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old);
4402 bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old);
4403 bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old);
4404
4405 void DiagnoseAmbiguousLookup(LookupResult &Result);
4406 //@}
4407
4408 /// Attempts to produce a RecoveryExpr after some AST node cannot be created.
4409 ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End,
4410 ArrayRef<Expr *> SubExprs,
4411 QualType T = QualType());
4412
4413 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id,
4414 SourceLocation IdLoc,
4415 bool TypoCorrection = false);
4416 FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID,
4417 SourceLocation Loc);
4418 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
4419 Scope *S, bool ForRedeclaration,
4420 SourceLocation Loc);
4421 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II,
4422 Scope *S);
4423 void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
4424 FunctionDecl *FD);
4425 void AddKnownFunctionAttributes(FunctionDecl *FD);
4426
4427 // More parsing and symbol table subroutines.
4428
4429 void ProcessPragmaWeak(Scope *S, Decl *D);
4430 // Decl attributes - this routine is the top level dispatcher.
4431 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD);
4432 // Helper for delayed processing of attributes.
4433 void ProcessDeclAttributeDelayed(Decl *D,
4434 const ParsedAttributesView &AttrList);
4435 void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL,
4436 bool IncludeCXX11Attributes = true);
4437 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl,
4438 const ParsedAttributesView &AttrList);
4439
4440 void checkUnusedDeclAttributes(Declarator &D);
4441
4442 /// Handles semantic checking for features that are common to all attributes,
4443 /// such as checking whether a parameter was properly specified, or the
4444 /// correct number of arguments were passed, etc. Returns true if the
4445 /// attribute has been diagnosed.
4446 bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A,
4447 bool SkipArgCountCheck = false);
4448 bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A,
4449 bool SkipArgCountCheck = false);
4450
4451 /// Determine if type T is a valid subject for a nonnull and similar
4452 /// attributes. By default, we look through references (the behavior used by
4453 /// nonnull), but if the second parameter is true, then we treat a reference
4454 /// type as valid.
4455 bool isValidPointerAttrType(QualType T, bool RefOkay = false);
4456
4457 bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value);
4458 bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC,
4459 const FunctionDecl *FD = nullptr);
4460 bool CheckAttrTarget(const ParsedAttr &CurrAttr);
4461 bool CheckAttrNoArgs(const ParsedAttr &CurrAttr);
4462 bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI,
4463 const Expr *E, StringRef &Str,
4464 SourceLocation *ArgLocation = nullptr);
4465 bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum,
4466 StringRef &Str,
4467 SourceLocation *ArgLocation = nullptr);
4468 llvm::Error isValidSectionSpecifier(StringRef Str);
4469 bool checkSectionName(SourceLocation LiteralLoc, StringRef Str);
4470 bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str);
4471 bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
4472 const StringLiteral *Literal,
4473 bool &HasDefault, bool &HasCommas,
4474 SmallVectorImpl<StringRef> &Strings);
4475 bool checkMSInheritanceAttrOnDefinition(
4476 CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4477 MSInheritanceModel SemanticSpelling);
4478
4479 void CheckAlignasUnderalignment(Decl *D);
4480
4481 /// Adjust the calling convention of a method to be the ABI default if it
4482 /// wasn't specified explicitly. This handles method types formed from
4483 /// function type typedefs and typename template arguments.
4484 void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
4485 SourceLocation Loc);
4486
4487 // Check if there is an explicit attribute, but only look through parens.
4488 // The intent is to look for an attribute on the current declarator, but not
4489 // one that came from a typedef.
4490 bool hasExplicitCallingConv(QualType T);
4491
4492 /// Get the outermost AttributedType node that sets a calling convention.
4493 /// Valid types should not have multiple attributes with different CCs.
4494 const AttributedType *getCallingConvAttributedType(QualType T) const;
4495
4496 /// Process the attributes before creating an attributed statement. Returns
4497 /// the semantic attributes that have been processed.
4498 void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributes &InAttrs,
4499 SmallVectorImpl<const Attr *> &OutAttrs);
4500
4501 void WarnConflictingTypedMethods(ObjCMethodDecl *Method,
4502 ObjCMethodDecl *MethodDecl,
4503 bool IsProtocolMethodDecl);
4504
4505 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
4506 ObjCMethodDecl *Overridden,
4507 bool IsProtocolMethodDecl);
4508
4509 /// WarnExactTypedMethods - This routine issues a warning if method
4510 /// implementation declaration matches exactly that of its declaration.
4511 void WarnExactTypedMethods(ObjCMethodDecl *Method,
4512 ObjCMethodDecl *MethodDecl,
4513 bool IsProtocolMethodDecl);
4514
4515 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet;
4516
4517 /// CheckImplementationIvars - This routine checks if the instance variables
4518 /// listed in the implelementation match those listed in the interface.
4519 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
4520 ObjCIvarDecl **Fields, unsigned nIvars,
4521 SourceLocation Loc);
4522
4523 /// ImplMethodsVsClassMethods - This is main routine to warn if any method
4524 /// remains unimplemented in the class or category \@implementation.
4525 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
4526 ObjCContainerDecl* IDecl,
4527 bool IncompleteImpl = false);
4528
4529 /// DiagnoseUnimplementedProperties - This routine warns on those properties
4530 /// which must be implemented by this implementation.
4531 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
4532 ObjCContainerDecl *CDecl,
4533 bool SynthesizeProperties);
4534
4535 /// Diagnose any null-resettable synthesized setters.
4536 void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl);
4537
4538 /// DefaultSynthesizeProperties - This routine default synthesizes all
4539 /// properties which must be synthesized in the class's \@implementation.
4540 void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl,
4541 ObjCInterfaceDecl *IDecl,
4542 SourceLocation AtEnd);
4543 void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd);
4544
4545 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is
4546 /// an ivar synthesized for 'Method' and 'Method' is a property accessor
4547 /// declared in class 'IFace'.
4548 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace,
4549 ObjCMethodDecl *Method, ObjCIvarDecl *IV);
4550
4551 /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which
4552 /// backs the property is not used in the property's accessor.
4553 void DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4554 const ObjCImplementationDecl *ImplD);
4555
4556 /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and
4557 /// it property has a backing ivar, returns this ivar; otherwise, returns NULL.
4558 /// It also returns ivar's property on success.
4559 ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4560 const ObjCPropertyDecl *&PDecl) const;
4561
4562 /// Called by ActOnProperty to handle \@property declarations in
4563 /// class extensions.
4564 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S,
4565 SourceLocation AtLoc,
4566 SourceLocation LParenLoc,
4567 FieldDeclarator &FD,
4568 Selector GetterSel,
4569 SourceLocation GetterNameLoc,
4570 Selector SetterSel,
4571 SourceLocation SetterNameLoc,
4572 const bool isReadWrite,
4573 unsigned &Attributes,
4574 const unsigned AttributesAsWritten,
4575 QualType T,
4576 TypeSourceInfo *TSI,
4577 tok::ObjCKeywordKind MethodImplKind);
4578
4579 /// Called by ActOnProperty and HandlePropertyInClassExtension to
4580 /// handle creating the ObjcPropertyDecl for a category or \@interface.
4581 ObjCPropertyDecl *CreatePropertyDecl(Scope *S,
4582 ObjCContainerDecl *CDecl,
4583 SourceLocation AtLoc,
4584 SourceLocation LParenLoc,
4585 FieldDeclarator &FD,
4586 Selector GetterSel,
4587 SourceLocation GetterNameLoc,
4588 Selector SetterSel,
4589 SourceLocation SetterNameLoc,
4590 const bool isReadWrite,
4591 const unsigned Attributes,
4592 const unsigned AttributesAsWritten,
4593 QualType T,
4594 TypeSourceInfo *TSI,
4595 tok::ObjCKeywordKind MethodImplKind,
4596 DeclContext *lexicalDC = nullptr);
4597
4598 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via
4599 /// warning) when atomic property has one but not the other user-declared
4600 /// setter or getter.
4601 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl,
4602 ObjCInterfaceDecl* IDecl);
4603
4604 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D);
4605
4606 void DiagnoseMissingDesignatedInitOverrides(
4607 const ObjCImplementationDecl *ImplD,
4608 const ObjCInterfaceDecl *IFD);
4609
4610 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID);
4611
4612 enum MethodMatchStrategy {
4613 MMS_loose,
4614 MMS_strict
4615 };
4616
4617 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns
4618 /// true, or false, accordingly.
4619 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
4620 const ObjCMethodDecl *PrevMethod,
4621 MethodMatchStrategy strategy = MMS_strict);
4622
4623 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
4624 /// or protocol against those declared in their implementations.
4625 void MatchAllMethodDeclarations(const SelectorSet &InsMap,
4626 const SelectorSet &ClsMap,
4627 SelectorSet &InsMapSeen,
4628 SelectorSet &ClsMapSeen,
4629 ObjCImplDecl* IMPDecl,
4630 ObjCContainerDecl* IDecl,
4631 bool &IncompleteImpl,
4632 bool ImmediateClass,
4633 bool WarnCategoryMethodImpl=false);
4634
4635 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
4636 /// category matches with those implemented in its primary class and
4637 /// warns each time an exact match is found.
4638 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP);
4639
4640 /// Add the given method to the list of globally-known methods.
4641 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method);
4642
4643 /// Returns default addr space for method qualifiers.
4644 LangAS getDefaultCXXMethodAddrSpace() const;
4645
4646private:
4647 /// AddMethodToGlobalPool - Add an instance or factory method to the global
4648 /// pool. See descriptoin of AddInstanceMethodToGlobalPool.
4649 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance);
4650
4651 /// LookupMethodInGlobalPool - Returns the instance or factory method and
4652 /// optionally warns if there are multiple signatures.
4653 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R,
4654 bool receiverIdOrClass,
4655 bool instance);
4656
4657public:
4658 /// - Returns instance or factory methods in global method pool for
4659 /// given selector. It checks the desired kind first, if none is found, and
4660 /// parameter checkTheOther is set, it then checks the other kind. If no such
4661 /// method or only one method is found, function returns false; otherwise, it
4662 /// returns true.
4663 bool
4664 CollectMultipleMethodsInGlobalPool(Selector Sel,
4665 SmallVectorImpl<ObjCMethodDecl*>& Methods,
4666 bool InstanceFirst, bool CheckTheOther,
4667 const ObjCObjectType *TypeBound = nullptr);
4668
4669 bool
4670 AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
4671 SourceRange R, bool receiverIdOrClass,
4672 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4673
4674 void
4675 DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
4676 Selector Sel, SourceRange R,
4677 bool receiverIdOrClass);
4678
4679private:
4680 /// - Returns a selector which best matches given argument list or
4681 /// nullptr if none could be found
4682 ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args,
4683 bool IsInstance,
4684 SmallVectorImpl<ObjCMethodDecl*>& Methods);
4685
4686
4687 /// Record the typo correction failure and return an empty correction.
4688 TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc,
4689 bool RecordFailure = true) {
4690 if (RecordFailure)
4691 TypoCorrectionFailures[Typo].insert(TypoLoc);
4692 return TypoCorrection();
4693 }
4694
4695public:
4696 /// AddInstanceMethodToGlobalPool - All instance methods in a translation
4697 /// unit are added to a global pool. This allows us to efficiently associate
4698 /// a selector with a method declaraation for purposes of typechecking
4699 /// messages sent to "id" (where the class of the object is unknown).
4700 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4701 AddMethodToGlobalPool(Method, impl, /*instance*/true);
4702 }
4703
4704 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
4705 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) {
4706 AddMethodToGlobalPool(Method, impl, /*instance*/false);
4707 }
4708
4709 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
4710 /// pool.
4711 void AddAnyMethodToGlobalPool(Decl *D);
4712
4713 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if
4714 /// there are multiple signatures.
4715 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R,
4716 bool receiverIdOrClass=false) {
4717 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4718 /*instance*/true);
4719 }
4720
4721 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if
4722 /// there are multiple signatures.
4723 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R,
4724 bool receiverIdOrClass=false) {
4725 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass,
4726 /*instance*/false);
4727 }
4728
4729 const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel,
4730 QualType ObjectType=QualType());
4731 /// LookupImplementedMethodInGlobalPool - Returns the method which has an
4732 /// implementation.
4733 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel);
4734
4735 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4736 /// initialization.
4737 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4738 SmallVectorImpl<ObjCIvarDecl*> &Ivars);
4739
4740 //===--------------------------------------------------------------------===//
4741 // Statement Parsing Callbacks: SemaStmt.cpp.
4742public:
4743 class FullExprArg {
4744 public:
4745 FullExprArg() : E(nullptr) { }
4746 FullExprArg(Sema &actions) : E(nullptr) { }
4747
4748 ExprResult release() {
4749 return E;
4750 }
4751
4752 Expr *get() const { return E; }
4753
4754 Expr *operator->() {
4755 return E;
4756 }
4757
4758 private:
4759 // FIXME: No need to make the entire Sema class a friend when it's just
4760 // Sema::MakeFullExpr that needs access to the constructor below.
4761 friend class Sema;
4762
4763 explicit FullExprArg(Expr *expr) : E(expr) {}
4764
4765 Expr *E;
4766 };
4767
4768 FullExprArg MakeFullExpr(Expr *Arg) {
4769 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation());
4770 }
4771 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) {
4772 return FullExprArg(
4773 ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get());
4774 }
4775 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) {
4776 ExprResult FE =
4777 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(),
4778 /*DiscardedValue*/ true);
4779 return FullExprArg(FE.get());
4780 }
4781
4782 StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true);
4783 StmtResult ActOnExprStmtError();
4784
4785 StmtResult ActOnNullStmt(SourceLocation SemiLoc,
4786 bool HasLeadingEmptyMacro = false);
4787
4788 void ActOnStartOfCompoundStmt(bool IsStmtExpr);
4789 void ActOnAfterCompoundStatementLeadingPragmas();
4790 void ActOnFinishOfCompoundStmt();
4791 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R,
4792 ArrayRef<Stmt *> Elts, bool isStmtExpr);
4793
4794 /// A RAII object to enter scope of a compound statement.
4795 class CompoundScopeRAII {
4796 public:
4797 CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) {
4798 S.ActOnStartOfCompoundStmt(IsStmtExpr);
4799 }
4800
4801 ~CompoundScopeRAII() {
4802 S.ActOnFinishOfCompoundStmt();
4803 }
4804
4805 private:
4806 Sema &S;
4807 };
4808
4809 /// An RAII helper that pops function a function scope on exit.
4810 struct FunctionScopeRAII {
4811 Sema &S;
4812 bool Active;
4813 FunctionScopeRAII(Sema &S) : S(S), Active(true) {}
4814 ~FunctionScopeRAII() {
4815 if (Active)
4816 S.PopFunctionScopeInfo();
4817 }
4818 void disable() { Active = false; }
4819 };
4820
4821 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl,
4822 SourceLocation StartLoc,
4823 SourceLocation EndLoc);
4824 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
4825 StmtResult ActOnForEachLValueExpr(Expr *E);
4826 ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val);
4827 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS,
4828 SourceLocation DotDotDotLoc, ExprResult RHS,
4829 SourceLocation ColonLoc);
4830 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt);
4831
4832 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc,
4833 SourceLocation ColonLoc,
4834 Stmt *SubStmt, Scope *CurScope);
4835 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl,
4836 SourceLocation ColonLoc, Stmt *SubStmt);
4837
4838 StmtResult BuildAttributedStmt(SourceLocation AttrsLoc,
4839 ArrayRef<const Attr *> Attrs, Stmt *SubStmt);
4840 StmtResult ActOnAttributedStmt(const ParsedAttributes &AttrList,
4841 Stmt *SubStmt);
4842
4843 class ConditionResult;
4844
4845 StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4846 SourceLocation LParenLoc, Stmt *InitStmt,
4847 ConditionResult Cond, SourceLocation RParenLoc,
4848 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4849 StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind,
4850 SourceLocation LParenLoc, Stmt *InitStmt,
4851 ConditionResult Cond, SourceLocation RParenLoc,
4852 Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal);
4853 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc,
4854 SourceLocation LParenLoc, Stmt *InitStmt,
4855 ConditionResult Cond,
4856 SourceLocation RParenLoc);
4857 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc,
4858 Stmt *Switch, Stmt *Body);
4859 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
4860 ConditionResult Cond, SourceLocation RParenLoc,
4861 Stmt *Body);
4862 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body,
4863 SourceLocation WhileLoc, SourceLocation CondLParen,
4864 Expr *Cond, SourceLocation CondRParen);
4865
4866 StmtResult ActOnForStmt(SourceLocation ForLoc,
4867 SourceLocation LParenLoc,
4868 Stmt *First,
4869 ConditionResult Second,
4870 FullExprArg Third,
4871 SourceLocation RParenLoc,
4872 Stmt *Body);
4873 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc,
4874 Expr *collection);
4875 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc,
4876 Stmt *First, Expr *collection,
4877 SourceLocation RParenLoc);
4878 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body);
4879
4880 enum BuildForRangeKind {
4881 /// Initial building of a for-range statement.
4882 BFRK_Build,
4883 /// Instantiation or recovery rebuild of a for-range statement. Don't
4884 /// attempt any typo-correction.
4885 BFRK_Rebuild,
4886 /// Determining whether a for-range statement could be built. Avoid any
4887 /// unnecessary or irreversible actions.
4888 BFRK_Check
4889 };
4890
4891 StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc,
4892 SourceLocation CoawaitLoc,
4893 Stmt *InitStmt,
4894 Stmt *LoopVar,
4895 SourceLocation ColonLoc, Expr *Collection,
4896 SourceLocation RParenLoc,
4897 BuildForRangeKind Kind);
4898 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc,
4899 SourceLocation CoawaitLoc,
4900 Stmt *InitStmt,
4901 SourceLocation ColonLoc,
4902 Stmt *RangeDecl, Stmt *Begin, Stmt *End,
4903 Expr *Cond, Expr *Inc,
4904 Stmt *LoopVarDecl,
4905 SourceLocation RParenLoc,
4906 BuildForRangeKind Kind);
4907 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body);
4908
4909 StmtResult ActOnGotoStmt(SourceLocation GotoLoc,
4910 SourceLocation LabelLoc,
4911 LabelDecl *TheDecl);
4912 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc,
4913 SourceLocation StarLoc,
4914 Expr *DestExp);
4915 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope);
4916 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope);
4917
4918 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4919 CapturedRegionKind Kind, unsigned NumParams);
4920 typedef std::pair<StringRef, QualType> CapturedParamNameType;
4921 void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope,
4922 CapturedRegionKind Kind,
4923 ArrayRef<CapturedParamNameType> Params,
4924 unsigned OpenMPCaptureLevel = 0);
4925 StmtResult ActOnCapturedRegionEnd(Stmt *S);
4926 void ActOnCapturedRegionError();
4927 RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD,
4928 SourceLocation Loc,
4929 unsigned NumParams);
4930
4931 struct NamedReturnInfo {
4932 const VarDecl *Candidate;
4933
4934 enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable };
4935 Status S;
4936
4937 bool isMoveEligible() const { return S != None; };
4938 bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; }
4939 };
4940 enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn };
4941 NamedReturnInfo getNamedReturnInfo(
4942 Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal);
4943 NamedReturnInfo getNamedReturnInfo(const VarDecl *VD);
4944 const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info,
4945 QualType ReturnType);
4946
4947 ExprResult
4948 PerformMoveOrCopyInitialization(const InitializedEntity &Entity,
4949 const NamedReturnInfo &NRInfo, Expr *Value,
4950 bool SupressSimplerImplicitMoves = false);
4951
4952 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4953 Scope *CurScope);
4954 StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4955 bool AllowRecovery = false);
4956 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp,
4957 NamedReturnInfo &NRInfo,
4958 bool SupressSimplerImplicitMoves);
4959
4960 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
4961 bool IsVolatile, unsigned NumOutputs,
4962 unsigned NumInputs, IdentifierInfo **Names,
4963 MultiExprArg Constraints, MultiExprArg Exprs,
4964 Expr *AsmString, MultiExprArg Clobbers,
4965 unsigned NumLabels,
4966 SourceLocation RParenLoc);
4967
4968 void FillInlineAsmIdentifierInfo(Expr *Res,
4969 llvm::InlineAsmIdentifierInfo &Info);
4970 ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS,
4971 SourceLocation TemplateKWLoc,
4972 UnqualifiedId &Id,
4973 bool IsUnevaluatedContext);
4974 bool LookupInlineAsmField(StringRef Base, StringRef Member,
4975 unsigned &Offset, SourceLocation AsmLoc);
4976 ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member,
4977 SourceLocation AsmLoc);
4978 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
4979 ArrayRef<Token> AsmToks,
4980 StringRef AsmString,
4981 unsigned NumOutputs, unsigned NumInputs,
4982 ArrayRef<StringRef> Constraints,
4983 ArrayRef<StringRef> Clobbers,
4984 ArrayRef<Expr*> Exprs,
4985 SourceLocation EndLoc);
4986 LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
4987 SourceLocation Location,
4988 bool AlwaysCreate);
4989
4990 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType,
4991 SourceLocation StartLoc,
4992 SourceLocation IdLoc, IdentifierInfo *Id,
4993 bool Invalid = false);
4994
4995 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D);
4996
4997 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen,
4998 Decl *Parm, Stmt *Body);
4999
5000 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body);
5001
5002 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try,
5003 MultiStmtArg Catch, Stmt *Finally);
5004
5005 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw);
5006 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw,
5007 Scope *CurScope);
5008 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc,
5009 Expr *operand);
5010 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc,
5011 Expr *SynchExpr,
5012 Stmt *SynchBody);
5013
5014 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body);
5015
5016 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
5017 SourceLocation StartLoc,
5018 SourceLocation IdLoc,
5019 IdentifierInfo *Id);
5020
5021 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D);
5022
5023 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc,
5024 Decl *ExDecl, Stmt *HandlerBlock);
5025 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock,
5026 ArrayRef<Stmt *> Handlers);
5027
5028 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ?
5029 SourceLocation TryLoc, Stmt *TryBlock,
5030 Stmt *Handler);
5031 StmtResult ActOnSEHExceptBlock(SourceLocation Loc,
5032 Expr *FilterExpr,
5033 Stmt *Block);
5034 void ActOnStartSEHFinallyBlock();
5035 void ActOnAbortSEHFinallyBlock();
5036 StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block);
5037 StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope);
5038
5039 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock);
5040
5041 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const;
5042
5043 /// If it's a file scoped decl that must warn if not used, keep track
5044 /// of it.
5045 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D);
5046
5047 /// DiagnoseUnusedExprResult - If the statement passed in is an expression
5048 /// whose result is unused, warn.
5049 void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);
5050 void DiagnoseUnusedNestedTypedefs(const RecordDecl *D);
5051 void DiagnoseUnusedDecl(const NamedDecl *ND);
5052
5053 /// If VD is set but not otherwise used, diagnose, for a parameter or a
5054 /// variable.
5055 void DiagnoseUnusedButSetDecl(const VarDecl *VD);
5056
5057 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null
5058 /// statement as a \p Body, and it is located on the same line.
5059 ///
5060 /// This helps prevent bugs due to typos, such as:
5061 /// if (condition);
5062 /// do_stuff();
5063 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
5064 const Stmt *Body,
5065 unsigned DiagID);
5066
5067 /// Warn if a for/while loop statement \p S, which is followed by
5068 /// \p PossibleBody, has a suspicious null statement as a body.
5069 void DiagnoseEmptyLoopBody(const Stmt *S,
5070 const Stmt *PossibleBody);
5071
5072 /// Warn if a value is moved to itself.
5073 void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
5074 SourceLocation OpLoc);
5075
5076 /// Warn if we're implicitly casting from a _Nullable pointer type to a
5077 /// _Nonnull one.
5078 void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType,
5079 SourceLocation Loc);
5080
5081 /// Warn when implicitly casting 0 to nullptr.
5082 void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E);
5083
5084 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) {
5085 return DelayedDiagnostics.push(pool);
5086 }
5087 void PopParsingDeclaration(ParsingDeclState state, Decl *decl);
5088
5089 typedef ProcessingContextState ParsingClassState;
5090 ParsingClassState PushParsingClass() {
5091 ParsingClassDepth++;
5092 return DelayedDiagnostics.pushUndelayed();
5093 }
5094 void PopParsingClass(ParsingClassState state) {
5095 ParsingClassDepth--;
5096 DelayedDiagnostics.popUndelayed(state);
5097 }
5098
5099 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool);
5100
5101 void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5102 const ObjCInterfaceDecl *UnknownObjCClass,
5103 bool ObjCPropertyAccess,
5104 bool AvoidPartialAvailabilityChecks = false,
5105 ObjCInterfaceDecl *ClassReceiver = nullptr);
5106
5107 bool makeUnavailableInSystemHeader(SourceLocation loc,
5108 UnavailableAttr::ImplicitReason reason);
5109
5110 /// Issue any -Wunguarded-availability warnings in \c FD
5111 void DiagnoseUnguardedAvailabilityViolations(Decl *FD);
5112
5113 void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
5114
5115 //===--------------------------------------------------------------------===//
5116 // Expression Parsing Callbacks: SemaExpr.cpp.
5117
5118 bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid);
5119 bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
5120 const ObjCInterfaceDecl *UnknownObjCClass = nullptr,
5121 bool ObjCPropertyAccess = false,
5122 bool AvoidPartialAvailabilityChecks = false,
5123 ObjCInterfaceDecl *ClassReciever = nullptr);
5124 void NoteDeletedFunction(FunctionDecl *FD);
5125 void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD);
5126 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD,
5127 ObjCMethodDecl *Getter,
5128 SourceLocation Loc);
5129 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
5130 ArrayRef<Expr *> Args);
5131
5132 void PushExpressionEvaluationContext(
5133 ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr,
5134 ExpressionEvaluationContextRecord::ExpressionKind Type =
5135 ExpressionEvaluationContextRecord::EK_Other);
5136 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl };
5137 void PushExpressionEvaluationContext(
5138 ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
5139 ExpressionEvaluationContextRecord::ExpressionKind Type =
5140 ExpressionEvaluationContextRecord::EK_Other);
5141 void PopExpressionEvaluationContext();
5142
5143 void DiscardCleanupsInEvaluationContext();
5144
5145 ExprResult TransformToPotentiallyEvaluated(Expr *E);
5146 TypeSourceInfo *TransformToPotentiallyEvaluated(TypeSourceInfo *TInfo);
5147 ExprResult HandleExprEvaluationContextForTypeof(Expr *E);
5148
5149 ExprResult CheckUnevaluatedOperand(Expr *E);
5150 void CheckUnusedVolatileAssignment(Expr *E);
5151
5152 ExprResult ActOnConstantExpression(ExprResult Res);
5153
5154 // Functions for marking a declaration referenced. These functions also
5155 // contain the relevant logic for marking if a reference to a function or
5156 // variable is an odr-use (in the C++11 sense). There are separate variants
5157 // for expressions referring to a decl; these exist because odr-use marking
5158 // needs to be delayed for some constant variables when we build one of the
5159 // named expressions.
5160 //
5161 // MightBeOdrUse indicates whether the use could possibly be an odr-use, and
5162 // should usually be true. This only needs to be set to false if the lack of
5163 // odr-use cannot be determined from the current context (for instance,
5164 // because the name denotes a virtual function and was written without an
5165 // explicit nested-name-specifier).
5166 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse);
5167 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
5168 bool MightBeOdrUse = true);
5169 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var);
5170 void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr);
5171 void MarkMemberReferenced(MemberExpr *E);
5172 void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E);
5173 void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc,
5174 unsigned CapturingScopeIndex);
5175
5176 ExprResult CheckLValueToRValueConversionOperand(Expr *E);
5177 void CleanupVarDeclMarking();
5178
5179 enum TryCaptureKind {
5180 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef
5181 };
5182
5183 /// Try to capture the given variable.
5184 ///
5185 /// \param Var The variable to capture.
5186 ///
5187 /// \param Loc The location at which the capture occurs.
5188 ///
5189 /// \param Kind The kind of capture, which may be implicit (for either a
5190 /// block or a lambda), or explicit by-value or by-reference (for a lambda).
5191 ///
5192 /// \param EllipsisLoc The location of the ellipsis, if one is provided in
5193 /// an explicit lambda capture.
5194 ///
5195 /// \param BuildAndDiagnose Whether we are actually supposed to add the
5196 /// captures or diagnose errors. If false, this routine merely check whether
5197 /// the capture can occur without performing the capture itself or complaining
5198 /// if the variable cannot be captured.
5199 ///
5200 /// \param CaptureType Will be set to the type of the field used to capture
5201 /// this variable in the innermost block or lambda. Only valid when the
5202 /// variable can be captured.
5203 ///
5204 /// \param DeclRefType Will be set to the type of a reference to the capture
5205 /// from within the current scope. Only valid when the variable can be
5206 /// captured.
5207 ///
5208 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
5209 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
5210 /// This is useful when enclosing lambdas must speculatively capture
5211 /// variables that may or may not be used in certain specializations of
5212 /// a nested generic lambda.
5213 ///
5214 /// \returns true if an error occurred (i.e., the variable cannot be
5215 /// captured) and false if the capture succeeded.
5216 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind,
5217 SourceLocation EllipsisLoc, bool BuildAndDiagnose,
5218 QualType &CaptureType,
5219 QualType &DeclRefType,
5220 const unsigned *const FunctionScopeIndexToStopAt);
5221
5222 /// Try to capture the given variable.
5223 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
5224 TryCaptureKind Kind = TryCapture_Implicit,
5225 SourceLocation EllipsisLoc = SourceLocation());
5226
5227 /// Checks if the variable must be captured.
5228 bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc);
5229
5230 /// Given a variable, determine the type that a reference to that
5231 /// variable will have in the given scope.
5232 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc);
5233
5234 /// Mark all of the declarations referenced within a particular AST node as
5235 /// referenced. Used when template instantiation instantiates a non-dependent
5236 /// type -- entities referenced by the type are now referenced.
5237 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T);
5238 void MarkDeclarationsReferencedInExpr(Expr *E,
5239 bool SkipLocalVariables = false,
5240 ArrayRef<const Expr *> StopAt = None);
5241
5242 /// Try to recover by turning the given expression into a
5243 /// call. Returns true if recovery was attempted or an error was
5244 /// emitted; this may also leave the ExprResult invalid.
5245 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD,
5246 bool ForceComplain = false,
5247 bool (*IsPlausibleResult)(QualType) = nullptr);
5248
5249 /// Figure out if an expression could be turned into a call.
5250 bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy,
5251 UnresolvedSetImpl &NonTemplateOverloads);
5252
5253 /// Try to convert an expression \p E to type \p Ty. Returns the result of the
5254 /// conversion.
5255 ExprResult tryConvertExprToType(Expr *E, QualType Ty);
5256
5257 /// Conditionally issue a diagnostic based on the statements's reachability
5258 /// analysis.
5259 ///
5260 /// \param Stmts If Stmts is non-empty, delay reporting the diagnostic until
5261 /// the function body is parsed, and then do a basic reachability analysis to
5262 /// determine if the statement is reachable. If it is unreachable, the
5263 /// diagnostic will not be emitted.
5264 bool DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts,
5265 const PartialDiagnostic &PD);
5266
5267 /// Conditionally issue a diagnostic based on the current
5268 /// evaluation context.
5269 ///
5270 /// \param Statement If Statement is non-null, delay reporting the
5271 /// diagnostic until the function body is parsed, and then do a basic
5272 /// reachability analysis to determine if the statement is reachable.
5273 /// If it is unreachable, the diagnostic will not be emitted.
5274 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
5275 const PartialDiagnostic &PD);
5276 /// Similar, but diagnostic is only produced if all the specified statements
5277 /// are reachable.
5278 bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts,
5279 const PartialDiagnostic &PD);
5280
5281 // Primary Expressions.
5282 SourceRange getExprRange(Expr *E) const;
5283
5284 ExprResult ActOnIdExpression(
5285 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5286 UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand,
5287 CorrectionCandidateCallback *CCC = nullptr,
5288 bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr);
5289
5290 ExprResult ActOnMutableAgnosticIdExpression(Scope *S, CXXScopeSpec &SS,
5291 UnqualifiedId &Id);
5292
5293 void DecomposeUnqualifiedId(const UnqualifiedId &Id,
5294 TemplateArgumentListInfo &Buffer,
5295 DeclarationNameInfo &NameInfo,
5296 const TemplateArgumentListInfo *&TemplateArgs);
5297
5298 bool DiagnoseDependentMemberLookup(LookupResult &R);
5299
5300 bool
5301 DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
5302 CorrectionCandidateCallback &CCC,
5303 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr,
5304 ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr);
5305
5306 DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S,
5307 IdentifierInfo *II);
5308 ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV);
5309
5310 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S,
5311 IdentifierInfo *II,
5312 bool AllowBuiltinCreation=false);
5313
5314 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS,
5315 SourceLocation TemplateKWLoc,
5316 const DeclarationNameInfo &NameInfo,
5317 bool isAddressOfOperand,
5318 const TemplateArgumentListInfo *TemplateArgs);
5319
5320 /// If \p D cannot be odr-used in the current expression evaluation context,
5321 /// return a reason explaining why. Otherwise, return NOUR_None.
5322 NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D);
5323
5324 DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5325 SourceLocation Loc,
5326 const CXXScopeSpec *SS = nullptr);
5327 DeclRefExpr *
5328 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5329 const DeclarationNameInfo &NameInfo,
5330 const CXXScopeSpec *SS = nullptr,
5331 NamedDecl *FoundD = nullptr,
5332 SourceLocation TemplateKWLoc = SourceLocation(),
5333 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5334 DeclRefExpr *
5335 BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
5336 const DeclarationNameInfo &NameInfo,
5337 NestedNameSpecifierLoc NNS,
5338 NamedDecl *FoundD = nullptr,
5339 SourceLocation TemplateKWLoc = SourceLocation(),
5340 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5341
5342 ExprResult
5343 BuildAnonymousStructUnionMemberReference(
5344 const CXXScopeSpec &SS,
5345 SourceLocation nameLoc,
5346 IndirectFieldDecl *indirectField,
5347 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none),
5348 Expr *baseObjectExpr = nullptr,
5349 SourceLocation opLoc = SourceLocation());
5350
5351 ExprResult BuildPossibleImplicitMemberExpr(
5352 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
5353 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
5354 UnresolvedLookupExpr *AsULE = nullptr);
5355 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS,
5356 SourceLocation TemplateKWLoc,
5357 LookupResult &R,
5358 const TemplateArgumentListInfo *TemplateArgs,
5359 bool IsDefiniteInstance,
5360 const Scope *S);
5361 bool UseArgumentDependentLookup(const CXXScopeSpec &SS,
5362 const LookupResult &R,
5363 bool HasTrailingLParen);
5364
5365 ExprResult
5366 BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
5367 const DeclarationNameInfo &NameInfo,
5368 bool IsAddressOfOperand, const Scope *S,
5369 TypeSourceInfo **RecoveryTSI = nullptr);
5370
5371 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS,
5372 SourceLocation TemplateKWLoc,
5373 const DeclarationNameInfo &NameInfo,
5374 const TemplateArgumentListInfo *TemplateArgs);
5375
5376 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS,
5377 LookupResult &R,
5378 bool NeedsADL,
5379 bool AcceptInvalidDecl = false);
5380 ExprResult BuildDeclarationNameExpr(
5381 const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
5382 NamedDecl *FoundD = nullptr,
5383 const TemplateArgumentListInfo *TemplateArgs = nullptr,
5384 bool AcceptInvalidDecl = false);
5385
5386 ExprResult BuildLiteralOperatorCall(LookupResult &R,
5387 DeclarationNameInfo &SuffixInfo,
5388 ArrayRef<Expr *> Args,
5389 SourceLocation LitEndLoc,
5390 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr);
5391
5392 ExprResult BuildPredefinedExpr(SourceLocation Loc,
5393 PredefinedExpr::IdentKind IK);
5394 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind);
5395 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val);
5396
5397 ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5398 SourceLocation LParen,
5399 SourceLocation RParen,
5400 TypeSourceInfo *TSI);
5401 ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc,
5402 SourceLocation LParen,
5403 SourceLocation RParen,
5404 ParsedType ParsedTy);
5405
5406 bool CheckLoopHintExpr(Expr *E, SourceLocation Loc);
5407
5408 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr);
5409 ExprResult ActOnCharacterConstant(const Token &Tok,
5410 Scope *UDLScope = nullptr);
5411 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E);
5412 ExprResult ActOnParenListExpr(SourceLocation L,
5413 SourceLocation R,
5414 MultiExprArg Val);
5415
5416 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
5417 /// fragments (e.g. "foo" "bar" L"baz").
5418 ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks,
5419 Scope *UDLScope = nullptr);
5420
5421 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc,
5422 SourceLocation DefaultLoc,
5423 SourceLocation RParenLoc,
5424 Expr *ControllingExpr,
5425 ArrayRef<ParsedType> ArgTypes,
5426 ArrayRef<Expr *> ArgExprs);
5427 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc,
5428 SourceLocation DefaultLoc,
5429 SourceLocation RParenLoc,
5430 Expr *ControllingExpr,
5431 ArrayRef<TypeSourceInfo *> Types,
5432 ArrayRef<Expr *> Exprs);
5433
5434 // Binary/Unary Operators. 'Tok' is the token for the operator.
5435 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
5436 Expr *InputExpr);
5437 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc,
5438 UnaryOperatorKind Opc, Expr *Input);
5439 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5440 tok::TokenKind Op, Expr *Input);
5441
5442 bool isQualifiedMemberAccess(Expr *E);
5443 QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc);
5444
5445 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
5446 SourceLocation OpLoc,
5447 UnaryExprOrTypeTrait ExprKind,
5448 SourceRange R);
5449 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
5450 UnaryExprOrTypeTrait ExprKind);
5451 ExprResult
5452 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
5453 UnaryExprOrTypeTrait ExprKind,
5454 bool IsType, void *TyOrEx,
5455 SourceRange ArgRange);
5456
5457 ExprResult CheckPlaceholderExpr(Expr *E);
5458 bool CheckVecStepExpr(Expr *E);
5459
5460 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind);
5461 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc,
5462 SourceRange ExprRange,
5463 UnaryExprOrTypeTrait ExprKind);
5464 ExprResult ActOnSizeofParameterPackExpr(Scope *S,
5465 SourceLocation OpLoc,
5466 IdentifierInfo &Name,
5467 SourceLocation NameLoc,
5468 SourceLocation RParenLoc);
5469 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
5470 tok::TokenKind Kind, Expr *Input);
5471
5472 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
5473 MultiExprArg ArgExprs,
5474 SourceLocation RLoc);
5475 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
5476 Expr *Idx, SourceLocation RLoc);
5477
5478 ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
5479 Expr *ColumnIdx,
5480 SourceLocation RBLoc);
5481
5482 ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
5483 Expr *LowerBound,
5484 SourceLocation ColonLocFirst,
5485 SourceLocation ColonLocSecond,
5486 Expr *Length, Expr *Stride,
5487 SourceLocation RBLoc);
5488 ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
5489 SourceLocation RParenLoc,
5490 ArrayRef<Expr *> Dims,
5491 ArrayRef<SourceRange> Brackets);
5492
5493 /// Data structure for iterator expression.
5494 struct OMPIteratorData {
5495 IdentifierInfo *DeclIdent = nullptr;
5496 SourceLocation DeclIdentLoc;
5497 ParsedType Type;
5498 OMPIteratorExpr::IteratorRange Range;
5499 SourceLocation AssignLoc;
5500 SourceLocation ColonLoc;
5501 SourceLocation SecColonLoc;
5502 };
5503
5504 ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc,
5505 SourceLocation LLoc, SourceLocation RLoc,
5506 ArrayRef<OMPIteratorData> Data);
5507
5508 // This struct is for use by ActOnMemberAccess to allow
5509 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after
5510 // changing the access operator from a '.' to a '->' (to see if that is the
5511 // change needed to fix an error about an unknown member, e.g. when the class
5512 // defines a custom operator->).
5513 struct ActOnMemberAccessExtraArgs {
5514 Scope *S;
5515 UnqualifiedId &Id;
5516 Decl *ObjCImpDecl;
5517 };
5518
5519 ExprResult BuildMemberReferenceExpr(
5520 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
5521 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
5522 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
5523 const TemplateArgumentListInfo *TemplateArgs,
5524 const Scope *S,
5525 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5526
5527 ExprResult
5528 BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc,
5529 bool IsArrow, const CXXScopeSpec &SS,
5530 SourceLocation TemplateKWLoc,
5531 NamedDecl *FirstQualifierInScope, LookupResult &R,
5532 const TemplateArgumentListInfo *TemplateArgs,
5533 const Scope *S,
5534 bool SuppressQualifierCheck = false,
5535 ActOnMemberAccessExtraArgs *ExtraArgs = nullptr);
5536
5537 ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
5538 SourceLocation OpLoc,
5539 const CXXScopeSpec &SS, FieldDecl *Field,
5540 DeclAccessPair FoundDecl,
5541 const DeclarationNameInfo &MemberNameInfo);
5542
5543 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow);
5544
5545 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType,
5546 const CXXScopeSpec &SS,
5547 const LookupResult &R);
5548
5549 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType,
5550 bool IsArrow, SourceLocation OpLoc,
5551 const CXXScopeSpec &SS,
5552 SourceLocation TemplateKWLoc,
5553 NamedDecl *FirstQualifierInScope,
5554 const DeclarationNameInfo &NameInfo,
5555 const TemplateArgumentListInfo *TemplateArgs);
5556
5557 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base,
5558 SourceLocation OpLoc,
5559 tok::TokenKind OpKind,
5560 CXXScopeSpec &SS,
5561 SourceLocation TemplateKWLoc,
5562 UnqualifiedId &Member,
5563 Decl *ObjCImpDecl);
5564
5565 MemberExpr *
5566 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5567 const CXXScopeSpec *SS, SourceLocation TemplateKWLoc,
5568 ValueDecl *Member, DeclAccessPair FoundDecl,
5569 bool HadMultipleCandidates,
5570 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5571 ExprValueKind VK, ExprObjectKind OK,
5572 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5573 MemberExpr *
5574 BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc,
5575 NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc,
5576 ValueDecl *Member, DeclAccessPair FoundDecl,
5577 bool HadMultipleCandidates,
5578 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
5579 ExprValueKind VK, ExprObjectKind OK,
5580 const TemplateArgumentListInfo *TemplateArgs = nullptr);
5581
5582 void ActOnDefaultCtorInitializers(Decl *CDtorDecl);
5583 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
5584 FunctionDecl *FDecl,
5585 const FunctionProtoType *Proto,
5586 ArrayRef<Expr *> Args,
5587 SourceLocation RParenLoc,
5588 bool ExecConfig = false);
5589 void CheckStaticArrayArgument(SourceLocation CallLoc,
5590 ParmVarDecl *Param,
5591 const Expr *ArgExpr);
5592
5593 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5594 /// This provides the location of the left/right parens and a list of comma
5595 /// locations.
5596 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5597 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5598 Expr *ExecConfig = nullptr);
5599 ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5600 MultiExprArg ArgExprs, SourceLocation RParenLoc,
5601 Expr *ExecConfig = nullptr,
5602 bool IsExecConfig = false,
5603 bool AllowRecovery = false);
5604 Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id,
5605 MultiExprArg CallArgs);
5606 enum class AtomicArgumentOrder { API, AST };
5607 ExprResult
5608 BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5609 SourceLocation RParenLoc, MultiExprArg Args,
5610 AtomicExpr::AtomicOp Op,
5611 AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API);
5612 ExprResult
5613 BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc,
5614 ArrayRef<Expr *> Arg, SourceLocation RParenLoc,
5615 Expr *Config = nullptr, bool IsExecConfig = false,
5616 ADLCallKind UsesADL = ADLCallKind::NotADL);
5617
5618 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
5619 MultiExprArg ExecConfig,
5620 SourceLocation GGGLoc);
5621
5622 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5623 Declarator &D, ParsedType &Ty,
5624 SourceLocation RParenLoc, Expr *CastExpr);
5625 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc,
5626 TypeSourceInfo *Ty,
5627 SourceLocation RParenLoc,
5628 Expr *Op);
5629 CastKind PrepareScalarCast(ExprResult &src, QualType destType);
5630
5631 /// Build an altivec or OpenCL literal.
5632 ExprResult BuildVectorLiteral(SourceLocation LParenLoc,
5633 SourceLocation RParenLoc, Expr *E,
5634 TypeSourceInfo *TInfo);
5635
5636 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME);
5637
5638 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc,
5639 ParsedType Ty,
5640 SourceLocation RParenLoc,
5641 Expr *InitExpr);
5642
5643 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc,
5644 TypeSourceInfo *TInfo,
5645 SourceLocation RParenLoc,
5646 Expr *LiteralExpr);
5647
5648 ExprResult ActOnInitList(SourceLocation LBraceLoc,
5649 MultiExprArg InitArgList,
5650 SourceLocation RBraceLoc);
5651
5652 ExprResult BuildInitList(SourceLocation LBraceLoc,
5653 MultiExprArg InitArgList,
5654 SourceLocation RBraceLoc);
5655
5656 ExprResult ActOnDesignatedInitializer(Designation &Desig,
5657 SourceLocation EqualOrColonLoc,
5658 bool GNUSyntax,
5659 ExprResult Init);
5660
5661private:
5662 static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind);
5663
5664public:
5665 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc,
5666 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr);
5667 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc,
5668 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr);
5669 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc,
5670 Expr *LHSExpr, Expr *RHSExpr);
5671 void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc,
5672 UnresolvedSetImpl &Functions);
5673
5674 void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc);
5675
5676 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
5677 /// in the case of a the GNU conditional expr extension.
5678 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc,
5679 SourceLocation ColonLoc,
5680 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr);
5681
5682 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5683 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
5684 LabelDecl *TheDecl);
5685
5686 void ActOnStartStmtExpr();
5687 ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt,
5688 SourceLocation RPLoc);
5689 ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
5690 SourceLocation RPLoc, unsigned TemplateDepth);
5691 // Handle the final expression in a statement expression.
5692 ExprResult ActOnStmtExprResult(ExprResult E);
5693 void ActOnStmtExprError();
5694
5695 // __builtin_offsetof(type, identifier(.identifier|[expr])*)
5696 struct OffsetOfComponent {
5697 SourceLocation LocStart, LocEnd;
5698 bool isBrackets; // true if [expr], false if .ident
5699 union {
5700 IdentifierInfo *IdentInfo;
5701 Expr *E;
5702 } U;
5703 };
5704
5705 /// __builtin_offsetof(type, a.b[123][456].c)
5706 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
5707 TypeSourceInfo *TInfo,
5708 ArrayRef<OffsetOfComponent> Components,
5709 SourceLocation RParenLoc);
5710 ExprResult ActOnBuiltinOffsetOf(Scope *S,
5711 SourceLocation BuiltinLoc,
5712 SourceLocation TypeLoc,
5713 ParsedType ParsedArgTy,
5714 ArrayRef<OffsetOfComponent> Components,
5715 SourceLocation RParenLoc);
5716
5717 // __builtin_choose_expr(constExpr, expr1, expr2)
5718 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc,
5719 Expr *CondExpr, Expr *LHSExpr,
5720 Expr *RHSExpr, SourceLocation RPLoc);
5721
5722 // __builtin_va_arg(expr, type)
5723 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
5724 SourceLocation RPLoc);
5725 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E,
5726 TypeSourceInfo *TInfo, SourceLocation RPLoc);
5727
5728 // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(),
5729 // __builtin_COLUMN(), __builtin_source_location()
5730 ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind,
5731 SourceLocation BuiltinLoc,
5732 SourceLocation RPLoc);
5733
5734 // Build a potentially resolved SourceLocExpr.
5735 ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
5736 QualType ResultTy, SourceLocation BuiltinLoc,
5737 SourceLocation RPLoc,
5738 DeclContext *ParentContext);
5739
5740 // __null
5741 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc);
5742
5743 bool CheckCaseExpression(Expr *E);
5744
5745 /// Describes the result of an "if-exists" condition check.
5746 enum IfExistsResult {
5747 /// The symbol exists.
5748 IER_Exists,
5749
5750 /// The symbol does not exist.
5751 IER_DoesNotExist,
5752
5753 /// The name is a dependent name, so the results will differ
5754 /// from one instantiation to the next.
5755 IER_Dependent,
5756
5757 /// An error occurred.
5758 IER_Error
5759 };
5760
5761 IfExistsResult
5762 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS,
5763 const DeclarationNameInfo &TargetNameInfo);
5764
5765 IfExistsResult
5766 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5767 bool IsIfExists, CXXScopeSpec &SS,
5768 UnqualifiedId &Name);
5769
5770 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc,
5771 bool IsIfExists,
5772 NestedNameSpecifierLoc QualifierLoc,
5773 DeclarationNameInfo NameInfo,
5774 Stmt *Nested);
5775 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc,
5776 bool IsIfExists,
5777 CXXScopeSpec &SS, UnqualifiedId &Name,
5778 Stmt *Nested);
5779
5780 //===------------------------- "Block" Extension ------------------------===//
5781
5782 /// ActOnBlockStart - This callback is invoked when a block literal is
5783 /// started.
5784 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope);
5785
5786 /// ActOnBlockArguments - This callback allows processing of block arguments.
5787 /// If there are no arguments, this is still invoked.
5788 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
5789 Scope *CurScope);
5790
5791 /// ActOnBlockError - If there is an error parsing a block, this callback
5792 /// is invoked to pop the information about the block from the action impl.
5793 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope);
5794
5795 /// ActOnBlockStmtExpr - This is called when the body of a block statement
5796 /// literal was successfully completed. ^(int x){...}
5797 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body,
5798 Scope *CurScope);
5799
5800 //===---------------------------- Clang Extensions ----------------------===//
5801
5802 /// __builtin_convertvector(...)
5803 ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5804 SourceLocation BuiltinLoc,
5805 SourceLocation RParenLoc);
5806
5807 //===---------------------------- OpenCL Features -----------------------===//
5808
5809 /// __builtin_astype(...)
5810 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5811 SourceLocation BuiltinLoc,
5812 SourceLocation RParenLoc);
5813 ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy,
5814 SourceLocation BuiltinLoc,
5815 SourceLocation RParenLoc);
5816
5817 //===---------------------------- C++ Features --------------------------===//
5818
5819 // Act on C++ namespaces
5820 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc,
5821 SourceLocation NamespaceLoc,
5822 SourceLocation IdentLoc, IdentifierInfo *Ident,
5823 SourceLocation LBrace,
5824 const ParsedAttributesView &AttrList,
5825 UsingDirectiveDecl *&UsingDecl);
5826 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace);
5827
5828 NamespaceDecl *getStdNamespace() const;
5829 NamespaceDecl *getOrCreateStdNamespace();
5830
5831 NamespaceDecl *lookupStdExperimentalNamespace();
5832 NamespaceDecl *getCachedCoroNamespace() { return CoroTraitsNamespaceCache; }
5833
5834 CXXRecordDecl *getStdBadAlloc() const;
5835 EnumDecl *getStdAlignValT() const;
5836
5837private:
5838 // A cache representing if we've fully checked the various comparison category
5839 // types stored in ASTContext. The bit-index corresponds to the integer value
5840 // of a ComparisonCategoryType enumerator.
5841 llvm::SmallBitVector FullyCheckedComparisonCategories;
5842
5843 ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
5844 CXXScopeSpec &SS,
5845 ParsedType TemplateTypeTy,
5846 IdentifierInfo *MemberOrBase);
5847
5848public:
5849 enum class ComparisonCategoryUsage {
5850 /// The '<=>' operator was used in an expression and a builtin operator
5851 /// was selected.
5852 OperatorInExpression,
5853 /// A defaulted 'operator<=>' needed the comparison category. This
5854 /// typically only applies to 'std::strong_ordering', due to the implicit
5855 /// fallback return value.
5856 DefaultedOperator,
5857 };
5858
5859 /// Lookup the specified comparison category types in the standard
5860 /// library, an check the VarDecls possibly returned by the operator<=>
5861 /// builtins for that type.
5862 ///
5863 /// \return The type of the comparison category type corresponding to the
5864 /// specified Kind, or a null type if an error occurs
5865 QualType CheckComparisonCategoryType(ComparisonCategoryType Kind,
5866 SourceLocation Loc,
5867 ComparisonCategoryUsage Usage);
5868
5869 /// Tests whether Ty is an instance of std::initializer_list and, if
5870 /// it is and Element is not NULL, assigns the element type to Element.
5871 bool isStdInitializerList(QualType Ty, QualType *Element);
5872
5873 /// Looks for the std::initializer_list template and instantiates it
5874 /// with Element, or emits an error if it's not found.
5875 ///
5876 /// \returns The instantiated template, or null on error.
5877 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc);
5878
5879 /// Determine whether Ctor is an initializer-list constructor, as
5880 /// defined in [dcl.init.list]p2.
5881 bool isInitListConstructor(const FunctionDecl *Ctor);
5882
5883 Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc,
5884 SourceLocation NamespcLoc, CXXScopeSpec &SS,
5885 SourceLocation IdentLoc,
5886 IdentifierInfo *NamespcName,
5887 const ParsedAttributesView &AttrList);
5888
5889 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir);
5890
5891 Decl *ActOnNamespaceAliasDef(Scope *CurScope,
5892 SourceLocation NamespaceLoc,
5893 SourceLocation AliasLoc,
5894 IdentifierInfo *Alias,
5895 CXXScopeSpec &SS,
5896 SourceLocation IdentLoc,
5897 IdentifierInfo *Ident);
5898
5899 void FilterUsingLookup(Scope *S, LookupResult &lookup);
5900 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow);
5901 bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target,
5902 const LookupResult &PreviousDecls,
5903 UsingShadowDecl *&PrevShadow);
5904 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
5905 NamedDecl *Target,
5906 UsingShadowDecl *PrevDecl);
5907
5908 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
5909 bool HasTypenameKeyword,
5910 const CXXScopeSpec &SS,
5911 SourceLocation NameLoc,
5912 const LookupResult &Previous);
5913 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
5914 const CXXScopeSpec &SS,
5915 const DeclarationNameInfo &NameInfo,
5916 SourceLocation NameLoc,
5917 const LookupResult *R = nullptr,
5918 const UsingDecl *UD = nullptr);
5919
5920 NamedDecl *BuildUsingDeclaration(
5921 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
5922 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
5923 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
5924 const ParsedAttributesView &AttrList, bool IsInstantiation,
5925 bool IsUsingIfExists);
5926 NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
5927 SourceLocation UsingLoc,
5928 SourceLocation EnumLoc,
5929 SourceLocation NameLoc, EnumDecl *ED);
5930 NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
5931 ArrayRef<NamedDecl *> Expansions);
5932
5933 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD);
5934
5935 /// Given a derived-class using shadow declaration for a constructor and the
5936 /// correspnding base class constructor, find or create the implicit
5937 /// synthesized derived class constructor to use for this initialization.
5938 CXXConstructorDecl *
5939 findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor,
5940 ConstructorUsingShadowDecl *DerivedShadow);
5941
5942 Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS,
5943 SourceLocation UsingLoc,
5944 SourceLocation TypenameLoc, CXXScopeSpec &SS,
5945 UnqualifiedId &Name, SourceLocation EllipsisLoc,
5946 const ParsedAttributesView &AttrList);
5947 Decl *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS,
5948 SourceLocation UsingLoc,
5949 SourceLocation EnumLoc, const DeclSpec &);
5950 Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS,
5951 MultiTemplateParamsArg TemplateParams,
5952 SourceLocation UsingLoc, UnqualifiedId &Name,
5953 const ParsedAttributesView &AttrList,
5954 TypeResult Type, Decl *DeclFromDeclSpec);
5955
5956 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
5957 /// including handling of its default argument expressions.
5958 ///
5959 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind
5960 ExprResult
5961 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5962 NamedDecl *FoundDecl,
5963 CXXConstructorDecl *Constructor, MultiExprArg Exprs,
5964 bool HadMultipleCandidates, bool IsListInitialization,
5965 bool IsStdInitListInitialization,
5966 bool RequiresZeroInit, unsigned ConstructKind,
5967 SourceRange ParenRange);
5968
5969 /// Build a CXXConstructExpr whose constructor has already been resolved if
5970 /// it denotes an inherited constructor.
5971 ExprResult
5972 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5973 CXXConstructorDecl *Constructor, bool Elidable,
5974 MultiExprArg Exprs,
5975 bool HadMultipleCandidates, bool IsListInitialization,
5976 bool IsStdInitListInitialization,
5977 bool RequiresZeroInit, unsigned ConstructKind,
5978 SourceRange ParenRange);
5979
5980 // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if
5981 // the constructor can be elidable?
5982 ExprResult
5983 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
5984 NamedDecl *FoundDecl,
5985 CXXConstructorDecl *Constructor, bool Elidable,
5986 MultiExprArg Exprs, bool HadMultipleCandidates,
5987 bool IsListInitialization,
5988 bool IsStdInitListInitialization, bool RequiresZeroInit,
5989 unsigned ConstructKind, SourceRange ParenRange);
5990
5991 ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field);
5992
5993
5994 /// Instantiate or parse a C++ default argument expression as necessary.
5995 /// Return true on error.
5996 bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
5997 ParmVarDecl *Param);
5998
5999 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating
6000 /// the default expr if needed.
6001 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc,
6002 FunctionDecl *FD,
6003 ParmVarDecl *Param);
6004
6005 /// FinalizeVarWithDestructor - Prepare for calling destructor on the
6006 /// constructed variable.
6007 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType);
6008
6009 /// Helper class that collects exception specifications for
6010 /// implicitly-declared special member functions.
6011 class ImplicitExceptionSpecification {
6012 // Pointer to allow copying
6013 Sema *Self;
6014 // We order exception specifications thus:
6015 // noexcept is the most restrictive, but is only used in C++11.
6016 // throw() comes next.
6017 // Then a throw(collected exceptions)
6018 // Finally no specification, which is expressed as noexcept(false).
6019 // throw(...) is used instead if any called function uses it.
6020 ExceptionSpecificationType ComputedEST;
6021 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen;
6022 SmallVector<QualType, 4> Exceptions;
6023
6024 void ClearExceptions() {
6025 ExceptionsSeen.clear();
6026 Exceptions.clear();
6027 }
6028
6029 public:
6030 explicit ImplicitExceptionSpecification(Sema &Self)
6031 : Self(&Self), ComputedEST(EST_BasicNoexcept) {
6032 if (!Self.getLangOpts().CPlusPlus11)
6033 ComputedEST = EST_DynamicNone;
6034 }
6035
6036 /// Get the computed exception specification type.
6037 ExceptionSpecificationType getExceptionSpecType() const {
6038 assert(!isComputedNoexcept(ComputedEST) &&(static_cast <bool> (!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result") ? void (0)
: __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "clang/include/clang/Sema/Sema.h", 6039, __extension__ __PRETTY_FUNCTION__
))
6039 "noexcept(expr) should not be a possible result")(static_cast <bool> (!isComputedNoexcept(ComputedEST) &&
"noexcept(expr) should not be a possible result") ? void (0)
: __assert_fail ("!isComputedNoexcept(ComputedEST) && \"noexcept(expr) should not be a possible result\""
, "clang/include/clang/Sema/Sema.h", 6039, __extension__ __PRETTY_FUNCTION__
))
;
6040 return ComputedEST;
6041 }
6042
6043 /// The number of exceptions in the exception specification.
6044 unsigned size() const { return Exceptions.size(); }
6045
6046 /// The set of exceptions in the exception specification.
6047 const QualType *data() const { return Exceptions.data(); }
6048
6049 /// Integrate another called method into the collected data.
6050 void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method);
6051
6052 /// Integrate an invoked expression into the collected data.
6053 void CalledExpr(Expr *E) { CalledStmt(E); }
6054
6055 /// Integrate an invoked statement into the collected data.
6056 void CalledStmt(Stmt *S);
6057
6058 /// Overwrite an EPI's exception specification with this
6059 /// computed exception specification.
6060 FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const {
6061 FunctionProtoType::ExceptionSpecInfo ESI;
6062 ESI.Type = getExceptionSpecType();
6063 if (ESI.Type == EST_Dynamic) {
6064 ESI.Exceptions = Exceptions;
6065 } else if (ESI.Type == EST_None) {
6066 /// C++11 [except.spec]p14:
6067 /// The exception-specification is noexcept(false) if the set of
6068 /// potential exceptions of the special member function contains "any"
6069 ESI.Type = EST_NoexceptFalse;
6070 ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(),
6071 tok::kw_false).get();
6072 }
6073 return ESI;
6074 }
6075 };
6076
6077 /// Evaluate the implicit exception specification for a defaulted
6078 /// special member function.
6079 void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD);
6080
6081 /// Check the given noexcept-specifier, convert its expression, and compute
6082 /// the appropriate ExceptionSpecificationType.
6083 ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr,
6084 ExceptionSpecificationType &EST);
6085
6086 /// Check the given exception-specification and update the
6087 /// exception specification information with the results.
6088 void checkExceptionSpecification(bool IsTopLevel,
6089 ExceptionSpecificationType EST,
6090 ArrayRef<ParsedType> DynamicExceptions,
6091 ArrayRef<SourceRange> DynamicExceptionRanges,
6092 Expr *NoexceptExpr,
6093 SmallVectorImpl<QualType> &Exceptions,
6094 FunctionProtoType::ExceptionSpecInfo &ESI);
6095
6096 /// Determine if we're in a case where we need to (incorrectly) eagerly
6097 /// parse an exception specification to work around a libstdc++ bug.
6098 bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D);
6099
6100 /// Add an exception-specification to the given member function
6101 /// (or member function template). The exception-specification was parsed
6102 /// after the method itself was declared.
6103 void actOnDelayedExceptionSpecification(Decl *Method,
6104 ExceptionSpecificationType EST,
6105 SourceRange SpecificationRange,
6106 ArrayRef<ParsedType> DynamicExceptions,
6107 ArrayRef<SourceRange> DynamicExceptionRanges,
6108 Expr *NoexceptExpr);
6109
6110 class InheritedConstructorInfo;
6111
6112 /// Determine if a special member function should have a deleted
6113 /// definition when it is defaulted.
6114 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6115 InheritedConstructorInfo *ICI = nullptr,
6116 bool Diagnose = false);
6117
6118 /// Produce notes explaining why a defaulted function was defined as deleted.
6119 void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD);
6120
6121 /// Declare the implicit default constructor for the given class.
6122 ///
6123 /// \param ClassDecl The class declaration into which the implicit
6124 /// default constructor will be added.
6125 ///
6126 /// \returns The implicitly-declared default constructor.
6127 CXXConstructorDecl *DeclareImplicitDefaultConstructor(
6128 CXXRecordDecl *ClassDecl);
6129
6130 /// DefineImplicitDefaultConstructor - Checks for feasibility of
6131 /// defining this constructor as the default constructor.
6132 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
6133 CXXConstructorDecl *Constructor);
6134
6135 /// Declare the implicit destructor for the given class.
6136 ///
6137 /// \param ClassDecl The class declaration into which the implicit
6138 /// destructor will be added.
6139 ///
6140 /// \returns The implicitly-declared destructor.
6141 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl);
6142
6143 /// DefineImplicitDestructor - Checks for feasibility of
6144 /// defining this destructor as the default destructor.
6145 void DefineImplicitDestructor(SourceLocation CurrentLocation,
6146 CXXDestructorDecl *Destructor);
6147
6148 /// Build an exception spec for destructors that don't have one.
6149 ///
6150 /// C++11 says that user-defined destructors with no exception spec get one
6151 /// that looks as if the destructor was implicitly declared.
6152 void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor);
6153
6154 /// Define the specified inheriting constructor.
6155 void DefineInheritingConstructor(SourceLocation UseLoc,
6156 CXXConstructorDecl *Constructor);
6157
6158 /// Declare the implicit copy constructor for the given class.
6159 ///
6160 /// \param ClassDecl The class declaration into which the implicit
6161 /// copy constructor will be added.
6162 ///
6163 /// \returns The implicitly-declared copy constructor.
6164 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl);
6165
6166 /// DefineImplicitCopyConstructor - Checks for feasibility of
6167 /// defining this constructor as the copy constructor.
6168 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
6169 CXXConstructorDecl *Constructor);
6170
6171 /// Declare the implicit move constructor for the given class.
6172 ///
6173 /// \param ClassDecl The Class declaration into which the implicit
6174 /// move constructor will be added.
6175 ///
6176 /// \returns The implicitly-declared move constructor, or NULL if it wasn't
6177 /// declared.
6178 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl);
6179
6180 /// DefineImplicitMoveConstructor - Checks for feasibility of
6181 /// defining this constructor as the move constructor.
6182 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
6183 CXXConstructorDecl *Constructor);
6184
6185 /// Declare the implicit copy assignment operator for the given class.
6186 ///
6187 /// \param ClassDecl The class declaration into which the implicit
6188 /// copy assignment operator will be added.
6189 ///
6190 /// \returns The implicitly-declared copy assignment operator.
6191 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl);
6192
6193 /// Defines an implicitly-declared copy assignment operator.
6194 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
6195 CXXMethodDecl *MethodDecl);
6196
6197 /// Declare the implicit move assignment operator for the given class.
6198 ///
6199 /// \param ClassDecl The Class declaration into which the implicit
6200 /// move assignment operator will be added.
6201 ///
6202 /// \returns The implicitly-declared move assignment operator, or NULL if it
6203 /// wasn't declared.
6204 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl);
6205
6206 /// Defines an implicitly-declared move assignment operator.
6207 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
6208 CXXMethodDecl *MethodDecl);
6209
6210 /// Force the declaration of any implicitly-declared members of this
6211 /// class.
6212 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class);
6213
6214 /// Check a completed declaration of an implicit special member.
6215 void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD);
6216
6217 /// Determine whether the given function is an implicitly-deleted
6218 /// special member function.
6219 bool isImplicitlyDeleted(FunctionDecl *FD);
6220
6221 /// Check whether 'this' shows up in the type of a static member
6222 /// function after the (naturally empty) cv-qualifier-seq would be.
6223 ///
6224 /// \returns true if an error occurred.
6225 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method);
6226
6227 /// Whether this' shows up in the exception specification of a static
6228 /// member function.
6229 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method);
6230
6231 /// Check whether 'this' shows up in the attributes of the given
6232 /// static member function.
6233 ///
6234 /// \returns true if an error occurred.
6235 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method);
6236
6237 /// MaybeBindToTemporary - If the passed in expression has a record type with
6238 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise
6239 /// it simply returns the passed in expression.
6240 ExprResult MaybeBindToTemporary(Expr *E);
6241
6242 /// Wrap the expression in a ConstantExpr if it is a potential immediate
6243 /// invocation.
6244 ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl);
6245
6246 bool CompleteConstructorCall(CXXConstructorDecl *Constructor,
6247 QualType DeclInitType, MultiExprArg ArgsPtr,
6248 SourceLocation Loc,
6249 SmallVectorImpl<Expr *> &ConvertedArgs,
6250 bool AllowExplicit = false,
6251 bool IsListInitialization = false);
6252
6253 ParsedType getInheritingConstructorName(CXXScopeSpec &SS,
6254 SourceLocation NameLoc,
6255 IdentifierInfo &Name);
6256
6257 ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc,
6258 Scope *S, CXXScopeSpec &SS,
6259 bool EnteringContext);
6260 ParsedType getDestructorName(SourceLocation TildeLoc,
6261 IdentifierInfo &II, SourceLocation NameLoc,
6262 Scope *S, CXXScopeSpec &SS,
6263 ParsedType ObjectType,
6264 bool EnteringContext);
6265
6266 ParsedType getDestructorTypeForDecltype(const DeclSpec &DS,
6267 ParsedType ObjectType);
6268
6269 // Checks that reinterpret casts don't have undefined behavior.
6270 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
6271 bool IsDereference, SourceRange Range);
6272
6273 // Checks that the vector type should be initialized from a scalar
6274 // by splatting the value rather than populating a single element.
6275 // This is the case for AltiVecVector types as well as with
6276 // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified.
6277 bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy);
6278
6279 // Checks if the -faltivec-src-compat=gcc option is specified.
6280 // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are
6281 // treated the same way as they are when trying to initialize
6282 // these vectors on gcc (an error is emitted).
6283 bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy,
6284 QualType SrcTy);
6285
6286 /// ActOnCXXNamedCast - Parse
6287 /// {dynamic,static,reinterpret,const,addrspace}_cast's.
6288 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc,
6289 tok::TokenKind Kind,
6290 SourceLocation LAngleBracketLoc,
6291 Declarator &D,
6292 SourceLocation RAngleBracketLoc,
6293 SourceLocation LParenLoc,
6294 Expr *E,
6295 SourceLocation RParenLoc);
6296
6297 ExprResult BuildCXXNamedCast(SourceLocation OpLoc,
6298 tok::TokenKind Kind,
6299 TypeSourceInfo *Ty,
6300 Expr *E,
6301 SourceRange AngleBrackets,
6302 SourceRange Parens);
6303
6304 ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl,
6305 ExprResult Operand,
6306 SourceLocation RParenLoc);
6307
6308 ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI,
6309 Expr *Operand, SourceLocation RParenLoc);
6310
6311 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6312 SourceLocation TypeidLoc,
6313 TypeSourceInfo *Operand,
6314 SourceLocation RParenLoc);
6315 ExprResult BuildCXXTypeId(QualType TypeInfoType,
6316 SourceLocation TypeidLoc,
6317 Expr *Operand,
6318 SourceLocation RParenLoc);
6319
6320 /// ActOnCXXTypeid - Parse typeid( something ).
6321 ExprResult ActOnCXXTypeid(SourceLocation OpLoc,
6322 SourceLocation LParenLoc, bool isType,
6323 void *TyOrExpr,
6324 SourceLocation RParenLoc);
6325
6326 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6327 SourceLocation TypeidLoc,
6328 TypeSourceInfo *Operand,
6329 SourceLocation RParenLoc);
6330 ExprResult BuildCXXUuidof(QualType TypeInfoType,
6331 SourceLocation TypeidLoc,
6332 Expr *Operand,
6333 SourceLocation RParenLoc);
6334
6335 /// ActOnCXXUuidof - Parse __uuidof( something ).
6336 ExprResult ActOnCXXUuidof(SourceLocation OpLoc,
6337 SourceLocation LParenLoc, bool isType,
6338 void *TyOrExpr,
6339 SourceLocation RParenLoc);
6340
6341 /// Handle a C++1z fold-expression: ( expr op ... op expr ).
6342 ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
6343 tok::TokenKind Operator,
6344 SourceLocation EllipsisLoc, Expr *RHS,
6345 SourceLocation RParenLoc);
6346 ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
6347 SourceLocation LParenLoc, Expr *LHS,
6348 BinaryOperatorKind Operator,
6349 SourceLocation EllipsisLoc, Expr *RHS,
6350 SourceLocation RParenLoc,
6351 Optional<unsigned> NumExpansions);
6352 ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
6353 BinaryOperatorKind Operator);
6354
6355 //// ActOnCXXThis - Parse 'this' pointer.
6356 ExprResult ActOnCXXThis(SourceLocation loc);
6357
6358 /// Build a CXXThisExpr and mark it referenced in the current context.
6359 Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
6360 void MarkThisReferenced(CXXThisExpr *This);
6361
6362 /// Try to retrieve the type of the 'this' pointer.
6363 ///
6364 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type.
6365 QualType getCurrentThisType();
6366
6367 /// When non-NULL, the C++ 'this' expression is allowed despite the
6368 /// current context not being a non-static member function. In such cases,
6369 /// this provides the type used for 'this'.
6370 QualType CXXThisTypeOverride;
6371
6372 /// RAII object used to temporarily allow the C++ 'this' expression
6373 /// to be used, with the given qualifiers on the current class type.
6374 class CXXThisScopeRAII {
6375 Sema &S;
6376 QualType OldCXXThisTypeOverride;
6377 bool Enabled;
6378
6379 public:
6380 /// Introduce a new scope where 'this' may be allowed (when enabled),
6381 /// using the given declaration (which is either a class template or a
6382 /// class) along with the given qualifiers.
6383 /// along with the qualifiers placed on '*this'.
6384 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals,
6385 bool Enabled = true);
6386
6387 ~CXXThisScopeRAII();
6388 };
6389
6390 /// Make sure the value of 'this' is actually available in the current
6391 /// context, if it is a potentially evaluated context.
6392 ///
6393 /// \param Loc The location at which the capture of 'this' occurs.
6394 ///
6395 /// \param Explicit Whether 'this' is explicitly captured in a lambda
6396 /// capture list.
6397 ///
6398 /// \param FunctionScopeIndexToStopAt If non-null, it points to the index
6399 /// of the FunctionScopeInfo stack beyond which we do not attempt to capture.
6400 /// This is useful when enclosing lambdas must speculatively capture
6401 /// 'this' that may or may not be used in certain specializations of
6402 /// a nested generic lambda (depending on whether the name resolves to
6403 /// a non-static member function or a static function).
6404 /// \return returns 'true' if failed, 'false' if success.
6405 bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false,
6406 bool BuildAndDiagnose = true,
6407 const unsigned *const FunctionScopeIndexToStopAt = nullptr,
6408 bool ByCopy = false);
6409
6410 /// Determine whether the given type is the type of *this that is used
6411 /// outside of the body of a member function for a type that is currently
6412 /// being defined.
6413 bool isThisOutsideMemberFunctionBody(QualType BaseType);
6414
6415 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
6416 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6417
6418
6419 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
6420 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind);
6421
6422 ExprResult
6423 ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs,
6424 SourceLocation AtLoc, SourceLocation RParen);
6425
6426 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
6427 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc);
6428
6429 //// ActOnCXXThrow - Parse throw expressions.
6430 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr);
6431 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
6432 bool IsThrownVarInScope);
6433 bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E);
6434
6435 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
6436 /// Can be interpreted either as function-style casting ("int(x)")
6437 /// or class type construction ("ClassType(x,y,z)")
6438 /// or creation of a value-initialized type ("int()").
6439 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep,
6440 SourceLocation LParenOrBraceLoc,
6441 MultiExprArg Exprs,
6442 SourceLocation RParenOrBraceLoc,
6443 bool ListInitialization);
6444
6445 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type,
6446 SourceLocation LParenLoc,
6447 MultiExprArg Exprs,
6448 SourceLocation RParenLoc,
6449 bool ListInitialization);
6450
6451 /// ActOnCXXNew - Parsed a C++ 'new' expression.
6452 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
6453 SourceLocation PlacementLParen,
6454 MultiExprArg PlacementArgs,
6455 SourceLocation PlacementRParen,
6456 SourceRange TypeIdParens, Declarator &D,
6457 Expr *Initializer);
6458 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal,
6459 SourceLocation PlacementLParen,
6460 MultiExprArg PlacementArgs,
6461 SourceLocation PlacementRParen,
6462 SourceRange TypeIdParens,
6463 QualType AllocType,
6464 TypeSourceInfo *AllocTypeInfo,
6465 Optional<Expr *> ArraySize,
6466 SourceRange DirectInitRange,
6467 Expr *Initializer);
6468
6469 /// Determine whether \p FD is an aligned allocation or deallocation
6470 /// function that is unavailable.
6471 bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const;
6472
6473 /// Produce diagnostics if \p FD is an aligned allocation or deallocation
6474 /// function that is unavailable.
6475 void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
6476 SourceLocation Loc);
6477
6478 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc,
6479 SourceRange R);
6480
6481 /// The scope in which to find allocation functions.
6482 enum AllocationFunctionScope {
6483 /// Only look for allocation functions in the global scope.
6484 AFS_Global,
6485 /// Only look for allocation functions in the scope of the
6486 /// allocated class.
6487 AFS_Class,
6488 /// Look for allocation functions in both the global scope
6489 /// and in the scope of the allocated class.
6490 AFS_Both
6491 };
6492
6493 /// Finds the overloads of operator new and delete that are appropriate
6494 /// for the allocation.
6495 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
6496 AllocationFunctionScope NewScope,
6497 AllocationFunctionScope DeleteScope,
6498 QualType AllocType, bool IsArray,
6499 bool &PassAlignment, MultiExprArg PlaceArgs,
6500 FunctionDecl *&OperatorNew,
6501 FunctionDecl *&OperatorDelete,
6502 bool Diagnose = true);
6503 void DeclareGlobalNewDelete();
6504 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return,
6505 ArrayRef<QualType> Params);
6506
6507 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
6508 DeclarationName Name, FunctionDecl* &Operator,
6509 bool Diagnose = true);
6510 FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc,
6511 bool CanProvideSize,
6512 bool Overaligned,
6513 DeclarationName Name);
6514 FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc,
6515 CXXRecordDecl *RD);
6516
6517 /// ActOnCXXDelete - Parsed a C++ 'delete' expression
6518 ExprResult ActOnCXXDelete(SourceLocation StartLoc,
6519 bool UseGlobal, bool ArrayForm,
6520 Expr *Operand);
6521 void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
6522 bool IsDelete, bool CallCanBeVirtual,
6523 bool WarnOnNonAbstractTypes,
6524 SourceLocation DtorLoc);
6525
6526 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen,
6527 Expr *Operand, SourceLocation RParen);
6528 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6529 SourceLocation RParen);
6530
6531 /// Parsed one of the type trait support pseudo-functions.
6532 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6533 ArrayRef<ParsedType> Args,
6534 SourceLocation RParenLoc);
6535 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
6536 ArrayRef<TypeSourceInfo *> Args,
6537 SourceLocation RParenLoc);
6538
6539 /// ActOnArrayTypeTrait - Parsed one of the binary type trait support
6540 /// pseudo-functions.
6541 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT,
6542 SourceLocation KWLoc,
6543 ParsedType LhsTy,
6544 Expr *DimExpr,
6545 SourceLocation RParen);
6546
6547 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT,
6548 SourceLocation KWLoc,
6549 TypeSourceInfo *TSInfo,
6550 Expr *DimExpr,
6551 SourceLocation RParen);
6552
6553 /// ActOnExpressionTrait - Parsed one of the unary type trait support
6554 /// pseudo-functions.
6555 ExprResult ActOnExpressionTrait(ExpressionTrait OET,
6556 SourceLocation KWLoc,
6557 Expr *Queried,
6558 SourceLocation RParen);
6559
6560 ExprResult BuildExpressionTrait(ExpressionTrait OET,
6561 SourceLocation KWLoc,
6562 Expr *Queried,
6563 SourceLocation RParen);
6564
6565 ExprResult ActOnStartCXXMemberReference(Scope *S,
6566 Expr *Base,
6567 SourceLocation OpLoc,
6568 tok::TokenKind OpKind,
6569 ParsedType &ObjectType,
6570 bool &MayBePseudoDestructor);
6571
6572 ExprResult BuildPseudoDestructorExpr(Expr *Base,
6573 SourceLocation OpLoc,
6574 tok::TokenKind OpKind,
6575 const CXXScopeSpec &SS,
6576 TypeSourceInfo *ScopeType,
6577 SourceLocation CCLoc,
6578 SourceLocation TildeLoc,
6579 PseudoDestructorTypeStorage DestroyedType);
6580
6581 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6582 SourceLocation OpLoc,
6583 tok::TokenKind OpKind,
6584 CXXScopeSpec &SS,
6585 UnqualifiedId &FirstTypeName,
6586 SourceLocation CCLoc,
6587 SourceLocation TildeLoc,
6588 UnqualifiedId &SecondTypeName);
6589
6590 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6591 SourceLocation OpLoc,
6592 tok::TokenKind OpKind,
6593 SourceLocation TildeLoc,
6594 const DeclSpec& DS);
6595
6596 /// MaybeCreateExprWithCleanups - If the current full-expression
6597 /// requires any cleanups, surround it with a ExprWithCleanups node.
6598 /// Otherwise, just returns the passed-in expression.
6599 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr);
6600 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt);
6601 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr);
6602
6603 MaterializeTemporaryExpr *
6604 CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary,
6605 bool BoundToLvalueReference);
6606
6607 ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) {
6608 return ActOnFinishFullExpr(
6609 Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue);
6610 }
6611 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC,
6612 bool DiscardedValue, bool IsConstexpr = false);
6613 StmtResult ActOnFinishFullStmt(Stmt *Stmt);
6614
6615 // Marks SS invalid if it represents an incomplete type.
6616 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC);
6617 // Complete an enum decl, maybe without a scope spec.
6618 bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L,
6619 CXXScopeSpec *SS = nullptr);
6620
6621 DeclContext *computeDeclContext(QualType T);
6622 DeclContext *computeDeclContext(const CXXScopeSpec &SS,
6623 bool EnteringContext = false);
6624 bool isDependentScopeSpecifier(const CXXScopeSpec &SS);
6625 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS);
6626
6627 /// The parser has parsed a global nested-name-specifier '::'.
6628 ///
6629 /// \param CCLoc The location of the '::'.
6630 ///
6631 /// \param SS The nested-name-specifier, which will be updated in-place
6632 /// to reflect the parsed nested-name-specifier.
6633 ///
6634 /// \returns true if an error occurred, false otherwise.
6635 bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS);
6636
6637 /// The parser has parsed a '__super' nested-name-specifier.
6638 ///
6639 /// \param SuperLoc The location of the '__super' keyword.
6640 ///
6641 /// \param ColonColonLoc The location of the '::'.
6642 ///
6643 /// \param SS The nested-name-specifier, which will be updated in-place
6644 /// to reflect the parsed nested-name-specifier.
6645 ///
6646 /// \returns true if an error occurred, false otherwise.
6647 bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc,
6648 SourceLocation ColonColonLoc, CXXScopeSpec &SS);
6649
6650 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD,
6651 bool *CanCorrect = nullptr);
6652 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS);
6653
6654 /// Keeps information about an identifier in a nested-name-spec.
6655 ///
6656 struct NestedNameSpecInfo {
6657 /// The type of the object, if we're parsing nested-name-specifier in
6658 /// a member access expression.
6659 ParsedType ObjectType;
6660
6661 /// The identifier preceding the '::'.
6662 IdentifierInfo *Identifier;
6663
6664 /// The location of the identifier.
6665 SourceLocation IdentifierLoc;
6666
6667 /// The location of the '::'.
6668 SourceLocation CCLoc;
6669
6670 /// Creates info object for the most typical case.
6671 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6672 SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType())
6673 : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc),
6674 CCLoc(ColonColonLoc) {
6675 }
6676
6677 NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc,
6678 SourceLocation ColonColonLoc, QualType ObjectType)
6679 : ObjectType(ParsedType::make(ObjectType)), Identifier(II),
6680 IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) {
6681 }
6682 };
6683
6684 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS,
6685 NestedNameSpecInfo &IdInfo);
6686
6687 bool BuildCXXNestedNameSpecifier(Scope *S,
6688 NestedNameSpecInfo &IdInfo,
6689 bool EnteringContext,
6690 CXXScopeSpec &SS,
6691 NamedDecl *ScopeLookupResult,
6692 bool ErrorRecoveryLookup,
6693 bool *IsCorrectedToColon = nullptr,
6694 bool OnlyNamespace = false);
6695
6696 /// The parser has parsed a nested-name-specifier 'identifier::'.
6697 ///
6698 /// \param S The scope in which this nested-name-specifier occurs.
6699 ///
6700 /// \param IdInfo Parser information about an identifier in the
6701 /// nested-name-spec.
6702 ///
6703 /// \param EnteringContext Whether we're entering the context nominated by
6704 /// this nested-name-specifier.
6705 ///
6706 /// \param SS The nested-name-specifier, which is both an input
6707 /// parameter (the nested-name-specifier before this type) and an
6708 /// output parameter (containing the full nested-name-specifier,
6709 /// including this new type).
6710 ///
6711 /// \param ErrorRecoveryLookup If true, then this method is called to improve
6712 /// error recovery. In this case do not emit error message.
6713 ///
6714 /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':'
6715 /// are allowed. The bool value pointed by this parameter is set to 'true'
6716 /// if the identifier is treated as if it was followed by ':', not '::'.
6717 ///
6718 /// \param OnlyNamespace If true, only considers namespaces in lookup.
6719 ///
6720 /// \returns true if an error occurred, false otherwise.
6721 bool ActOnCXXNestedNameSpecifier(Scope *S,
6722 NestedNameSpecInfo &IdInfo,
6723 bool EnteringContext,
6724 CXXScopeSpec &SS,
6725 bool ErrorRecoveryLookup = false,
6726 bool *IsCorrectedToColon = nullptr,
6727 bool OnlyNamespace = false);
6728
6729 ExprResult ActOnDecltypeExpression(Expr *E);
6730
6731 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS,
6732 const DeclSpec &DS,
6733 SourceLocation ColonColonLoc);
6734
6735 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS,
6736 NestedNameSpecInfo &IdInfo,
6737 bool EnteringContext);
6738
6739 /// The parser has parsed a nested-name-specifier
6740 /// 'template[opt] template-name < template-args >::'.
6741 ///
6742 /// \param S The scope in which this nested-name-specifier occurs.
6743 ///
6744 /// \param SS The nested-name-specifier, which is both an input
6745 /// parameter (the nested-name-specifier before this type) and an
6746 /// output parameter (containing the full nested-name-specifier,
6747 /// including this new type).
6748 ///
6749 /// \param TemplateKWLoc the location of the 'template' keyword, if any.
6750 /// \param TemplateName the template name.
6751 /// \param TemplateNameLoc The location of the template name.
6752 /// \param LAngleLoc The location of the opening angle bracket ('<').
6753 /// \param TemplateArgs The template arguments.
6754 /// \param RAngleLoc The location of the closing angle bracket ('>').
6755 /// \param CCLoc The location of the '::'.
6756 ///
6757 /// \param EnteringContext Whether we're entering the context of the
6758 /// nested-name-specifier.
6759 ///
6760 ///
6761 /// \returns true if an error occurred, false otherwise.
6762 bool ActOnCXXNestedNameSpecifier(Scope *S,
6763 CXXScopeSpec &SS,
6764 SourceLocation TemplateKWLoc,
6765 TemplateTy TemplateName,
6766 SourceLocation TemplateNameLoc,
6767 SourceLocation LAngleLoc,
6768 ASTTemplateArgsPtr TemplateArgs,
6769 SourceLocation RAngleLoc,
6770 SourceLocation CCLoc,
6771 bool EnteringContext);
6772
6773 /// Given a C++ nested-name-specifier, produce an annotation value
6774 /// that the parser can use later to reconstruct the given
6775 /// nested-name-specifier.
6776 ///
6777 /// \param SS A nested-name-specifier.
6778 ///
6779 /// \returns A pointer containing all of the information in the
6780 /// nested-name-specifier \p SS.
6781 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS);
6782
6783 /// Given an annotation pointer for a nested-name-specifier, restore
6784 /// the nested-name-specifier structure.
6785 ///
6786 /// \param Annotation The annotation pointer, produced by
6787 /// \c SaveNestedNameSpecifierAnnotation().
6788 ///
6789 /// \param AnnotationRange The source range corresponding to the annotation.
6790 ///
6791 /// \param SS The nested-name-specifier that will be updated with the contents
6792 /// of the annotation pointer.
6793 void RestoreNestedNameSpecifierAnnotation(void *Annotation,
6794 SourceRange AnnotationRange,
6795 CXXScopeSpec &SS);
6796
6797 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6798
6799 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global
6800 /// scope or nested-name-specifier) is parsed, part of a declarator-id.
6801 /// After this method is called, according to [C++ 3.4.3p3], names should be
6802 /// looked up in the declarator-id's scope, until the declarator is parsed and
6803 /// ActOnCXXExitDeclaratorScope is called.
6804 /// The 'SS' should be a non-empty valid CXXScopeSpec.
6805 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS);
6806
6807 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously
6808 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same
6809 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well.
6810 /// Used to indicate that names should revert to being looked up in the
6811 /// defining scope.
6812 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS);
6813
6814 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an
6815 /// initializer for the declaration 'Dcl'.
6816 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
6817 /// static data member of class X, names should be looked up in the scope of
6818 /// class X.
6819 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl);
6820
6821 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an
6822 /// initializer for the declaration 'Dcl'.
6823 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl);
6824
6825 /// Create a new lambda closure type.
6826 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange,
6827 TypeSourceInfo *Info,
6828 unsigned LambdaDependencyKind,
6829 LambdaCaptureDefault CaptureDefault);
6830
6831 /// Start the definition of a lambda expression.
6832 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class,
6833 SourceRange IntroducerRange,
6834 TypeSourceInfo *MethodType,
6835 SourceLocation EndLoc,
6836 ArrayRef<ParmVarDecl *> Params,
6837 ConstexprSpecKind ConstexprKind,
6838 Expr *TrailingRequiresClause);
6839
6840 /// Number lambda for linkage purposes if necessary.
6841 void handleLambdaNumbering(
6842 CXXRecordDecl *Class, CXXMethodDecl *Method,
6843 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None);
6844
6845 /// Endow the lambda scope info with the relevant properties.
6846 void buildLambdaScope(sema::LambdaScopeInfo *LSI,
6847 CXXMethodDecl *CallOperator,
6848 SourceRange IntroducerRange,
6849 LambdaCaptureDefault CaptureDefault,
6850 SourceLocation CaptureDefaultLoc,
6851 bool ExplicitParams,
6852 bool ExplicitResultType,
6853 bool Mutable);
6854
6855 /// Perform initialization analysis of the init-capture and perform
6856 /// any implicit conversions such as an lvalue-to-rvalue conversion if
6857 /// not being used to initialize a reference.
6858 ParsedType actOnLambdaInitCaptureInitialization(
6859 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6860 IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) {
6861 return ParsedType::make(buildLambdaInitCaptureInitialization(
6862 Loc, ByRef, EllipsisLoc, None, Id,
6863 InitKind != LambdaCaptureInitKind::CopyInit, Init));
6864 }
6865 QualType buildLambdaInitCaptureInitialization(
6866 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
6867 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit,
6868 Expr *&Init);
6869
6870 /// Create a dummy variable within the declcontext of the lambda's
6871 /// call operator, for name lookup purposes for a lambda init capture.
6872 ///
6873 /// CodeGen handles emission of lambda captures, ignoring these dummy
6874 /// variables appropriately.
6875 VarDecl *createLambdaInitCaptureVarDecl(
6876 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
6877 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx);
6878
6879 /// Add an init-capture to a lambda scope.
6880 void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var);
6881
6882 /// Note that we have finished the explicit captures for the
6883 /// given lambda.
6884 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI);
6885
6886 /// Deduce a block or lambda's return type based on the return
6887 /// statements present in the body.
6888 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI);
6889
6890 /// Once the Lambdas capture are known, we can
6891 /// start to create the closure, call operator method,
6892 /// and keep track of the captures.
6893 /// We do the capture lookup here, but they are not actually captured
6894 /// until after we know what the qualifiers of the call operator are.
6895 void ActOnLambdaIntroducer(LambdaIntroducer &Intro, Scope *CurContext);
6896
6897 /// This is called after parsing the explicit template parameter list
6898 /// on a lambda (if it exists) in C++2a.
6899 void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro,
6900 SourceLocation LAngleLoc,
6901 ArrayRef<NamedDecl *> TParams,
6902 SourceLocation RAngleLoc,
6903 ExprResult RequiresClause);
6904
6905 void ActOnLambdaClosureQualifiers(
6906 LambdaIntroducer &Intro, SourceLocation MutableLoc, SourceLocation EndLoc,
6907 MutableArrayRef<DeclaratorChunk::ParamInfo> ParamInfo,
6908 const DeclSpec &DS);
6909
6910 /// ActOnStartOfLambdaDefinition - This is called just before we start
6911 /// parsing the body of a lambda; it analyzes the explicit captures and
6912 /// arguments, and sets up various data-structures for the body of the
6913 /// lambda.
6914 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
6915 Declarator &ParamInfo, Scope *CurScope);
6916
6917 /// ActOnLambdaError - If there is an error parsing a lambda, this callback
6918 /// is invoked to pop the information about the lambda.
6919 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
6920 bool IsInstantiation = false);
6921
6922 /// ActOnLambdaExpr - This is called when the body of a lambda expression
6923 /// was successfully completed.
6924 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
6925 Scope *CurScope);
6926
6927 /// Does copying/destroying the captured variable have side effects?
6928 bool CaptureHasSideEffects(const sema::Capture &From);
6929
6930 /// Diagnose if an explicit lambda capture is unused. Returns true if a
6931 /// diagnostic is emitted.
6932 bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
6933 const sema::Capture &From);
6934
6935 /// Build a FieldDecl suitable to hold the given capture.
6936 FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture);
6937
6938 /// Initialize the given capture with a suitable expression.
6939 ExprResult BuildCaptureInit(const sema::Capture &Capture,
6940 SourceLocation ImplicitCaptureLoc,
6941 bool IsOpenMPMapping = false);
6942
6943 /// Complete a lambda-expression having processed and attached the
6944 /// lambda body.
6945 ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
6946 sema::LambdaScopeInfo *LSI);
6947
6948 /// Get the return type to use for a lambda's conversion function(s) to
6949 /// function pointer type, given the type of the call operator.
6950 QualType
6951 getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType,
6952 CallingConv CC);
6953
6954 /// Define the "body" of the conversion from a lambda object to a
6955 /// function pointer.
6956 ///
6957 /// This routine doesn't actually define a sensible body; rather, it fills
6958 /// in the initialization expression needed to copy the lambda object into
6959 /// the block, and IR generation actually generates the real body of the
6960 /// block pointer conversion.
6961 void DefineImplicitLambdaToFunctionPointerConversion(
6962 SourceLocation CurrentLoc, CXXConversionDecl *Conv);
6963
6964 /// Define the "body" of the conversion from a lambda object to a
6965 /// block pointer.
6966 ///
6967 /// This routine doesn't actually define a sensible body; rather, it fills
6968 /// in the initialization expression needed to copy the lambda object into
6969 /// the block, and IR generation actually generates the real body of the
6970 /// block pointer conversion.
6971 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc,
6972 CXXConversionDecl *Conv);
6973
6974 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
6975 SourceLocation ConvLocation,
6976 CXXConversionDecl *Conv,
6977 Expr *Src);
6978
6979 /// Check whether the given expression is a valid constraint expression.
6980 /// A diagnostic is emitted if it is not, false is returned, and
6981 /// PossibleNonPrimary will be set to true if the failure might be due to a
6982 /// non-primary expression being used as an atomic constraint.
6983 bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(),
6984 bool *PossibleNonPrimary = nullptr,
6985 bool IsTrailingRequiresClause = false);
6986
6987private:
6988 /// Caches pairs of template-like decls whose associated constraints were
6989 /// checked for subsumption and whether or not the first's constraints did in
6990 /// fact subsume the second's.
6991 llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache;
6992 /// Caches the normalized associated constraints of declarations (concepts or
6993 /// constrained declarations). If an error occurred while normalizing the
6994 /// associated constraints of the template or concept, nullptr will be cached
6995 /// here.
6996 llvm::DenseMap<NamedDecl *, NormalizedConstraint *>
6997 NormalizationCache;
6998
6999 llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &>
7000 SatisfactionCache;
7001
7002 /// Introduce the instantiated function parameters into the local
7003 /// instantiation scope, and set the parameter names to those used
7004 /// in the template.
7005 bool addInstantiatedParametersToScope(
7006 FunctionDecl *Function, const FunctionDecl *PatternDecl,
7007 LocalInstantiationScope &Scope,
7008 const MultiLevelTemplateArgumentList &TemplateArgs);
7009
7010public:
7011 const NormalizedConstraint *
7012 getNormalizedAssociatedConstraints(
7013 NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints);
7014
7015 /// \brief Check whether the given declaration's associated constraints are
7016 /// at least as constrained than another declaration's according to the
7017 /// partial ordering of constraints.
7018 ///
7019 /// \param Result If no error occurred, receives the result of true if D1 is
7020 /// at least constrained than D2, and false otherwise.
7021 ///
7022 /// \returns true if an error occurred, false otherwise.
7023 bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1,
7024 NamedDecl *D2, ArrayRef<const Expr *> AC2,
7025 bool &Result);
7026
7027 /// If D1 was not at least as constrained as D2, but would've been if a pair
7028 /// of atomic constraints involved had been declared in a concept and not
7029 /// repeated in two separate places in code.
7030 /// \returns true if such a diagnostic was emitted, false otherwise.
7031 bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1,
7032 ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2);
7033
7034 /// \brief Check whether the given list of constraint expressions are
7035 /// satisfied (as if in a 'conjunction') given template arguments.
7036 /// \param Template the template-like entity that triggered the constraints
7037 /// check (either a concept or a constrained entity).
7038 /// \param ConstraintExprs a list of constraint expressions, treated as if
7039 /// they were 'AND'ed together.
7040 /// \param TemplateArgs the list of template arguments to substitute into the
7041 /// constraint expression.
7042 /// \param TemplateIDRange The source range of the template id that
7043 /// caused the constraints check.
7044 /// \param Satisfaction if true is returned, will contain details of the
7045 /// satisfaction, with enough information to diagnose an unsatisfied
7046 /// expression.
7047 /// \returns true if an error occurred and satisfaction could not be checked,
7048 /// false otherwise.
7049 bool CheckConstraintSatisfaction(
7050 const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs,
7051 ArrayRef<TemplateArgument> TemplateArgs,
7052 SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction);
7053
7054 /// \brief Check whether the given non-dependent constraint expression is
7055 /// satisfied. Returns false and updates Satisfaction with the satisfaction
7056 /// verdict if successful, emits a diagnostic and returns true if an error
7057 /// occurred and satisfaction could not be determined.
7058 ///
7059 /// \returns true if an error occurred, false otherwise.
7060 bool CheckConstraintSatisfaction(const Expr *ConstraintExpr,
7061 ConstraintSatisfaction &Satisfaction);
7062
7063 /// Check whether the given function decl's trailing requires clause is
7064 /// satisfied, if any. Returns false and updates Satisfaction with the
7065 /// satisfaction verdict if successful, emits a diagnostic and returns true if
7066 /// an error occurred and satisfaction could not be determined.
7067 ///
7068 /// \returns true if an error occurred, false otherwise.
7069 bool CheckFunctionConstraints(const FunctionDecl *FD,
7070 ConstraintSatisfaction &Satisfaction,
7071 SourceLocation UsageLoc = SourceLocation());
7072
7073
7074 /// \brief Ensure that the given template arguments satisfy the constraints
7075 /// associated with the given template, emitting a diagnostic if they do not.
7076 ///
7077 /// \param Template The template to which the template arguments are being
7078 /// provided.
7079 ///
7080 /// \param TemplateArgs The converted, canonicalized template arguments.
7081 ///
7082 /// \param TemplateIDRange The source range of the template id that
7083 /// caused the constraints check.
7084 ///
7085 /// \returns true if the constrains are not satisfied or could not be checked
7086 /// for satisfaction, false if the constraints are satisfied.
7087 bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template,
7088 ArrayRef<TemplateArgument> TemplateArgs,
7089 SourceRange TemplateIDRange);
7090
7091 /// \brief Emit diagnostics explaining why a constraint expression was deemed
7092 /// unsatisfied.
7093 /// \param First whether this is the first time an unsatisfied constraint is
7094 /// diagnosed for this error.
7095 void
7096 DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction,
7097 bool First = true);
7098
7099 /// \brief Emit diagnostics explaining why a constraint expression was deemed
7100 /// unsatisfied.
7101 void
7102 DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction,
7103 bool First = true);
7104
7105 // ParseObjCStringLiteral - Parse Objective-C string literals.
7106 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs,
7107 ArrayRef<Expr *> Strings);
7108
7109 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S);
7110
7111 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
7112 /// numeric literal expression. Type of the expression will be "NSNumber *"
7113 /// or "id" if NSNumber is unavailable.
7114 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number);
7115 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc,
7116 bool Value);
7117 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements);
7118
7119 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the
7120 /// '@' prefixed parenthesized expression. The type of the expression will
7121 /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type
7122 /// of ValueType, which is allowed to be a built-in numeric type, "char *",
7123 /// "const char *" or C structure with attribute 'objc_boxable'.
7124 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr);
7125
7126 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
7127 Expr *IndexExpr,
7128 ObjCMethodDecl *getterMethod,
7129 ObjCMethodDecl *setterMethod);
7130
7131 ExprResult BuildObjCDictionaryLiteral(SourceRange SR,
7132 MutableArrayRef<ObjCDictionaryElement> Elements);
7133
7134 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc,
7135 TypeSourceInfo *EncodedTypeInfo,
7136 SourceLocation RParenLoc);
7137 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl,
7138 CXXConversionDecl *Method,
7139 bool HadMultipleCandidates);
7140
7141 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc,
7142 SourceLocation EncodeLoc,
7143 SourceLocation LParenLoc,
7144 ParsedType Ty,
7145 SourceLocation RParenLoc);
7146
7147 /// ParseObjCSelectorExpression - Build selector expression for \@selector
7148 ExprResult ParseObjCSelectorExpression(Selector Sel,
7149 SourceLocation AtLoc,
7150 SourceLocation SelLoc,
7151 SourceLocation LParenLoc,
7152 SourceLocation RParenLoc,
7153 bool WarnMultipleSelectors);
7154
7155 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol
7156 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName,
7157 SourceLocation AtLoc,
7158 SourceLocation ProtoLoc,
7159 SourceLocation LParenLoc,
7160 SourceLocation ProtoIdLoc,
7161 SourceLocation RParenLoc);
7162
7163 //===--------------------------------------------------------------------===//
7164 // C++ Declarations
7165 //
7166 Decl *ActOnStartLinkageSpecification(Scope *S,
7167 SourceLocation ExternLoc,
7168 Expr *LangStr,
7169 SourceLocation LBraceLoc);
7170 Decl *ActOnFinishLinkageSpecification(Scope *S,
7171 Decl *LinkageSpec,
7172 SourceLocation RBraceLoc);
7173
7174
7175 //===--------------------------------------------------------------------===//
7176 // C++ Classes
7177 //
7178 CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS);
7179 bool isCurrentClassName(const IdentifierInfo &II, Scope *S,
7180 const CXXScopeSpec *SS = nullptr);
7181 bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS);
7182
7183 bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
7184 SourceLocation ColonLoc,
7185 const ParsedAttributesView &Attrs);
7186
7187 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS,
7188 Declarator &D,
7189 MultiTemplateParamsArg TemplateParameterLists,
7190 Expr *BitfieldWidth, const VirtSpecifiers &VS,
7191 InClassInitStyle InitStyle);
7192
7193 void ActOnStartCXXInClassMemberInitializer();
7194 void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl,
7195 SourceLocation EqualLoc,
7196 Expr *Init);
7197
7198 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7199 Scope *S,
7200 CXXScopeSpec &SS,
7201 IdentifierInfo *MemberOrBase,
7202 ParsedType TemplateTypeTy,
7203 const DeclSpec &DS,
7204 SourceLocation IdLoc,
7205 SourceLocation LParenLoc,
7206 ArrayRef<Expr *> Args,
7207 SourceLocation RParenLoc,
7208 SourceLocation EllipsisLoc);
7209
7210 MemInitResult ActOnMemInitializer(Decl *ConstructorD,
7211 Scope *S,
7212 CXXScopeSpec &SS,
7213 IdentifierInfo *MemberOrBase,
7214 ParsedType TemplateTypeTy,
7215 const DeclSpec &DS,
7216 SourceLocation IdLoc,
7217 Expr *InitList,
7218 SourceLocation EllipsisLoc);
7219
7220 MemInitResult BuildMemInitializer(Decl *ConstructorD,
7221 Scope *S,
7222 CXXScopeSpec &SS,
7223 IdentifierInfo *MemberOrBase,
7224 ParsedType TemplateTypeTy,
7225 const DeclSpec &DS,
7226 SourceLocation IdLoc,
7227 Expr *Init,
7228 SourceLocation EllipsisLoc);
7229
7230 MemInitResult BuildMemberInitializer(ValueDecl *Member,
7231 Expr *Init,
7232 SourceLocation IdLoc);
7233
7234 MemInitResult BuildBaseInitializer(QualType BaseType,
7235 TypeSourceInfo *BaseTInfo,
7236 Expr *Init,
7237 CXXRecordDecl *ClassDecl,
7238 SourceLocation EllipsisLoc);
7239
7240 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo,
7241 Expr *Init,
7242 CXXRecordDecl *ClassDecl);
7243
7244 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor,
7245 CXXCtorInitializer *Initializer);
7246
7247 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
7248 ArrayRef<CXXCtorInitializer *> Initializers = None);
7249
7250 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation);
7251
7252
7253 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl,
7254 /// mark all the non-trivial destructors of its members and bases as
7255 /// referenced.
7256 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc,
7257 CXXRecordDecl *Record);
7258
7259 /// Mark destructors of virtual bases of this class referenced. In the Itanium
7260 /// C++ ABI, this is done when emitting a destructor for any non-abstract
7261 /// class. In the Microsoft C++ ABI, this is done any time a class's
7262 /// destructor is referenced.
7263 void MarkVirtualBaseDestructorsReferenced(
7264 SourceLocation Location, CXXRecordDecl *ClassDecl,
7265 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr);
7266
7267 /// Do semantic checks to allow the complete destructor variant to be emitted
7268 /// when the destructor is defined in another translation unit. In the Itanium
7269 /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they
7270 /// can be emitted in separate TUs. To emit the complete variant, run a subset
7271 /// of the checks performed when emitting a regular destructor.
7272 void CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
7273 CXXDestructorDecl *Dtor);
7274
7275 /// The list of classes whose vtables have been used within
7276 /// this translation unit, and the source locations at which the
7277 /// first use occurred.
7278 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse;
7279
7280 /// The list of vtables that are required but have not yet been
7281 /// materialized.
7282 SmallVector<VTableUse, 16> VTableUses;
7283
7284 /// The set of classes whose vtables have been used within
7285 /// this translation unit, and a bit that will be true if the vtable is
7286 /// required to be emitted (otherwise, it should be emitted only if needed
7287 /// by code generation).
7288 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed;
7289
7290 /// Load any externally-stored vtable uses.
7291 void LoadExternalVTableUses();
7292
7293 /// Note that the vtable for the given class was used at the
7294 /// given location.
7295 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
7296 bool DefinitionRequired = false);
7297
7298 /// Mark the exception specifications of all virtual member functions
7299 /// in the given class as needed.
7300 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
7301 const CXXRecordDecl *RD);
7302
7303 /// MarkVirtualMembersReferenced - Will mark all members of the given
7304 /// CXXRecordDecl referenced.
7305 void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD,
7306 bool ConstexprOnly = false);
7307
7308 /// Define all of the vtables that have been used in this
7309 /// translation unit and reference any virtual members used by those
7310 /// vtables.
7311 ///
7312 /// \returns true if any work was done, false otherwise.
7313 bool DefineUsedVTables();
7314
7315 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl);
7316
7317 void ActOnMemInitializers(Decl *ConstructorDecl,
7318 SourceLocation ColonLoc,
7319 ArrayRef<CXXCtorInitializer*> MemInits,
7320 bool AnyErrors);
7321
7322 /// Check class-level dllimport/dllexport attribute. The caller must
7323 /// ensure that referenceDLLExportedClassMethods is called some point later
7324 /// when all outer classes of Class are complete.
7325 void checkClassLevelDLLAttribute(CXXRecordDecl *Class);
7326 void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class);
7327
7328 void referenceDLLExportedClassMethods();
7329
7330 void propagateDLLAttrToBaseClassTemplate(
7331 CXXRecordDecl *Class, Attr *ClassAttr,
7332 ClassTemplateSpecializationDecl *BaseTemplateSpec,
7333 SourceLocation BaseLoc);
7334
7335 /// Add gsl::Pointer attribute to std::container::iterator
7336 /// \param ND The declaration that introduces the name
7337 /// std::container::iterator. \param UnderlyingRecord The record named by ND.
7338 void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord);
7339
7340 /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types.
7341 void inferGslOwnerPointerAttribute(CXXRecordDecl *Record);
7342
7343 /// Add [[gsl::Pointer]] attributes for std:: types.
7344 void inferGslPointerAttribute(TypedefNameDecl *TD);
7345
7346 void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record);
7347
7348 /// Check that the C++ class annoated with "trivial_abi" satisfies all the
7349 /// conditions that are needed for the attribute to have an effect.
7350 void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD);
7351
7352 void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc,
7353 Decl *TagDecl, SourceLocation LBrac,
7354 SourceLocation RBrac,
7355 const ParsedAttributesView &AttrList);
7356 void ActOnFinishCXXMemberDecls();
7357 void ActOnFinishCXXNonNestedClass();
7358
7359 void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param);
7360 unsigned ActOnReenterTemplateScope(Decl *Template,
7361 llvm::function_ref<Scope *()> EnterScope);
7362 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record);
7363 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7364 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param);
7365 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record);
7366 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method);
7367 void ActOnFinishDelayedMemberInitializers(Decl *Record);
7368 void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD,
7369 CachedTokens &Toks);
7370 void UnmarkAsLateParsedTemplate(FunctionDecl *FD);
7371 bool IsInsideALocalClassWithinATemplateFunction();
7372
7373 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7374 Expr *AssertExpr,
7375 Expr *AssertMessageExpr,
7376 SourceLocation RParenLoc);
7377 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
7378 Expr *AssertExpr,
7379 StringLiteral *AssertMessageExpr,
7380 SourceLocation RParenLoc,
7381 bool Failed);
7382
7383 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart,
7384 SourceLocation FriendLoc,
7385 TypeSourceInfo *TSInfo);
7386 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
7387 MultiTemplateParamsArg TemplateParams);
7388 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D,
7389 MultiTemplateParamsArg TemplateParams);
7390
7391 QualType CheckConstructorDeclarator(Declarator &D, QualType R,
7392 StorageClass& SC);
7393 void CheckConstructor(CXXConstructorDecl *Constructor);
7394 QualType CheckDestructorDeclarator(Declarator &D, QualType R,
7395 StorageClass& SC);
7396 bool CheckDestructor(CXXDestructorDecl *Destructor);
7397 void CheckConversionDeclarator(Declarator &D, QualType &R,
7398 StorageClass& SC);
7399 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion);
7400 void CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
7401 StorageClass &SC);
7402 void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD);
7403
7404 void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD);
7405
7406 bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7407 CXXSpecialMember CSM);
7408 void CheckDelayedMemberExceptionSpecs();
7409
7410 bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD,
7411 DefaultedComparisonKind DCK);
7412 void DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
7413 FunctionDecl *Spaceship);
7414 void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD,
7415 DefaultedComparisonKind DCK);
7416
7417 //===--------------------------------------------------------------------===//
7418 // C++ Derived Classes
7419 //
7420
7421 /// ActOnBaseSpecifier - Parsed a base specifier
7422 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class,
7423 SourceRange SpecifierRange,
7424 bool Virtual, AccessSpecifier Access,
7425 TypeSourceInfo *TInfo,
7426 SourceLocation EllipsisLoc);
7427
7428 BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
7429 const ParsedAttributesView &Attrs, bool Virtual,
7430 AccessSpecifier Access, ParsedType basetype,
7431 SourceLocation BaseLoc,
7432 SourceLocation EllipsisLoc);
7433
7434 bool AttachBaseSpecifiers(CXXRecordDecl *Class,
7435 MutableArrayRef<CXXBaseSpecifier *> Bases);
7436 void ActOnBaseSpecifiers(Decl *ClassDecl,
7437 MutableArrayRef<CXXBaseSpecifier *> Bases);
7438
7439 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base);
7440 bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
7441 CXXBasePaths &Paths);
7442
7443 // FIXME: I don't like this name.
7444 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath);
7445
7446 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7447 SourceLocation Loc, SourceRange Range,
7448 CXXCastPath *BasePath = nullptr,
7449 bool IgnoreAccess = false);
7450 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base,
7451 unsigned InaccessibleBaseID,
7452 unsigned AmbiguousBaseConvID,
7453 SourceLocation Loc, SourceRange Range,
7454 DeclarationName Name,
7455 CXXCastPath *BasePath,
7456 bool IgnoreAccess = false);
7457
7458 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths);
7459
7460 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
7461 const CXXMethodDecl *Old);
7462
7463 /// CheckOverridingFunctionReturnType - Checks whether the return types are
7464 /// covariant, according to C++ [class.virtual]p5.
7465 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
7466 const CXXMethodDecl *Old);
7467
7468 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception
7469 /// spec is a subset of base spec.
7470 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New,
7471 const CXXMethodDecl *Old);
7472
7473 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange);
7474
7475 /// CheckOverrideControl - Check C++11 override control semantics.
7476 void CheckOverrideControl(NamedDecl *D);
7477
7478 /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was
7479 /// not used in the declaration of an overriding method.
7480 void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent);
7481
7482 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function
7483 /// overrides a virtual member function marked 'final', according to
7484 /// C++11 [class.virtual]p4.
7485 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
7486 const CXXMethodDecl *Old);
7487
7488
7489 //===--------------------------------------------------------------------===//
7490 // C++ Access Control
7491 //
7492
7493 enum AccessResult {
7494 AR_accessible,
7495 AR_inaccessible,
7496 AR_dependent,
7497 AR_delayed
7498 };
7499
7500 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl,
7501 NamedDecl *PrevMemberDecl,
7502 AccessSpecifier LexicalAS);
7503
7504 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
7505 DeclAccessPair FoundDecl);
7506 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
7507 DeclAccessPair FoundDecl);
7508 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc,
7509 SourceRange PlacementRange,
7510 CXXRecordDecl *NamingClass,
7511 DeclAccessPair FoundDecl,
7512 bool Diagnose = true);
7513 AccessResult CheckConstructorAccess(SourceLocation Loc,
7514 CXXConstructorDecl *D,
7515 DeclAccessPair FoundDecl,
7516 const InitializedEntity &Entity,
7517 bool IsCopyBindingRefToTemp = false);
7518 AccessResult CheckConstructorAccess(SourceLocation Loc,
7519 CXXConstructorDecl *D,
7520 DeclAccessPair FoundDecl,
7521 const InitializedEntity &Entity,
7522 const PartialDiagnostic &PDiag);
7523 AccessResult CheckDestructorAccess(SourceLocation Loc,
7524 CXXDestructorDecl *Dtor,
7525 const PartialDiagnostic &PDiag,
7526 QualType objectType = QualType());
7527 AccessResult CheckFriendAccess(NamedDecl *D);
7528 AccessResult CheckMemberAccess(SourceLocation UseLoc,
7529 CXXRecordDecl *NamingClass,
7530 DeclAccessPair Found);
7531 AccessResult
7532 CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
7533 CXXRecordDecl *DecomposedClass,
7534 DeclAccessPair Field);
7535 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7536 const SourceRange &,
7537 DeclAccessPair FoundDecl);
7538 AccessResult CheckMemberOperatorAccess(SourceLocation Loc,
7539 Expr *ObjectExpr,
7540 Expr *ArgExpr,
7541 DeclAccessPair FoundDecl);
7542 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr,
7543 ArrayRef<Expr *> ArgExprs,
7544 DeclAccessPair FoundDecl);
7545 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr,
7546 DeclAccessPair FoundDecl);
7547 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc,
7548 QualType Base, QualType Derived,
7549 const CXXBasePath &Path,
7550 unsigned DiagID,
7551 bool ForceCheck = false,
7552 bool ForceUnprivileged = false);
7553 void CheckLookupAccess(const LookupResult &R);
7554 bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass,
7555 QualType BaseType);
7556 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7557 DeclAccessPair Found, QualType ObjectType,
7558 SourceLocation Loc,
7559 const PartialDiagnostic &Diag);
7560 bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
7561 DeclAccessPair Found,
7562 QualType ObjectType) {
7563 return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType,
7564 SourceLocation(), PDiag());
7565 }
7566
7567 void HandleDependentAccessCheck(const DependentDiagnostic &DD,
7568 const MultiLevelTemplateArgumentList &TemplateArgs);
7569 void PerformDependentDiagnostics(const DeclContext *Pattern,
7570 const MultiLevelTemplateArgumentList &TemplateArgs);
7571
7572 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx);
7573
7574 /// When true, access checking violations are treated as SFINAE
7575 /// failures rather than hard errors.
7576 bool AccessCheckingSFINAE;
7577
7578 enum AbstractDiagSelID {
7579 AbstractNone = -1,
7580 AbstractReturnType,
7581 AbstractParamType,
7582 AbstractVariableType,
7583 AbstractFieldType,
7584 AbstractIvarType,
7585 AbstractSynthesizedIvarType,
7586 AbstractArrayType
7587 };
7588
7589 bool isAbstractType(SourceLocation Loc, QualType T);
7590 bool RequireNonAbstractType(SourceLocation Loc, QualType T,
7591 TypeDiagnoser &Diagnoser);
7592 template <typename... Ts>
7593 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID,
7594 const Ts &...Args) {
7595 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
7596 return RequireNonAbstractType(Loc, T, Diagnoser);
7597 }
7598
7599 void DiagnoseAbstractType(const CXXRecordDecl *RD);
7600
7601 //===--------------------------------------------------------------------===//
7602 // C++ Overloaded Operators [C++ 13.5]
7603 //
7604
7605 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl);
7606
7607 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl);
7608
7609 //===--------------------------------------------------------------------===//
7610 // C++ Templates [C++ 14]
7611 //
7612 void FilterAcceptableTemplateNames(LookupResult &R,
7613 bool AllowFunctionTemplates = true,
7614 bool AllowDependent = true);
7615 bool hasAnyAcceptableTemplateNames(LookupResult &R,
7616 bool AllowFunctionTemplates = true,
7617 bool AllowDependent = true,
7618 bool AllowNonTemplateFunctions = false);
7619 /// Try to interpret the lookup result D as a template-name.
7620 ///
7621 /// \param D A declaration found by name lookup.
7622 /// \param AllowFunctionTemplates Whether function templates should be
7623 /// considered valid results.
7624 /// \param AllowDependent Whether unresolved using declarations (that might
7625 /// name templates) should be considered valid results.
7626 static NamedDecl *getAsTemplateNameDecl(NamedDecl *D,
7627 bool AllowFunctionTemplates = true,
7628 bool AllowDependent = true);
7629
7630 enum TemplateNameIsRequiredTag { TemplateNameIsRequired };
7631 /// Whether and why a template name is required in this lookup.
7632 class RequiredTemplateKind {
7633 public:
7634 /// Template name is required if TemplateKWLoc is valid.
7635 RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation())
7636 : TemplateKW(TemplateKWLoc) {}
7637 /// Template name is unconditionally required.
7638 RequiredTemplateKind(TemplateNameIsRequiredTag) {}
7639
7640 SourceLocation getTemplateKeywordLoc() const {
7641 return TemplateKW.getValueOr(SourceLocation());
7642 }
7643 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
7644 bool isRequired() const { return TemplateKW != SourceLocation(); }
7645 explicit operator bool() const { return isRequired(); }
7646
7647 private:
7648 llvm::Optional<SourceLocation> TemplateKW;
7649 };
7650
7651 enum class AssumedTemplateKind {
7652 /// This is not assumed to be a template name.
7653 None,
7654 /// This is assumed to be a template name because lookup found nothing.
7655 FoundNothing,
7656 /// This is assumed to be a template name because lookup found one or more
7657 /// functions (but no function templates).
7658 FoundFunctions,
7659 };
7660 bool LookupTemplateName(
7661 LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType,
7662 bool EnteringContext, bool &MemberOfUnknownSpecialization,
7663 RequiredTemplateKind RequiredTemplate = SourceLocation(),
7664 AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true);
7665
7666 TemplateNameKind isTemplateName(Scope *S,
7667 CXXScopeSpec &SS,
7668 bool hasTemplateKeyword,
7669 const UnqualifiedId &Name,
7670 ParsedType ObjectType,
7671 bool EnteringContext,
7672 TemplateTy &Template,
7673 bool &MemberOfUnknownSpecialization,
7674 bool Disambiguation = false);
7675
7676 /// Try to resolve an undeclared template name as a type template.
7677 ///
7678 /// Sets II to the identifier corresponding to the template name, and updates
7679 /// Name to a corresponding (typo-corrected) type template name and TNK to
7680 /// the corresponding kind, if possible.
7681 void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name,
7682 TemplateNameKind &TNK,
7683 SourceLocation NameLoc,
7684 IdentifierInfo *&II);
7685
7686 bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name,
7687 SourceLocation NameLoc,
7688 bool Diagnose = true);
7689
7690 /// Determine whether a particular identifier might be the name in a C++1z
7691 /// deduction-guide declaration.
7692 bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name,
7693 SourceLocation NameLoc,
7694 ParsedTemplateTy *Template = nullptr);
7695
7696 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II,
7697 SourceLocation IILoc,
7698 Scope *S,
7699 const CXXScopeSpec *SS,
7700 TemplateTy &SuggestedTemplate,
7701 TemplateNameKind &SuggestedKind);
7702
7703 bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation,
7704 NamedDecl *Instantiation,
7705 bool InstantiatedFromMember,
7706 const NamedDecl *Pattern,
7707 const NamedDecl *PatternDef,
7708 TemplateSpecializationKind TSK,
7709 bool Complain = true);
7710
7711 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl);
7712 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl);
7713
7714 NamedDecl *ActOnTypeParameter(Scope *S, bool Typename,
7715 SourceLocation EllipsisLoc,
7716 SourceLocation KeyLoc,
7717 IdentifierInfo *ParamName,
7718 SourceLocation ParamNameLoc,
7719 unsigned Depth, unsigned Position,
7720 SourceLocation EqualLoc,
7721 ParsedType DefaultArg, bool HasTypeConstraint);
7722
7723 bool ActOnTypeConstraint(const CXXScopeSpec &SS,
7724 TemplateIdAnnotation *TypeConstraint,
7725 TemplateTypeParmDecl *ConstrainedParameter,
7726 SourceLocation EllipsisLoc);
7727 bool BuildTypeConstraint(const CXXScopeSpec &SS,
7728 TemplateIdAnnotation *TypeConstraint,
7729 TemplateTypeParmDecl *ConstrainedParameter,
7730 SourceLocation EllipsisLoc,
7731 bool AllowUnexpandedPack);
7732
7733 bool AttachTypeConstraint(NestedNameSpecifierLoc NS,
7734 DeclarationNameInfo NameInfo,
7735 ConceptDecl *NamedConcept,
7736 const TemplateArgumentListInfo *TemplateArgs,
7737 TemplateTypeParmDecl *ConstrainedParameter,
7738 SourceLocation EllipsisLoc);
7739
7740 bool AttachTypeConstraint(AutoTypeLoc TL,
7741 NonTypeTemplateParmDecl *ConstrainedParameter,
7742 SourceLocation EllipsisLoc);
7743
7744 bool RequireStructuralType(QualType T, SourceLocation Loc);
7745
7746 QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI,
7747 SourceLocation Loc);
7748 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc);
7749
7750 NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D,
7751 unsigned Depth,
7752 unsigned Position,
7753 SourceLocation EqualLoc,
7754 Expr *DefaultArg);
7755 NamedDecl *ActOnTemplateTemplateParameter(Scope *S,
7756 SourceLocation TmpLoc,
7757 TemplateParameterList *Params,
7758 SourceLocation EllipsisLoc,
7759 IdentifierInfo *ParamName,
7760 SourceLocation ParamNameLoc,
7761 unsigned Depth,
7762 unsigned Position,
7763 SourceLocation EqualLoc,
7764 ParsedTemplateArgument DefaultArg);
7765
7766 TemplateParameterList *
7767 ActOnTemplateParameterList(unsigned Depth,
7768 SourceLocation ExportLoc,
7769 SourceLocation TemplateLoc,
7770 SourceLocation LAngleLoc,
7771 ArrayRef<NamedDecl *> Params,
7772 SourceLocation RAngleLoc,
7773 Expr *RequiresClause);
7774
7775 /// The context in which we are checking a template parameter list.
7776 enum TemplateParamListContext {
7777 TPC_ClassTemplate,
7778 TPC_VarTemplate,
7779 TPC_FunctionTemplate,
7780 TPC_ClassTemplateMember,
7781 TPC_FriendClassTemplate,
7782 TPC_FriendFunctionTemplate,
7783 TPC_FriendFunctionTemplateDefinition,
7784 TPC_TypeAliasTemplate
7785 };
7786
7787 bool CheckTemplateParameterList(TemplateParameterList *NewParams,
7788 TemplateParameterList *OldParams,
7789 TemplateParamListContext TPC,
7790 SkipBodyInfo *SkipBody = nullptr);
7791 TemplateParameterList *MatchTemplateParametersToScopeSpecifier(
7792 SourceLocation DeclStartLoc, SourceLocation DeclLoc,
7793 const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId,
7794 ArrayRef<TemplateParameterList *> ParamLists,
7795 bool IsFriend, bool &IsMemberSpecialization, bool &Invalid,
7796 bool SuppressDiagnostic = false);
7797
7798 DeclResult CheckClassTemplate(
7799 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7800 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
7801 const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams,
7802 AccessSpecifier AS, SourceLocation ModulePrivateLoc,
7803 SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists,
7804 TemplateParameterList **OuterTemplateParamLists,
7805 SkipBodyInfo *SkipBody = nullptr);
7806
7807 TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg,
7808 QualType NTTPType,
7809 SourceLocation Loc);
7810
7811 /// Get a template argument mapping the given template parameter to itself,
7812 /// e.g. for X in \c template<int X>, this would return an expression template
7813 /// argument referencing X.
7814 TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param,
7815 SourceLocation Location);
7816
7817 void translateTemplateArguments(const ASTTemplateArgsPtr &In,
7818 TemplateArgumentListInfo &Out);
7819
7820 ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType);
7821
7822 void NoteAllFoundTemplates(TemplateName Name);
7823
7824 QualType CheckTemplateIdType(TemplateName Template,
7825 SourceLocation TemplateLoc,
7826 TemplateArgumentListInfo &TemplateArgs);
7827
7828 TypeResult
7829 ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7830 TemplateTy Template, IdentifierInfo *TemplateII,
7831 SourceLocation TemplateIILoc, SourceLocation LAngleLoc,
7832 ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc,
7833 bool IsCtorOrDtorName = false, bool IsClassName = false);
7834
7835 /// Parsed an elaborated-type-specifier that refers to a template-id,
7836 /// such as \c class T::template apply<U>.
7837 TypeResult ActOnTagTemplateIdType(TagUseKind TUK,
7838 TypeSpecifierType TagSpec,
7839 SourceLocation TagLoc,
7840 CXXScopeSpec &SS,
7841 SourceLocation TemplateKWLoc,
7842 TemplateTy TemplateD,
7843 SourceLocation TemplateLoc,
7844 SourceLocation LAngleLoc,
7845 ASTTemplateArgsPtr TemplateArgsIn,
7846 SourceLocation RAngleLoc);
7847
7848 DeclResult ActOnVarTemplateSpecialization(
7849 Scope *S, Declarator &D, TypeSourceInfo *DI,
7850 SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams,
7851 StorageClass SC, bool IsPartialSpecialization);
7852
7853 /// Get the specialization of the given variable template corresponding to
7854 /// the specified argument list, or a null-but-valid result if the arguments
7855 /// are dependent.
7856 DeclResult CheckVarTemplateId(VarTemplateDecl *Template,
7857 SourceLocation TemplateLoc,
7858 SourceLocation TemplateNameLoc,
7859 const TemplateArgumentListInfo &TemplateArgs);
7860
7861 /// Form a reference to the specialization of the given variable template
7862 /// corresponding to the specified argument list, or a null-but-valid result
7863 /// if the arguments are dependent.
7864 ExprResult CheckVarTemplateId(const CXXScopeSpec &SS,
7865 const DeclarationNameInfo &NameInfo,
7866 VarTemplateDecl *Template,
7867 SourceLocation TemplateLoc,
7868 const TemplateArgumentListInfo *TemplateArgs);
7869
7870 ExprResult
7871 CheckConceptTemplateId(const CXXScopeSpec &SS,
7872 SourceLocation TemplateKWLoc,
7873 const DeclarationNameInfo &ConceptNameInfo,
7874 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
7875 const TemplateArgumentListInfo *TemplateArgs);
7876
7877 void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc);
7878
7879 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS,
7880 SourceLocation TemplateKWLoc,
7881 LookupResult &R,
7882 bool RequiresADL,
7883 const TemplateArgumentListInfo *TemplateArgs);
7884
7885 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS,
7886 SourceLocation TemplateKWLoc,
7887 const DeclarationNameInfo &NameInfo,
7888 const TemplateArgumentListInfo *TemplateArgs);
7889
7890 TemplateNameKind ActOnTemplateName(
7891 Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
7892 const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext,
7893 TemplateTy &Template, bool AllowInjectedClassName = false);
7894
7895 DeclResult ActOnClassTemplateSpecialization(
7896 Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc,
7897 SourceLocation ModulePrivateLoc, CXXScopeSpec &SS,
7898 TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr,
7899 MultiTemplateParamsArg TemplateParameterLists,
7900 SkipBodyInfo *SkipBody = nullptr);
7901
7902 bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc,
7903 TemplateDecl *PrimaryTemplate,
7904 unsigned NumExplicitArgs,
7905 ArrayRef<TemplateArgument> Args);
7906 void CheckTemplatePartialSpecialization(
7907 ClassTemplatePartialSpecializationDecl *Partial);
7908 void CheckTemplatePartialSpecialization(
7909 VarTemplatePartialSpecializationDecl *Partial);
7910
7911 Decl *ActOnTemplateDeclarator(Scope *S,
7912 MultiTemplateParamsArg TemplateParameterLists,
7913 Declarator &D);
7914
7915 bool
7916 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc,
7917 TemplateSpecializationKind NewTSK,
7918 NamedDecl *PrevDecl,
7919 TemplateSpecializationKind PrevTSK,
7920 SourceLocation PrevPtOfInstantiation,
7921 bool &SuppressNew);
7922
7923 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD,
7924 const TemplateArgumentListInfo &ExplicitTemplateArgs,
7925 LookupResult &Previous);
7926
7927 bool CheckFunctionTemplateSpecialization(
7928 FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs,
7929 LookupResult &Previous, bool QualifiedFriend = false);
7930 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7931 void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous);
7932
7933 DeclResult ActOnExplicitInstantiation(
7934 Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc,
7935 unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS,
7936 TemplateTy Template, SourceLocation TemplateNameLoc,
7937 SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs,
7938 SourceLocation RAngleLoc, const ParsedAttributesView &Attr);
7939
7940 DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc,
7941 SourceLocation TemplateLoc,
7942 unsigned TagSpec, SourceLocation KWLoc,
7943 CXXScopeSpec &SS, IdentifierInfo *Name,
7944 SourceLocation NameLoc,
7945 const ParsedAttributesView &Attr);
7946
7947 DeclResult ActOnExplicitInstantiation(Scope *S,
7948 SourceLocation ExternLoc,
7949 SourceLocation TemplateLoc,
7950 Declarator &D);
7951
7952 TemplateArgumentLoc
7953 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template,
7954 SourceLocation TemplateLoc,
7955 SourceLocation RAngleLoc,
7956 Decl *Param,
7957 SmallVectorImpl<TemplateArgument>
7958 &Converted,
7959 bool &HasDefaultArg);
7960
7961 /// Specifies the context in which a particular template
7962 /// argument is being checked.
7963 enum CheckTemplateArgumentKind {
7964 /// The template argument was specified in the code or was
7965 /// instantiated with some deduced template arguments.
7966 CTAK_Specified,
7967
7968 /// The template argument was deduced via template argument
7969 /// deduction.
7970 CTAK_Deduced,
7971
7972 /// The template argument was deduced from an array bound
7973 /// via template argument deduction.
7974 CTAK_DeducedFromArrayBound
7975 };
7976
7977 bool CheckTemplateArgument(NamedDecl *Param,
7978 TemplateArgumentLoc &Arg,
7979 NamedDecl *Template,
7980 SourceLocation TemplateLoc,
7981 SourceLocation RAngleLoc,
7982 unsigned ArgumentPackIndex,
7983 SmallVectorImpl<TemplateArgument> &Converted,
7984 CheckTemplateArgumentKind CTAK = CTAK_Specified);
7985
7986 /// Check that the given template arguments can be be provided to
7987 /// the given template, converting the arguments along the way.
7988 ///
7989 /// \param Template The template to which the template arguments are being
7990 /// provided.
7991 ///
7992 /// \param TemplateLoc The location of the template name in the source.
7993 ///
7994 /// \param TemplateArgs The list of template arguments. If the template is
7995 /// a template template parameter, this function may extend the set of
7996 /// template arguments to also include substituted, defaulted template
7997 /// arguments.
7998 ///
7999 /// \param PartialTemplateArgs True if the list of template arguments is
8000 /// intentionally partial, e.g., because we're checking just the initial
8001 /// set of template arguments.
8002 ///
8003 /// \param Converted Will receive the converted, canonicalized template
8004 /// arguments.
8005 ///
8006 /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to
8007 /// contain the converted forms of the template arguments as written.
8008 /// Otherwise, \p TemplateArgs will not be modified.
8009 ///
8010 /// \param ConstraintsNotSatisfied If provided, and an error occurred, will
8011 /// receive true if the cause for the error is the associated constraints of
8012 /// the template not being satisfied by the template arguments.
8013 ///
8014 /// \returns true if an error occurred, false otherwise.
8015 bool CheckTemplateArgumentList(TemplateDecl *Template,
8016 SourceLocation TemplateLoc,
8017 TemplateArgumentListInfo &TemplateArgs,
8018 bool PartialTemplateArgs,
8019 SmallVectorImpl<TemplateArgument> &Converted,
8020 bool UpdateArgsWithConversions = true,
8021 bool *ConstraintsNotSatisfied = nullptr);
8022
8023 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param,
8024 TemplateArgumentLoc &Arg,
8025 SmallVectorImpl<TemplateArgument> &Converted);
8026
8027 bool CheckTemplateArgument(TypeSourceInfo *Arg);
8028 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param,
8029 QualType InstantiatedParamType, Expr *Arg,
8030 TemplateArgument &Converted,
8031 CheckTemplateArgumentKind CTAK = CTAK_Specified);
8032 bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param,
8033 TemplateParameterList *Params,
8034 TemplateArgumentLoc &Arg);
8035
8036 ExprResult
8037 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg,
8038 QualType ParamType,
8039 SourceLocation Loc);
8040 ExprResult
8041 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg,
8042 SourceLocation Loc);
8043
8044 /// Enumeration describing how template parameter lists are compared
8045 /// for equality.
8046 enum TemplateParameterListEqualKind {
8047 /// We are matching the template parameter lists of two templates
8048 /// that might be redeclarations.
8049 ///
8050 /// \code
8051 /// template<typename T> struct X;
8052 /// template<typename T> struct X;
8053 /// \endcode
8054 TPL_TemplateMatch,
8055
8056 /// We are matching the template parameter lists of two template
8057 /// template parameters as part of matching the template parameter lists
8058 /// of two templates that might be redeclarations.
8059 ///
8060 /// \code
8061 /// template<template<int I> class TT> struct X;
8062 /// template<template<int Value> class Other> struct X;
8063 /// \endcode
8064 TPL_TemplateTemplateParmMatch,
8065
8066 /// We are matching the template parameter lists of a template
8067 /// template argument against the template parameter lists of a template
8068 /// template parameter.
8069 ///
8070 /// \code
8071 /// template<template<int Value> class Metafun> struct X;
8072 /// template<int Value> struct integer_c;
8073 /// X<integer_c> xic;
8074 /// \endcode
8075 TPL_TemplateTemplateArgumentMatch
8076 };
8077
8078 bool TemplateParameterListsAreEqual(TemplateParameterList *New,
8079 TemplateParameterList *Old,
8080 bool Complain,
8081 TemplateParameterListEqualKind Kind,
8082 SourceLocation TemplateArgLoc
8083 = SourceLocation());
8084
8085 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams);
8086
8087 /// Called when the parser has parsed a C++ typename
8088 /// specifier, e.g., "typename T::type".
8089 ///
8090 /// \param S The scope in which this typename type occurs.
8091 /// \param TypenameLoc the location of the 'typename' keyword
8092 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8093 /// \param II the identifier we're retrieving (e.g., 'type' in the example).
8094 /// \param IdLoc the location of the identifier.
8095 TypeResult
8096 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8097 const CXXScopeSpec &SS, const IdentifierInfo &II,
8098 SourceLocation IdLoc);
8099
8100 /// Called when the parser has parsed a C++ typename
8101 /// specifier that ends in a template-id, e.g.,
8102 /// "typename MetaFun::template apply<T1, T2>".
8103 ///
8104 /// \param S The scope in which this typename type occurs.
8105 /// \param TypenameLoc the location of the 'typename' keyword
8106 /// \param SS the nested-name-specifier following the typename (e.g., 'T::').
8107 /// \param TemplateLoc the location of the 'template' keyword, if any.
8108 /// \param TemplateName The template name.
8109 /// \param TemplateII The identifier used to name the template.
8110 /// \param TemplateIILoc The location of the template name.
8111 /// \param LAngleLoc The location of the opening angle bracket ('<').
8112 /// \param TemplateArgs The template arguments.
8113 /// \param RAngleLoc The location of the closing angle bracket ('>').
8114 TypeResult
8115 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc,
8116 const CXXScopeSpec &SS,
8117 SourceLocation TemplateLoc,
8118 TemplateTy TemplateName,
8119 IdentifierInfo *TemplateII,
8120 SourceLocation TemplateIILoc,
8121 SourceLocation LAngleLoc,
8122 ASTTemplateArgsPtr TemplateArgs,
8123 SourceLocation RAngleLoc);
8124
8125 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8126 SourceLocation KeywordLoc,
8127 NestedNameSpecifierLoc QualifierLoc,
8128 const IdentifierInfo &II,
8129 SourceLocation IILoc,
8130 TypeSourceInfo **TSI,
8131 bool DeducedTSTContext);
8132
8133 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword,
8134 SourceLocation KeywordLoc,
8135 NestedNameSpecifierLoc QualifierLoc,
8136 const IdentifierInfo &II,
8137 SourceLocation IILoc,
8138 bool DeducedTSTContext = true);
8139
8140
8141 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T,
8142 SourceLocation Loc,
8143 DeclarationName Name);
8144 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS);
8145
8146 ExprResult RebuildExprInCurrentInstantiation(Expr *E);
8147 bool RebuildTemplateParamsInCurrentInstantiation(
8148 TemplateParameterList *Params);
8149
8150 std::string
8151 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8152 const TemplateArgumentList &Args);
8153
8154 std::string
8155 getTemplateArgumentBindingsText(const TemplateParameterList *Params,
8156 const TemplateArgument *Args,
8157 unsigned NumArgs);
8158
8159 //===--------------------------------------------------------------------===//
8160 // C++ Concepts
8161 //===--------------------------------------------------------------------===//
8162 Decl *ActOnConceptDefinition(
8163 Scope *S, MultiTemplateParamsArg TemplateParameterLists,
8164 IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr);
8165
8166 RequiresExprBodyDecl *
8167 ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
8168 ArrayRef<ParmVarDecl *> LocalParameters,
8169 Scope *BodyScope);
8170 void ActOnFinishRequiresExpr();
8171 concepts::Requirement *ActOnSimpleRequirement(Expr *E);
8172 concepts::Requirement *ActOnTypeRequirement(
8173 SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc,
8174 IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId);
8175 concepts::Requirement *ActOnCompoundRequirement(Expr *E,
8176 SourceLocation NoexceptLoc);
8177 concepts::Requirement *
8178 ActOnCompoundRequirement(
8179 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8180 TemplateIdAnnotation *TypeConstraint, unsigned Depth);
8181 concepts::Requirement *ActOnNestedRequirement(Expr *Constraint);
8182 concepts::ExprRequirement *
8183 BuildExprRequirement(
8184 Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc,
8185 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8186 concepts::ExprRequirement *
8187 BuildExprRequirement(
8188 concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag,
8189 bool IsSatisfied, SourceLocation NoexceptLoc,
8190 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement);
8191 concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type);
8192 concepts::TypeRequirement *
8193 BuildTypeRequirement(
8194 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8195 concepts::NestedRequirement *BuildNestedRequirement(Expr *E);
8196 concepts::NestedRequirement *
8197 BuildNestedRequirement(
8198 concepts::Requirement::SubstitutionDiagnostic *SubstDiag);
8199 ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc,
8200 RequiresExprBodyDecl *Body,
8201 ArrayRef<ParmVarDecl *> LocalParameters,
8202 ArrayRef<concepts::Requirement *> Requirements,
8203 SourceLocation ClosingBraceLoc);
8204
8205 //===--------------------------------------------------------------------===//
8206 // C++ Variadic Templates (C++0x [temp.variadic])
8207 //===--------------------------------------------------------------------===//
8208
8209 /// Determine whether an unexpanded parameter pack might be permitted in this
8210 /// location. Useful for error recovery.
8211 bool isUnexpandedParameterPackPermitted();
8212
8213 /// The context in which an unexpanded parameter pack is
8214 /// being diagnosed.
8215 ///
8216 /// Note that the values of this enumeration line up with the first
8217 /// argument to the \c err_unexpanded_parameter_pack diagnostic.
8218 enum UnexpandedParameterPackContext {
8219 /// An arbitrary expression.
8220 UPPC_Expression = 0,
8221
8222 /// The base type of a class type.
8223 UPPC_BaseType,
8224
8225 /// The type of an arbitrary declaration.
8226 UPPC_DeclarationType,
8227
8228 /// The type of a data member.
8229 UPPC_DataMemberType,
8230
8231 /// The size of a bit-field.
8232 UPPC_BitFieldWidth,
8233
8234 /// The expression in a static assertion.
8235 UPPC_StaticAssertExpression,
8236
8237 /// The fixed underlying type of an enumeration.
8238 UPPC_FixedUnderlyingType,
8239
8240 /// The enumerator value.
8241 UPPC_EnumeratorValue,
8242
8243 /// A using declaration.
8244 UPPC_UsingDeclaration,
8245
8246 /// A friend declaration.
8247 UPPC_FriendDeclaration,
8248
8249 /// A declaration qualifier.
8250 UPPC_DeclarationQualifier,
8251
8252 /// An initializer.
8253 UPPC_Initializer,
8254
8255 /// A default argument.
8256 UPPC_DefaultArgument,
8257
8258 /// The type of a non-type template parameter.
8259 UPPC_NonTypeTemplateParameterType,
8260
8261 /// The type of an exception.
8262 UPPC_ExceptionType,
8263
8264 /// Partial specialization.
8265 UPPC_PartialSpecialization,
8266
8267 /// Microsoft __if_exists.
8268 UPPC_IfExists,
8269
8270 /// Microsoft __if_not_exists.
8271 UPPC_IfNotExists,
8272
8273 /// Lambda expression.
8274 UPPC_Lambda,
8275
8276 /// Block expression.
8277 UPPC_Block,
8278
8279 /// A type constraint.
8280 UPPC_TypeConstraint,
8281
8282 // A requirement in a requires-expression.
8283 UPPC_Requirement,
8284
8285 // A requires-clause.
8286 UPPC_RequiresClause,
8287 };
8288
8289 /// Diagnose unexpanded parameter packs.
8290 ///
8291 /// \param Loc The location at which we should emit the diagnostic.
8292 ///
8293 /// \param UPPC The context in which we are diagnosing unexpanded
8294 /// parameter packs.
8295 ///
8296 /// \param Unexpanded the set of unexpanded parameter packs.
8297 ///
8298 /// \returns true if an error occurred, false otherwise.
8299 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
8300 UnexpandedParameterPackContext UPPC,
8301 ArrayRef<UnexpandedParameterPack> Unexpanded);
8302
8303 /// If the given type contains an unexpanded parameter pack,
8304 /// diagnose the error.
8305 ///
8306 /// \param Loc The source location where a diagnostc should be emitted.
8307 ///
8308 /// \param T The type that is being checked for unexpanded parameter
8309 /// packs.
8310 ///
8311 /// \returns true if an error occurred, false otherwise.
8312 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T,
8313 UnexpandedParameterPackContext UPPC);
8314
8315 /// If the given expression contains an unexpanded parameter
8316 /// pack, diagnose the error.
8317 ///
8318 /// \param E The expression that is being checked for unexpanded
8319 /// parameter packs.
8320 ///
8321 /// \returns true if an error occurred, false otherwise.
8322 bool DiagnoseUnexpandedParameterPack(Expr *E,
8323 UnexpandedParameterPackContext UPPC = UPPC_Expression);
8324
8325 /// If the given requirees-expression contains an unexpanded reference to one
8326 /// of its own parameter packs, diagnose the error.
8327 ///
8328 /// \param RE The requiress-expression that is being checked for unexpanded
8329 /// parameter packs.
8330 ///
8331 /// \returns true if an error occurred, false otherwise.
8332 bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE);
8333
8334 /// If the given nested-name-specifier contains an unexpanded
8335 /// parameter pack, diagnose the error.
8336 ///
8337 /// \param SS The nested-name-specifier that is being checked for
8338 /// unexpanded parameter packs.
8339 ///
8340 /// \returns true if an error occurred, false otherwise.
8341 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
8342 UnexpandedParameterPackContext UPPC);
8343
8344 /// If the given name contains an unexpanded parameter pack,
8345 /// diagnose the error.
8346 ///
8347 /// \param NameInfo The name (with source location information) that
8348 /// is being checked for unexpanded parameter packs.
8349 ///
8350 /// \returns true if an error occurred, false otherwise.
8351 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
8352 UnexpandedParameterPackContext UPPC);
8353
8354 /// If the given template name contains an unexpanded parameter pack,
8355 /// diagnose the error.
8356 ///
8357 /// \param Loc The location of the template name.
8358 ///
8359 /// \param Template The template name that is being checked for unexpanded
8360 /// parameter packs.
8361 ///
8362 /// \returns true if an error occurred, false otherwise.
8363 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc,
8364 TemplateName Template,
8365 UnexpandedParameterPackContext UPPC);
8366
8367 /// If the given template argument contains an unexpanded parameter
8368 /// pack, diagnose the error.
8369 ///
8370 /// \param Arg The template argument that is being checked for unexpanded
8371 /// parameter packs.
8372 ///
8373 /// \returns true if an error occurred, false otherwise.
8374 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
8375 UnexpandedParameterPackContext UPPC);
8376
8377 /// Collect the set of unexpanded parameter packs within the given
8378 /// template argument.
8379 ///
8380 /// \param Arg The template argument that will be traversed to find
8381 /// unexpanded parameter packs.
8382 void collectUnexpandedParameterPacks(TemplateArgument Arg,
8383 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8384
8385 /// Collect the set of unexpanded parameter packs within the given
8386 /// template argument.
8387 ///
8388 /// \param Arg The template argument that will be traversed to find
8389 /// unexpanded parameter packs.
8390 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
8391 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8392
8393 /// Collect the set of unexpanded parameter packs within the given
8394 /// type.
8395 ///
8396 /// \param T The type that will be traversed to find
8397 /// unexpanded parameter packs.
8398 void collectUnexpandedParameterPacks(QualType T,
8399 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8400
8401 /// Collect the set of unexpanded parameter packs within the given
8402 /// type.
8403 ///
8404 /// \param TL The type that will be traversed to find
8405 /// unexpanded parameter packs.
8406 void collectUnexpandedParameterPacks(TypeLoc TL,
8407 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8408
8409 /// Collect the set of unexpanded parameter packs within the given
8410 /// nested-name-specifier.
8411 ///
8412 /// \param NNS The nested-name-specifier that will be traversed to find
8413 /// unexpanded parameter packs.
8414 void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS,
8415 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8416
8417 /// Collect the set of unexpanded parameter packs within the given
8418 /// name.
8419 ///
8420 /// \param NameInfo The name that will be traversed to find
8421 /// unexpanded parameter packs.
8422 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo,
8423 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded);
8424
8425 /// Invoked when parsing a template argument followed by an
8426 /// ellipsis, which creates a pack expansion.
8427 ///
8428 /// \param Arg The template argument preceding the ellipsis, which
8429 /// may already be invalid.
8430 ///
8431 /// \param EllipsisLoc The location of the ellipsis.
8432 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg,
8433 SourceLocation EllipsisLoc);
8434
8435 /// Invoked when parsing a type followed by an ellipsis, which
8436 /// creates a pack expansion.
8437 ///
8438 /// \param Type The type preceding the ellipsis, which will become
8439 /// the pattern of the pack expansion.
8440 ///
8441 /// \param EllipsisLoc The location of the ellipsis.
8442 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc);
8443
8444 /// Construct a pack expansion type from the pattern of the pack
8445 /// expansion.
8446 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern,
8447 SourceLocation EllipsisLoc,
8448 Optional<unsigned> NumExpansions);
8449
8450 /// Construct a pack expansion type from the pattern of the pack
8451 /// expansion.
8452 QualType CheckPackExpansion(QualType Pattern,
8453 SourceRange PatternRange,
8454 SourceLocation EllipsisLoc,
8455 Optional<unsigned> NumExpansions);
8456
8457 /// Invoked when parsing an expression followed by an ellipsis, which
8458 /// creates a pack expansion.
8459 ///
8460 /// \param Pattern The expression preceding the ellipsis, which will become
8461 /// the pattern of the pack expansion.
8462 ///
8463 /// \param EllipsisLoc The location of the ellipsis.
8464 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc);
8465
8466 /// Invoked when parsing an expression followed by an ellipsis, which
8467 /// creates a pack expansion.
8468 ///
8469 /// \param Pattern The expression preceding the ellipsis, which will become
8470 /// the pattern of the pack expansion.
8471 ///
8472 /// \param EllipsisLoc The location of the ellipsis.
8473 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
8474 Optional<unsigned> NumExpansions);
8475
8476 /// Determine whether we could expand a pack expansion with the
8477 /// given set of parameter packs into separate arguments by repeatedly
8478 /// transforming the pattern.
8479 ///
8480 /// \param EllipsisLoc The location of the ellipsis that identifies the
8481 /// pack expansion.
8482 ///
8483 /// \param PatternRange The source range that covers the entire pattern of
8484 /// the pack expansion.
8485 ///
8486 /// \param Unexpanded The set of unexpanded parameter packs within the
8487 /// pattern.
8488 ///
8489 /// \param ShouldExpand Will be set to \c true if the transformer should
8490 /// expand the corresponding pack expansions into separate arguments. When
8491 /// set, \c NumExpansions must also be set.
8492 ///
8493 /// \param RetainExpansion Whether the caller should add an unexpanded
8494 /// pack expansion after all of the expanded arguments. This is used
8495 /// when extending explicitly-specified template argument packs per
8496 /// C++0x [temp.arg.explicit]p9.
8497 ///
8498 /// \param NumExpansions The number of separate arguments that will be in
8499 /// the expanded form of the corresponding pack expansion. This is both an
8500 /// input and an output parameter, which can be set by the caller if the
8501 /// number of expansions is known a priori (e.g., due to a prior substitution)
8502 /// and will be set by the callee when the number of expansions is known.
8503 /// The callee must set this value when \c ShouldExpand is \c true; it may
8504 /// set this value in other cases.
8505 ///
8506 /// \returns true if an error occurred (e.g., because the parameter packs
8507 /// are to be instantiated with arguments of different lengths), false
8508 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
8509 /// must be set.
8510 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc,
8511 SourceRange PatternRange,
8512 ArrayRef<UnexpandedParameterPack> Unexpanded,
8513 const MultiLevelTemplateArgumentList &TemplateArgs,
8514 bool &ShouldExpand,
8515 bool &RetainExpansion,
8516 Optional<unsigned> &NumExpansions);
8517
8518 /// Determine the number of arguments in the given pack expansion
8519 /// type.
8520 ///
8521 /// This routine assumes that the number of arguments in the expansion is
8522 /// consistent across all of the unexpanded parameter packs in its pattern.
8523 ///
8524 /// Returns an empty Optional if the type can't be expanded.
8525 Optional<unsigned> getNumArgumentsInExpansion(QualType T,
8526 const MultiLevelTemplateArgumentList &TemplateArgs);
8527
8528 /// Determine whether the given declarator contains any unexpanded
8529 /// parameter packs.
8530 ///
8531 /// This routine is used by the parser to disambiguate function declarators
8532 /// with an ellipsis prior to the ')', e.g.,
8533 ///
8534 /// \code
8535 /// void f(T...);
8536 /// \endcode
8537 ///
8538 /// To determine whether we have an (unnamed) function parameter pack or
8539 /// a variadic function.
8540 ///
8541 /// \returns true if the declarator contains any unexpanded parameter packs,
8542 /// false otherwise.
8543 bool containsUnexpandedParameterPacks(Declarator &D);
8544
8545 /// Returns the pattern of the pack expansion for a template argument.
8546 ///
8547 /// \param OrigLoc The template argument to expand.
8548 ///
8549 /// \param Ellipsis Will be set to the location of the ellipsis.
8550 ///
8551 /// \param NumExpansions Will be set to the number of expansions that will
8552 /// be generated from this pack expansion, if known a priori.
8553 TemplateArgumentLoc getTemplateArgumentPackExpansionPattern(
8554 TemplateArgumentLoc OrigLoc,
8555 SourceLocation &Ellipsis,
8556 Optional<unsigned> &NumExpansions) const;
8557
8558 /// Given a template argument that contains an unexpanded parameter pack, but
8559 /// which has already been substituted, attempt to determine the number of
8560 /// elements that will be produced once this argument is fully-expanded.
8561 ///
8562 /// This is intended for use when transforming 'sizeof...(Arg)' in order to
8563 /// avoid actually expanding the pack where possible.
8564 Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg);
8565
8566 //===--------------------------------------------------------------------===//
8567 // C++ Template Argument Deduction (C++ [temp.deduct])
8568 //===--------------------------------------------------------------------===//
8569
8570 /// Adjust the type \p ArgFunctionType to match the calling convention,
8571 /// noreturn, and optionally the exception specification of \p FunctionType.
8572 /// Deduction often wants to ignore these properties when matching function
8573 /// types.
8574 QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType,
8575 bool AdjustExceptionSpec = false);
8576
8577 /// Describes the result of template argument deduction.
8578 ///
8579 /// The TemplateDeductionResult enumeration describes the result of
8580 /// template argument deduction, as returned from
8581 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo
8582 /// structure provides additional information about the results of
8583 /// template argument deduction, e.g., the deduced template argument
8584 /// list (if successful) or the specific template parameters or
8585 /// deduced arguments that were involved in the failure.
8586 enum TemplateDeductionResult {
8587 /// Template argument deduction was successful.
8588 TDK_Success = 0,
8589 /// The declaration was invalid; do nothing.
8590 TDK_Invalid,
8591 /// Template argument deduction exceeded the maximum template
8592 /// instantiation depth (which has already been diagnosed).
8593 TDK_InstantiationDepth,
8594 /// Template argument deduction did not deduce a value
8595 /// for every template parameter.
8596 TDK_Incomplete,
8597 /// Template argument deduction did not deduce a value for every
8598 /// expansion of an expanded template parameter pack.
8599 TDK_IncompletePack,
8600 /// Template argument deduction produced inconsistent
8601 /// deduced values for the given template parameter.
8602 TDK_Inconsistent,
8603 /// Template argument deduction failed due to inconsistent
8604 /// cv-qualifiers on a template parameter type that would
8605 /// otherwise be deduced, e.g., we tried to deduce T in "const T"
8606 /// but were given a non-const "X".
8607 TDK_Underqualified,
8608 /// Substitution of the deduced template argument values
8609 /// resulted in an error.
8610 TDK_SubstitutionFailure,
8611 /// After substituting deduced template arguments, a dependent
8612 /// parameter type did not match the corresponding argument.
8613 TDK_DeducedMismatch,
8614 /// After substituting deduced template arguments, an element of
8615 /// a dependent parameter type did not match the corresponding element
8616 /// of the corresponding argument (when deducing from an initializer list).
8617 TDK_DeducedMismatchNested,
8618 /// A non-depnedent component of the parameter did not match the
8619 /// corresponding component of the argument.
8620 TDK_NonDeducedMismatch,
8621 /// When performing template argument deduction for a function
8622 /// template, there were too many call arguments.
8623 TDK_TooManyArguments,
8624 /// When performing template argument deduction for a function
8625 /// template, there were too few call arguments.
8626 TDK_TooFewArguments,
8627 /// The explicitly-specified template arguments were not valid
8628 /// template arguments for the given template.
8629 TDK_InvalidExplicitArguments,
8630 /// Checking non-dependent argument conversions failed.
8631 TDK_NonDependentConversionFailure,
8632 /// The deduced arguments did not satisfy the constraints associated
8633 /// with the template.
8634 TDK_ConstraintsNotSatisfied,
8635 /// Deduction failed; that's all we know.
8636 TDK_MiscellaneousDeductionFailure,
8637 /// CUDA Target attributes do not match.
8638 TDK_CUDATargetMismatch
8639 };
8640
8641 TemplateDeductionResult
8642 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial,
8643 const TemplateArgumentList &TemplateArgs,
8644 sema::TemplateDeductionInfo &Info);
8645
8646 TemplateDeductionResult
8647 DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial,
8648 const TemplateArgumentList &TemplateArgs,
8649 sema::TemplateDeductionInfo &Info);
8650
8651 TemplateDeductionResult SubstituteExplicitTemplateArguments(
8652 FunctionTemplateDecl *FunctionTemplate,
8653 TemplateArgumentListInfo &ExplicitTemplateArgs,
8654 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8655 SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType,
8656 sema::TemplateDeductionInfo &Info);
8657
8658 /// brief A function argument from which we performed template argument
8659 // deduction for a call.
8660 struct OriginalCallArg {
8661 OriginalCallArg(QualType OriginalParamType, bool DecomposedParam,
8662 unsigned ArgIdx, QualType OriginalArgType)
8663 : OriginalParamType(OriginalParamType),
8664 DecomposedParam(DecomposedParam), ArgIdx(ArgIdx),
8665 OriginalArgType(OriginalArgType) {}
8666
8667 QualType OriginalParamType;
8668 bool DecomposedParam;
8669 unsigned ArgIdx;
8670 QualType OriginalArgType;
8671 };
8672
8673 TemplateDeductionResult FinishTemplateArgumentDeduction(
8674 FunctionTemplateDecl *FunctionTemplate,
8675 SmallVectorImpl<DeducedTemplateArgument> &Deduced,
8676 unsigned NumExplicitlySpecified, FunctionDecl *&Specialization,
8677 sema::TemplateDeductionInfo &Info,
8678 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr,
8679 bool PartialOverloading = false,
8680 llvm::function_ref<bool()> CheckNonDependent = []{ return false; });
8681
8682 TemplateDeductionResult DeduceTemplateArguments(
8683 FunctionTemplateDecl *FunctionTemplate,
8684 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8685 FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info,
8686 bool PartialOverloading,
8687 llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent);
8688
8689 TemplateDeductionResult
8690 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8691 TemplateArgumentListInfo *ExplicitTemplateArgs,
8692 QualType ArgFunctionType,
8693 FunctionDecl *&Specialization,
8694 sema::TemplateDeductionInfo &Info,
8695 bool IsAddressOfFunction = false);
8696
8697 TemplateDeductionResult
8698 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8699 QualType ToType,
8700 CXXConversionDecl *&Specialization,
8701 sema::TemplateDeductionInfo &Info);
8702
8703 TemplateDeductionResult
8704 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate,
8705 TemplateArgumentListInfo *ExplicitTemplateArgs,
8706 FunctionDecl *&Specialization,
8707 sema::TemplateDeductionInfo &Info,
8708 bool IsAddressOfFunction = false);
8709
8710 /// Substitute Replacement for \p auto in \p TypeWithAuto
8711 QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement);
8712 /// Substitute Replacement for auto in TypeWithAuto
8713 TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8714 QualType Replacement);
8715
8716 // Substitute auto in TypeWithAuto for a Dependent auto type
8717 QualType SubstAutoTypeDependent(QualType TypeWithAuto);
8718
8719 // Substitute auto in TypeWithAuto for a Dependent auto type
8720 TypeSourceInfo *
8721 SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto);
8722
8723 /// Completely replace the \c auto in \p TypeWithAuto by
8724 /// \p Replacement. This does not retain any \c auto type sugar.
8725 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement);
8726 TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto,
8727 QualType Replacement);
8728
8729 /// Result type of DeduceAutoType.
8730 enum DeduceAutoResult {
8731 DAR_Succeeded,
8732 DAR_Failed,
8733 DAR_FailedAlreadyDiagnosed
8734 };
8735
8736 DeduceAutoResult
8737 DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result,
8738 Optional<unsigned> DependentDeductionDepth = None,
8739 bool IgnoreConstraints = false);
8740 DeduceAutoResult
8741 DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result,
8742 Optional<unsigned> DependentDeductionDepth = None,
8743 bool IgnoreConstraints = false);
8744 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init);
8745 bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc,
8746 bool Diagnose = true);
8747
8748 /// Declare implicit deduction guides for a class template if we've
8749 /// not already done so.
8750 void DeclareImplicitDeductionGuides(TemplateDecl *Template,
8751 SourceLocation Loc);
8752
8753 QualType DeduceTemplateSpecializationFromInitializer(
8754 TypeSourceInfo *TInfo, const InitializedEntity &Entity,
8755 const InitializationKind &Kind, MultiExprArg Init);
8756
8757 QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name,
8758 QualType Type, TypeSourceInfo *TSI,
8759 SourceRange Range, bool DirectInit,
8760 Expr *Init);
8761
8762 TypeLoc getReturnTypeLoc(FunctionDecl *FD) const;
8763
8764 bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD,
8765 SourceLocation ReturnLoc,
8766 Expr *&RetExpr, const AutoType *AT);
8767
8768 FunctionTemplateDecl *getMoreSpecializedTemplate(
8769 FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc,
8770 TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1,
8771 unsigned NumCallArguments2, bool Reversed = false);
8772 UnresolvedSetIterator
8773 getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd,
8774 TemplateSpecCandidateSet &FailedCandidates,
8775 SourceLocation Loc,
8776 const PartialDiagnostic &NoneDiag,
8777 const PartialDiagnostic &AmbigDiag,
8778 const PartialDiagnostic &CandidateDiag,
8779 bool Complain = true, QualType TargetType = QualType());
8780
8781 ClassTemplatePartialSpecializationDecl *
8782 getMoreSpecializedPartialSpecialization(
8783 ClassTemplatePartialSpecializationDecl *PS1,
8784 ClassTemplatePartialSpecializationDecl *PS2,
8785 SourceLocation Loc);
8786
8787 bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T,
8788 sema::TemplateDeductionInfo &Info);
8789
8790 VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization(
8791 VarTemplatePartialSpecializationDecl *PS1,
8792 VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc);
8793
8794 bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T,
8795 sema::TemplateDeductionInfo &Info);
8796
8797 bool isTemplateTemplateParameterAtLeastAsSpecializedAs(
8798 TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc);
8799
8800 void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced,
8801 unsigned Depth, llvm::SmallBitVector &Used);
8802
8803 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs,
8804 bool OnlyDeduced,
8805 unsigned Depth,
8806 llvm::SmallBitVector &Used);
8807 void MarkDeducedTemplateParameters(
8808 const FunctionTemplateDecl *FunctionTemplate,
8809 llvm::SmallBitVector &Deduced) {
8810 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced);
8811 }
8812 static void MarkDeducedTemplateParameters(ASTContext &Ctx,
8813 const FunctionTemplateDecl *FunctionTemplate,
8814 llvm::SmallBitVector &Deduced);
8815
8816 //===--------------------------------------------------------------------===//
8817 // C++ Template Instantiation
8818 //
8819
8820 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(
8821 const NamedDecl *D, const TemplateArgumentList *Innermost = nullptr,
8822 bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr);
8823
8824 /// A context in which code is being synthesized (where a source location
8825 /// alone is not sufficient to identify the context). This covers template
8826 /// instantiation and various forms of implicitly-generated functions.
8827 struct CodeSynthesisContext {
8828 /// The kind of template instantiation we are performing
8829 enum SynthesisKind {
8830 /// We are instantiating a template declaration. The entity is
8831 /// the declaration we're instantiating (e.g., a CXXRecordDecl).
8832 TemplateInstantiation,
8833
8834 /// We are instantiating a default argument for a template
8835 /// parameter. The Entity is the template parameter whose argument is
8836 /// being instantiated, the Template is the template, and the
8837 /// TemplateArgs/NumTemplateArguments provide the template arguments as
8838 /// specified.
8839 DefaultTemplateArgumentInstantiation,
8840
8841 /// We are instantiating a default argument for a function.
8842 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs
8843 /// provides the template arguments as specified.
8844 DefaultFunctionArgumentInstantiation,
8845
8846 /// We are substituting explicit template arguments provided for
8847 /// a function template. The entity is a FunctionTemplateDecl.
8848 ExplicitTemplateArgumentSubstitution,
8849
8850 /// We are substituting template argument determined as part of
8851 /// template argument deduction for either a class template
8852 /// partial specialization or a function template. The
8853 /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or
8854 /// a TemplateDecl.
8855 DeducedTemplateArgumentSubstitution,
8856
8857 /// We are substituting prior template arguments into a new
8858 /// template parameter. The template parameter itself is either a
8859 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl.
8860 PriorTemplateArgumentSubstitution,
8861
8862 /// We are checking the validity of a default template argument that
8863 /// has been used when naming a template-id.
8864 DefaultTemplateArgumentChecking,
8865
8866 /// We are computing the exception specification for a defaulted special
8867 /// member function.
8868 ExceptionSpecEvaluation,
8869
8870 /// We are instantiating the exception specification for a function
8871 /// template which was deferred until it was needed.
8872 ExceptionSpecInstantiation,
8873
8874 /// We are instantiating a requirement of a requires expression.
8875 RequirementInstantiation,
8876
8877 /// We are checking the satisfaction of a nested requirement of a requires
8878 /// expression.
8879 NestedRequirementConstraintsCheck,
8880
8881 /// We are declaring an implicit special member function.
8882 DeclaringSpecialMember,
8883
8884 /// We are declaring an implicit 'operator==' for a defaulted
8885 /// 'operator<=>'.
8886 DeclaringImplicitEqualityComparison,
8887
8888 /// We are defining a synthesized function (such as a defaulted special
8889 /// member).
8890 DefiningSynthesizedFunction,
8891
8892 // We are checking the constraints associated with a constrained entity or
8893 // the constraint expression of a concept. This includes the checks that
8894 // atomic constraints have the type 'bool' and that they can be constant
8895 // evaluated.
8896 ConstraintsCheck,
8897
8898 // We are substituting template arguments into a constraint expression.
8899 ConstraintSubstitution,
8900
8901 // We are normalizing a constraint expression.
8902 ConstraintNormalization,
8903
8904 // We are substituting into the parameter mapping of an atomic constraint
8905 // during normalization.
8906 ParameterMappingSubstitution,
8907
8908 /// We are rewriting a comparison operator in terms of an operator<=>.
8909 RewritingOperatorAsSpaceship,
8910
8911 /// We are initializing a structured binding.
8912 InitializingStructuredBinding,
8913
8914 /// We are marking a class as __dllexport.
8915 MarkingClassDllexported,
8916
8917 /// Added for Template instantiation observation.
8918 /// Memoization means we are _not_ instantiating a template because
8919 /// it is already instantiated (but we entered a context where we
8920 /// would have had to if it was not already instantiated).
8921 Memoization
8922 } Kind;
8923
8924 /// Was the enclosing context a non-instantiation SFINAE context?
8925 bool SavedInNonInstantiationSFINAEContext;
8926
8927 /// The point of instantiation or synthesis within the source code.
8928 SourceLocation PointOfInstantiation;
8929
8930 /// The entity that is being synthesized.
8931 Decl *Entity;
8932
8933 /// The template (or partial specialization) in which we are
8934 /// performing the instantiation, for substitutions of prior template
8935 /// arguments.
8936 NamedDecl *Template;
8937
8938 /// The list of template arguments we are substituting, if they
8939 /// are not part of the entity.
8940 const TemplateArgument *TemplateArgs;
8941
8942 // FIXME: Wrap this union around more members, or perhaps store the
8943 // kind-specific members in the RAII object owning the context.
8944 union {
8945 /// The number of template arguments in TemplateArgs.
8946 unsigned NumTemplateArgs;
8947
8948 /// The special member being declared or defined.
8949 CXXSpecialMember SpecialMember;
8950 };
8951
8952 ArrayRef<TemplateArgument> template_arguments() const {
8953 assert(Kind != DeclaringSpecialMember)(static_cast <bool> (Kind != DeclaringSpecialMember) ? void
(0) : __assert_fail ("Kind != DeclaringSpecialMember", "clang/include/clang/Sema/Sema.h"
, 8953, __extension__ __PRETTY_FUNCTION__))
;
8954 return {TemplateArgs, NumTemplateArgs};
8955 }
8956
8957 /// The template deduction info object associated with the
8958 /// substitution or checking of explicit or deduced template arguments.
8959 sema::TemplateDeductionInfo *DeductionInfo;
8960
8961 /// The source range that covers the construct that cause
8962 /// the instantiation, e.g., the template-id that causes a class
8963 /// template instantiation.
8964 SourceRange InstantiationRange;
8965
8966 CodeSynthesisContext()
8967 : Kind(TemplateInstantiation),
8968 SavedInNonInstantiationSFINAEContext(false), Entity(nullptr),
8969 Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0),
8970 DeductionInfo(nullptr) {}
8971
8972 /// Determines whether this template is an actual instantiation
8973 /// that should be counted toward the maximum instantiation depth.
8974 bool isInstantiationRecord() const;
8975 };
8976
8977 /// List of active code synthesis contexts.
8978 ///
8979 /// This vector is treated as a stack. As synthesis of one entity requires
8980 /// synthesis of another, additional contexts are pushed onto the stack.
8981 SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts;
8982
8983 /// Specializations whose definitions are currently being instantiated.
8984 llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations;
8985
8986 /// Non-dependent types used in templates that have already been instantiated
8987 /// by some template instantiation.
8988 llvm::DenseSet<QualType> InstantiatedNonDependentTypes;
8989
8990 /// Extra modules inspected when performing a lookup during a template
8991 /// instantiation. Computed lazily.
8992 SmallVector<Module*, 16> CodeSynthesisContextLookupModules;
8993
8994 /// Cache of additional modules that should be used for name lookup
8995 /// within the current template instantiation. Computed lazily; use
8996 /// getLookupModules() to get a complete set.
8997 llvm::DenseSet<Module*> LookupModulesCache;
8998
8999 /// Get the set of additional modules that should be checked during
9000 /// name lookup. A module and its imports become visible when instanting a
9001 /// template defined within it.
9002 llvm::DenseSet<Module*> &getLookupModules();
9003
9004 /// Map from the most recent declaration of a namespace to the most
9005 /// recent visible declaration of that namespace.
9006 llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache;
9007
9008 /// Whether we are in a SFINAE context that is not associated with
9009 /// template instantiation.
9010 ///
9011 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside
9012 /// of a template instantiation or template argument deduction.
9013 bool InNonInstantiationSFINAEContext;
9014
9015 /// The number of \p CodeSynthesisContexts that are not template
9016 /// instantiations and, therefore, should not be counted as part of the
9017 /// instantiation depth.
9018 ///
9019 /// When the instantiation depth reaches the user-configurable limit
9020 /// \p LangOptions::InstantiationDepth we will abort instantiation.
9021 // FIXME: Should we have a similar limit for other forms of synthesis?
9022 unsigned NonInstantiationEntries;
9023
9024 /// The depth of the context stack at the point when the most recent
9025 /// error or warning was produced.
9026 ///
9027 /// This value is used to suppress printing of redundant context stacks
9028 /// when there are multiple errors or warnings in the same instantiation.
9029 // FIXME: Does this belong in Sema? It's tough to implement it anywhere else.
9030 unsigned LastEmittedCodeSynthesisContextDepth = 0;
9031
9032 /// The template instantiation callbacks to trace or track
9033 /// instantiations (objects can be chained).
9034 ///
9035 /// This callbacks is used to print, trace or track template
9036 /// instantiations as they are being constructed.
9037 std::vector<std::unique_ptr<TemplateInstantiationCallback>>
9038 TemplateInstCallbacks;
9039
9040 /// The current index into pack expansion arguments that will be
9041 /// used for substitution of parameter packs.
9042 ///
9043 /// The pack expansion index will be -1 to indicate that parameter packs
9044 /// should be instantiated as themselves. Otherwise, the index specifies
9045 /// which argument within the parameter pack will be used for substitution.
9046 int ArgumentPackSubstitutionIndex;
9047
9048 /// RAII object used to change the argument pack substitution index
9049 /// within a \c Sema object.
9050 ///
9051 /// See \c ArgumentPackSubstitutionIndex for more information.
9052 class ArgumentPackSubstitutionIndexRAII {
9053 Sema &Self;
9054 int OldSubstitutionIndex;
9055
9056 public:
9057 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex)
9058 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) {
9059 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex;
9060 }
9061
9062 ~ArgumentPackSubstitutionIndexRAII() {
9063 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex;
9064 }
9065 };
9066
9067 friend class ArgumentPackSubstitutionRAII;
9068
9069 /// For each declaration that involved template argument deduction, the
9070 /// set of diagnostics that were suppressed during that template argument
9071 /// deduction.
9072 ///
9073 /// FIXME: Serialize this structure to the AST file.
9074 typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >
9075 SuppressedDiagnosticsMap;
9076 SuppressedDiagnosticsMap SuppressedDiagnostics;
9077
9078 /// A stack object to be created when performing template
9079 /// instantiation.
9080 ///
9081 /// Construction of an object of type \c InstantiatingTemplate
9082 /// pushes the current instantiation onto the stack of active
9083 /// instantiations. If the size of this stack exceeds the maximum
9084 /// number of recursive template instantiations, construction
9085 /// produces an error and evaluates true.
9086 ///
9087 /// Destruction of this object will pop the named instantiation off
9088 /// the stack.
9089 struct InstantiatingTemplate {
9090 /// Note that we are instantiating a class template,
9091 /// function template, variable template, alias template,
9092 /// or a member thereof.
9093 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9094 Decl *Entity,
9095 SourceRange InstantiationRange = SourceRange());
9096
9097 struct ExceptionSpecification {};
9098 /// Note that we are instantiating an exception specification
9099 /// of a function template.
9100 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9101 FunctionDecl *Entity, ExceptionSpecification,
9102 SourceRange InstantiationRange = SourceRange());
9103
9104 /// Note that we are instantiating a default argument in a
9105 /// template-id.
9106 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9107 TemplateParameter Param, TemplateDecl *Template,
9108 ArrayRef<TemplateArgument> TemplateArgs,
9109 SourceRange InstantiationRange = SourceRange());
9110
9111 /// Note that we are substituting either explicitly-specified or
9112 /// deduced template arguments during function template argument deduction.
9113 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9114 FunctionTemplateDecl *FunctionTemplate,
9115 ArrayRef<TemplateArgument> TemplateArgs,
9116 CodeSynthesisContext::SynthesisKind Kind,
9117 sema::TemplateDeductionInfo &DeductionInfo,
9118 SourceRange InstantiationRange = SourceRange());
9119
9120 /// Note that we are instantiating as part of template
9121 /// argument deduction for a class template declaration.
9122 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9123 TemplateDecl *Template,
9124 ArrayRef<TemplateArgument> TemplateArgs,
9125 sema::TemplateDeductionInfo &DeductionInfo,
9126 SourceRange InstantiationRange = SourceRange());
9127
9128 /// Note that we are instantiating as part of template
9129 /// argument deduction for a class template partial
9130 /// specialization.
9131 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9132 ClassTemplatePartialSpecializationDecl *PartialSpec,
9133 ArrayRef<TemplateArgument> TemplateArgs,
9134 sema::TemplateDeductionInfo &DeductionInfo,
9135 SourceRange InstantiationRange = SourceRange());
9136
9137 /// Note that we are instantiating as part of template
9138 /// argument deduction for a variable template partial
9139 /// specialization.
9140 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9141 VarTemplatePartialSpecializationDecl *PartialSpec,
9142 ArrayRef<TemplateArgument> TemplateArgs,
9143 sema::TemplateDeductionInfo &DeductionInfo,
9144 SourceRange InstantiationRange = SourceRange());
9145
9146 /// Note that we are instantiating a default argument for a function
9147 /// parameter.
9148 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9149 ParmVarDecl *Param,
9150 ArrayRef<TemplateArgument> TemplateArgs,
9151 SourceRange InstantiationRange = SourceRange());
9152
9153 /// Note that we are substituting prior template arguments into a
9154 /// non-type parameter.
9155 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9156 NamedDecl *Template,
9157 NonTypeTemplateParmDecl *Param,
9158 ArrayRef<TemplateArgument> TemplateArgs,
9159 SourceRange InstantiationRange);
9160
9161 /// Note that we are substituting prior template arguments into a
9162 /// template template parameter.
9163 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9164 NamedDecl *Template,
9165 TemplateTemplateParmDecl *Param,
9166 ArrayRef<TemplateArgument> TemplateArgs,
9167 SourceRange InstantiationRange);
9168
9169 /// Note that we are checking the default template argument
9170 /// against the template parameter for a given template-id.
9171 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9172 TemplateDecl *Template,
9173 NamedDecl *Param,
9174 ArrayRef<TemplateArgument> TemplateArgs,
9175 SourceRange InstantiationRange);
9176
9177 struct ConstraintsCheck {};
9178 /// \brief Note that we are checking the constraints associated with some
9179 /// constrained entity (a concept declaration or a template with associated
9180 /// constraints).
9181 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9182 ConstraintsCheck, NamedDecl *Template,
9183 ArrayRef<TemplateArgument> TemplateArgs,
9184 SourceRange InstantiationRange);
9185
9186 struct ConstraintSubstitution {};
9187 /// \brief Note that we are checking a constraint expression associated
9188 /// with a template declaration or as part of the satisfaction check of a
9189 /// concept.
9190 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9191 ConstraintSubstitution, NamedDecl *Template,
9192 sema::TemplateDeductionInfo &DeductionInfo,
9193 SourceRange InstantiationRange);
9194
9195 struct ConstraintNormalization {};
9196 /// \brief Note that we are normalizing a constraint expression.
9197 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9198 ConstraintNormalization, NamedDecl *Template,
9199 SourceRange InstantiationRange);
9200
9201 struct ParameterMappingSubstitution {};
9202 /// \brief Note that we are subtituting into the parameter mapping of an
9203 /// atomic constraint during constraint normalization.
9204 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9205 ParameterMappingSubstitution, NamedDecl *Template,
9206 SourceRange InstantiationRange);
9207
9208 /// \brief Note that we are substituting template arguments into a part of
9209 /// a requirement of a requires expression.
9210 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9211 concepts::Requirement *Req,
9212 sema::TemplateDeductionInfo &DeductionInfo,
9213 SourceRange InstantiationRange = SourceRange());
9214
9215 /// \brief Note that we are checking the satisfaction of the constraint
9216 /// expression inside of a nested requirement.
9217 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation,
9218 concepts::NestedRequirement *Req, ConstraintsCheck,
9219 SourceRange InstantiationRange = SourceRange());
9220
9221 /// Note that we have finished instantiating this template.
9222 void Clear();
9223
9224 ~InstantiatingTemplate() { Clear(); }
9225
9226 /// Determines whether we have exceeded the maximum
9227 /// recursive template instantiations.
9228 bool isInvalid() const { return Invalid; }
9229
9230 /// Determine whether we are already instantiating this
9231 /// specialization in some surrounding active instantiation.
9232 bool isAlreadyInstantiating() const { return AlreadyInstantiating; }
9233
9234 private:
9235 Sema &SemaRef;
9236 bool Invalid;
9237 bool AlreadyInstantiating;
9238 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation,
9239 SourceRange InstantiationRange);
9240
9241 InstantiatingTemplate(
9242 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
9243 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
9244 Decl *Entity, NamedDecl *Template = nullptr,
9245 ArrayRef<TemplateArgument> TemplateArgs = None,
9246 sema::TemplateDeductionInfo *DeductionInfo = nullptr);
9247
9248 InstantiatingTemplate(const InstantiatingTemplate&) = delete;
9249
9250 InstantiatingTemplate&
9251 operator=(const InstantiatingTemplate&) = delete;
9252 };
9253
9254 void pushCodeSynthesisContext(CodeSynthesisContext Ctx);
9255 void popCodeSynthesisContext();
9256
9257 /// Determine whether we are currently performing template instantiation.
9258 bool inTemplateInstantiation() const {
9259 return CodeSynthesisContexts.size() > NonInstantiationEntries;
9260 }
9261
9262 void PrintContextStack() {
9263 if (!CodeSynthesisContexts.empty() &&
9264 CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) {
9265 PrintInstantiationStack();
9266 LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size();
9267 }
9268 if (PragmaAttributeCurrentTargetDecl)
9269 PrintPragmaAttributeInstantiationPoint();
9270 }
9271 void PrintInstantiationStack();
9272
9273 void PrintPragmaAttributeInstantiationPoint();
9274
9275 /// Determines whether we are currently in a context where
9276 /// template argument substitution failures are not considered
9277 /// errors.
9278 ///
9279 /// \returns An empty \c Optional if we're not in a SFINAE context.
9280 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest
9281 /// template-deduction context object, which can be used to capture
9282 /// diagnostics that will be suppressed.
9283 Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const;
9284
9285 /// Determines whether we are currently in a context that
9286 /// is not evaluated as per C++ [expr] p5.
9287 bool isUnevaluatedContext() const {
9288 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9289, __extension__ __PRETTY_FUNCTION__
))
9289 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9289, __extension__ __PRETTY_FUNCTION__
))
;
9290 return ExprEvalContexts.back().isUnevaluated();
9291 }
9292
9293 bool isImmediateFunctionContext() const {
9294 assert(!ExprEvalContexts.empty() &&(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9295, __extension__ __PRETTY_FUNCTION__
))
9295 "Must be in an expression evaluation context")(static_cast <bool> (!ExprEvalContexts.empty() &&
"Must be in an expression evaluation context") ? void (0) : __assert_fail
("!ExprEvalContexts.empty() && \"Must be in an expression evaluation context\""
, "clang/include/clang/Sema/Sema.h", 9295, __extension__ __PRETTY_FUNCTION__
))
;
9296 return ExprEvalContexts.back().isImmediateFunctionContext();
9297 }
9298
9299 /// RAII class used to determine whether SFINAE has
9300 /// trapped any errors that occur during template argument
9301 /// deduction.
9302 class SFINAETrap {
9303 Sema &SemaRef;
9304 unsigned PrevSFINAEErrors;
9305 bool PrevInNonInstantiationSFINAEContext;
9306 bool PrevAccessCheckingSFINAE;
9307 bool PrevLastDiagnosticIgnored;
9308
9309 public:
9310 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false)
9311 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors),
9312 PrevInNonInstantiationSFINAEContext(
9313 SemaRef.InNonInstantiationSFINAEContext),
9314 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE),
9315 PrevLastDiagnosticIgnored(
9316 SemaRef.getDiagnostics().isLastDiagnosticIgnored())
9317 {
9318 if (!SemaRef.isSFINAEContext())
9319 SemaRef.InNonInstantiationSFINAEContext = true;
9320 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE;
9321 }
9322
9323 ~SFINAETrap() {
9324 SemaRef.NumSFINAEErrors = PrevSFINAEErrors;
9325 SemaRef.InNonInstantiationSFINAEContext
9326 = PrevInNonInstantiationSFINAEContext;
9327 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE;
9328 SemaRef.getDiagnostics().setLastDiagnosticIgnored(
9329 PrevLastDiagnosticIgnored);
9330 }
9331
9332 /// Determine whether any SFINAE errors have been trapped.
9333 bool hasErrorOccurred() const {
9334 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors;
9335 }
9336 };
9337
9338 /// RAII class used to indicate that we are performing provisional
9339 /// semantic analysis to determine the validity of a construct, so
9340 /// typo-correction and diagnostics in the immediate context (not within
9341 /// implicitly-instantiated templates) should be suppressed.
9342 class TentativeAnalysisScope {
9343 Sema &SemaRef;
9344 // FIXME: Using a SFINAETrap for this is a hack.
9345 SFINAETrap Trap;
9346 bool PrevDisableTypoCorrection;
9347 public:
9348 explicit TentativeAnalysisScope(Sema &SemaRef)
9349 : SemaRef(SemaRef), Trap(SemaRef, true),
9350 PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) {
9351 SemaRef.DisableTypoCorrection = true;
9352 }
9353 ~TentativeAnalysisScope() {
9354 SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection;
9355 }
9356 };
9357
9358 /// The current instantiation scope used to store local
9359 /// variables.
9360 LocalInstantiationScope *CurrentInstantiationScope;
9361
9362 /// Tracks whether we are in a context where typo correction is
9363 /// disabled.
9364 bool DisableTypoCorrection;
9365
9366 /// The number of typos corrected by CorrectTypo.
9367 unsigned TyposCorrected;
9368
9369 typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet;
9370 typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations;
9371
9372 /// A cache containing identifiers for which typo correction failed and
9373 /// their locations, so that repeated attempts to correct an identifier in a
9374 /// given location are ignored if typo correction already failed for it.
9375 IdentifierSourceLocations TypoCorrectionFailures;
9376
9377 /// Worker object for performing CFG-based warnings.
9378 sema::AnalysisBasedWarnings AnalysisWarnings;
9379 threadSafety::BeforeSet *ThreadSafetyDeclCache;
9380
9381 /// An entity for which implicit template instantiation is required.
9382 ///
9383 /// The source location associated with the declaration is the first place in
9384 /// the source code where the declaration was "used". It is not necessarily
9385 /// the point of instantiation (which will be either before or after the
9386 /// namespace-scope declaration that triggered this implicit instantiation),
9387 /// However, it is the location that diagnostics should generally refer to,
9388 /// because users will need to know what code triggered the instantiation.
9389 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation;
9390
9391 /// The queue of implicit template instantiations that are required
9392 /// but have not yet been performed.
9393 std::deque<PendingImplicitInstantiation> PendingInstantiations;
9394
9395 /// Queue of implicit template instantiations that cannot be performed
9396 /// eagerly.
9397 SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations;
9398
9399 class GlobalEagerInstantiationScope {
9400 public:
9401 GlobalEagerInstantiationScope(Sema &S, bool Enabled)
9402 : S(S), Enabled(Enabled) {
9403 if (!Enabled) return;
9404
9405 SavedPendingInstantiations.swap(S.PendingInstantiations);
9406 SavedVTableUses.swap(S.VTableUses);
9407 }
9408
9409 void perform() {
9410 if (Enabled) {
9411 S.DefineUsedVTables();
9412 S.PerformPendingInstantiations();
9413 }
9414 }
9415
9416 ~GlobalEagerInstantiationScope() {
9417 if (!Enabled) return;
9418
9419 // Restore the set of pending vtables.
9420 assert(S.VTableUses.empty() &&(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9421, __extension__ __PRETTY_FUNCTION__
))
9421 "VTableUses should be empty before it is discarded.")(static_cast <bool> (S.VTableUses.empty() && "VTableUses should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.VTableUses.empty() && \"VTableUses should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9421, __extension__ __PRETTY_FUNCTION__
))
;
9422 S.VTableUses.swap(SavedVTableUses);
9423
9424 // Restore the set of pending implicit instantiations.
9425 if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) {
9426 assert(S.PendingInstantiations.empty() &&(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9427, __extension__ __PRETTY_FUNCTION__
))
9427 "PendingInstantiations should be empty before it is discarded.")(static_cast <bool> (S.PendingInstantiations.empty() &&
"PendingInstantiations should be empty before it is discarded."
) ? void (0) : __assert_fail ("S.PendingInstantiations.empty() && \"PendingInstantiations should be empty before it is discarded.\""
, "clang/include/clang/Sema/Sema.h", 9427, __extension__ __PRETTY_FUNCTION__
))
;
9428 S.PendingInstantiations.swap(SavedPendingInstantiations);
9429 } else {
9430 // Template instantiations in the PCH may be delayed until the TU.
9431 S.PendingInstantiations.swap(SavedPendingInstantiations);
9432 S.PendingInstantiations.insert(S.PendingInstantiations.end(),
9433 SavedPendingInstantiations.begin(),
9434 SavedPendingInstantiations.end());
9435 }
9436 }
9437
9438 private:
9439 Sema &S;
9440 SmallVector<VTableUse, 16> SavedVTableUses;
9441 std::deque<PendingImplicitInstantiation> SavedPendingInstantiations;
9442 bool Enabled;
9443 };
9444
9445 /// The queue of implicit template instantiations that are required
9446 /// and must be performed within the current local scope.
9447 ///
9448 /// This queue is only used for member functions of local classes in
9449 /// templates, which must be instantiated in the same scope as their
9450 /// enclosing function, so that they can reference function-local
9451 /// types, static variables, enumerators, etc.
9452 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations;
9453
9454 class LocalEagerInstantiationScope {
9455 public:
9456 LocalEagerInstantiationScope(Sema &S) : S(S) {
9457 SavedPendingLocalImplicitInstantiations.swap(
9458 S.PendingLocalImplicitInstantiations);
9459 }
9460
9461 void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); }
9462
9463 ~LocalEagerInstantiationScope() {
9464 assert(S.PendingLocalImplicitInstantiations.empty() &&(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "clang/include/clang/Sema/Sema.h", 9465, __extension__ __PRETTY_FUNCTION__
))
9465 "there shouldn't be any pending local implicit instantiations")(static_cast <bool> (S.PendingLocalImplicitInstantiations
.empty() && "there shouldn't be any pending local implicit instantiations"
) ? void (0) : __assert_fail ("S.PendingLocalImplicitInstantiations.empty() && \"there shouldn't be any pending local implicit instantiations\""
, "clang/include/clang/Sema/Sema.h", 9465, __extension__ __PRETTY_FUNCTION__
))
;
9466 SavedPendingLocalImplicitInstantiations.swap(
9467 S.PendingLocalImplicitInstantiations);
9468 }
9469
9470 private:
9471 Sema &S;
9472 std::deque<PendingImplicitInstantiation>
9473 SavedPendingLocalImplicitInstantiations;
9474 };
9475
9476 /// A helper class for building up ExtParameterInfos.
9477 class ExtParameterInfoBuilder {
9478 SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos;
9479 bool HasInteresting = false;
9480
9481 public:
9482 /// Set the ExtParameterInfo for the parameter at the given index,
9483 ///
9484 void set(unsigned index, FunctionProtoType::ExtParameterInfo info) {
9485 assert(Infos.size() <= index)(static_cast <bool> (Infos.size() <= index) ? void (
0) : __assert_fail ("Infos.size() <= index", "clang/include/clang/Sema/Sema.h"
, 9485, __extension__ __PRETTY_FUNCTION__))
;
9486 Infos.resize(index);
9487 Infos.push_back(info);
9488
9489 if (!HasInteresting)
9490 HasInteresting = (info != FunctionProtoType::ExtParameterInfo());
9491 }
9492
9493 /// Return a pointer (suitable for setting in an ExtProtoInfo) to the
9494 /// ExtParameterInfo array we've built up.
9495 const FunctionProtoType::ExtParameterInfo *
9496 getPointerOrNull(unsigned numParams) {
9497 if (!HasInteresting) return nullptr;
9498 Infos.resize(numParams);
9499 return Infos.data();
9500 }
9501 };
9502
9503 void PerformPendingInstantiations(bool LocalOnly = false);
9504
9505 TypeSourceInfo *SubstType(TypeSourceInfo *T,
9506 const MultiLevelTemplateArgumentList &TemplateArgs,
9507 SourceLocation Loc, DeclarationName Entity,
9508 bool AllowDeducedTST = false);
9509
9510 QualType SubstType(QualType T,
9511 const MultiLevelTemplateArgumentList &TemplateArgs,
9512 SourceLocation Loc, DeclarationName Entity);
9513
9514 TypeSourceInfo *SubstType(TypeLoc TL,
9515 const MultiLevelTemplateArgumentList &TemplateArgs,
9516 SourceLocation Loc, DeclarationName Entity);
9517
9518 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T,
9519 const MultiLevelTemplateArgumentList &TemplateArgs,
9520 SourceLocation Loc,
9521 DeclarationName Entity,
9522 CXXRecordDecl *ThisContext,
9523 Qualifiers ThisTypeQuals);
9524 void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
9525 const MultiLevelTemplateArgumentList &Args);
9526 bool SubstExceptionSpec(SourceLocation Loc,
9527 FunctionProtoType::ExceptionSpecInfo &ESI,
9528 SmallVectorImpl<QualType> &ExceptionStorage,
9529 const MultiLevelTemplateArgumentList &Args);
9530 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D,
9531 const MultiLevelTemplateArgumentList &TemplateArgs,
9532 int indexAdjustment,
9533 Optional<unsigned> NumExpansions,
9534 bool ExpectParameterPack);
9535 bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
9536 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
9537 const MultiLevelTemplateArgumentList &TemplateArgs,
9538 SmallVectorImpl<QualType> &ParamTypes,
9539 SmallVectorImpl<ParmVarDecl *> *OutParams,
9540 ExtParameterInfoBuilder &ParamInfos);
9541 ExprResult SubstExpr(Expr *E,
9542 const MultiLevelTemplateArgumentList &TemplateArgs);
9543
9544 /// Substitute the given template arguments into a list of
9545 /// expressions, expanding pack expansions if required.
9546 ///
9547 /// \param Exprs The list of expressions to substitute into.
9548 ///
9549 /// \param IsCall Whether this is some form of call, in which case
9550 /// default arguments will be dropped.
9551 ///
9552 /// \param TemplateArgs The set of template arguments to substitute.
9553 ///
9554 /// \param Outputs Will receive all of the substituted arguments.
9555 ///
9556 /// \returns true if an error occurred, false otherwise.
9557 bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
9558 const MultiLevelTemplateArgumentList &TemplateArgs,
9559 SmallVectorImpl<Expr *> &Outputs);
9560
9561 StmtResult SubstStmt(Stmt *S,
9562 const MultiLevelTemplateArgumentList &TemplateArgs);
9563
9564 TemplateParameterList *
9565 SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
9566 const MultiLevelTemplateArgumentList &TemplateArgs);
9567
9568 bool
9569 SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
9570 const MultiLevelTemplateArgumentList &TemplateArgs,
9571 TemplateArgumentListInfo &Outputs);
9572
9573
9574 Decl *SubstDecl(Decl *D, DeclContext *Owner,
9575 const MultiLevelTemplateArgumentList &TemplateArgs);
9576
9577 /// Substitute the name and return type of a defaulted 'operator<=>' to form
9578 /// an implicit 'operator=='.
9579 FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
9580 FunctionDecl *Spaceship);
9581
9582 ExprResult SubstInitializer(Expr *E,
9583 const MultiLevelTemplateArgumentList &TemplateArgs,
9584 bool CXXDirectInit);
9585
9586 bool
9587 SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
9588 CXXRecordDecl *Pattern,
9589 const MultiLevelTemplateArgumentList &TemplateArgs);
9590
9591 bool
9592 InstantiateClass(SourceLocation PointOfInstantiation,
9593 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
9594 const MultiLevelTemplateArgumentList &TemplateArgs,
9595 TemplateSpecializationKind TSK,
9596 bool Complain = true);
9597
9598 bool InstantiateEnum(SourceLocation PointOfInstantiation,
9599 EnumDecl *Instantiation, EnumDecl *Pattern,
9600 const MultiLevelTemplateArgumentList &TemplateArgs,
9601 TemplateSpecializationKind TSK);
9602
9603 bool InstantiateInClassInitializer(
9604 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
9605 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs);
9606
9607 struct LateInstantiatedAttribute {
9608 const Attr *TmplAttr;
9609 LocalInstantiationScope *Scope;
9610 Decl *NewDecl;
9611
9612 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S,
9613 Decl *D)
9614 : TmplAttr(A), Scope(S), NewDecl(D)
9615 { }
9616 };
9617 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec;
9618
9619 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
9620 const Decl *Pattern, Decl *Inst,
9621 LateInstantiatedAttrVec *LateAttrs = nullptr,
9622 LocalInstantiationScope *OuterMostScope = nullptr);
9623
9624 void
9625 InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs,
9626 const Decl *Pattern, Decl *Inst,
9627 LateInstantiatedAttrVec *LateAttrs = nullptr,
9628 LocalInstantiationScope *OuterMostScope = nullptr);
9629
9630 void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor);
9631
9632 bool usesPartialOrExplicitSpecialization(
9633 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec);
9634
9635 bool
9636 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation,
9637 ClassTemplateSpecializationDecl *ClassTemplateSpec,
9638 TemplateSpecializationKind TSK,
9639 bool Complain = true);
9640
9641 void InstantiateClassMembers(SourceLocation PointOfInstantiation,
9642 CXXRecordDecl *Instantiation,
9643 const MultiLevelTemplateArgumentList &TemplateArgs,
9644 TemplateSpecializationKind TSK);
9645
9646 void InstantiateClassTemplateSpecializationMembers(
9647 SourceLocation PointOfInstantiation,
9648 ClassTemplateSpecializationDecl *ClassTemplateSpec,
9649 TemplateSpecializationKind TSK);
9650
9651 NestedNameSpecifierLoc
9652 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
9653 const MultiLevelTemplateArgumentList &TemplateArgs);
9654
9655 DeclarationNameInfo
9656 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
9657 const MultiLevelTemplateArgumentList &TemplateArgs);
9658 TemplateName
9659 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name,
9660 SourceLocation Loc,
9661 const MultiLevelTemplateArgumentList &TemplateArgs);
9662
9663 bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
9664 const MultiLevelTemplateArgumentList &TemplateArgs);
9665
9666 bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
9667 ParmVarDecl *Param);
9668 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
9669 FunctionDecl *Function);
9670 bool CheckInstantiatedFunctionTemplateConstraints(
9671 SourceLocation PointOfInstantiation, FunctionDecl *Decl,
9672 ArrayRef<TemplateArgument> TemplateArgs,
9673 ConstraintSatisfaction &Satisfaction);
9674 FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
9675 const TemplateArgumentList *Args,
9676 SourceLocation Loc);
9677 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
9678 FunctionDecl *Function,
9679 bool Recursive = false,
9680 bool DefinitionRequired = false,
9681 bool AtEndOfTU = false);
9682 VarTemplateSpecializationDecl *BuildVarTemplateInstantiation(
9683 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
9684 const TemplateArgumentList &TemplateArgList,
9685 const TemplateArgumentListInfo &TemplateArgsInfo,
9686 SmallVectorImpl<TemplateArgument> &Converted,
9687 SourceLocation PointOfInstantiation,
9688 LateInstantiatedAttrVec *LateAttrs = nullptr,
9689 LocalInstantiationScope *StartingScope = nullptr);
9690 VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl(
9691 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
9692 const MultiLevelTemplateArgumentList &TemplateArgs);
9693 void
9694 BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar,
9695 const MultiLevelTemplateArgumentList &TemplateArgs,
9696 LateInstantiatedAttrVec *LateAttrs,
9697 DeclContext *Owner,
9698 LocalInstantiationScope *StartingScope,
9699 bool InstantiatingVarTemplate = false,
9700 VarTemplateSpecializationDecl *PrevVTSD = nullptr);
9701
9702 void InstantiateVariableInitializer(
9703 VarDecl *Var, VarDecl *OldVar,
9704 const MultiLevelTemplateArgumentList &TemplateArgs);
9705 void InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
9706 VarDecl *Var, bool Recursive = false,
9707 bool DefinitionRequired = false,
9708 bool AtEndOfTU = false);
9709
9710 void InstantiateMemInitializers(CXXConstructorDecl *New,
9711 const CXXConstructorDecl *Tmpl,
9712 const MultiLevelTemplateArgumentList &TemplateArgs);
9713
9714 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
9715 const MultiLevelTemplateArgumentList &TemplateArgs,
9716 bool FindingInstantiatedContext = false);
9717 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC,
9718 const MultiLevelTemplateArgumentList &TemplateArgs);
9719
9720 // Objective-C declarations.
9721 enum ObjCContainerKind {
9722 OCK_None = -1,
9723 OCK_Interface = 0,
9724 OCK_Protocol,
9725 OCK_Category,
9726 OCK_ClassExtension,
9727 OCK_Implementation,
9728 OCK_CategoryImplementation
9729 };
9730 ObjCContainerKind getObjCContainerKind() const;
9731
9732 DeclResult actOnObjCTypeParam(Scope *S,
9733 ObjCTypeParamVariance variance,
9734 SourceLocation varianceLoc,
9735 unsigned index,
9736 IdentifierInfo *paramName,
9737 SourceLocation paramLoc,
9738 SourceLocation colonLoc,
9739 ParsedType typeBound);
9740
9741 ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
9742 ArrayRef<Decl *> typeParams,
9743 SourceLocation rAngleLoc);
9744 void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList);
9745
9746 Decl *ActOnStartClassInterface(
9747 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9748 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9749 IdentifierInfo *SuperName, SourceLocation SuperLoc,
9750 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
9751 Decl *const *ProtoRefs, unsigned NumProtoRefs,
9752 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9753 const ParsedAttributesView &AttrList);
9754
9755 void ActOnSuperClassOfClassInterface(Scope *S,
9756 SourceLocation AtInterfaceLoc,
9757 ObjCInterfaceDecl *IDecl,
9758 IdentifierInfo *ClassName,
9759 SourceLocation ClassLoc,
9760 IdentifierInfo *SuperName,
9761 SourceLocation SuperLoc,
9762 ArrayRef<ParsedType> SuperTypeArgs,
9763 SourceRange SuperTypeArgsRange);
9764
9765 void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
9766 SmallVectorImpl<SourceLocation> &ProtocolLocs,
9767 IdentifierInfo *SuperName,
9768 SourceLocation SuperLoc);
9769
9770 Decl *ActOnCompatibilityAlias(
9771 SourceLocation AtCompatibilityAliasLoc,
9772 IdentifierInfo *AliasName, SourceLocation AliasLocation,
9773 IdentifierInfo *ClassName, SourceLocation ClassLocation);
9774
9775 bool CheckForwardProtocolDeclarationForCircularDependency(
9776 IdentifierInfo *PName,
9777 SourceLocation &PLoc, SourceLocation PrevLoc,
9778 const ObjCList<ObjCProtocolDecl> &PList);
9779
9780 Decl *ActOnStartProtocolInterface(
9781 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
9782 SourceLocation ProtocolLoc, Decl *const *ProtoRefNames,
9783 unsigned NumProtoRefs, const SourceLocation *ProtoLocs,
9784 SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList);
9785
9786 Decl *ActOnStartCategoryInterface(
9787 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
9788 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
9789 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
9790 Decl *const *ProtoRefs, unsigned NumProtoRefs,
9791 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
9792 const ParsedAttributesView &AttrList);
9793
9794 Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc,
9795 IdentifierInfo *ClassName,
9796 SourceLocation ClassLoc,
9797 IdentifierInfo *SuperClassname,
9798 SourceLocation SuperClassLoc,
9799 const ParsedAttributesView &AttrList);
9800
9801 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,
9802 IdentifierInfo *ClassName,
9803 SourceLocation ClassLoc,
9804 IdentifierInfo *CatName,
9805 SourceLocation CatLoc,
9806 const ParsedAttributesView &AttrList);
9807
9808 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
9809 ArrayRef<Decl *> Decls);
9810
9811 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc,
9812 IdentifierInfo **IdentList,
9813 SourceLocation *IdentLocs,
9814 ArrayRef<ObjCTypeParamList *> TypeParamLists,
9815 unsigned NumElts);
9816
9817 DeclGroupPtrTy
9818 ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc,
9819 ArrayRef<IdentifierLocPair> IdentList,
9820 const ParsedAttributesView &attrList);
9821
9822 void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
9823 ArrayRef<IdentifierLocPair> ProtocolId,
9824 SmallVectorImpl<Decl *> &Protocols);
9825
9826 void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
9827 SourceLocation ProtocolLoc,
9828 IdentifierInfo *TypeArgId,
9829 SourceLocation TypeArgLoc,
9830 bool SelectProtocolFirst = false);
9831
9832 /// Given a list of identifiers (and their locations), resolve the
9833 /// names to either Objective-C protocol qualifiers or type
9834 /// arguments, as appropriate.
9835 void actOnObjCTypeArgsOrProtocolQualifiers(
9836 Scope *S,
9837 ParsedType baseType,
9838 SourceLocation lAngleLoc,
9839 ArrayRef<IdentifierInfo *> identifiers,
9840 ArrayRef<SourceLocation> identifierLocs,
9841 SourceLocation rAngleLoc,
9842 SourceLocation &typeArgsLAngleLoc,
9843 SmallVectorImpl<ParsedType> &typeArgs,
9844 SourceLocation &typeArgsRAngleLoc,
9845 SourceLocation &protocolLAngleLoc,
9846 SmallVectorImpl<Decl *> &protocols,
9847 SourceLocation &protocolRAngleLoc,
9848 bool warnOnIncompleteProtocols);
9849
9850 /// Build a an Objective-C protocol-qualified 'id' type where no
9851 /// base type was specified.
9852 TypeResult actOnObjCProtocolQualifierType(
9853 SourceLocation lAngleLoc,
9854 ArrayRef<Decl *> protocols,
9855 ArrayRef<SourceLocation> protocolLocs,
9856 SourceLocation rAngleLoc);
9857
9858 /// Build a specialized and/or protocol-qualified Objective-C type.
9859 TypeResult actOnObjCTypeArgsAndProtocolQualifiers(
9860 Scope *S,
9861 SourceLocation Loc,
9862 ParsedType BaseType,
9863 SourceLocation TypeArgsLAngleLoc,
9864 ArrayRef<ParsedType> TypeArgs,
9865 SourceLocation TypeArgsRAngleLoc,
9866 SourceLocation ProtocolLAngleLoc,
9867 ArrayRef<Decl *> Protocols,
9868 ArrayRef<SourceLocation> ProtocolLocs,
9869 SourceLocation ProtocolRAngleLoc);
9870
9871 /// Build an Objective-C type parameter type.
9872 QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
9873 SourceLocation ProtocolLAngleLoc,
9874 ArrayRef<ObjCProtocolDecl *> Protocols,
9875 ArrayRef<SourceLocation> ProtocolLocs,
9876 SourceLocation ProtocolRAngleLoc,
9877 bool FailOnError = false);
9878
9879 /// Build an Objective-C object pointer type.
9880 QualType BuildObjCObjectType(QualType BaseType,
9881 SourceLocation Loc,
9882 SourceLocation TypeArgsLAngleLoc,
9883 ArrayRef<TypeSourceInfo *> TypeArgs,
9884 SourceLocation TypeArgsRAngleLoc,
9885 SourceLocation ProtocolLAngleLoc,
9886 ArrayRef<ObjCProtocolDecl *> Protocols,
9887 ArrayRef<SourceLocation> ProtocolLocs,
9888 SourceLocation ProtocolRAngleLoc,
9889 bool FailOnError = false);
9890
9891 /// Ensure attributes are consistent with type.
9892 /// \param [in, out] Attributes The attributes to check; they will
9893 /// be modified to be consistent with \p PropertyTy.
9894 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy,
9895 SourceLocation Loc,
9896 unsigned &Attributes,
9897 bool propertyInPrimaryClass);
9898
9899 /// Process the specified property declaration and create decls for the
9900 /// setters and getters as needed.
9901 /// \param property The property declaration being processed
9902 void ProcessPropertyDecl(ObjCPropertyDecl *property);
9903
9904
9905 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
9906 ObjCPropertyDecl *SuperProperty,
9907 const IdentifierInfo *Name,
9908 bool OverridingProtocolProperty);
9909
9910 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
9911 ObjCInterfaceDecl *ID);
9912
9913 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd,
9914 ArrayRef<Decl *> allMethods = None,
9915 ArrayRef<DeclGroupPtrTy> allTUVars = None);
9916
9917 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc,
9918 SourceLocation LParenLoc,
9919 FieldDeclarator &FD, ObjCDeclSpec &ODS,
9920 Selector GetterSel, Selector SetterSel,
9921 tok::ObjCKeywordKind MethodImplKind,
9922 DeclContext *lexicalDC = nullptr);
9923
9924 Decl *ActOnPropertyImplDecl(Scope *S,
9925 SourceLocation AtLoc,
9926 SourceLocation PropertyLoc,
9927 bool ImplKind,
9928 IdentifierInfo *PropertyId,
9929 IdentifierInfo *PropertyIvar,
9930 SourceLocation PropertyIvarLoc,
9931 ObjCPropertyQueryKind QueryKind);
9932
9933 enum ObjCSpecialMethodKind {
9934 OSMK_None,
9935 OSMK_Alloc,
9936 OSMK_New,
9937 OSMK_Copy,
9938 OSMK_RetainingInit,
9939 OSMK_NonRetainingInit
9940 };
9941
9942 struct ObjCArgInfo {
9943 IdentifierInfo *Name;
9944 SourceLocation NameLoc;
9945 // The Type is null if no type was specified, and the DeclSpec is invalid
9946 // in this case.
9947 ParsedType Type;
9948 ObjCDeclSpec DeclSpec;
9949
9950 /// ArgAttrs - Attribute list for this argument.
9951 ParsedAttributesView ArgAttrs;
9952 };
9953
9954 Decl *ActOnMethodDeclaration(
9955 Scope *S,
9956 SourceLocation BeginLoc, // location of the + or -.
9957 SourceLocation EndLoc, // location of the ; or {.
9958 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
9959 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
9960 // optional arguments. The number of types/arguments is obtained
9961 // from the Sel.getNumArgs().
9962 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
9963 unsigned CNumArgs, // c-style args
9964 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind,
9965 bool isVariadic, bool MethodDefinition);
9966
9967 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel,
9968 const ObjCObjectPointerType *OPT,
9969 bool IsInstance);
9970 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty,
9971 bool IsInstance);
9972
9973 bool CheckARCMethodDecl(ObjCMethodDecl *method);
9974 bool inferObjCARCLifetime(ValueDecl *decl);
9975
9976 void deduceOpenCLAddressSpace(ValueDecl *decl);
9977
9978 ExprResult
9979 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
9980 Expr *BaseExpr,
9981 SourceLocation OpLoc,
9982 DeclarationName MemberName,
9983 SourceLocation MemberLoc,
9984 SourceLocation SuperLoc, QualType SuperType,
9985 bool Super);
9986
9987 ExprResult
9988 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
9989 IdentifierInfo &propertyName,
9990 SourceLocation receiverNameLoc,
9991 SourceLocation propertyNameLoc);
9992
9993 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc);
9994
9995 /// Describes the kind of message expression indicated by a message
9996 /// send that starts with an identifier.
9997 enum ObjCMessageKind {
9998 /// The message is sent to 'super'.
9999 ObjCSuperMessage,
10000 /// The message is an instance message.
10001 ObjCInstanceMessage,
10002 /// The message is a class message, and the identifier is a type
10003 /// name.
10004 ObjCClassMessage
10005 };
10006
10007 ObjCMessageKind getObjCMessageKind(Scope *S,
10008 IdentifierInfo *Name,
10009 SourceLocation NameLoc,
10010 bool IsSuper,
10011 bool HasTrailingDot,
10012 ParsedType &ReceiverType);
10013
10014 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc,
10015 Selector Sel,
10016 SourceLocation LBracLoc,
10017 ArrayRef<SourceLocation> SelectorLocs,
10018 SourceLocation RBracLoc,
10019 MultiExprArg Args);
10020
10021 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
10022 QualType ReceiverType,
10023 SourceLocation SuperLoc,
10024 Selector Sel,
10025 ObjCMethodDecl *Method,
10026 SourceLocation LBracLoc,
10027 ArrayRef<SourceLocation> SelectorLocs,
10028 SourceLocation RBracLoc,
10029 MultiExprArg Args,
10030 bool isImplicit = false);
10031
10032 ExprResult BuildClassMessageImplicit(QualType ReceiverType,
10033 bool isSuperReceiver,
10034 SourceLocation Loc,
10035 Selector Sel,
10036 ObjCMethodDecl *Method,
10037 MultiExprArg Args);
10038
10039 ExprResult ActOnClassMessage(Scope *S,
10040 ParsedType Receiver,
10041 Selector Sel,
10042 SourceLocation LBracLoc,
10043 ArrayRef<SourceLocation> SelectorLocs,
10044 SourceLocation RBracLoc,
10045 MultiExprArg Args);
10046
10047 ExprResult BuildInstanceMessage(Expr *Receiver,
10048 QualType ReceiverType,
10049 SourceLocation SuperLoc,
10050 Selector Sel,
10051 ObjCMethodDecl *Method,
10052 SourceLocation LBracLoc,
10053 ArrayRef<SourceLocation> SelectorLocs,
10054 SourceLocation RBracLoc,
10055 MultiExprArg Args,
10056 bool isImplicit = false);
10057
10058 ExprResult BuildInstanceMessageImplicit(Expr *Receiver,
10059 QualType ReceiverType,
10060 SourceLocation Loc,
10061 Selector Sel,
10062 ObjCMethodDecl *Method,
10063 MultiExprArg Args);
10064
10065 ExprResult ActOnInstanceMessage(Scope *S,
10066 Expr *Receiver,
10067 Selector Sel,
10068 SourceLocation LBracLoc,
10069 ArrayRef<SourceLocation> SelectorLocs,
10070 SourceLocation RBracLoc,
10071 MultiExprArg Args);
10072
10073 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc,
10074 ObjCBridgeCastKind Kind,
10075 SourceLocation BridgeKeywordLoc,
10076 TypeSourceInfo *TSInfo,
10077 Expr *SubExpr);
10078
10079 ExprResult ActOnObjCBridgedCast(Scope *S,
10080 SourceLocation LParenLoc,
10081 ObjCBridgeCastKind Kind,
10082 SourceLocation BridgeKeywordLoc,
10083 ParsedType Type,
10084 SourceLocation RParenLoc,
10085 Expr *SubExpr);
10086
10087 void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr);
10088
10089 void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr);
10090
10091 bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
10092 CastKind &Kind);
10093
10094 bool checkObjCBridgeRelatedComponents(SourceLocation Loc,
10095 QualType DestType, QualType SrcType,
10096 ObjCInterfaceDecl *&RelatedClass,
10097 ObjCMethodDecl *&ClassMethod,
10098 ObjCMethodDecl *&InstanceMethod,
10099 TypedefNameDecl *&TDNDecl,
10100 bool CfToNs, bool Diagnose = true);
10101
10102 bool CheckObjCBridgeRelatedConversions(SourceLocation Loc,
10103 QualType DestType, QualType SrcType,
10104 Expr *&SrcExpr, bool Diagnose = true);
10105
10106 bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr,
10107 bool Diagnose = true);
10108
10109 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall);
10110
10111 /// Check whether the given new method is a valid override of the
10112 /// given overridden method, and set any properties that should be inherited.
10113 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
10114 const ObjCMethodDecl *Overridden);
10115
10116 /// Describes the compatibility of a result type with its method.
10117 enum ResultTypeCompatibilityKind {
10118 RTC_Compatible,
10119 RTC_Incompatible,
10120 RTC_Unknown
10121 };
10122
10123 void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
10124 ObjCMethodDecl *overridden);
10125
10126 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
10127 ObjCInterfaceDecl *CurrentClass,
10128 ResultTypeCompatibilityKind RTC);
10129
10130 enum PragmaOptionsAlignKind {
10131 POAK_Native, // #pragma options align=native
10132 POAK_Natural, // #pragma options align=natural
10133 POAK_Packed, // #pragma options align=packed
10134 POAK_Power, // #pragma options align=power
10135 POAK_Mac68k, // #pragma options align=mac68k
10136 POAK_Reset // #pragma options align=reset
10137 };
10138
10139 /// ActOnPragmaClangSection - Called on well formed \#pragma clang section
10140 void ActOnPragmaClangSection(SourceLocation PragmaLoc,
10141 PragmaClangSectionAction Action,
10142 PragmaClangSectionKind SecKind, StringRef SecName);
10143
10144 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align.
10145 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind,
10146 SourceLocation PragmaLoc);
10147
10148 /// ActOnPragmaPack - Called on well formed \#pragma pack(...).
10149 void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action,
10150 StringRef SlotLabel, Expr *Alignment);
10151
10152 enum class PragmaAlignPackDiagnoseKind {
10153 NonDefaultStateAtInclude,
10154 ChangedStateAtExit
10155 };
10156
10157 void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind,
10158 SourceLocation IncludeLoc);
10159 void DiagnoseUnterminatedPragmaAlignPack();
10160
10161 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off].
10162 void ActOnPragmaMSStruct(PragmaMSStructKind Kind);
10163
10164 /// ActOnPragmaMSComment - Called on well formed
10165 /// \#pragma comment(kind, "arg").
10166 void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind,
10167 StringRef Arg);
10168
10169 /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma
10170 /// pointers_to_members(representation method[, general purpose
10171 /// representation]).
10172 void ActOnPragmaMSPointersToMembers(
10173 LangOptions::PragmaMSPointersToMembersKind Kind,
10174 SourceLocation PragmaLoc);
10175
10176 /// Called on well formed \#pragma vtordisp().
10177 void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action,
10178 SourceLocation PragmaLoc,
10179 MSVtorDispMode Value);
10180
10181 enum PragmaSectionKind {
10182 PSK_DataSeg,
10183 PSK_BSSSeg,
10184 PSK_ConstSeg,
10185 PSK_CodeSeg,
10186 };
10187
10188 bool UnifySection(StringRef SectionName, int SectionFlags,
10189 NamedDecl *TheDecl);
10190 bool UnifySection(StringRef SectionName,
10191 int SectionFlags,
10192 SourceLocation PragmaSectionLocation);
10193
10194 /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg.
10195 void ActOnPragmaMSSeg(SourceLocation PragmaLocation,
10196 PragmaMsStackAction Action,
10197 llvm::StringRef StackSlotLabel,
10198 StringLiteral *SegmentName,
10199 llvm::StringRef PragmaName);
10200
10201 /// Called on well formed \#pragma section().
10202 void ActOnPragmaMSSection(SourceLocation PragmaLocation,
10203 int SectionFlags, StringLiteral *SegmentName);
10204
10205 /// Called on well-formed \#pragma init_seg().
10206 void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation,
10207 StringLiteral *SegmentName);
10208
10209 /// Called on #pragma clang __debug dump II
10210 void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II);
10211
10212 /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch
10213 void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name,
10214 StringRef Value);
10215
10216 /// Are precise floating point semantics currently enabled?
10217 bool isPreciseFPEnabled() {
10218 return !CurFPFeatures.getAllowFPReassociate() &&
10219 !CurFPFeatures.getNoSignedZero() &&
10220 !CurFPFeatures.getAllowReciprocal() &&
10221 !CurFPFeatures.getAllowApproxFunc();
10222 }
10223
10224 void ActOnPragmaFPEvalMethod(SourceLocation Loc,
10225 LangOptions::FPEvalMethodKind Value);
10226
10227 /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control
10228 void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action,
10229 PragmaFloatControlKind Value);
10230
10231 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'.
10232 void ActOnPragmaUnused(const Token &Identifier,
10233 Scope *curScope,
10234 SourceLocation PragmaLoc);
10235
10236 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... .
10237 void ActOnPragmaVisibility(const IdentifierInfo* VisType,
10238 SourceLocation PragmaLoc);
10239
10240 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, const IdentifierInfo *II,
10241 SourceLocation Loc);
10242 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, const WeakInfo &W);
10243
10244 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident.
10245 void ActOnPragmaWeakID(IdentifierInfo* WeakName,
10246 SourceLocation PragmaLoc,
10247 SourceLocation WeakNameLoc);
10248
10249 /// ActOnPragmaRedefineExtname - Called on well formed
10250 /// \#pragma redefine_extname oldname newname.
10251 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName,
10252 IdentifierInfo* AliasName,
10253 SourceLocation PragmaLoc,
10254 SourceLocation WeakNameLoc,
10255 SourceLocation AliasNameLoc);
10256
10257 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident.
10258 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName,
10259 IdentifierInfo* AliasName,
10260 SourceLocation PragmaLoc,
10261 SourceLocation WeakNameLoc,
10262 SourceLocation AliasNameLoc);
10263
10264 /// ActOnPragmaFPContract - Called on well formed
10265 /// \#pragma {STDC,OPENCL} FP_CONTRACT and
10266 /// \#pragma clang fp contract
10267 void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC);
10268
10269 /// Called on well formed
10270 /// \#pragma clang fp reassociate
10271 void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled);
10272
10273 /// ActOnPragmaFenvAccess - Called on well formed
10274 /// \#pragma STDC FENV_ACCESS
10275 void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled);
10276
10277 /// Called on well formed '\#pragma clang fp' that has option 'exceptions'.
10278 void ActOnPragmaFPExceptions(SourceLocation Loc,
10279 LangOptions::FPExceptionModeKind);
10280
10281 /// Called to set constant rounding mode for floating point operations.
10282 void setRoundingMode(SourceLocation Loc, llvm::RoundingMode);
10283
10284 /// Called to set exception behavior for floating point operations.
10285 void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind);
10286
10287 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to
10288 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'.
10289 void AddAlignmentAttributesForRecord(RecordDecl *RD);
10290
10291 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record.
10292 void AddMsStructLayoutForRecord(RecordDecl *RD);
10293
10294 /// PushNamespaceVisibilityAttr - Note that we've entered a
10295 /// namespace with a visibility attribute.
10296 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr,
10297 SourceLocation Loc);
10298
10299 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used,
10300 /// add an appropriate visibility attribute.
10301 void AddPushedVisibilityAttribute(Decl *RD);
10302
10303 /// PopPragmaVisibility - Pop the top element of the visibility stack; used
10304 /// for '\#pragma GCC visibility' and visibility attributes on namespaces.
10305 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc);
10306
10307 /// FreeVisContext - Deallocate and null out VisContext.
10308 void FreeVisContext();
10309
10310 /// AddCFAuditedAttribute - Check whether we're currently within
10311 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding
10312 /// the appropriate attribute.
10313 void AddCFAuditedAttribute(Decl *D);
10314
10315 void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute,
10316 SourceLocation PragmaLoc,
10317 attr::ParsedSubjectMatchRuleSet Rules);
10318 void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc,
10319 const IdentifierInfo *Namespace);
10320
10321 /// Called on well-formed '\#pragma clang attribute pop'.
10322 void ActOnPragmaAttributePop(SourceLocation PragmaLoc,
10323 const IdentifierInfo *Namespace);
10324
10325 /// Adds the attributes that have been specified using the
10326 /// '\#pragma clang attribute push' directives to the given declaration.
10327 void AddPragmaAttributes(Scope *S, Decl *D);
10328
10329 void DiagnoseUnterminatedPragmaAttribute();
10330
10331 /// Called on well formed \#pragma clang optimize.
10332 void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc);
10333
10334 /// Get the location for the currently active "\#pragma clang optimize
10335 /// off". If this location is invalid, then the state of the pragma is "on".
10336 SourceLocation getOptimizeOffPragmaLocation() const {
10337 return OptimizeOffPragmaLocation;
10338 }
10339
10340 /// Only called on function definitions; if there is a pragma in scope
10341 /// with the effect of a range-based optnone, consider marking the function
10342 /// with attribute optnone.
10343 void AddRangeBasedOptnone(FunctionDecl *FD);
10344
10345 /// Adds the 'optnone' attribute to the function declaration if there
10346 /// are no conflicts; Loc represents the location causing the 'optnone'
10347 /// attribute to be added (usually because of a pragma).
10348 void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc);
10349
10350 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration.
10351 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10352 bool IsPackExpansion);
10353 void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T,
10354 bool IsPackExpansion);
10355
10356 /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular
10357 /// declaration.
10358 void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E,
10359 Expr *OE);
10360
10361 /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular
10362 /// declaration.
10363 void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI,
10364 Expr *ParamExpr);
10365
10366 /// AddAlignValueAttr - Adds an align_value attribute to a particular
10367 /// declaration.
10368 void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E);
10369
10370 /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D.
10371 void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI,
10372 StringRef Annot, MutableArrayRef<Expr *> Args);
10373
10374 /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular
10375 /// declaration.
10376 void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI,
10377 Expr *MaxThreads, Expr *MinBlocks);
10378
10379 /// AddModeAttr - Adds a mode attribute to a particular declaration.
10380 void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name,
10381 bool InInstantiation = false);
10382
10383 void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI,
10384 ParameterABI ABI);
10385
10386 enum class RetainOwnershipKind {NS, CF, OS};
10387 void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI,
10388 RetainOwnershipKind K, bool IsTemplateInstantiation);
10389
10390 /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size
10391 /// attribute to a particular declaration.
10392 void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI,
10393 Expr *Min, Expr *Max);
10394
10395 /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a
10396 /// particular declaration.
10397 void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI,
10398 Expr *Min, Expr *Max);
10399
10400 bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type);
10401
10402 //===--------------------------------------------------------------------===//
10403 // C++ Coroutines TS
10404 //
10405 bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc,
10406 StringRef Keyword);
10407 ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10408 ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E);
10409 StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E);
10410
10411 ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10412 bool IsImplicit = false);
10413 ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E,
10414 UnresolvedLookupExpr* Lookup);
10415 ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E);
10416 StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E,
10417 bool IsImplicit = false);
10418 StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs);
10419 bool buildCoroutineParameterMoves(SourceLocation Loc);
10420 VarDecl *buildCoroutinePromise(SourceLocation Loc);
10421 void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body);
10422 /// Lookup 'coroutine_traits' in std namespace and std::experimental
10423 /// namespace. The namespace found is recorded in Namespace.
10424 ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc,
10425 SourceLocation FuncLoc,
10426 NamespaceDecl *&Namespace);
10427 /// Check that the expression co_await promise.final_suspend() shall not be
10428 /// potentially-throwing.
10429 bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend);
10430
10431 //===--------------------------------------------------------------------===//
10432 // OpenMP directives and clauses.
10433 //
10434private:
10435 void *VarDataSharingAttributesStack;
10436
10437 struct DeclareTargetContextInfo {
10438 struct MapInfo {
10439 OMPDeclareTargetDeclAttr::MapTypeTy MT;
10440 SourceLocation Loc;
10441 };
10442 /// Explicitly listed variables and functions in a 'to' or 'link' clause.
10443 llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped;
10444
10445 /// The 'device_type' as parsed from the clause.
10446 OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any;
10447
10448 /// The directive kind, `begin declare target` or `declare target`.
10449 OpenMPDirectiveKind Kind;
10450
10451 /// The directive with indirect clause.
10452 Optional<Expr *> Indirect;
10453
10454 /// The directive location.
10455 SourceLocation Loc;
10456
10457 DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc)
10458 : Kind(Kind), Loc(Loc) {}
10459 };
10460
10461 /// Number of nested '#pragma omp declare target' directives.
10462 SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting;
10463
10464 /// Initialization of data-sharing attributes stack.
10465 void InitDataSharingAttributesStack();
10466 void DestroyDataSharingAttributesStack();
10467 ExprResult
10468 VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind,
10469 bool StrictlyPositive = true,
10470 bool SuppressExprDiags = false);
10471 /// Returns OpenMP nesting level for current directive.
10472 unsigned getOpenMPNestingLevel() const;
10473
10474 /// Adjusts the function scopes index for the target-based regions.
10475 void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
10476 unsigned Level) const;
10477
10478 /// Returns the number of scopes associated with the construct on the given
10479 /// OpenMP level.
10480 int getNumberOfConstructScopes(unsigned Level) const;
10481
10482 /// Push new OpenMP function region for non-capturing function.
10483 void pushOpenMPFunctionRegion();
10484
10485 /// Pop OpenMP function region for non-capturing function.
10486 void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI);
10487
10488 /// Analyzes and checks a loop nest for use by a loop transformation.
10489 ///
10490 /// \param Kind The loop transformation directive kind.
10491 /// \param NumLoops How many nested loops the directive is expecting.
10492 /// \param AStmt Associated statement of the transformation directive.
10493 /// \param LoopHelpers [out] The loop analysis result.
10494 /// \param Body [out] The body code nested in \p NumLoops loop.
10495 /// \param OriginalInits [out] Collection of statements and declarations that
10496 /// must have been executed/declared before entering the
10497 /// loop.
10498 ///
10499 /// \return Whether there was any error.
10500 bool checkTransformableLoopNest(
10501 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops,
10502 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers,
10503 Stmt *&Body,
10504 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>>
10505 &OriginalInits);
10506
10507 /// Helper to keep information about the current `omp begin/end declare
10508 /// variant` nesting.
10509 struct OMPDeclareVariantScope {
10510 /// The associated OpenMP context selector.
10511 OMPTraitInfo *TI;
10512
10513 /// The associated OpenMP context selector mangling.
10514 std::string NameSuffix;
10515
10516 OMPDeclareVariantScope(OMPTraitInfo &TI);
10517 };
10518
10519 /// Return the OMPTraitInfo for the surrounding scope, if any.
10520 OMPTraitInfo *getOMPTraitInfoForSurroundingScope() {
10521 return OMPDeclareVariantScopes.empty() ? nullptr
10522 : OMPDeclareVariantScopes.back().TI;
10523 }
10524
10525 /// The current `omp begin/end declare variant` scopes.
10526 SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes;
10527
10528 /// The current `omp begin/end assumes` scopes.
10529 SmallVector<AssumptionAttr *, 4> OMPAssumeScoped;
10530
10531 /// All `omp assumes` we encountered so far.
10532 SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal;
10533
10534public:
10535 /// The declarator \p D defines a function in the scope \p S which is nested
10536 /// in an `omp begin/end declare variant` scope. In this method we create a
10537 /// declaration for \p D and rename \p D according to the OpenMP context
10538 /// selector of the surrounding scope. Return all base functions in \p Bases.
10539 void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
10540 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists,
10541 SmallVectorImpl<FunctionDecl *> &Bases);
10542
10543 /// Register \p D as specialization of all base functions in \p Bases in the
10544 /// current `omp begin/end declare variant` scope.
10545 void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(
10546 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases);
10547
10548 /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`.
10549 void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D);
10550
10551 /// Can we exit an OpenMP declare variant scope at the moment.
10552 bool isInOpenMPDeclareVariantScope() const {
10553 return !OMPDeclareVariantScopes.empty();
10554 }
10555
10556 /// Given the potential call expression \p Call, determine if there is a
10557 /// specialization via the OpenMP declare variant mechanism available. If
10558 /// there is, return the specialized call expression, otherwise return the
10559 /// original \p Call.
10560 ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope,
10561 SourceLocation LParenLoc, MultiExprArg ArgExprs,
10562 SourceLocation RParenLoc, Expr *ExecConfig);
10563
10564 /// Handle a `omp begin declare variant`.
10565 void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI);
10566
10567 /// Handle a `omp end declare variant`.
10568 void ActOnOpenMPEndDeclareVariant();
10569
10570 /// Checks if the variant/multiversion functions are compatible.
10571 bool areMultiversionVariantFunctionsCompatible(
10572 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10573 const PartialDiagnostic &NoProtoDiagID,
10574 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10575 const PartialDiagnosticAt &NoSupportDiagIDAt,
10576 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10577 bool ConstexprSupported, bool CLinkageMayDiffer);
10578
10579 /// Function tries to capture lambda's captured variables in the OpenMP region
10580 /// before the original lambda is captured.
10581 void tryCaptureOpenMPLambdas(ValueDecl *V);
10582
10583 /// Return true if the provided declaration \a VD should be captured by
10584 /// reference.
10585 /// \param Level Relative level of nested OpenMP construct for that the check
10586 /// is performed.
10587 /// \param OpenMPCaptureLevel Capture level within an OpenMP construct.
10588 bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
10589 unsigned OpenMPCaptureLevel) const;
10590
10591 /// Check if the specified variable is used in one of the private
10592 /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP
10593 /// constructs.
10594 VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false,
10595 unsigned StopAt = 0);
10596 ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
10597 ExprObjectKind OK, SourceLocation Loc);
10598
10599 /// If the current region is a loop-based region, mark the start of the loop
10600 /// construct.
10601 void startOpenMPLoop();
10602
10603 /// If the current region is a range loop-based region, mark the start of the
10604 /// loop construct.
10605 void startOpenMPCXXRangeFor();
10606
10607 /// Check if the specified variable is used in 'private' clause.
10608 /// \param Level Relative level of nested OpenMP construct for that the check
10609 /// is performed.
10610 OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level,
10611 unsigned CapLevel) const;
10612
10613 /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.)
10614 /// for \p FD based on DSA for the provided corresponding captured declaration
10615 /// \p D.
10616 void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level);
10617
10618 /// Check if the specified variable is captured by 'target' directive.
10619 /// \param Level Relative level of nested OpenMP construct for that the check
10620 /// is performed.
10621 bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
10622 unsigned CaptureLevel) const;
10623
10624 /// Check if the specified global variable must be captured by outer capture
10625 /// regions.
10626 /// \param Level Relative level of nested OpenMP construct for that
10627 /// the check is performed.
10628 bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level,
10629 unsigned CaptureLevel) const;
10630
10631 ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc,
10632 Expr *Op);
10633 /// Called on start of new data sharing attribute block.
10634 void StartOpenMPDSABlock(OpenMPDirectiveKind K,
10635 const DeclarationNameInfo &DirName, Scope *CurScope,
10636 SourceLocation Loc);
10637 /// Start analysis of clauses.
10638 void StartOpenMPClause(OpenMPClauseKind K);
10639 /// End analysis of clauses.
10640 void EndOpenMPClause();
10641 /// Called on end of data sharing attribute block.
10642 void EndOpenMPDSABlock(Stmt *CurDirective);
10643
10644 /// Check if the current region is an OpenMP loop region and if it is,
10645 /// mark loop control variable, used in \p Init for loop initialization, as
10646 /// private by default.
10647 /// \param Init First part of the for loop.
10648 void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init);
10649
10650 /// Called on well-formed '\#pragma omp metadirective' after parsing
10651 /// of the associated statement.
10652 StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses,
10653 Stmt *AStmt, SourceLocation StartLoc,
10654 SourceLocation EndLoc);
10655
10656 // OpenMP directives and clauses.
10657 /// Called on correct id-expression from the '#pragma omp
10658 /// threadprivate'.
10659 ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec,
10660 const DeclarationNameInfo &Id,
10661 OpenMPDirectiveKind Kind);
10662 /// Called on well-formed '#pragma omp threadprivate'.
10663 DeclGroupPtrTy ActOnOpenMPThreadprivateDirective(
10664 SourceLocation Loc,
10665 ArrayRef<Expr *> VarList);
10666 /// Builds a new OpenMPThreadPrivateDecl and checks its correctness.
10667 OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc,
10668 ArrayRef<Expr *> VarList);
10669 /// Called on well-formed '#pragma omp allocate'.
10670 DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc,
10671 ArrayRef<Expr *> VarList,
10672 ArrayRef<OMPClause *> Clauses,
10673 DeclContext *Owner = nullptr);
10674
10675 /// Called on well-formed '#pragma omp [begin] assume[s]'.
10676 void ActOnOpenMPAssumesDirective(SourceLocation Loc,
10677 OpenMPDirectiveKind DKind,
10678 ArrayRef<std::string> Assumptions,
10679 bool SkippedClauses);
10680
10681 /// Check if there is an active global `omp begin assumes` directive.
10682 bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); }
10683
10684 /// Check if there is an active global `omp assumes` directive.
10685 bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); }
10686
10687 /// Called on well-formed '#pragma omp end assumes'.
10688 void ActOnOpenMPEndAssumesDirective();
10689
10690 /// Called on well-formed '#pragma omp requires'.
10691 DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc,
10692 ArrayRef<OMPClause *> ClauseList);
10693 /// Check restrictions on Requires directive
10694 OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc,
10695 ArrayRef<OMPClause *> Clauses);
10696 /// Check if the specified type is allowed to be used in 'omp declare
10697 /// reduction' construct.
10698 QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
10699 TypeResult ParsedType);
10700 /// Called on start of '#pragma omp declare reduction'.
10701 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart(
10702 Scope *S, DeclContext *DC, DeclarationName Name,
10703 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
10704 AccessSpecifier AS, Decl *PrevDeclInScope = nullptr);
10705 /// Initialize declare reduction construct initializer.
10706 void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D);
10707 /// Finish current declare reduction construct initializer.
10708 void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner);
10709 /// Initialize declare reduction construct initializer.
10710 /// \return omp_priv variable.
10711 VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D);
10712 /// Finish current declare reduction construct initializer.
10713 void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
10714 VarDecl *OmpPrivParm);
10715 /// Called at the end of '#pragma omp declare reduction'.
10716 DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd(
10717 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid);
10718
10719 /// Check variable declaration in 'omp declare mapper' construct.
10720 TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D);
10721 /// Check if the specified type is allowed to be used in 'omp declare
10722 /// mapper' construct.
10723 QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
10724 TypeResult ParsedType);
10725 /// Called on start of '#pragma omp declare mapper'.
10726 DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective(
10727 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
10728 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
10729 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses,
10730 Decl *PrevDeclInScope = nullptr);
10731 /// Build the mapper variable of '#pragma omp declare mapper'.
10732 ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S,
10733 QualType MapperType,
10734 SourceLocation StartLoc,
10735 DeclarationName VN);
10736 bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const;
10737 const ValueDecl *getOpenMPDeclareMapperVarName() const;
10738
10739 /// Called on the start of target region i.e. '#pragma omp declare target'.
10740 bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10741
10742 /// Called at the end of target region i.e. '#pragma omp end declare target'.
10743 const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective();
10744
10745 /// Called once a target context is completed, that can be when a
10746 /// '#pragma omp end declare target' was encountered or when a
10747 /// '#pragma omp declare target' without declaration-definition-seq was
10748 /// encountered.
10749 void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI);
10750
10751 /// Searches for the provided declaration name for OpenMP declare target
10752 /// directive.
10753 NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope,
10754 CXXScopeSpec &ScopeSpec,
10755 const DeclarationNameInfo &Id);
10756
10757 /// Called on correct id-expression from the '#pragma omp declare target'.
10758 void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc,
10759 OMPDeclareTargetDeclAttr::MapTypeTy MT,
10760 DeclareTargetContextInfo &DTCI);
10761
10762 /// Check declaration inside target region.
10763 void
10764 checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
10765 SourceLocation IdLoc = SourceLocation());
10766 /// Finishes analysis of the deferred functions calls that may be declared as
10767 /// host/nohost during device/host compilation.
10768 void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller,
10769 const FunctionDecl *Callee,
10770 SourceLocation Loc);
10771
10772 /// Return true if currently in OpenMP task with untied clause context.
10773 bool isInOpenMPTaskUntiedContext() const;
10774
10775 /// Return true inside OpenMP declare target region.
10776 bool isInOpenMPDeclareTargetContext() const {
10777 return !DeclareTargetNesting.empty();
10778 }
10779 /// Return true inside OpenMP target region.
10780 bool isInOpenMPTargetExecutionDirective() const;
10781
10782 /// Return the number of captured regions created for an OpenMP directive.
10783 static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind);
10784
10785 /// Initialization of captured region for OpenMP region.
10786 void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope);
10787
10788 /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to
10789 /// an OpenMP loop directive.
10790 StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt);
10791
10792 /// Process a canonical OpenMP loop nest that can either be a canonical
10793 /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an
10794 /// OpenMP loop transformation construct.
10795 StmtResult ActOnOpenMPLoopnest(Stmt *AStmt);
10796
10797 /// End of OpenMP region.
10798 ///
10799 /// \param S Statement associated with the current OpenMP region.
10800 /// \param Clauses List of clauses for the current OpenMP region.
10801 ///
10802 /// \returns Statement for finished OpenMP region.
10803 StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses);
10804 StmtResult ActOnOpenMPExecutableDirective(
10805 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
10806 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
10807 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc);
10808 /// Called on well-formed '\#pragma omp parallel' after parsing
10809 /// of the associated statement.
10810 StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
10811 Stmt *AStmt,
10812 SourceLocation StartLoc,
10813 SourceLocation EndLoc);
10814 using VarsWithInheritedDSAType =
10815 llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>;
10816 /// Called on well-formed '\#pragma omp simd' after parsing
10817 /// of the associated statement.
10818 StmtResult
10819 ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10820 SourceLocation StartLoc, SourceLocation EndLoc,
10821 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10822 /// Called on well-formed '#pragma omp tile' after parsing of its clauses and
10823 /// the associated statement.
10824 StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses,
10825 Stmt *AStmt, SourceLocation StartLoc,
10826 SourceLocation EndLoc);
10827 /// Called on well-formed '#pragma omp unroll' after parsing of its clauses
10828 /// and the associated statement.
10829 StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses,
10830 Stmt *AStmt, SourceLocation StartLoc,
10831 SourceLocation EndLoc);
10832 /// Called on well-formed '\#pragma omp for' after parsing
10833 /// of the associated statement.
10834 StmtResult
10835 ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10836 SourceLocation StartLoc, SourceLocation EndLoc,
10837 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10838 /// Called on well-formed '\#pragma omp for simd' after parsing
10839 /// of the associated statement.
10840 StmtResult
10841 ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
10842 SourceLocation StartLoc, SourceLocation EndLoc,
10843 VarsWithInheritedDSAType &VarsWithImplicitDSA);
10844 /// Called on well-formed '\#pragma omp sections' after parsing
10845 /// of the associated statement.
10846 StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
10847 Stmt *AStmt, SourceLocation StartLoc,
10848 SourceLocation EndLoc);
10849 /// Called on well-formed '\#pragma omp section' after parsing of the
10850 /// associated statement.
10851 StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc,
10852 SourceLocation EndLoc);
10853 /// Called on well-formed '\#pragma omp single' after parsing of the
10854 /// associated statement.
10855 StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
10856 Stmt *AStmt, SourceLocation StartLoc,
10857 SourceLocation EndLoc);
10858 /// Called on well-formed '\#pragma omp master' after parsing of the
10859 /// associated statement.
10860 StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc,
10861 SourceLocation EndLoc);
10862 /// Called on well-formed '\#pragma omp critical' after parsing of the
10863 /// associated statement.
10864 StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName,
10865 ArrayRef<OMPClause *> Clauses,
10866 Stmt *AStmt, SourceLocation StartLoc,
10867 SourceLocation EndLoc);
10868 /// Called on well-formed '\#pragma omp parallel for' after parsing
10869 /// of the associated statement.
10870 StmtResult ActOnOpenMPParallelForDirective(
10871 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10872 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10873 /// Called on well-formed '\#pragma omp parallel for simd' after
10874 /// parsing of the associated statement.
10875 StmtResult ActOnOpenMPParallelForSimdDirective(
10876 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10877 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10878 /// Called on well-formed '\#pragma omp parallel master' after
10879 /// parsing of the associated statement.
10880 StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
10881 Stmt *AStmt,
10882 SourceLocation StartLoc,
10883 SourceLocation EndLoc);
10884 /// Called on well-formed '\#pragma omp parallel sections' after
10885 /// parsing of the associated statement.
10886 StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
10887 Stmt *AStmt,
10888 SourceLocation StartLoc,
10889 SourceLocation EndLoc);
10890 /// Called on well-formed '\#pragma omp task' after parsing of the
10891 /// associated statement.
10892 StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
10893 Stmt *AStmt, SourceLocation StartLoc,
10894 SourceLocation EndLoc);
10895 /// Called on well-formed '\#pragma omp taskyield'.
10896 StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
10897 SourceLocation EndLoc);
10898 /// Called on well-formed '\#pragma omp barrier'.
10899 StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
10900 SourceLocation EndLoc);
10901 /// Called on well-formed '\#pragma omp taskwait'.
10902 StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses,
10903 SourceLocation StartLoc,
10904 SourceLocation EndLoc);
10905 /// Called on well-formed '\#pragma omp taskgroup'.
10906 StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
10907 Stmt *AStmt, SourceLocation StartLoc,
10908 SourceLocation EndLoc);
10909 /// Called on well-formed '\#pragma omp flush'.
10910 StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
10911 SourceLocation StartLoc,
10912 SourceLocation EndLoc);
10913 /// Called on well-formed '\#pragma omp depobj'.
10914 StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses,
10915 SourceLocation StartLoc,
10916 SourceLocation EndLoc);
10917 /// Called on well-formed '\#pragma omp scan'.
10918 StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses,
10919 SourceLocation StartLoc,
10920 SourceLocation EndLoc);
10921 /// Called on well-formed '\#pragma omp ordered' after parsing of the
10922 /// associated statement.
10923 StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
10924 Stmt *AStmt, SourceLocation StartLoc,
10925 SourceLocation EndLoc);
10926 /// Called on well-formed '\#pragma omp atomic' after parsing of the
10927 /// associated statement.
10928 StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
10929 Stmt *AStmt, SourceLocation StartLoc,
10930 SourceLocation EndLoc);
10931 /// Called on well-formed '\#pragma omp target' after parsing of the
10932 /// associated statement.
10933 StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
10934 Stmt *AStmt, SourceLocation StartLoc,
10935 SourceLocation EndLoc);
10936 /// Called on well-formed '\#pragma omp target data' after parsing of
10937 /// the associated statement.
10938 StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
10939 Stmt *AStmt, SourceLocation StartLoc,
10940 SourceLocation EndLoc);
10941 /// Called on well-formed '\#pragma omp target enter data' after
10942 /// parsing of the associated statement.
10943 StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
10944 SourceLocation StartLoc,
10945 SourceLocation EndLoc,
10946 Stmt *AStmt);
10947 /// Called on well-formed '\#pragma omp target exit data' after
10948 /// parsing of the associated statement.
10949 StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
10950 SourceLocation StartLoc,
10951 SourceLocation EndLoc,
10952 Stmt *AStmt);
10953 /// Called on well-formed '\#pragma omp target parallel' after
10954 /// parsing of the associated statement.
10955 StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
10956 Stmt *AStmt,
10957 SourceLocation StartLoc,
10958 SourceLocation EndLoc);
10959 /// Called on well-formed '\#pragma omp target parallel for' after
10960 /// parsing of the associated statement.
10961 StmtResult ActOnOpenMPTargetParallelForDirective(
10962 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10963 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10964 /// Called on well-formed '\#pragma omp teams' after parsing of the
10965 /// associated statement.
10966 StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
10967 Stmt *AStmt, SourceLocation StartLoc,
10968 SourceLocation EndLoc);
10969 /// Called on well-formed '\#pragma omp teams loop' after parsing of the
10970 /// associated statement.
10971 StmtResult ActOnOpenMPTeamsGenericLoopDirective(
10972 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10973 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10974 /// Called on well-formed '\#pragma omp target teams loop' after parsing of
10975 /// the associated statement.
10976 StmtResult ActOnOpenMPTargetTeamsGenericLoopDirective(
10977 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10978 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10979 /// Called on well-formed '\#pragma omp parallel loop' after parsing of the
10980 /// associated statement.
10981 StmtResult ActOnOpenMPParallelGenericLoopDirective(
10982 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10983 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10984 /// Called on well-formed '\#pragma omp target parallel loop' after parsing
10985 /// of the associated statement.
10986 StmtResult ActOnOpenMPTargetParallelGenericLoopDirective(
10987 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
10988 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
10989 /// Called on well-formed '\#pragma omp cancellation point'.
10990 StmtResult
10991 ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
10992 SourceLocation EndLoc,
10993 OpenMPDirectiveKind CancelRegion);
10994 /// Called on well-formed '\#pragma omp cancel'.
10995 StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
10996 SourceLocation StartLoc,
10997 SourceLocation EndLoc,
10998 OpenMPDirectiveKind CancelRegion);
10999 /// Called on well-formed '\#pragma omp taskloop' after parsing of the
11000 /// associated statement.
11001 StmtResult
11002 ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11003 SourceLocation StartLoc, SourceLocation EndLoc,
11004 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11005 /// Called on well-formed '\#pragma omp taskloop simd' after parsing of
11006 /// the associated statement.
11007 StmtResult ActOnOpenMPTaskLoopSimdDirective(
11008 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11009 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11010 /// Called on well-formed '\#pragma omp master taskloop' after parsing of the
11011 /// associated statement.
11012 StmtResult ActOnOpenMPMasterTaskLoopDirective(
11013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11014 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11015 /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of
11016 /// the associated statement.
11017 StmtResult ActOnOpenMPMasterTaskLoopSimdDirective(
11018 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11019 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11020 /// Called on well-formed '\#pragma omp parallel master taskloop' after
11021 /// parsing of the associated statement.
11022 StmtResult ActOnOpenMPParallelMasterTaskLoopDirective(
11023 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11024 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11025 /// Called on well-formed '\#pragma omp parallel master taskloop simd' after
11026 /// parsing of the associated statement.
11027 StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective(
11028 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11029 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11030 /// Called on well-formed '\#pragma omp distribute' after parsing
11031 /// of the associated statement.
11032 StmtResult
11033 ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11034 SourceLocation StartLoc, SourceLocation EndLoc,
11035 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11036 /// Called on well-formed '\#pragma omp target update'.
11037 StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
11038 SourceLocation StartLoc,
11039 SourceLocation EndLoc,
11040 Stmt *AStmt);
11041 /// Called on well-formed '\#pragma omp distribute parallel for' after
11042 /// parsing of the associated statement.
11043 StmtResult ActOnOpenMPDistributeParallelForDirective(
11044 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11045 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11046 /// Called on well-formed '\#pragma omp distribute parallel for simd'
11047 /// after parsing of the associated statement.
11048 StmtResult ActOnOpenMPDistributeParallelForSimdDirective(
11049 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11050 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11051 /// Called on well-formed '\#pragma omp distribute simd' after
11052 /// parsing of the associated statement.
11053 StmtResult ActOnOpenMPDistributeSimdDirective(
11054 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11055 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11056 /// Called on well-formed '\#pragma omp target parallel for simd' after
11057 /// parsing of the associated statement.
11058 StmtResult ActOnOpenMPTargetParallelForSimdDirective(
11059 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11060 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11061 /// Called on well-formed '\#pragma omp target simd' after parsing of
11062 /// the associated statement.
11063 StmtResult
11064 ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
11065 SourceLocation StartLoc, SourceLocation EndLoc,
11066 VarsWithInheritedDSAType &VarsWithImplicitDSA);
11067 /// Called on well-formed '\#pragma omp teams distribute' after parsing of
11068 /// the associated statement.
11069 StmtResult ActOnOpenMPTeamsDistributeDirective(
11070 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11071 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11072 /// Called on well-formed '\#pragma omp teams distribute simd' after parsing
11073 /// of the associated statement.
11074 StmtResult ActOnOpenMPTeamsDistributeSimdDirective(
11075 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11076 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11077 /// Called on well-formed '\#pragma omp teams distribute parallel for simd'
11078 /// after parsing of the associated statement.
11079 StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective(
11080 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11081 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11082 /// Called on well-formed '\#pragma omp teams distribute parallel for'
11083 /// after parsing of the associated statement.
11084 StmtResult ActOnOpenMPTeamsDistributeParallelForDirective(
11085 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11086 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11087 /// Called on well-formed '\#pragma omp target teams' after parsing of the
11088 /// associated statement.
11089 StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
11090 Stmt *AStmt,
11091 SourceLocation StartLoc,
11092 SourceLocation EndLoc);
11093 /// Called on well-formed '\#pragma omp target teams distribute' after parsing
11094 /// of the associated statement.
11095 StmtResult ActOnOpenMPTargetTeamsDistributeDirective(
11096 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11097 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11098 /// Called on well-formed '\#pragma omp target teams distribute parallel for'
11099 /// after parsing of the associated statement.
11100 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective(
11101 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11102 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11103 /// Called on well-formed '\#pragma omp target teams distribute parallel for
11104 /// simd' after parsing of the associated statement.
11105 StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
11106 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11107 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11108 /// Called on well-formed '\#pragma omp target teams distribute simd' after
11109 /// parsing of the associated statement.
11110 StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective(
11111 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11112 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11113 /// Called on well-formed '\#pragma omp interop'.
11114 StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses,
11115 SourceLocation StartLoc,
11116 SourceLocation EndLoc);
11117 /// Called on well-formed '\#pragma omp dispatch' after parsing of the
11118 // /associated statement.
11119 StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses,
11120 Stmt *AStmt, SourceLocation StartLoc,
11121 SourceLocation EndLoc);
11122 /// Called on well-formed '\#pragma omp masked' after parsing of the
11123 // /associated statement.
11124 StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses,
11125 Stmt *AStmt, SourceLocation StartLoc,
11126 SourceLocation EndLoc);
11127
11128 /// Called on well-formed '\#pragma omp loop' after parsing of the
11129 /// associated statement.
11130 StmtResult ActOnOpenMPGenericLoopDirective(
11131 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
11132 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
11133
11134 /// Checks correctness of linear modifiers.
11135 bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11136 SourceLocation LinLoc);
11137 /// Checks that the specified declaration matches requirements for the linear
11138 /// decls.
11139 bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
11140 OpenMPLinearClauseKind LinKind, QualType Type,
11141 bool IsDeclareSimd = false);
11142
11143 /// Called on well-formed '\#pragma omp declare simd' after parsing of
11144 /// the associated method/function.
11145 DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective(
11146 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS,
11147 Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
11148 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
11149 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR);
11150
11151 /// Checks '\#pragma omp declare variant' variant function and original
11152 /// functions after parsing of the associated method/function.
11153 /// \param DG Function declaration to which declare variant directive is
11154 /// applied to.
11155 /// \param VariantRef Expression that references the variant function, which
11156 /// must be used instead of the original one, specified in \p DG.
11157 /// \param TI The trait info object representing the match clause.
11158 /// \param NumAppendArgs The number of omp_interop_t arguments to account for
11159 /// in checking.
11160 /// \returns None, if the function/variant function are not compatible with
11161 /// the pragma, pair of original function/variant ref expression otherwise.
11162 Optional<std::pair<FunctionDecl *, Expr *>>
11163 checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef,
11164 OMPTraitInfo &TI, unsigned NumAppendArgs,
11165 SourceRange SR);
11166
11167 /// Called on well-formed '\#pragma omp declare variant' after parsing of
11168 /// the associated method/function.
11169 /// \param FD Function declaration to which declare variant directive is
11170 /// applied to.
11171 /// \param VariantRef Expression that references the variant function, which
11172 /// must be used instead of the original one, specified in \p DG.
11173 /// \param TI The context traits associated with the function variant.
11174 /// \param AdjustArgsNothing The list of 'nothing' arguments.
11175 /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments.
11176 /// \param AppendArgs The list of 'append_args' arguments.
11177 /// \param AdjustArgsLoc The Location of an 'adjust_args' clause.
11178 /// \param AppendArgsLoc The Location of an 'append_args' clause.
11179 /// \param SR The SourceRange of the 'declare variant' directive.
11180 void ActOnOpenMPDeclareVariantDirective(
11181 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI,
11182 ArrayRef<Expr *> AdjustArgsNothing,
11183 ArrayRef<Expr *> AdjustArgsNeedDevicePtr,
11184 ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs,
11185 SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc,
11186 SourceRange SR);
11187
11188 OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind,
11189 Expr *Expr,
11190 SourceLocation StartLoc,
11191 SourceLocation LParenLoc,
11192 SourceLocation EndLoc);
11193 /// Called on well-formed 'allocator' clause.
11194 OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator,
11195 SourceLocation StartLoc,
11196 SourceLocation LParenLoc,
11197 SourceLocation EndLoc);
11198 /// Called on well-formed 'if' clause.
11199 OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11200 Expr *Condition, SourceLocation StartLoc,
11201 SourceLocation LParenLoc,
11202 SourceLocation NameModifierLoc,
11203 SourceLocation ColonLoc,
11204 SourceLocation EndLoc);
11205 /// Called on well-formed 'final' clause.
11206 OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc,
11207 SourceLocation LParenLoc,
11208 SourceLocation EndLoc);
11209 /// Called on well-formed 'num_threads' clause.
11210 OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11211 SourceLocation StartLoc,
11212 SourceLocation LParenLoc,
11213 SourceLocation EndLoc);
11214 /// Called on well-formed 'align' clause.
11215 OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, SourceLocation StartLoc,
11216 SourceLocation LParenLoc,
11217 SourceLocation EndLoc);
11218 /// Called on well-formed 'safelen' clause.
11219 OMPClause *ActOnOpenMPSafelenClause(Expr *Length,
11220 SourceLocation StartLoc,
11221 SourceLocation LParenLoc,
11222 SourceLocation EndLoc);
11223 /// Called on well-formed 'simdlen' clause.
11224 OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc,
11225 SourceLocation LParenLoc,
11226 SourceLocation EndLoc);
11227 /// Called on well-form 'sizes' clause.
11228 OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs,
11229 SourceLocation StartLoc,
11230 SourceLocation LParenLoc,
11231 SourceLocation EndLoc);
11232 /// Called on well-form 'full' clauses.
11233 OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc,
11234 SourceLocation EndLoc);
11235 /// Called on well-form 'partial' clauses.
11236 OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc,
11237 SourceLocation LParenLoc,
11238 SourceLocation EndLoc);
11239 /// Called on well-formed 'collapse' clause.
11240 OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops,
11241 SourceLocation StartLoc,
11242 SourceLocation LParenLoc,
11243 SourceLocation EndLoc);
11244 /// Called on well-formed 'ordered' clause.
11245 OMPClause *
11246 ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc,
11247 SourceLocation LParenLoc = SourceLocation(),
11248 Expr *NumForLoops = nullptr);
11249 /// Called on well-formed 'grainsize' clause.
11250 OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc,
11251 SourceLocation LParenLoc,
11252 SourceLocation EndLoc);
11253 /// Called on well-formed 'num_tasks' clause.
11254 OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc,
11255 SourceLocation LParenLoc,
11256 SourceLocation EndLoc);
11257 /// Called on well-formed 'hint' clause.
11258 OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
11259 SourceLocation LParenLoc,
11260 SourceLocation EndLoc);
11261 /// Called on well-formed 'detach' clause.
11262 OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc,
11263 SourceLocation LParenLoc,
11264 SourceLocation EndLoc);
11265
11266 OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind,
11267 unsigned Argument,
11268 SourceLocation ArgumentLoc,
11269 SourceLocation StartLoc,
11270 SourceLocation LParenLoc,
11271 SourceLocation EndLoc);
11272 /// Called on well-formed 'when' clause.
11273 OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc,
11274 SourceLocation LParenLoc,
11275 SourceLocation EndLoc);
11276 /// Called on well-formed 'default' clause.
11277 OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind,
11278 SourceLocation KindLoc,
11279 SourceLocation StartLoc,
11280 SourceLocation LParenLoc,
11281 SourceLocation EndLoc);
11282 /// Called on well-formed 'proc_bind' clause.
11283 OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind,
11284 SourceLocation KindLoc,
11285 SourceLocation StartLoc,
11286 SourceLocation LParenLoc,
11287 SourceLocation EndLoc);
11288 /// Called on well-formed 'order' clause.
11289 OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
11290 SourceLocation KindLoc,
11291 SourceLocation StartLoc,
11292 SourceLocation LParenLoc,
11293 SourceLocation EndLoc);
11294 /// Called on well-formed 'update' clause.
11295 OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind,
11296 SourceLocation KindLoc,
11297 SourceLocation StartLoc,
11298 SourceLocation LParenLoc,
11299 SourceLocation EndLoc);
11300
11301 OMPClause *ActOnOpenMPSingleExprWithArgClause(
11302 OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr,
11303 SourceLocation StartLoc, SourceLocation LParenLoc,
11304 ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc,
11305 SourceLocation EndLoc);
11306 /// Called on well-formed 'schedule' clause.
11307 OMPClause *ActOnOpenMPScheduleClause(
11308 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
11309 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
11310 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
11311 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc);
11312
11313 OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
11314 SourceLocation EndLoc);
11315 /// Called on well-formed 'nowait' clause.
11316 OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
11317 SourceLocation EndLoc);
11318 /// Called on well-formed 'untied' clause.
11319 OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc,
11320 SourceLocation EndLoc);
11321 /// Called on well-formed 'mergeable' clause.
11322 OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc,
11323 SourceLocation EndLoc);
11324 /// Called on well-formed 'read' clause.
11325 OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc,
11326 SourceLocation EndLoc);
11327 /// Called on well-formed 'write' clause.
11328 OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc,
11329 SourceLocation EndLoc);
11330 /// Called on well-formed 'update' clause.
11331 OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc,
11332 SourceLocation EndLoc);
11333 /// Called on well-formed 'capture' clause.
11334 OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc,
11335 SourceLocation EndLoc);
11336 /// Called on well-formed 'compare' clause.
11337 OMPClause *ActOnOpenMPCompareClause(SourceLocation StartLoc,
11338 SourceLocation EndLoc);
11339 /// Called on well-formed 'seq_cst' clause.
11340 OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
11341 SourceLocation EndLoc);
11342 /// Called on well-formed 'acq_rel' clause.
11343 OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc,
11344 SourceLocation EndLoc);
11345 /// Called on well-formed 'acquire' clause.
11346 OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc,
11347 SourceLocation EndLoc);
11348 /// Called on well-formed 'release' clause.
11349 OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc,
11350 SourceLocation EndLoc);
11351 /// Called on well-formed 'relaxed' clause.
11352 OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc,
11353 SourceLocation EndLoc);
11354
11355 /// Called on well-formed 'init' clause.
11356 OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs,
11357 bool IsTarget, bool IsTargetSync,
11358 SourceLocation StartLoc,
11359 SourceLocation LParenLoc,
11360 SourceLocation VarLoc,
11361 SourceLocation EndLoc);
11362
11363 /// Called on well-formed 'use' clause.
11364 OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
11365 SourceLocation LParenLoc,
11366 SourceLocation VarLoc, SourceLocation EndLoc);
11367
11368 /// Called on well-formed 'destroy' clause.
11369 OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
11370 SourceLocation LParenLoc,
11371 SourceLocation VarLoc,
11372 SourceLocation EndLoc);
11373 /// Called on well-formed 'novariants' clause.
11374 OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition,
11375 SourceLocation StartLoc,
11376 SourceLocation LParenLoc,
11377 SourceLocation EndLoc);
11378 /// Called on well-formed 'nocontext' clause.
11379 OMPClause *ActOnOpenMPNocontextClause(Expr *Condition,
11380 SourceLocation StartLoc,
11381 SourceLocation LParenLoc,
11382 SourceLocation EndLoc);
11383 /// Called on well-formed 'filter' clause.
11384 OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
11385 SourceLocation LParenLoc,
11386 SourceLocation EndLoc);
11387 /// Called on well-formed 'threads' clause.
11388 OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc,
11389 SourceLocation EndLoc);
11390 /// Called on well-formed 'simd' clause.
11391 OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc,
11392 SourceLocation EndLoc);
11393 /// Called on well-formed 'nogroup' clause.
11394 OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc,
11395 SourceLocation EndLoc);
11396 /// Called on well-formed 'unified_address' clause.
11397 OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
11398 SourceLocation EndLoc);
11399
11400 /// Called on well-formed 'unified_address' clause.
11401 OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
11402 SourceLocation EndLoc);
11403
11404 /// Called on well-formed 'reverse_offload' clause.
11405 OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
11406 SourceLocation EndLoc);
11407
11408 /// Called on well-formed 'dynamic_allocators' clause.
11409 OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
11410 SourceLocation EndLoc);
11411
11412 /// Called on well-formed 'atomic_default_mem_order' clause.
11413 OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause(
11414 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc,
11415 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11416
11417 OMPClause *ActOnOpenMPVarListClause(
11418 OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr,
11419 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
11420 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
11421 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
11422 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11423 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
11424 SourceLocation ExtraModifierLoc,
11425 ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11426 ArrayRef<SourceLocation> MotionModifiersLoc);
11427 /// Called on well-formed 'inclusive' clause.
11428 OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList,
11429 SourceLocation StartLoc,
11430 SourceLocation LParenLoc,
11431 SourceLocation EndLoc);
11432 /// Called on well-formed 'exclusive' clause.
11433 OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList,
11434 SourceLocation StartLoc,
11435 SourceLocation LParenLoc,
11436 SourceLocation EndLoc);
11437 /// Called on well-formed 'allocate' clause.
11438 OMPClause *
11439 ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList,
11440 SourceLocation StartLoc, SourceLocation ColonLoc,
11441 SourceLocation LParenLoc, SourceLocation EndLoc);
11442 /// Called on well-formed 'private' clause.
11443 OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
11444 SourceLocation StartLoc,
11445 SourceLocation LParenLoc,
11446 SourceLocation EndLoc);
11447 /// Called on well-formed 'firstprivate' clause.
11448 OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
11449 SourceLocation StartLoc,
11450 SourceLocation LParenLoc,
11451 SourceLocation EndLoc);
11452 /// Called on well-formed 'lastprivate' clause.
11453 OMPClause *ActOnOpenMPLastprivateClause(
11454 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
11455 SourceLocation LPKindLoc, SourceLocation ColonLoc,
11456 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc);
11457 /// Called on well-formed 'shared' clause.
11458 OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11459 SourceLocation StartLoc,
11460 SourceLocation LParenLoc,
11461 SourceLocation EndLoc);
11462 /// Called on well-formed 'reduction' clause.
11463 OMPClause *ActOnOpenMPReductionClause(
11464 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
11465 SourceLocation StartLoc, SourceLocation LParenLoc,
11466 SourceLocation ModifierLoc, SourceLocation ColonLoc,
11467 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
11468 const DeclarationNameInfo &ReductionId,
11469 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11470 /// Called on well-formed 'task_reduction' clause.
11471 OMPClause *ActOnOpenMPTaskReductionClause(
11472 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11473 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11474 CXXScopeSpec &ReductionIdScopeSpec,
11475 const DeclarationNameInfo &ReductionId,
11476 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11477 /// Called on well-formed 'in_reduction' clause.
11478 OMPClause *ActOnOpenMPInReductionClause(
11479 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11480 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
11481 CXXScopeSpec &ReductionIdScopeSpec,
11482 const DeclarationNameInfo &ReductionId,
11483 ArrayRef<Expr *> UnresolvedReductions = llvm::None);
11484 /// Called on well-formed 'linear' clause.
11485 OMPClause *
11486 ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
11487 SourceLocation StartLoc, SourceLocation LParenLoc,
11488 OpenMPLinearClauseKind LinKind, SourceLocation LinLoc,
11489 SourceLocation ColonLoc, SourceLocation EndLoc);
11490 /// Called on well-formed 'aligned' clause.
11491 OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList,
11492 Expr *Alignment,
11493 SourceLocation StartLoc,
11494 SourceLocation LParenLoc,
11495 SourceLocation ColonLoc,
11496 SourceLocation EndLoc);
11497 /// Called on well-formed 'copyin' clause.
11498 OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11499 SourceLocation StartLoc,
11500 SourceLocation LParenLoc,
11501 SourceLocation EndLoc);
11502 /// Called on well-formed 'copyprivate' clause.
11503 OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11504 SourceLocation StartLoc,
11505 SourceLocation LParenLoc,
11506 SourceLocation EndLoc);
11507 /// Called on well-formed 'flush' pseudo clause.
11508 OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11509 SourceLocation StartLoc,
11510 SourceLocation LParenLoc,
11511 SourceLocation EndLoc);
11512 /// Called on well-formed 'depobj' pseudo clause.
11513 OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
11514 SourceLocation LParenLoc,
11515 SourceLocation EndLoc);
11516 /// Called on well-formed 'depend' clause.
11517 OMPClause *
11518 ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind,
11519 SourceLocation DepLoc, SourceLocation ColonLoc,
11520 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11521 SourceLocation LParenLoc, SourceLocation EndLoc);
11522 /// Called on well-formed 'device' clause.
11523 OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
11524 Expr *Device, SourceLocation StartLoc,
11525 SourceLocation LParenLoc,
11526 SourceLocation ModifierLoc,
11527 SourceLocation EndLoc);
11528 /// Called on well-formed 'map' clause.
11529 OMPClause *ActOnOpenMPMapClause(
11530 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
11531 ArrayRef<SourceLocation> MapTypeModifiersLoc,
11532 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
11533 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
11534 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
11535 const OMPVarListLocTy &Locs, bool NoDiagnose = false,
11536 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11537 /// Called on well-formed 'num_teams' clause.
11538 OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
11539 SourceLocation LParenLoc,
11540 SourceLocation EndLoc);
11541 /// Called on well-formed 'thread_limit' clause.
11542 OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
11543 SourceLocation StartLoc,
11544 SourceLocation LParenLoc,
11545 SourceLocation EndLoc);
11546 /// Called on well-formed 'priority' clause.
11547 OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
11548 SourceLocation LParenLoc,
11549 SourceLocation EndLoc);
11550 /// Called on well-formed 'dist_schedule' clause.
11551 OMPClause *ActOnOpenMPDistScheduleClause(
11552 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize,
11553 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc,
11554 SourceLocation CommaLoc, SourceLocation EndLoc);
11555 /// Called on well-formed 'defaultmap' clause.
11556 OMPClause *ActOnOpenMPDefaultmapClause(
11557 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
11558 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
11559 SourceLocation KindLoc, SourceLocation EndLoc);
11560 /// Called on well-formed 'to' clause.
11561 OMPClause *
11562 ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11563 ArrayRef<SourceLocation> MotionModifiersLoc,
11564 CXXScopeSpec &MapperIdScopeSpec,
11565 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11566 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11567 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11568 /// Called on well-formed 'from' clause.
11569 OMPClause *
11570 ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
11571 ArrayRef<SourceLocation> MotionModifiersLoc,
11572 CXXScopeSpec &MapperIdScopeSpec,
11573 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
11574 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
11575 ArrayRef<Expr *> UnresolvedMappers = llvm::None);
11576 /// Called on well-formed 'use_device_ptr' clause.
11577 OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
11578 const OMPVarListLocTy &Locs);
11579 /// Called on well-formed 'use_device_addr' clause.
11580 OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
11581 const OMPVarListLocTy &Locs);
11582 /// Called on well-formed 'is_device_ptr' clause.
11583 OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
11584 const OMPVarListLocTy &Locs);
11585 /// Called on well-formed 'has_device_addr' clause.
11586 OMPClause *ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
11587 const OMPVarListLocTy &Locs);
11588 /// Called on well-formed 'nontemporal' clause.
11589 OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
11590 SourceLocation StartLoc,
11591 SourceLocation LParenLoc,
11592 SourceLocation EndLoc);
11593
11594 /// Data for list of allocators.
11595 struct UsesAllocatorsData {
11596 /// Allocator.
11597 Expr *Allocator = nullptr;
11598 /// Allocator traits.
11599 Expr *AllocatorTraits = nullptr;
11600 /// Locations of '(' and ')' symbols.
11601 SourceLocation LParenLoc, RParenLoc;
11602 };
11603 /// Called on well-formed 'uses_allocators' clause.
11604 OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc,
11605 SourceLocation LParenLoc,
11606 SourceLocation EndLoc,
11607 ArrayRef<UsesAllocatorsData> Data);
11608 /// Called on well-formed 'affinity' clause.
11609 OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc,
11610 SourceLocation LParenLoc,
11611 SourceLocation ColonLoc,
11612 SourceLocation EndLoc, Expr *Modifier,
11613 ArrayRef<Expr *> Locators);
11614 /// Called on a well-formed 'bind' clause.
11615 OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind,
11616 SourceLocation KindLoc,
11617 SourceLocation StartLoc,
11618 SourceLocation LParenLoc,
11619 SourceLocation EndLoc);
11620
11621 /// The kind of conversion being performed.
11622 enum CheckedConversionKind {
11623 /// An implicit conversion.
11624 CCK_ImplicitConversion,
11625 /// A C-style cast.
11626 CCK_CStyleCast,
11627 /// A functional-style cast.
11628 CCK_FunctionalCast,
11629 /// A cast other than a C-style cast.
11630 CCK_OtherCast,
11631 /// A conversion for an operand of a builtin overloaded operator.
11632 CCK_ForBuiltinOverloadedOp
11633 };
11634
11635 static bool isCast(CheckedConversionKind CCK) {
11636 return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast ||
11637 CCK == CCK_OtherCast;
11638 }
11639
11640 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit
11641 /// cast. If there is already an implicit cast, merge into the existing one.
11642 /// If isLvalue, the result of the cast is an lvalue.
11643 ExprResult
11644 ImpCastExprToType(Expr *E, QualType Type, CastKind CK,
11645 ExprValueKind VK = VK_PRValue,
11646 const CXXCastPath *BasePath = nullptr,
11647 CheckedConversionKind CCK = CCK_ImplicitConversion);
11648
11649 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding
11650 /// to the conversion from scalar type ScalarTy to the Boolean type.
11651 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy);
11652
11653 /// IgnoredValueConversions - Given that an expression's result is
11654 /// syntactically ignored, perform any conversions that are
11655 /// required.
11656 ExprResult IgnoredValueConversions(Expr *E);
11657
11658 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts
11659 // functions and arrays to their respective pointers (C99 6.3.2.1).
11660 ExprResult UsualUnaryConversions(Expr *E);
11661
11662 /// CallExprUnaryConversions - a special case of an unary conversion
11663 /// performed on a function designator of a call expression.
11664 ExprResult CallExprUnaryConversions(Expr *E);
11665
11666 // DefaultFunctionArrayConversion - converts functions and arrays
11667 // to their respective pointers (C99 6.3.2.1).
11668 ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true);
11669
11670 // DefaultFunctionArrayLvalueConversion - converts functions and
11671 // arrays to their respective pointers and performs the
11672 // lvalue-to-rvalue conversion.
11673 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E,
11674 bool Diagnose = true);
11675
11676 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on
11677 // the operand. This function is a no-op if the operand has a function type
11678 // or an array type.
11679 ExprResult DefaultLvalueConversion(Expr *E);
11680
11681 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
11682 // do not have a prototype. Integer promotions are performed on each
11683 // argument, and arguments that have type float are promoted to double.
11684 ExprResult DefaultArgumentPromotion(Expr *E);
11685
11686 /// If \p E is a prvalue denoting an unmaterialized temporary, materialize
11687 /// it as an xvalue. In C++98, the result will still be a prvalue, because
11688 /// we don't have xvalues there.
11689 ExprResult TemporaryMaterializationConversion(Expr *E);
11690
11691 // Used for emitting the right warning by DefaultVariadicArgumentPromotion
11692 enum VariadicCallType {
11693 VariadicFunction,
11694 VariadicBlock,
11695 VariadicMethod,
11696 VariadicConstructor,
11697 VariadicDoesNotApply
11698 };
11699
11700 VariadicCallType getVariadicCallType(FunctionDecl *FDecl,
11701 const FunctionProtoType *Proto,
11702 Expr *Fn);
11703
11704 // Used for determining in which context a type is allowed to be passed to a
11705 // vararg function.
11706 enum VarArgKind {
11707 VAK_Valid,
11708 VAK_ValidInCXX11,
11709 VAK_Undefined,
11710 VAK_MSVCUndefined,
11711 VAK_Invalid
11712 };
11713
11714 // Determines which VarArgKind fits an expression.
11715 VarArgKind isValidVarArgType(const QualType &Ty);
11716
11717 /// Check to see if the given expression is a valid argument to a variadic
11718 /// function, issuing a diagnostic if not.
11719 void checkVariadicArgument(const Expr *E, VariadicCallType CT);
11720
11721 /// Check whether the given statement can have musttail applied to it,
11722 /// issuing a diagnostic and returning false if not. In the success case,
11723 /// the statement is rewritten to remove implicit nodes from the return
11724 /// value.
11725 bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA);
11726
11727private:
11728 /// Check whether the given statement can have musttail applied to it,
11729 /// issuing a diagnostic and returning false if not.
11730 bool checkMustTailAttr(const Stmt *St, const Attr &MTA);
11731
11732public:
11733 /// Check to see if a given expression could have '.c_str()' called on it.
11734 bool hasCStrMethod(const Expr *E);
11735
11736 /// GatherArgumentsForCall - Collector argument expressions for various
11737 /// form of call prototypes.
11738 bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
11739 const FunctionProtoType *Proto,
11740 unsigned FirstParam, ArrayRef<Expr *> Args,
11741 SmallVectorImpl<Expr *> &AllArgs,
11742 VariadicCallType CallType = VariadicDoesNotApply,
11743 bool AllowExplicit = false,
11744 bool IsListInitialization = false);
11745
11746 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
11747 // will create a runtime trap if the resulting type is not a POD type.
11748 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
11749 FunctionDecl *FDecl);
11750
11751 /// Context in which we're performing a usual arithmetic conversion.
11752 enum ArithConvKind {
11753 /// An arithmetic operation.
11754 ACK_Arithmetic,
11755 /// A bitwise operation.
11756 ACK_BitwiseOp,
11757 /// A comparison.
11758 ACK_Comparison,
11759 /// A conditional (?:) operator.
11760 ACK_Conditional,
11761 /// A compound assignment expression.
11762 ACK_CompAssign,
11763 };
11764
11765 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's
11766 // operands and then handles various conversions that are common to binary
11767 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this
11768 // routine returns the first non-arithmetic type found. The client is
11769 // responsible for emitting appropriate error diagnostics.
11770 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
11771 SourceLocation Loc, ArithConvKind ACK);
11772
11773 /// AssignConvertType - All of the 'assignment' semantic checks return this
11774 /// enum to indicate whether the assignment was allowed. These checks are
11775 /// done for simple assignments, as well as initialization, return from
11776 /// function, argument passing, etc. The query is phrased in terms of a
11777 /// source and destination type.
11778 enum AssignConvertType {
11779 /// Compatible - the types are compatible according to the standard.
11780 Compatible,
11781
11782 /// PointerToInt - The assignment converts a pointer to an int, which we
11783 /// accept as an extension.
11784 PointerToInt,
11785
11786 /// IntToPointer - The assignment converts an int to a pointer, which we
11787 /// accept as an extension.
11788 IntToPointer,
11789
11790 /// FunctionVoidPointer - The assignment is between a function pointer and
11791 /// void*, which the standard doesn't allow, but we accept as an extension.
11792 FunctionVoidPointer,
11793
11794 /// IncompatiblePointer - The assignment is between two pointers types that
11795 /// are not compatible, but we accept them as an extension.
11796 IncompatiblePointer,
11797
11798 /// IncompatibleFunctionPointer - The assignment is between two function
11799 /// pointers types that are not compatible, but we accept them as an
11800 /// extension.
11801 IncompatibleFunctionPointer,
11802
11803 /// IncompatiblePointerSign - The assignment is between two pointers types
11804 /// which point to integers which have a different sign, but are otherwise
11805 /// identical. This is a subset of the above, but broken out because it's by
11806 /// far the most common case of incompatible pointers.
11807 IncompatiblePointerSign,
11808
11809 /// CompatiblePointerDiscardsQualifiers - The assignment discards
11810 /// c/v/r qualifiers, which we accept as an extension.
11811 CompatiblePointerDiscardsQualifiers,
11812
11813 /// IncompatiblePointerDiscardsQualifiers - The assignment
11814 /// discards qualifiers that we don't permit to be discarded,
11815 /// like address spaces.
11816 IncompatiblePointerDiscardsQualifiers,
11817
11818 /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment
11819 /// changes address spaces in nested pointer types which is not allowed.
11820 /// For instance, converting __private int ** to __generic int ** is
11821 /// illegal even though __private could be converted to __generic.
11822 IncompatibleNestedPointerAddressSpaceMismatch,
11823
11824 /// IncompatibleNestedPointerQualifiers - The assignment is between two
11825 /// nested pointer types, and the qualifiers other than the first two
11826 /// levels differ e.g. char ** -> const char **, but we accept them as an
11827 /// extension.
11828 IncompatibleNestedPointerQualifiers,
11829
11830 /// IncompatibleVectors - The assignment is between two vector types that
11831 /// have the same size, which we accept as an extension.
11832 IncompatibleVectors,
11833
11834 /// IntToBlockPointer - The assignment converts an int to a block
11835 /// pointer. We disallow this.
11836 IntToBlockPointer,
11837
11838 /// IncompatibleBlockPointer - The assignment is between two block
11839 /// pointers types that are not compatible.
11840 IncompatibleBlockPointer,
11841
11842 /// IncompatibleObjCQualifiedId - The assignment is between a qualified
11843 /// id type and something else (that is incompatible with it). For example,
11844 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol.
11845 IncompatibleObjCQualifiedId,
11846
11847 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an
11848 /// object with __weak qualifier.
11849 IncompatibleObjCWeakRef,
11850
11851 /// Incompatible - We reject this conversion outright, it is invalid to
11852 /// represent it in the AST.
11853 Incompatible
11854 };
11855
11856 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the
11857 /// assignment conversion type specified by ConvTy. This returns true if the
11858 /// conversion was invalid or false if the conversion was accepted.
11859 bool DiagnoseAssignmentResult(AssignConvertType ConvTy,
11860 SourceLocation Loc,
11861 QualType DstType, QualType SrcType,
11862 Expr *SrcExpr, AssignmentAction Action,
11863 bool *Complained = nullptr);
11864
11865 /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag
11866 /// enum. If AllowMask is true, then we also allow the complement of a valid
11867 /// value, to be used as a mask.
11868 bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
11869 bool AllowMask) const;
11870
11871 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant
11872 /// integer not in the range of enum values.
11873 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType,
11874 Expr *SrcExpr);
11875
11876 /// CheckAssignmentConstraints - Perform type checking for assignment,
11877 /// argument passing, variable initialization, and function return values.
11878 /// C99 6.5.16.
11879 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc,
11880 QualType LHSType,
11881 QualType RHSType);
11882
11883 /// Check assignment constraints and optionally prepare for a conversion of
11884 /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS
11885 /// is true.
11886 AssignConvertType CheckAssignmentConstraints(QualType LHSType,
11887 ExprResult &RHS,
11888 CastKind &Kind,
11889 bool ConvertRHS = true);
11890
11891 /// Check assignment constraints for an assignment of RHS to LHSType.
11892 ///
11893 /// \param LHSType The destination type for the assignment.
11894 /// \param RHS The source expression for the assignment.
11895 /// \param Diagnose If \c true, diagnostics may be produced when checking
11896 /// for assignability. If a diagnostic is produced, \p RHS will be
11897 /// set to ExprError(). Note that this function may still return
11898 /// without producing a diagnostic, even for an invalid assignment.
11899 /// \param DiagnoseCFAudited If \c true, the target is a function parameter
11900 /// in an audited Core Foundation API and does not need to be checked
11901 /// for ARC retain issues.
11902 /// \param ConvertRHS If \c true, \p RHS will be updated to model the
11903 /// conversions necessary to perform the assignment. If \c false,
11904 /// \p Diagnose must also be \c false.
11905 AssignConvertType CheckSingleAssignmentConstraints(
11906 QualType LHSType, ExprResult &RHS, bool Diagnose = true,
11907 bool DiagnoseCFAudited = false, bool ConvertRHS = true);
11908
11909 // If the lhs type is a transparent union, check whether we
11910 // can initialize the transparent union with the given expression.
11911 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType,
11912 ExprResult &RHS);
11913
11914 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType);
11915
11916 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType);
11917
11918 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11919 AssignmentAction Action,
11920 bool AllowExplicit = false);
11921 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11922 const ImplicitConversionSequence& ICS,
11923 AssignmentAction Action,
11924 CheckedConversionKind CCK
11925 = CCK_ImplicitConversion);
11926 ExprResult PerformImplicitConversion(Expr *From, QualType ToType,
11927 const StandardConversionSequence& SCS,
11928 AssignmentAction Action,
11929 CheckedConversionKind CCK);
11930
11931 ExprResult PerformQualificationConversion(
11932 Expr *E, QualType Ty, ExprValueKind VK = VK_PRValue,
11933 CheckedConversionKind CCK = CCK_ImplicitConversion);
11934
11935 /// the following "Check" methods will return a valid/converted QualType
11936 /// or a null QualType (indicating an error diagnostic was issued).
11937
11938 /// type checking binary operators (subroutines of CreateBuiltinBinOp).
11939 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS,
11940 ExprResult &RHS);
11941 QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
11942 ExprResult &RHS);
11943 QualType CheckPointerToMemberOperands( // C++ 5.5
11944 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK,
11945 SourceLocation OpLoc, bool isIndirect);
11946 QualType CheckMultiplyDivideOperands( // C99 6.5.5
11947 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign,
11948 bool IsDivide);
11949 QualType CheckRemainderOperands( // C99 6.5.5
11950 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11951 bool IsCompAssign = false);
11952 QualType CheckAdditionOperands( // C99 6.5.6
11953 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11954 BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr);
11955 QualType CheckSubtractionOperands( // C99 6.5.6
11956 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11957 QualType* CompLHSTy = nullptr);
11958 QualType CheckShiftOperands( // C99 6.5.7
11959 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11960 BinaryOperatorKind Opc, bool IsCompAssign = false);
11961 void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE);
11962 QualType CheckCompareOperands( // C99 6.5.8/9
11963 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11964 BinaryOperatorKind Opc);
11965 QualType CheckBitwiseOperands( // C99 6.5.[10...12]
11966 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11967 BinaryOperatorKind Opc);
11968 QualType CheckLogicalOperands( // C99 6.5.[13,14]
11969 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc,
11970 BinaryOperatorKind Opc);
11971 // CheckAssignmentOperands is used for both simple and compound assignment.
11972 // For simple assignment, pass both expressions and a null converted type.
11973 // For compound assignment, pass both expressions and the converted type.
11974 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2]
11975 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType);
11976
11977 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc,
11978 UnaryOperatorKind Opcode, Expr *Op);
11979 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc,
11980 BinaryOperatorKind Opcode,
11981 Expr *LHS, Expr *RHS);
11982 ExprResult checkPseudoObjectRValue(Expr *E);
11983 Expr *recreateSyntacticForm(PseudoObjectExpr *E);
11984
11985 QualType CheckConditionalOperands( // C99 6.5.15
11986 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
11987 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc);
11988 QualType CXXCheckConditionalOperands( // C++ 5.16
11989 ExprResult &cond, ExprResult &lhs, ExprResult &rhs,
11990 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc);
11991 QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
11992 ExprResult &RHS,
11993 SourceLocation QuestionLoc);
11994 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2,
11995 bool ConvertArgs = true);
11996 QualType FindCompositePointerType(SourceLocation Loc,
11997 ExprResult &E1, ExprResult &E2,
11998 bool ConvertArgs = true) {
11999 Expr *E1Tmp = E1.get(), *E2Tmp = E2.get();
12000 QualType Composite =
12001 FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs);
12002 E1 = E1Tmp;
12003 E2 = E2Tmp;
12004 return Composite;
12005 }
12006
12007 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
12008 SourceLocation QuestionLoc);
12009
12010 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
12011 SourceLocation QuestionLoc);
12012
12013 void DiagnoseAlwaysNonNullPointer(Expr *E,
12014 Expr::NullPointerConstantKind NullType,
12015 bool IsEqual, SourceRange Range);
12016
12017 /// type checking for vector binary operators.
12018 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
12019 SourceLocation Loc, bool IsCompAssign,
12020 bool AllowBothBool, bool AllowBoolConversion,
12021 bool AllowBoolOperation, bool ReportInvalid);
12022 QualType GetSignedVectorType(QualType V);
12023 QualType GetSignedSizelessVectorType(QualType V);
12024 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12025 SourceLocation Loc,
12026 BinaryOperatorKind Opc);
12027 QualType CheckSizelessVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
12028 SourceLocation Loc,
12029 BinaryOperatorKind Opc);
12030 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
12031 SourceLocation Loc);
12032
12033 // type checking for sizeless vector binary operators.
12034 QualType CheckSizelessVectorOperands(ExprResult &LHS, ExprResult &RHS,
12035 SourceLocation Loc, bool IsCompAssign,
12036 ArithConvKind OperationKind);
12037
12038 /// Type checking for matrix binary operators.
12039 QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS,
12040 SourceLocation Loc,
12041 bool IsCompAssign);
12042 QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS,
12043 SourceLocation Loc, bool IsCompAssign);
12044
12045 bool isValidSveBitcast(QualType srcType, QualType destType);
12046
12047 bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy);
12048
12049 bool areVectorTypesSameSize(QualType srcType, QualType destType);
12050 bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType);
12051 bool isLaxVectorConversion(QualType srcType, QualType destType);
12052
12053 /// type checking declaration initializers (C99 6.7.8)
12054 bool CheckForConstantInitializer(Expr *e, QualType t);
12055
12056 // type checking C++ declaration initializers (C++ [dcl.init]).
12057
12058 /// ReferenceCompareResult - Expresses the result of comparing two
12059 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the
12060 /// purposes of initialization by reference (C++ [dcl.init.ref]p4).
12061 enum ReferenceCompareResult {
12062 /// Ref_Incompatible - The two types are incompatible, so direct
12063 /// reference binding is not possible.
12064 Ref_Incompatible = 0,
12065 /// Ref_Related - The two types are reference-related, which means
12066 /// that their unqualified forms (T1 and T2) are either the same
12067 /// or T1 is a base class of T2.
12068 Ref_Related,
12069 /// Ref_Compatible - The two types are reference-compatible.
12070 Ref_Compatible
12071 };
12072
12073 // Fake up a scoped enumeration that still contextually converts to bool.
12074 struct ReferenceConversionsScope {
12075 /// The conversions that would be performed on an lvalue of type T2 when
12076 /// binding a reference of type T1 to it, as determined when evaluating
12077 /// whether T1 is reference-compatible with T2.
12078 enum ReferenceConversions {
12079 Qualification = 0x1,
12080 NestedQualification = 0x2,
12081 Function = 0x4,
12082 DerivedToBase = 0x8,
12083 ObjC = 0x10,
12084 ObjCLifetime = 0x20,
12085
12086 LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime)LLVM_BITMASK_LARGEST_ENUMERATOR = ObjCLifetime
12087 };
12088 };
12089 using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions;
12090
12091 ReferenceCompareResult
12092 CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2,
12093 ReferenceConversions *Conv = nullptr);
12094
12095 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12096 Expr *CastExpr, CastKind &CastKind,
12097 ExprValueKind &VK, CXXCastPath &Path);
12098
12099 /// Force an expression with unknown-type to an expression of the
12100 /// given type.
12101 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType);
12102
12103 /// Type-check an expression that's being passed to an
12104 /// __unknown_anytype parameter.
12105 ExprResult checkUnknownAnyArg(SourceLocation callLoc,
12106 Expr *result, QualType &paramType);
12107
12108 // CheckMatrixCast - Check type constraints for matrix casts.
12109 // We allow casting between matrixes of the same dimensions i.e. when they
12110 // have the same number of rows and column. Returns true if the cast is
12111 // invalid.
12112 bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy,
12113 CastKind &Kind);
12114
12115 // CheckVectorCast - check type constraints for vectors.
12116 // Since vectors are an extension, there are no C standard reference for this.
12117 // We allow casting between vectors and integer datatypes of the same size.
12118 // returns true if the cast is invalid
12119 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
12120 CastKind &Kind);
12121
12122 /// Prepare `SplattedExpr` for a vector splat operation, adding
12123 /// implicit casts if necessary.
12124 ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr);
12125
12126 // CheckExtVectorCast - check type constraints for extended vectors.
12127 // Since vectors are an extension, there are no C standard reference for this.
12128 // We allow casting between vectors and integer datatypes of the same size,
12129 // or vectors and the element type of that vector.
12130 // returns the cast expr
12131 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr,
12132 CastKind &Kind);
12133
12134 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type,
12135 SourceLocation LParenLoc,
12136 Expr *CastExpr,
12137 SourceLocation RParenLoc);
12138
12139 enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error };
12140
12141 /// Checks for invalid conversions and casts between
12142 /// retainable pointers and other pointer kinds for ARC and Weak.
12143 ARCConversionResult CheckObjCConversion(SourceRange castRange,
12144 QualType castType, Expr *&op,
12145 CheckedConversionKind CCK,
12146 bool Diagnose = true,
12147 bool DiagnoseCFAudited = false,
12148 BinaryOperatorKind Opc = BO_PtrMemD
12149 );
12150
12151 Expr *stripARCUnbridgedCast(Expr *e);
12152 void diagnoseARCUnbridgedCast(Expr *e);
12153
12154 bool CheckObjCARCUnavailableWeakConversion(QualType castType,
12155 QualType ExprType);
12156
12157 /// checkRetainCycles - Check whether an Objective-C message send
12158 /// might create an obvious retain cycle.
12159 void checkRetainCycles(ObjCMessageExpr *msg);
12160 void checkRetainCycles(Expr *receiver, Expr *argument);
12161 void checkRetainCycles(VarDecl *Var, Expr *Init);
12162
12163 /// checkUnsafeAssigns - Check whether +1 expr is being assigned
12164 /// to weak/__unsafe_unretained type.
12165 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS);
12166
12167 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned
12168 /// to weak/__unsafe_unretained expression.
12169 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS);
12170
12171 /// CheckMessageArgumentTypes - Check types in an Obj-C message send.
12172 /// \param Method - May be null.
12173 /// \param [out] ReturnType - The return type of the send.
12174 /// \return true iff there were any incompatible types.
12175 bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType,
12176 MultiExprArg Args, Selector Sel,
12177 ArrayRef<SourceLocation> SelectorLocs,
12178 ObjCMethodDecl *Method, bool isClassMessage,
12179 bool isSuperMessage, SourceLocation lbrac,
12180 SourceLocation rbrac, SourceRange RecRange,
12181 QualType &ReturnType, ExprValueKind &VK);
12182
12183 /// Determine the result of a message send expression based on
12184 /// the type of the receiver, the method expected to receive the message,
12185 /// and the form of the message send.
12186 QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType,
12187 ObjCMethodDecl *Method, bool isClassMessage,
12188 bool isSuperMessage);
12189
12190 /// If the given expression involves a message send to a method
12191 /// with a related result type, emit a note describing what happened.
12192 void EmitRelatedResultTypeNote(const Expr *E);
12193
12194 /// Given that we had incompatible pointer types in a return
12195 /// statement, check whether we're in a method with a related result
12196 /// type, and if so, emit a note describing what happened.
12197 void EmitRelatedResultTypeNoteForReturn(QualType destType);
12198
12199 class ConditionResult {
12200 Decl *ConditionVar;
12201 FullExprArg Condition;
12202 bool Invalid;
12203 bool HasKnownValue;
12204 bool KnownValue;
12205
12206 friend class Sema;
12207 ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition,
12208 bool IsConstexpr)
12209 : ConditionVar(ConditionVar), Condition(Condition), Invalid(false),
12210 HasKnownValue(IsConstexpr && Condition.get() &&
12211 !Condition.get()->isValueDependent()),
12212 KnownValue(HasKnownValue &&
12213 !!Condition.get()->EvaluateKnownConstInt(S.Context)) {}
12214 explicit ConditionResult(bool Invalid)
12215 : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid),
12216 HasKnownValue(false), KnownValue(false) {}
12217
12218 public:
12219 ConditionResult() : ConditionResult(false) {}
12220 bool isInvalid() const { return Invalid; }
12221 std::pair<VarDecl *, Expr *> get() const {
12222 return std::make_pair(cast_or_null<VarDecl>(ConditionVar),
12223 Condition.get());
12224 }
12225 llvm::Optional<bool> getKnownValue() const {
12226 if (!HasKnownValue)
12227 return None;
12228 return KnownValue;
12229 }
12230 };
12231 static ConditionResult ConditionError() { return ConditionResult(true); }
12232
12233 enum class ConditionKind {
12234 Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'.
12235 ConstexprIf, ///< A constant boolean condition from 'if constexpr'.
12236 Switch ///< An integral condition for a 'switch' statement.
12237 };
12238 QualType PreferredConditionType(ConditionKind K) const {
12239 return K == ConditionKind::Switch ? Context.IntTy : Context.BoolTy;
12240 }
12241
12242 ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr,
12243 ConditionKind CK, bool MissingOK = false);
12244
12245 ConditionResult ActOnConditionVariable(Decl *ConditionVar,
12246 SourceLocation StmtLoc,
12247 ConditionKind CK);
12248
12249 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D);
12250
12251 ExprResult CheckConditionVariable(VarDecl *ConditionVar,
12252 SourceLocation StmtLoc,
12253 ConditionKind CK);
12254 ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond);
12255
12256 /// CheckBooleanCondition - Diagnose problems involving the use of
12257 /// the given expression as a boolean condition (e.g. in an if
12258 /// statement). Also performs the standard function and array
12259 /// decays, possibly changing the input variable.
12260 ///
12261 /// \param Loc - A location associated with the condition, e.g. the
12262 /// 'if' keyword.
12263 /// \return true iff there were any errors
12264 ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E,
12265 bool IsConstexpr = false);
12266
12267 /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression
12268 /// found in an explicit(bool) specifier.
12269 ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E);
12270
12271 /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier.
12272 /// Returns true if the explicit specifier is now resolved.
12273 bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec);
12274
12275 /// DiagnoseAssignmentAsCondition - Given that an expression is
12276 /// being used as a boolean condition, warn if it's an assignment.
12277 void DiagnoseAssignmentAsCondition(Expr *E);
12278
12279 /// Redundant parentheses over an equality comparison can indicate
12280 /// that the user intended an assignment used as condition.
12281 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE);
12282
12283 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid.
12284 ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false);
12285
12286 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have
12287 /// the specified width and sign. If an overflow occurs, detect it and emit
12288 /// the specified diagnostic.
12289 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal,
12290 unsigned NewWidth, bool NewSign,
12291 SourceLocation Loc, unsigned DiagID);
12292
12293 /// Checks that the Objective-C declaration is declared in the global scope.
12294 /// Emits an error and marks the declaration as invalid if it's not declared
12295 /// in the global scope.
12296 bool CheckObjCDeclScope(Decl *D);
12297
12298 /// Abstract base class used for diagnosing integer constant
12299 /// expression violations.
12300 class VerifyICEDiagnoser {
12301 public:
12302 bool Suppress;
12303
12304 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { }
12305
12306 virtual SemaDiagnosticBuilder
12307 diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T);
12308 virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
12309 SourceLocation Loc) = 0;
12310 virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc);
12311 virtual ~VerifyICEDiagnoser() {}
12312 };
12313
12314 enum AllowFoldKind {
12315 NoFold,
12316 AllowFold,
12317 };
12318
12319 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE,
12320 /// and reports the appropriate diagnostics. Returns false on success.
12321 /// Can optionally return the value of the expression.
12322 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12323 VerifyICEDiagnoser &Diagnoser,
12324 AllowFoldKind CanFold = NoFold);
12325 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12326 unsigned DiagID,
12327 AllowFoldKind CanFold = NoFold);
12328 ExprResult VerifyIntegerConstantExpression(Expr *E,
12329 llvm::APSInt *Result = nullptr,
12330 AllowFoldKind CanFold = NoFold);
12331 ExprResult VerifyIntegerConstantExpression(Expr *E,
12332 AllowFoldKind CanFold = NoFold) {
12333 return VerifyIntegerConstantExpression(E, nullptr, CanFold);
12334 }
12335
12336 /// VerifyBitField - verifies that a bit field expression is an ICE and has
12337 /// the correct width, and that the field type is valid.
12338 /// Returns false on success.
12339 /// Can optionally return whether the bit-field is of width 0
12340 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
12341 QualType FieldTy, bool IsMsStruct,
12342 Expr *BitWidth, bool *ZeroWidth = nullptr);
12343
12344private:
12345 unsigned ForceCUDAHostDeviceDepth = 0;
12346
12347public:
12348 /// Increments our count of the number of times we've seen a pragma forcing
12349 /// functions to be __host__ __device__. So long as this count is greater
12350 /// than zero, all functions encountered will be __host__ __device__.
12351 void PushForceCUDAHostDevice();
12352
12353 /// Decrements our count of the number of times we've seen a pragma forcing
12354 /// functions to be __host__ __device__. Returns false if the count is 0
12355 /// before incrementing, so you can emit an error.
12356 bool PopForceCUDAHostDevice();
12357
12358 /// Diagnostics that are emitted only if we discover that the given function
12359 /// must be codegen'ed. Because handling these correctly adds overhead to
12360 /// compilation, this is currently only enabled for CUDA compilations.
12361 llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>,
12362 std::vector<PartialDiagnosticAt>>
12363 DeviceDeferredDiags;
12364
12365 /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the
12366 /// key in a hashtable, both the FD and location are hashed.
12367 struct FunctionDeclAndLoc {
12368 CanonicalDeclPtr<FunctionDecl> FD;
12369 SourceLocation Loc;
12370 };
12371
12372 /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a
12373 /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the
12374 /// same deferred diag twice.
12375 llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags;
12376
12377 /// An inverse call graph, mapping known-emitted functions to one of their
12378 /// known-emitted callers (plus the location of the call).
12379 ///
12380 /// Functions that we can tell a priori must be emitted aren't added to this
12381 /// map.
12382 llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>,
12383 /* Caller = */ FunctionDeclAndLoc>
12384 DeviceKnownEmittedFns;
12385
12386 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12387 /// context is "used as device code".
12388 ///
12389 /// - If CurContext is a __host__ function, does not emit any diagnostics
12390 /// unless \p EmitOnBothSides is true.
12391 /// - If CurContext is a __device__ or __global__ function, emits the
12392 /// diagnostics immediately.
12393 /// - If CurContext is a __host__ __device__ function and we are compiling for
12394 /// the device, creates a diagnostic which is emitted if and when we realize
12395 /// that the function will be codegen'ed.
12396 ///
12397 /// Example usage:
12398 ///
12399 /// // Variable-length arrays are not allowed in CUDA device code.
12400 /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget())
12401 /// return ExprError();
12402 /// // Otherwise, continue parsing as normal.
12403 SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc,
12404 unsigned DiagID);
12405
12406 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12407 /// context is "used as host code".
12408 ///
12409 /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched.
12410 SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID);
12411
12412 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12413 /// context is "used as device code".
12414 ///
12415 /// - If CurContext is a `declare target` function or it is known that the
12416 /// function is emitted for the device, emits the diagnostics immediately.
12417 /// - If CurContext is a non-`declare target` function and we are compiling
12418 /// for the device, creates a diagnostic which is emitted if and when we
12419 /// realize that the function will be codegen'ed.
12420 ///
12421 /// Example usage:
12422 ///
12423 /// // Variable-length arrays are not allowed in NVPTX device code.
12424 /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported))
12425 /// return ExprError();
12426 /// // Otherwise, continue parsing as normal.
12427 SemaDiagnosticBuilder
12428 diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD);
12429
12430 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
12431 /// context is "used as host code".
12432 ///
12433 /// - If CurContext is a `declare target` function or it is known that the
12434 /// function is emitted for the host, emits the diagnostics immediately.
12435 /// - If CurContext is a non-host function, just ignore it.
12436 ///
12437 /// Example usage:
12438 ///
12439 /// // Variable-length arrays are not allowed in NVPTX device code.
12440 /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported))
12441 /// return ExprError();
12442 /// // Otherwise, continue parsing as normal.
12443 SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc,
12444 unsigned DiagID, FunctionDecl *FD);
12445
12446 SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID,
12447 FunctionDecl *FD = nullptr);
12448 SemaDiagnosticBuilder targetDiag(SourceLocation Loc,
12449 const PartialDiagnostic &PD,
12450 FunctionDecl *FD = nullptr) {
12451 return targetDiag(Loc, PD.getDiagID(), FD) << PD;
12452 }
12453
12454 /// Check if the type is allowed to be used for the current target.
12455 void checkTypeSupport(QualType Ty, SourceLocation Loc,
12456 ValueDecl *D = nullptr);
12457
12458 enum CUDAFunctionTarget {
12459 CFT_Device,
12460 CFT_Global,
12461 CFT_Host,
12462 CFT_HostDevice,
12463 CFT_InvalidTarget
12464 };
12465
12466 /// Determines whether the given function is a CUDA device/host/kernel/etc.
12467 /// function.
12468 ///
12469 /// Use this rather than examining the function's attributes yourself -- you
12470 /// will get it wrong. Returns CFT_Host if D is null.
12471 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D,
12472 bool IgnoreImplicitHDAttr = false);
12473 CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs);
12474
12475 enum CUDAVariableTarget {
12476 CVT_Device, /// Emitted on device side with a shadow variable on host side
12477 CVT_Host, /// Emitted on host side only
12478 CVT_Both, /// Emitted on both sides with different addresses
12479 CVT_Unified, /// Emitted as a unified address, e.g. managed variables
12480 };
12481 /// Determines whether the given variable is emitted on host or device side.
12482 CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D);
12483
12484 /// Gets the CUDA target for the current context.
12485 CUDAFunctionTarget CurrentCUDATarget() {
12486 return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext));
12487 }
12488
12489 static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D);
12490
12491 // CUDA function call preference. Must be ordered numerically from
12492 // worst to best.
12493 enum CUDAFunctionPreference {
12494 CFP_Never, // Invalid caller/callee combination.
12495 CFP_WrongSide, // Calls from host-device to host or device
12496 // function that do not match current compilation
12497 // mode.
12498 CFP_HostDevice, // Any calls to host/device functions.
12499 CFP_SameSide, // Calls from host-device to host or device
12500 // function matching current compilation mode.
12501 CFP_Native, // host-to-host or device-to-device calls.
12502 };
12503
12504 /// Identifies relative preference of a given Caller/Callee
12505 /// combination, based on their host/device attributes.
12506 /// \param Caller function which needs address of \p Callee.
12507 /// nullptr in case of global context.
12508 /// \param Callee target function
12509 ///
12510 /// \returns preference value for particular Caller/Callee combination.
12511 CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller,
12512 const FunctionDecl *Callee);
12513
12514 /// Determines whether Caller may invoke Callee, based on their CUDA
12515 /// host/device attributes. Returns false if the call is not allowed.
12516 ///
12517 /// Note: Will return true for CFP_WrongSide calls. These may appear in
12518 /// semantically correct CUDA programs, but only if they're never codegen'ed.
12519 bool IsAllowedCUDACall(const FunctionDecl *Caller,
12520 const FunctionDecl *Callee) {
12521 return IdentifyCUDAPreference(Caller, Callee) != CFP_Never;
12522 }
12523
12524 /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD,
12525 /// depending on FD and the current compilation settings.
12526 void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD,
12527 const LookupResult &Previous);
12528
12529 /// May add implicit CUDAConstantAttr attribute to VD, depending on VD
12530 /// and current compilation settings.
12531 void MaybeAddCUDAConstantAttr(VarDecl *VD);
12532
12533public:
12534 /// Check whether we're allowed to call Callee from the current context.
12535 ///
12536 /// - If the call is never allowed in a semantically-correct program
12537 /// (CFP_Never), emits an error and returns false.
12538 ///
12539 /// - If the call is allowed in semantically-correct programs, but only if
12540 /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to
12541 /// be emitted if and when the caller is codegen'ed, and returns true.
12542 ///
12543 /// Will only create deferred diagnostics for a given SourceLocation once,
12544 /// so you can safely call this multiple times without generating duplicate
12545 /// deferred errors.
12546 ///
12547 /// - Otherwise, returns true without emitting any diagnostics.
12548 bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee);
12549
12550 void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture);
12551
12552 /// Set __device__ or __host__ __device__ attributes on the given lambda
12553 /// operator() method.
12554 ///
12555 /// CUDA lambdas by default is host device function unless it has explicit
12556 /// host or device attribute.
12557 void CUDASetLambdaAttrs(CXXMethodDecl *Method);
12558
12559 /// Finds a function in \p Matches with highest calling priority
12560 /// from \p Caller context and erases all functions with lower
12561 /// calling priority.
12562 void EraseUnwantedCUDAMatches(
12563 const FunctionDecl *Caller,
12564 SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches);
12565
12566 /// Given a implicit special member, infer its CUDA target from the
12567 /// calls it needs to make to underlying base/field special members.
12568 /// \param ClassDecl the class for which the member is being created.
12569 /// \param CSM the kind of special member.
12570 /// \param MemberDecl the special member itself.
12571 /// \param ConstRHS true if this is a copy operation with a const object on
12572 /// its RHS.
12573 /// \param Diagnose true if this call should emit diagnostics.
12574 /// \return true if there was an error inferring.
12575 /// The result of this call is implicit CUDA target attribute(s) attached to
12576 /// the member declaration.
12577 bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl,
12578 CXXSpecialMember CSM,
12579 CXXMethodDecl *MemberDecl,
12580 bool ConstRHS,
12581 bool Diagnose);
12582
12583 /// \return true if \p CD can be considered empty according to CUDA
12584 /// (E.2.3.1 in CUDA 7.5 Programming guide).
12585 bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD);
12586 bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD);
12587
12588 // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In
12589 // case of error emits appropriate diagnostic and invalidates \p Var.
12590 //
12591 // \details CUDA allows only empty constructors as initializers for global
12592 // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all
12593 // __shared__ variables whether they are local or not (they all are implicitly
12594 // static in CUDA). One exception is that CUDA allows constant initializers
12595 // for __constant__ and __device__ variables.
12596 void checkAllowedCUDAInitializer(VarDecl *VD);
12597
12598 /// Check whether NewFD is a valid overload for CUDA. Emits
12599 /// diagnostics and invalidates NewFD if not.
12600 void checkCUDATargetOverload(FunctionDecl *NewFD,
12601 const LookupResult &Previous);
12602 /// Copies target attributes from the template TD to the function FD.
12603 void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD);
12604
12605 /// Returns the name of the launch configuration function. This is the name
12606 /// of the function that will be called to configure kernel call, with the
12607 /// parameters specified via <<<>>>.
12608 std::string getCudaConfigureFuncName() const;
12609
12610 /// \name Code completion
12611 //@{
12612 /// Describes the context in which code completion occurs.
12613 enum ParserCompletionContext {
12614 /// Code completion occurs at top-level or namespace context.
12615 PCC_Namespace,
12616 /// Code completion occurs within a class, struct, or union.
12617 PCC_Class,
12618 /// Code completion occurs within an Objective-C interface, protocol,
12619 /// or category.
12620 PCC_ObjCInterface,
12621 /// Code completion occurs within an Objective-C implementation or
12622 /// category implementation
12623 PCC_ObjCImplementation,
12624 /// Code completion occurs within the list of instance variables
12625 /// in an Objective-C interface, protocol, category, or implementation.
12626 PCC_ObjCInstanceVariableList,
12627 /// Code completion occurs following one or more template
12628 /// headers.
12629 PCC_Template,
12630 /// Code completion occurs following one or more template
12631 /// headers within a class.
12632 PCC_MemberTemplate,
12633 /// Code completion occurs within an expression.
12634 PCC_Expression,
12635 /// Code completion occurs within a statement, which may
12636 /// also be an expression or a declaration.
12637 PCC_Statement,
12638 /// Code completion occurs at the beginning of the
12639 /// initialization statement (or expression) in a for loop.
12640 PCC_ForInit,
12641 /// Code completion occurs within the condition of an if,
12642 /// while, switch, or for statement.
12643 PCC_Condition,
12644 /// Code completion occurs within the body of a function on a
12645 /// recovery path, where we do not have a specific handle on our position
12646 /// in the grammar.
12647 PCC_RecoveryInFunction,
12648 /// Code completion occurs where only a type is permitted.
12649 PCC_Type,
12650 /// Code completion occurs in a parenthesized expression, which
12651 /// might also be a type cast.
12652 PCC_ParenthesizedExpression,
12653 /// Code completion occurs within a sequence of declaration
12654 /// specifiers within a function, method, or block.
12655 PCC_LocalDeclarationSpecifiers
12656 };
12657
12658 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path);
12659 void CodeCompleteOrdinaryName(Scope *S,
12660 ParserCompletionContext CompletionContext);
12661 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS,
12662 bool AllowNonIdentifiers,
12663 bool AllowNestedNameSpecifiers);
12664
12665 struct CodeCompleteExpressionData;
12666 void CodeCompleteExpression(Scope *S,
12667 const CodeCompleteExpressionData &Data);
12668 void CodeCompleteExpression(Scope *S, QualType PreferredType,
12669 bool IsParenthesized = false);
12670 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase,
12671 SourceLocation OpLoc, bool IsArrow,
12672 bool IsBaseExprStatement,
12673 QualType PreferredType);
12674 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS,
12675 QualType PreferredType);
12676 void CodeCompleteTag(Scope *S, unsigned TagSpec);
12677 void CodeCompleteTypeQualifiers(DeclSpec &DS);
12678 void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D,
12679 const VirtSpecifiers *VS = nullptr);
12680 void CodeCompleteBracketDeclarator(Scope *S);
12681 void CodeCompleteCase(Scope *S);
12682 enum class AttributeCompletion {
12683 Attribute,
12684 Scope,
12685 None,
12686 };
12687 void CodeCompleteAttribute(
12688 AttributeCommonInfo::Syntax Syntax,
12689 AttributeCompletion Completion = AttributeCompletion::Attribute,
12690 const IdentifierInfo *Scope = nullptr);
12691 /// Determines the preferred type of the current function argument, by
12692 /// examining the signatures of all possible overloads.
12693 /// Returns null if unknown or ambiguous, or if code completion is off.
12694 ///
12695 /// If the code completion point has been reached, also reports the function
12696 /// signatures that were considered.
12697 ///
12698 /// FIXME: rename to GuessCallArgumentType to reduce confusion.
12699 QualType ProduceCallSignatureHelp(Expr *Fn, ArrayRef<Expr *> Args,
12700 SourceLocation OpenParLoc);
12701 QualType ProduceConstructorSignatureHelp(QualType Type, SourceLocation Loc,
12702 ArrayRef<Expr *> Args,
12703 SourceLocation OpenParLoc,
12704 bool Braced);
12705 QualType ProduceCtorInitMemberSignatureHelp(
12706 Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy,
12707 ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc,
12708 bool Braced);
12709 QualType ProduceTemplateArgumentSignatureHelp(
12710 TemplateTy, ArrayRef<ParsedTemplateArgument>, SourceLocation LAngleLoc);
12711 void CodeCompleteInitializer(Scope *S, Decl *D);
12712 /// Trigger code completion for a record of \p BaseType. \p InitExprs are
12713 /// expressions in the initializer list seen so far and \p D is the current
12714 /// Designation being parsed.
12715 void CodeCompleteDesignator(const QualType BaseType,
12716 llvm::ArrayRef<Expr *> InitExprs,
12717 const Designation &D);
12718 void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
12719
12720 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext,
12721 bool IsUsingDeclaration, QualType BaseType,
12722 QualType PreferredType);
12723 void CodeCompleteUsing(Scope *S);
12724 void CodeCompleteUsingDirective(Scope *S);
12725 void CodeCompleteNamespaceDecl(Scope *S);
12726 void CodeCompleteNamespaceAliasDecl(Scope *S);
12727 void CodeCompleteOperatorName(Scope *S);
12728 void CodeCompleteConstructorInitializer(
12729 Decl *Constructor,
12730 ArrayRef<CXXCtorInitializer *> Initializers);
12731
12732 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro,
12733 bool AfterAmpersand);
12734 void CodeCompleteAfterFunctionEquals(Declarator &D);
12735
12736 void CodeCompleteObjCAtDirective(Scope *S);
12737 void CodeCompleteObjCAtVisibility(Scope *S);
12738 void CodeCompleteObjCAtStatement(Scope *S);
12739 void CodeCompleteObjCAtExpression(Scope *S);
12740 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS);
12741 void CodeCompleteObjCPropertyGetter(Scope *S);
12742 void CodeCompleteObjCPropertySetter(Scope *S);
12743 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS,
12744 bool IsParameter);
12745 void CodeCompleteObjCMessageReceiver(Scope *S);
12746 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc,
12747 ArrayRef<IdentifierInfo *> SelIdents,
12748 bool AtArgumentExpression);
12749 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver,
12750 ArrayRef<IdentifierInfo *> SelIdents,
12751 bool AtArgumentExpression,
12752 bool IsSuper = false);
12753 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver,
12754 ArrayRef<IdentifierInfo *> SelIdents,
12755 bool AtArgumentExpression,
12756 ObjCInterfaceDecl *Super = nullptr);
12757 void CodeCompleteObjCForCollection(Scope *S,
12758 DeclGroupPtrTy IterationVar);
12759 void CodeCompleteObjCSelector(Scope *S,
12760 ArrayRef<IdentifierInfo *> SelIdents);
12761 void CodeCompleteObjCProtocolReferences(
12762 ArrayRef<IdentifierLocPair> Protocols);
12763 void CodeCompleteObjCProtocolDecl(Scope *S);
12764 void CodeCompleteObjCInterfaceDecl(Scope *S);
12765 void CodeCompleteObjCSuperclass(Scope *S,
12766 IdentifierInfo *ClassName,
12767 SourceLocation ClassNameLoc);
12768 void CodeCompleteObjCImplementationDecl(Scope *S);
12769 void CodeCompleteObjCInterfaceCategory(Scope *S,
12770 IdentifierInfo *ClassName,
12771 SourceLocation ClassNameLoc);
12772 void CodeCompleteObjCImplementationCategory(Scope *S,
12773 IdentifierInfo *ClassName,
12774 SourceLocation ClassNameLoc);
12775 void CodeCompleteObjCPropertyDefinition(Scope *S);
12776 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S,
12777 IdentifierInfo *PropertyName);
12778 void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod,
12779 ParsedType ReturnType);
12780 void CodeCompleteObjCMethodDeclSelector(Scope *S,
12781 bool IsInstanceMethod,
12782 bool AtParameterName,
12783 ParsedType ReturnType,
12784 ArrayRef<IdentifierInfo *> SelIdents);
12785 void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName,
12786 SourceLocation ClassNameLoc,
12787 bool IsBaseExprStatement);
12788 void CodeCompletePreprocessorDirective(bool InConditional);
12789 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S);
12790 void CodeCompletePreprocessorMacroName(bool IsDefinition);
12791 void CodeCompletePreprocessorExpression();
12792 void CodeCompletePreprocessorMacroArgument(Scope *S,
12793 IdentifierInfo *Macro,
12794 MacroInfo *MacroInfo,
12795 unsigned Argument);
12796 void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled);
12797 void CodeCompleteNaturalLanguage();
12798 void CodeCompleteAvailabilityPlatformName();
12799 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator,
12800 CodeCompletionTUInfo &CCTUInfo,
12801 SmallVectorImpl<CodeCompletionResult> &Results);
12802 //@}
12803
12804 //===--------------------------------------------------------------------===//
12805 // Extra semantic analysis beyond the C type system
12806
12807public:
12808 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL,
12809 unsigned ByteNo) const;
12810
12811private:
12812 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
12813 const ArraySubscriptExpr *ASE=nullptr,
12814 bool AllowOnePastEnd=true, bool IndexNegated=false);
12815 void CheckArrayAccess(const Expr *E);
12816 // Used to grab the relevant information from a FormatAttr and a
12817 // FunctionDeclaration.
12818 struct FormatStringInfo {
12819 unsigned FormatIdx;
12820 unsigned FirstDataArg;
12821 bool HasVAListArg;
12822 };
12823
12824 static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
12825 FormatStringInfo *FSI);
12826 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
12827 const FunctionProtoType *Proto);
12828 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc,
12829 ArrayRef<const Expr *> Args);
12830 bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
12831 const FunctionProtoType *Proto);
12832 bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto);
12833 void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
12834 ArrayRef<const Expr *> Args,
12835 const FunctionProtoType *Proto, SourceLocation Loc);
12836
12837 void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
12838 StringRef ParamName, QualType ArgTy, QualType ParamTy);
12839
12840 void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
12841 const Expr *ThisArg, ArrayRef<const Expr *> Args,
12842 bool IsMemberFunction, SourceLocation Loc, SourceRange Range,
12843 VariadicCallType CallType);
12844
12845 bool CheckObjCString(Expr *Arg);
12846 ExprResult CheckOSLogFormatStringArg(Expr *Arg);
12847
12848 ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl,
12849 unsigned BuiltinID, CallExpr *TheCall);
12850
12851 bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12852 CallExpr *TheCall);
12853
12854 void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall);
12855
12856 bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
12857 unsigned MaxWidth);
12858 bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12859 CallExpr *TheCall);
12860 bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12861 bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12862 bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12863 CallExpr *TheCall);
12864 bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg,
12865 bool WantCDE);
12866 bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12867 CallExpr *TheCall);
12868
12869 bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12870 CallExpr *TheCall);
12871 bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12872 bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12873 bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12874 bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12875 CallExpr *TheCall);
12876 bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
12877 CallExpr *TheCall);
12878 bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall);
12879 bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12880 bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall);
12881 bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall);
12882 bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall);
12883 bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
12884 ArrayRef<int> ArgNums);
12885 bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums);
12886 bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
12887 ArrayRef<int> ArgNums);
12888 bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12889 CallExpr *TheCall);
12890 bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12891 CallExpr *TheCall);
12892 bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall);
12893 bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum);
12894 bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
12895 CallExpr *TheCall);
12896
12897 bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall);
12898 bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call);
12899 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall);
12900 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs);
12901 bool SemaBuiltinComplex(CallExpr *TheCall);
12902 bool SemaBuiltinVSX(CallExpr *TheCall);
12903 bool SemaBuiltinOSLogFormat(CallExpr *TheCall);
12904 bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
12905
12906public:
12907 // Used by C++ template instantiation.
12908 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall);
12909 ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
12910 SourceLocation BuiltinLoc,
12911 SourceLocation RParenLoc);
12912
12913private:
12914 bool SemaBuiltinPrefetch(CallExpr *TheCall);
12915 bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall);
12916 bool SemaBuiltinArithmeticFence(CallExpr *TheCall);
12917 bool SemaBuiltinAssume(CallExpr *TheCall);
12918 bool SemaBuiltinAssumeAligned(CallExpr *TheCall);
12919 bool SemaBuiltinLongjmp(CallExpr *TheCall);
12920 bool SemaBuiltinSetjmp(CallExpr *TheCall);
12921 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult);
12922 ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult);
12923 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult,
12924 AtomicExpr::AtomicOp Op);
12925 ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
12926 bool IsDelete);
12927 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
12928 llvm::APSInt &Result);
12929 bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low,
12930 int High, bool RangeIsError = true);
12931 bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
12932 unsigned Multiple);
12933 bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum);
12934 bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
12935 unsigned ArgBits);
12936 bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum,
12937 unsigned ArgBits);
12938 bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
12939 int ArgNum, unsigned ExpectedFieldNum,
12940 bool AllowName);
12941 bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall);
12942 bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
12943 const char *TypeDesc);
12944
12945 bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc);
12946
12947 bool SemaBuiltinElementwiseMath(CallExpr *TheCall);
12948 bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall);
12949 bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall);
12950
12951 // Matrix builtin handling.
12952 ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall,
12953 ExprResult CallResult);
12954 ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
12955 ExprResult CallResult);
12956 ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
12957 ExprResult CallResult);
12958
12959public:
12960 enum FormatStringType {
12961 FST_Scanf,
12962 FST_Printf,
12963 FST_NSString,
12964 FST_Strftime,
12965 FST_Strfmon,
12966 FST_Kprintf,
12967 FST_FreeBSDKPrintf,
12968 FST_OSTrace,
12969 FST_OSLog,
12970 FST_Unknown
12971 };
12972 static FormatStringType GetFormatStringType(const FormatAttr *Format);
12973
12974 bool FormatStringHasSArg(const StringLiteral *FExpr);
12975
12976 static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx);
12977
12978private:
12979 bool CheckFormatArguments(const FormatAttr *Format,
12980 ArrayRef<const Expr *> Args,
12981 bool IsCXXMember,
12982 VariadicCallType CallType,
12983 SourceLocation Loc, SourceRange Range,
12984 llvm::SmallBitVector &CheckedVarArgs);
12985 bool CheckFormatArguments(ArrayRef<const Expr *> Args,
12986 bool HasVAListArg, unsigned format_idx,
12987 unsigned firstDataArg, FormatStringType Type,
12988 VariadicCallType CallType,
12989 SourceLocation Loc, SourceRange range,
12990 llvm::SmallBitVector &CheckedVarArgs);
12991
12992 void CheckAbsoluteValueFunction(const CallExpr *Call,
12993 const FunctionDecl *FDecl);
12994
12995 void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl);
12996
12997 void CheckMemaccessArguments(const CallExpr *Call,
12998 unsigned BId,
12999 IdentifierInfo *FnName);
13000
13001 void CheckStrlcpycatArguments(const CallExpr *Call,
13002 IdentifierInfo *FnName);
13003
13004 void CheckStrncatArguments(const CallExpr *Call,
13005 IdentifierInfo *FnName);
13006
13007 void CheckFreeArguments(const CallExpr *E);
13008
13009 void CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
13010 SourceLocation ReturnLoc,
13011 bool isObjCMethod = false,
13012 const AttrVec *Attrs = nullptr,
13013 const FunctionDecl *FD = nullptr);
13014
13015public:
13016 void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS,
13017 BinaryOperatorKind Opcode);
13018
13019private:
13020 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation());
13021 void CheckBoolLikeConversion(Expr *E, SourceLocation CC);
13022 void CheckForIntOverflow(Expr *E);
13023 void CheckUnsequencedOperations(const Expr *E);
13024
13025 /// Perform semantic checks on a completed expression. This will either
13026 /// be a full-expression or a default argument expression.
13027 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(),
13028 bool IsConstexpr = false);
13029
13030 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field,
13031 Expr *Init);
13032
13033 /// Check if there is a field shadowing.
13034 void CheckShadowInheritedFields(const SourceLocation &Loc,
13035 DeclarationName FieldName,
13036 const CXXRecordDecl *RD,
13037 bool DeclIsField = true);
13038
13039 /// Check if the given expression contains 'break' or 'continue'
13040 /// statement that produces control flow different from GCC.
13041 void CheckBreakContinueBinding(Expr *E);
13042
13043 /// Check whether receiver is mutable ObjC container which
13044 /// attempts to add itself into the container
13045 void CheckObjCCircularContainer(ObjCMessageExpr *Message);
13046
13047 void CheckTCBEnforcement(const SourceLocation CallExprLoc,
13048 const NamedDecl *Callee);
13049
13050 void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE);
13051 void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
13052 bool DeleteWasArrayForm);
13053public:
13054 /// Register a magic integral constant to be used as a type tag.
13055 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
13056 uint64_t MagicValue, QualType Type,
13057 bool LayoutCompatible, bool MustBeNull);
13058
13059 struct TypeTagData {
13060 TypeTagData() {}
13061
13062 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) :
13063 Type(Type), LayoutCompatible(LayoutCompatible),
13064 MustBeNull(MustBeNull)
13065 {}
13066
13067 QualType Type;
13068
13069 /// If true, \c Type should be compared with other expression's types for
13070 /// layout-compatibility.
13071 unsigned LayoutCompatible : 1;
13072 unsigned MustBeNull : 1;
13073 };
13074
13075 /// A pair of ArgumentKind identifier and magic value. This uniquely
13076 /// identifies the magic value.
13077 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue;
13078
13079private:
13080 /// A map from magic value to type information.
13081 std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>>
13082 TypeTagForDatatypeMagicValues;
13083
13084 /// Peform checks on a call of a function with argument_with_type_tag
13085 /// or pointer_with_type_tag attributes.
13086 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
13087 const ArrayRef<const Expr *> ExprArgs,
13088 SourceLocation CallSiteLoc);
13089
13090 /// Check if we are taking the address of a packed field
13091 /// as this may be a problem if the pointer value is dereferenced.
13092 void CheckAddressOfPackedMember(Expr *rhs);
13093
13094 /// The parser's current scope.
13095 ///
13096 /// The parser maintains this state here.
13097 Scope *CurScope;
13098
13099 mutable IdentifierInfo *Ident_super;
13100 mutable IdentifierInfo *Ident___float128;
13101
13102 /// Nullability type specifiers.
13103 IdentifierInfo *Ident__Nonnull = nullptr;
13104 IdentifierInfo *Ident__Nullable = nullptr;
13105 IdentifierInfo *Ident__Nullable_result = nullptr;
13106 IdentifierInfo *Ident__Null_unspecified = nullptr;
13107
13108 IdentifierInfo *Ident_NSError = nullptr;
13109
13110 /// The handler for the FileChanged preprocessor events.
13111 ///
13112 /// Used for diagnostics that implement custom semantic analysis for #include
13113 /// directives, like -Wpragma-pack.
13114 sema::SemaPPCallbacks *SemaPPCallbackHandler;
13115
13116protected:
13117 friend class Parser;
13118 friend class InitializationSequence;
13119 friend class ASTReader;
13120 friend class ASTDeclReader;
13121 friend class ASTWriter;
13122
13123public:
13124 /// Retrieve the keyword associated
13125 IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability);
13126
13127 /// The struct behind the CFErrorRef pointer.
13128 RecordDecl *CFError = nullptr;
13129 bool isCFError(RecordDecl *D);
13130
13131 /// Retrieve the identifier "NSError".
13132 IdentifierInfo *getNSErrorIdent();
13133
13134 /// Retrieve the parser's current scope.
13135 ///
13136 /// This routine must only be used when it is certain that semantic analysis
13137 /// and the parser are in precisely the same context, which is not the case
13138 /// when, e.g., we are performing any kind of template instantiation.
13139 /// Therefore, the only safe places to use this scope are in the parser
13140 /// itself and in routines directly invoked from the parser and *never* from
13141 /// template substitution or instantiation.
13142 Scope *getCurScope() const { return CurScope; }
13143
13144 void incrementMSManglingNumber() const {
13145 return CurScope->incrementMSManglingNumber();
13146 }
13147
13148 IdentifierInfo *getSuperIdentifier() const;
13149 IdentifierInfo *getFloat128Identifier() const;
13150
13151 Decl *getObjCDeclContext() const;
13152
13153 DeclContext *getCurLexicalContext() const {
13154 return OriginalLexicalContext ? OriginalLexicalContext : CurContext;
13155 }
13156
13157 const DeclContext *getCurObjCLexicalContext() const {
13158 const DeclContext *DC = getCurLexicalContext();
13159 // A category implicitly has the attribute of the interface.
13160 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC))
13161 DC = CatD->getClassInterface();
13162 return DC;
13163 }
13164
13165 /// Determine the number of levels of enclosing template parameters. This is
13166 /// only usable while parsing. Note that this does not include dependent
13167 /// contexts in which no template parameters have yet been declared, such as
13168 /// in a terse function template or generic lambda before the first 'auto' is
13169 /// encountered.
13170 unsigned getTemplateDepth(Scope *S) const;
13171
13172 /// To be used for checking whether the arguments being passed to
13173 /// function exceeds the number of parameters expected for it.
13174 static bool TooManyArguments(size_t NumParams, size_t NumArgs,
13175 bool PartialOverloading = false) {
13176 // We check whether we're just after a comma in code-completion.
13177 if (NumArgs > 0 && PartialOverloading)
13178 return NumArgs + 1 > NumParams; // If so, we view as an extra argument.
13179 return NumArgs > NumParams;
13180 }
13181
13182 // Emitting members of dllexported classes is delayed until the class
13183 // (including field initializers) is fully parsed.
13184 SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses;
13185 SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions;
13186
13187private:
13188 int ParsingClassDepth = 0;
13189
13190 class SavePendingParsedClassStateRAII {
13191 public:
13192 SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); }
13193
13194 ~SavePendingParsedClassStateRAII() {
13195 assert(S.DelayedOverridingExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedOverridingExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13196, __extension__ __PRETTY_FUNCTION__
))
13196 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedOverridingExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedOverridingExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13196, __extension__ __PRETTY_FUNCTION__
))
;
13197 assert(S.DelayedEquivalentExceptionSpecChecks.empty() &&(static_cast <bool> (S.DelayedEquivalentExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13198, __extension__ __PRETTY_FUNCTION__
))
13198 "there shouldn't be any pending delayed exception spec checks")(static_cast <bool> (S.DelayedEquivalentExceptionSpecChecks
.empty() && "there shouldn't be any pending delayed exception spec checks"
) ? void (0) : __assert_fail ("S.DelayedEquivalentExceptionSpecChecks.empty() && \"there shouldn't be any pending delayed exception spec checks\""
, "clang/include/clang/Sema/Sema.h", 13198, __extension__ __PRETTY_FUNCTION__
))
;
13199 swapSavedState();
13200 }
13201
13202 private:
13203 Sema &S;
13204 decltype(DelayedOverridingExceptionSpecChecks)
13205 SavedOverridingExceptionSpecChecks;
13206 decltype(DelayedEquivalentExceptionSpecChecks)
13207 SavedEquivalentExceptionSpecChecks;
13208
13209 void swapSavedState() {
13210 SavedOverridingExceptionSpecChecks.swap(
13211 S.DelayedOverridingExceptionSpecChecks);
13212 SavedEquivalentExceptionSpecChecks.swap(
13213 S.DelayedEquivalentExceptionSpecChecks);
13214 }
13215 };
13216
13217 /// Helper class that collects misaligned member designations and
13218 /// their location info for delayed diagnostics.
13219 struct MisalignedMember {
13220 Expr *E;
13221 RecordDecl *RD;
13222 ValueDecl *MD;
13223 CharUnits Alignment;
13224
13225 MisalignedMember() : E(), RD(), MD() {}
13226 MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD,
13227 CharUnits Alignment)
13228 : E(E), RD(RD), MD(MD), Alignment(Alignment) {}
13229 explicit MisalignedMember(Expr *E)
13230 : MisalignedMember(E, nullptr, nullptr, CharUnits()) {}
13231
13232 bool operator==(const MisalignedMember &m) { return this->E == m.E; }
13233 };
13234 /// Small set of gathered accesses to potentially misaligned members
13235 /// due to the packed attribute.
13236 SmallVector<MisalignedMember, 4> MisalignedMembers;
13237
13238 /// Adds an expression to the set of gathered misaligned members.
13239 void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
13240 CharUnits Alignment);
13241
13242public:
13243 /// Diagnoses the current set of gathered accesses. This typically
13244 /// happens at full expression level. The set is cleared after emitting the
13245 /// diagnostics.
13246 void DiagnoseMisalignedMembers();
13247
13248 /// This function checks if the expression is in the sef of potentially
13249 /// misaligned members and it is converted to some pointer type T with lower
13250 /// or equal alignment requirements. If so it removes it. This is used when
13251 /// we do not want to diagnose such misaligned access (e.g. in conversions to
13252 /// void*).
13253 void DiscardMisalignedMemberAddress(const Type *T, Expr *E);
13254
13255 /// This function calls Action when it determines that E designates a
13256 /// misaligned member due to the packed attribute. This is used to emit
13257 /// local diagnostics like in reference binding.
13258 void RefersToMemberWithReducedAlignment(
13259 Expr *E,
13260 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
13261 Action);
13262
13263 /// Describes the reason a calling convention specification was ignored, used
13264 /// for diagnostics.
13265 enum class CallingConventionIgnoredReason {
13266 ForThisTarget = 0,
13267 VariadicFunction,
13268 ConstructorDestructor,
13269 BuiltinFunction
13270 };
13271 /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current
13272 /// context is "used as device code".
13273 ///
13274 /// - If CurLexicalContext is a kernel function or it is known that the
13275 /// function will be emitted for the device, emits the diagnostics
13276 /// immediately.
13277 /// - If CurLexicalContext is a function and we are compiling
13278 /// for the device, but we don't know that this function will be codegen'ed
13279 /// for devive yet, creates a diagnostic which is emitted if and when we
13280 /// realize that the function will be codegen'ed.
13281 ///
13282 /// Example usage:
13283 ///
13284 /// Diagnose __float128 type usage only from SYCL device code if the current
13285 /// target doesn't support it
13286 /// if (!S.Context.getTargetInfo().hasFloat128Type() &&
13287 /// S.getLangOpts().SYCLIsDevice)
13288 /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128";
13289 SemaDiagnosticBuilder SYCLDiagIfDeviceCode(SourceLocation Loc,
13290 unsigned DiagID);
13291
13292 /// Check whether we're allowed to call Callee from the current context.
13293 ///
13294 /// - If the call is never allowed in a semantically-correct program
13295 /// emits an error and returns false.
13296 ///
13297 /// - If the call is allowed in semantically-correct programs, but only if
13298 /// it's never codegen'ed, creates a deferred diagnostic to be emitted if
13299 /// and when the caller is codegen'ed, and returns true.
13300 ///
13301 /// - Otherwise, returns true without emitting any diagnostics.
13302 ///
13303 /// Adds Callee to DeviceCallGraph if we don't know if its caller will be
13304 /// codegen'ed yet.
13305 bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee);
13306 void deepTypeCheckForSYCLDevice(SourceLocation UsedAt,
13307 llvm::DenseSet<QualType> Visited,
13308 ValueDecl *DeclToCheck);
13309};
13310
13311/// RAII object that enters a new expression evaluation context.
13312class EnterExpressionEvaluationContext {
13313 Sema &Actions;
13314 bool Entered = true;
13315
13316public:
13317 EnterExpressionEvaluationContext(
13318 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13319 Decl *LambdaContextDecl = nullptr,
13320 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13321 Sema::ExpressionEvaluationContextRecord::EK_Other,
13322 bool ShouldEnter = true)
13323 : Actions(Actions), Entered(ShouldEnter) {
13324 if (Entered)
13325 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl,
13326 ExprContext);
13327 }
13328 EnterExpressionEvaluationContext(
13329 Sema &Actions, Sema::ExpressionEvaluationContext NewContext,
13330 Sema::ReuseLambdaContextDecl_t,
13331 Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext =
13332 Sema::ExpressionEvaluationContextRecord::EK_Other)
13333 : Actions(Actions) {
13334 Actions.PushExpressionEvaluationContext(
13335 NewContext, Sema::ReuseLambdaContextDecl, ExprContext);
13336 }
13337
13338 enum InitListTag { InitList };
13339 EnterExpressionEvaluationContext(Sema &Actions, InitListTag,
13340 bool ShouldEnter = true)
13341 : Actions(Actions), Entered(false) {
13342 // In C++11 onwards, narrowing checks are performed on the contents of
13343 // braced-init-lists, even when they occur within unevaluated operands.
13344 // Therefore we still need to instantiate constexpr functions used in such
13345 // a context.
13346 if (ShouldEnter && Actions.isUnevaluatedContext() &&
13347 Actions.getLangOpts().CPlusPlus11) {
13348 Actions.PushExpressionEvaluationContext(
13349 Sema::ExpressionEvaluationContext::UnevaluatedList);
13350 Entered = true;
13351 }
13352 }
13353
13354 ~EnterExpressionEvaluationContext() {
13355 if (Entered)
13356 Actions.PopExpressionEvaluationContext();
13357 }
13358};
13359
13360DeductionFailureInfo
13361MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK,
13362 sema::TemplateDeductionInfo &Info);
13363
13364/// Contains a late templated function.
13365/// Will be parsed at the end of the translation unit, used by Sema & Parser.
13366struct LateParsedTemplate {
13367 CachedTokens Toks;
13368 /// The template function declaration to be late parsed.
13369 Decl *D;
13370};
13371
13372template <>
13373void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation,
13374 PragmaMsStackAction Action,
13375 llvm::StringRef StackSlotLabel,
13376 AlignPackInfo Value);
13377
13378} // end namespace clang
13379
13380namespace llvm {
13381// Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its
13382// SourceLocation.
13383template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> {
13384 using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc;
13385 using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>;
13386
13387 static FunctionDeclAndLoc getEmptyKey() {
13388 return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()};
13389 }
13390
13391 static FunctionDeclAndLoc getTombstoneKey() {
13392 return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()};
13393 }
13394
13395 static unsigned getHashValue(const FunctionDeclAndLoc &FDL) {
13396 return hash_combine(FDBaseInfo::getHashValue(FDL.FD),
13397 FDL.Loc.getHashValue());
13398 }
13399
13400 static bool isEqual(const FunctionDeclAndLoc &LHS,
13401 const FunctionDeclAndLoc &RHS) {
13402 return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc;
13403 }
13404};
13405} // namespace llvm
13406
13407#endif

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include/clang/AST/ExprCXX.h

1//===- ExprCXX.h - Classes for representing expressions ---------*- 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/// \file
10/// Defines the clang::Expr interface and subclasses for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_EXPRCXX_H
15#define LLVM_CLANG_AST_EXPRCXX_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ComputeDependence.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/DependenceFlags.h"
25#include "clang/AST/Expr.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/OperationKinds.h"
28#include "clang/AST/Stmt.h"
29#include "clang/AST/StmtCXX.h"
30#include "clang/AST/TemplateBase.h"
31#include "clang/AST/Type.h"
32#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/ExceptionSpecificationType.h"
34#include "clang/Basic/ExpressionTraits.h"
35#include "clang/Basic/LLVM.h"
36#include "clang/Basic/Lambda.h"
37#include "clang/Basic/LangOptions.h"
38#include "clang/Basic/OperatorKinds.h"
39#include "clang/Basic/SourceLocation.h"
40#include "clang/Basic/Specifiers.h"
41#include "clang/Basic/TypeTraits.h"
42#include "llvm/ADT/ArrayRef.h"
43#include "llvm/ADT/None.h"
44#include "llvm/ADT/Optional.h"
45#include "llvm/ADT/PointerUnion.h"
46#include "llvm/ADT/StringRef.h"
47#include "llvm/ADT/iterator_range.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/Compiler.h"
50#include "llvm/Support/TrailingObjects.h"
51#include <cassert>
52#include <cstddef>
53#include <cstdint>
54#include <memory>
55
56namespace clang {
57
58class ASTContext;
59class DeclAccessPair;
60class IdentifierInfo;
61class LambdaCapture;
62class NonTypeTemplateParmDecl;
63class TemplateParameterList;
64
65//===--------------------------------------------------------------------===//
66// C++ Expressions.
67//===--------------------------------------------------------------------===//
68
69/// A call to an overloaded operator written using operator
70/// syntax.
71///
72/// Represents a call to an overloaded operator written using operator
73/// syntax, e.g., "x + y" or "*p". While semantically equivalent to a
74/// normal call, this AST node provides better information about the
75/// syntactic representation of the call.
76///
77/// In a C++ template, this expression node kind will be used whenever
78/// any of the arguments are type-dependent. In this case, the
79/// function itself will be a (possibly empty) set of functions and
80/// function templates that were found by name lookup at template
81/// definition time.
82class CXXOperatorCallExpr final : public CallExpr {
83 friend class ASTStmtReader;
84 friend class ASTStmtWriter;
85
86 SourceRange Range;
87
88 // CXXOperatorCallExpr has some trailing objects belonging
89 // to CallExpr. See CallExpr for the details.
90
91 SourceRange getSourceRangeImpl() const LLVM_READONLY__attribute__((__pure__));
92
93 CXXOperatorCallExpr(OverloadedOperatorKind OpKind, Expr *Fn,
94 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
95 SourceLocation OperatorLoc, FPOptionsOverride FPFeatures,
96 ADLCallKind UsesADL);
97
98 CXXOperatorCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
99
100public:
101 static CXXOperatorCallExpr *
102 Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn,
103 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
104 SourceLocation OperatorLoc, FPOptionsOverride FPFeatures,
105 ADLCallKind UsesADL = NotADL);
106
107 static CXXOperatorCallExpr *CreateEmpty(const ASTContext &Ctx,
108 unsigned NumArgs, bool HasFPFeatures,
109 EmptyShell Empty);
110
111 /// Returns the kind of overloaded operator that this expression refers to.
112 OverloadedOperatorKind getOperator() const {
113 return static_cast<OverloadedOperatorKind>(
114 CXXOperatorCallExprBits.OperatorKind);
115 }
116
117 static bool isAssignmentOp(OverloadedOperatorKind Opc) {
118 return Opc == OO_Equal || Opc == OO_StarEqual || Opc == OO_SlashEqual ||
119 Opc == OO_PercentEqual || Opc == OO_PlusEqual ||
120 Opc == OO_MinusEqual || Opc == OO_LessLessEqual ||
121 Opc == OO_GreaterGreaterEqual || Opc == OO_AmpEqual ||
122 Opc == OO_CaretEqual || Opc == OO_PipeEqual;
123 }
124 bool isAssignmentOp() const { return isAssignmentOp(getOperator()); }
125
126 static bool isComparisonOp(OverloadedOperatorKind Opc) {
127 switch (Opc) {
128 case OO_EqualEqual:
129 case OO_ExclaimEqual:
130 case OO_Greater:
131 case OO_GreaterEqual:
132 case OO_Less:
133 case OO_LessEqual:
134 case OO_Spaceship:
135 return true;
136 default:
137 return false;
138 }
139 }
140 bool isComparisonOp() const { return isComparisonOp(getOperator()); }
141
142 /// Is this written as an infix binary operator?
143 bool isInfixBinaryOp() const;
144
145 /// Returns the location of the operator symbol in the expression.
146 ///
147 /// When \c getOperator()==OO_Call, this is the location of the right
148 /// parentheses; when \c getOperator()==OO_Subscript, this is the location
149 /// of the right bracket.
150 SourceLocation getOperatorLoc() const { return getRParenLoc(); }
151
152 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
153 OverloadedOperatorKind Operator = getOperator();
154 return (Operator < OO_Plus || Operator >= OO_Arrow ||
155 Operator == OO_PlusPlus || Operator == OO_MinusMinus)
156 ? getBeginLoc()
157 : getOperatorLoc();
158 }
159
160 SourceLocation getBeginLoc() const { return Range.getBegin(); }
161 SourceLocation getEndLoc() const { return Range.getEnd(); }
162 SourceRange getSourceRange() const { return Range; }
163
164 static bool classof(const Stmt *T) {
165 return T->getStmtClass() == CXXOperatorCallExprClass;
166 }
167};
168
169/// Represents a call to a member function that
170/// may be written either with member call syntax (e.g., "obj.func()"
171/// or "objptr->func()") or with normal function-call syntax
172/// ("func()") within a member function that ends up calling a member
173/// function. The callee in either case is a MemberExpr that contains
174/// both the object argument and the member function, while the
175/// arguments are the arguments within the parentheses (not including
176/// the object argument).
177class CXXMemberCallExpr final : public CallExpr {
178 // CXXMemberCallExpr has some trailing objects belonging
179 // to CallExpr. See CallExpr for the details.
180
181 CXXMemberCallExpr(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
182 ExprValueKind VK, SourceLocation RP,
183 FPOptionsOverride FPOptions, unsigned MinNumArgs);
184
185 CXXMemberCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
186
187public:
188 static CXXMemberCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
189 ArrayRef<Expr *> Args, QualType Ty,
190 ExprValueKind VK, SourceLocation RP,
191 FPOptionsOverride FPFeatures,
192 unsigned MinNumArgs = 0);
193
194 static CXXMemberCallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
195 bool HasFPFeatures, EmptyShell Empty);
196
197 /// Retrieve the implicit object argument for the member call.
198 ///
199 /// For example, in "x.f(5)", this returns the sub-expression "x".
200 Expr *getImplicitObjectArgument() const;
201
202 /// Retrieve the type of the object argument.
203 ///
204 /// Note that this always returns a non-pointer type.
205 QualType getObjectType() const;
206
207 /// Retrieve the declaration of the called method.
208 CXXMethodDecl *getMethodDecl() const;
209
210 /// Retrieve the CXXRecordDecl for the underlying type of
211 /// the implicit object argument.
212 ///
213 /// Note that this is may not be the same declaration as that of the class
214 /// context of the CXXMethodDecl which this function is calling.
215 /// FIXME: Returns 0 for member pointer call exprs.
216 CXXRecordDecl *getRecordDecl() const;
217
218 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
219 SourceLocation CLoc = getCallee()->getExprLoc();
220 if (CLoc.isValid())
221 return CLoc;
222
223 return getBeginLoc();
224 }
225
226 static bool classof(const Stmt *T) {
227 return T->getStmtClass() == CXXMemberCallExprClass;
228 }
229};
230
231/// Represents a call to a CUDA kernel function.
232class CUDAKernelCallExpr final : public CallExpr {
233 friend class ASTStmtReader;
234
235 enum { CONFIG, END_PREARG };
236
237 // CUDAKernelCallExpr has some trailing objects belonging
238 // to CallExpr. See CallExpr for the details.
239
240 CUDAKernelCallExpr(Expr *Fn, CallExpr *Config, ArrayRef<Expr *> Args,
241 QualType Ty, ExprValueKind VK, SourceLocation RP,
242 FPOptionsOverride FPFeatures, unsigned MinNumArgs);
243
244 CUDAKernelCallExpr(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
245
246public:
247 static CUDAKernelCallExpr *Create(const ASTContext &Ctx, Expr *Fn,
248 CallExpr *Config, ArrayRef<Expr *> Args,
249 QualType Ty, ExprValueKind VK,
250 SourceLocation RP,
251 FPOptionsOverride FPFeatures,
252 unsigned MinNumArgs = 0);
253
254 static CUDAKernelCallExpr *CreateEmpty(const ASTContext &Ctx,
255 unsigned NumArgs, bool HasFPFeatures,
256 EmptyShell Empty);
257
258 const CallExpr *getConfig() const {
259 return cast_or_null<CallExpr>(getPreArg(CONFIG));
260 }
261 CallExpr *getConfig() { return cast_or_null<CallExpr>(getPreArg(CONFIG)); }
262
263 static bool classof(const Stmt *T) {
264 return T->getStmtClass() == CUDAKernelCallExprClass;
265 }
266};
267
268/// A rewritten comparison expression that was originally written using
269/// operator syntax.
270///
271/// In C++20, the following rewrites are performed:
272/// - <tt>a == b</tt> -> <tt>b == a</tt>
273/// - <tt>a != b</tt> -> <tt>!(a == b)</tt>
274/// - <tt>a != b</tt> -> <tt>!(b == a)</tt>
275/// - For \c \@ in \c <, \c <=, \c >, \c >=, \c <=>:
276/// - <tt>a @ b</tt> -> <tt>(a <=> b) @ 0</tt>
277/// - <tt>a @ b</tt> -> <tt>0 @ (b <=> a)</tt>
278///
279/// This expression provides access to both the original syntax and the
280/// rewritten expression.
281///
282/// Note that the rewritten calls to \c ==, \c <=>, and \c \@ are typically
283/// \c CXXOperatorCallExprs, but could theoretically be \c BinaryOperators.
284class CXXRewrittenBinaryOperator : public Expr {
285 friend class ASTStmtReader;
286
287 /// The rewritten semantic form.
288 Stmt *SemanticForm;
289
290public:
291 CXXRewrittenBinaryOperator(Expr *SemanticForm, bool IsReversed)
292 : Expr(CXXRewrittenBinaryOperatorClass, SemanticForm->getType(),
293 SemanticForm->getValueKind(), SemanticForm->getObjectKind()),
294 SemanticForm(SemanticForm) {
295 CXXRewrittenBinaryOperatorBits.IsReversed = IsReversed;
296 setDependence(computeDependence(this));
297 }
298 CXXRewrittenBinaryOperator(EmptyShell Empty)
299 : Expr(CXXRewrittenBinaryOperatorClass, Empty), SemanticForm() {}
300
301 /// Get an equivalent semantic form for this expression.
302 Expr *getSemanticForm() { return cast<Expr>(SemanticForm); }
303 const Expr *getSemanticForm() const { return cast<Expr>(SemanticForm); }
304
305 struct DecomposedForm {
306 /// The original opcode, prior to rewriting.
307 BinaryOperatorKind Opcode;
308 /// The original left-hand side.
309 const Expr *LHS;
310 /// The original right-hand side.
311 const Expr *RHS;
312 /// The inner \c == or \c <=> operator expression.
313 const Expr *InnerBinOp;
314 };
315
316 /// Decompose this operator into its syntactic form.
317 DecomposedForm getDecomposedForm() const LLVM_READONLY__attribute__((__pure__));
318
319 /// Determine whether this expression was rewritten in reverse form.
320 bool isReversed() const { return CXXRewrittenBinaryOperatorBits.IsReversed; }
321
322 BinaryOperatorKind getOperator() const { return getDecomposedForm().Opcode; }
323 BinaryOperatorKind getOpcode() const { return getOperator(); }
324 static StringRef getOpcodeStr(BinaryOperatorKind Op) {
325 return BinaryOperator::getOpcodeStr(Op);
326 }
327 StringRef getOpcodeStr() const {
328 return BinaryOperator::getOpcodeStr(getOpcode());
329 }
330 bool isComparisonOp() const { return true; }
331 bool isAssignmentOp() const { return false; }
332
333 const Expr *getLHS() const { return getDecomposedForm().LHS; }
334 const Expr *getRHS() const { return getDecomposedForm().RHS; }
335
336 SourceLocation getOperatorLoc() const LLVM_READONLY__attribute__((__pure__)) {
337 return getDecomposedForm().InnerBinOp->getExprLoc();
338 }
339 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return getOperatorLoc(); }
340
341 /// Compute the begin and end locations from the decomposed form.
342 /// The locations of the semantic form are not reliable if this is
343 /// a reversed expression.
344 //@{
345 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
346 return getDecomposedForm().LHS->getBeginLoc();
347 }
348 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
349 return getDecomposedForm().RHS->getEndLoc();
350 }
351 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
352 DecomposedForm DF = getDecomposedForm();
353 return SourceRange(DF.LHS->getBeginLoc(), DF.RHS->getEndLoc());
354 }
355 //@}
356
357 child_range children() {
358 return child_range(&SemanticForm, &SemanticForm + 1);
359 }
360
361 static bool classof(const Stmt *T) {
362 return T->getStmtClass() == CXXRewrittenBinaryOperatorClass;
363 }
364};
365
366/// Abstract class common to all of the C++ "named"/"keyword" casts.
367///
368/// This abstract class is inherited by all of the classes
369/// representing "named" casts: CXXStaticCastExpr for \c static_cast,
370/// CXXDynamicCastExpr for \c dynamic_cast, CXXReinterpretCastExpr for
371/// reinterpret_cast, CXXConstCastExpr for \c const_cast and
372/// CXXAddrspaceCastExpr for addrspace_cast (in OpenCL).
373class CXXNamedCastExpr : public ExplicitCastExpr {
374private:
375 // the location of the casting op
376 SourceLocation Loc;
377
378 // the location of the right parenthesis
379 SourceLocation RParenLoc;
380
381 // range for '<' '>'
382 SourceRange AngleBrackets;
383
384protected:
385 friend class ASTStmtReader;
386
387 CXXNamedCastExpr(StmtClass SC, QualType ty, ExprValueKind VK, CastKind kind,
388 Expr *op, unsigned PathSize, bool HasFPFeatures,
389 TypeSourceInfo *writtenTy, SourceLocation l,
390 SourceLocation RParenLoc, SourceRange AngleBrackets)
391 : ExplicitCastExpr(SC, ty, VK, kind, op, PathSize, HasFPFeatures,
392 writtenTy),
393 Loc(l), RParenLoc(RParenLoc), AngleBrackets(AngleBrackets) {}
394
395 explicit CXXNamedCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
396 bool HasFPFeatures)
397 : ExplicitCastExpr(SC, Shell, PathSize, HasFPFeatures) {}
398
399public:
400 const char *getCastName() const;
401
402 /// Retrieve the location of the cast operator keyword, e.g.,
403 /// \c static_cast.
404 SourceLocation getOperatorLoc() const { return Loc; }
405
406 /// Retrieve the location of the closing parenthesis.
407 SourceLocation getRParenLoc() const { return RParenLoc; }
408
409 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
410 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
411 SourceRange getAngleBrackets() const LLVM_READONLY__attribute__((__pure__)) { return AngleBrackets; }
412
413 static bool classof(const Stmt *T) {
414 switch (T->getStmtClass()) {
415 case CXXStaticCastExprClass:
416 case CXXDynamicCastExprClass:
417 case CXXReinterpretCastExprClass:
418 case CXXConstCastExprClass:
419 case CXXAddrspaceCastExprClass:
420 return true;
421 default:
422 return false;
423 }
424 }
425};
426
427/// A C++ \c static_cast expression (C++ [expr.static.cast]).
428///
429/// This expression node represents a C++ static cast, e.g.,
430/// \c static_cast<int>(1.0).
431class CXXStaticCastExpr final
432 : public CXXNamedCastExpr,
433 private llvm::TrailingObjects<CXXStaticCastExpr, CXXBaseSpecifier *,
434 FPOptionsOverride> {
435 CXXStaticCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
436 unsigned pathSize, TypeSourceInfo *writtenTy,
437 FPOptionsOverride FPO, SourceLocation l,
438 SourceLocation RParenLoc, SourceRange AngleBrackets)
439 : CXXNamedCastExpr(CXXStaticCastExprClass, ty, vk, kind, op, pathSize,
440 FPO.requiresTrailingStorage(), writtenTy, l, RParenLoc,
441 AngleBrackets) {
442 if (hasStoredFPFeatures())
443 *getTrailingFPFeatures() = FPO;
444 }
445
446 explicit CXXStaticCastExpr(EmptyShell Empty, unsigned PathSize,
447 bool HasFPFeatures)
448 : CXXNamedCastExpr(CXXStaticCastExprClass, Empty, PathSize,
449 HasFPFeatures) {}
450
451 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
452 return path_size();
453 }
454
455public:
456 friend class CastExpr;
457 friend TrailingObjects;
458
459 static CXXStaticCastExpr *
460 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
461 Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written,
462 FPOptionsOverride FPO, SourceLocation L, SourceLocation RParenLoc,
463 SourceRange AngleBrackets);
464 static CXXStaticCastExpr *CreateEmpty(const ASTContext &Context,
465 unsigned PathSize, bool hasFPFeatures);
466
467 static bool classof(const Stmt *T) {
468 return T->getStmtClass() == CXXStaticCastExprClass;
469 }
470};
471
472/// A C++ @c dynamic_cast expression (C++ [expr.dynamic.cast]).
473///
474/// This expression node represents a dynamic cast, e.g.,
475/// \c dynamic_cast<Derived*>(BasePtr). Such a cast may perform a run-time
476/// check to determine how to perform the type conversion.
477class CXXDynamicCastExpr final
478 : public CXXNamedCastExpr,
479 private llvm::TrailingObjects<CXXDynamicCastExpr, CXXBaseSpecifier *> {
480 CXXDynamicCastExpr(QualType ty, ExprValueKind VK, CastKind kind, Expr *op,
481 unsigned pathSize, TypeSourceInfo *writtenTy,
482 SourceLocation l, SourceLocation RParenLoc,
483 SourceRange AngleBrackets)
484 : CXXNamedCastExpr(CXXDynamicCastExprClass, ty, VK, kind, op, pathSize,
485 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
486 AngleBrackets) {}
487
488 explicit CXXDynamicCastExpr(EmptyShell Empty, unsigned pathSize)
489 : CXXNamedCastExpr(CXXDynamicCastExprClass, Empty, pathSize,
490 /*HasFPFeatures*/ false) {}
491
492public:
493 friend class CastExpr;
494 friend TrailingObjects;
495
496 static CXXDynamicCastExpr *Create(const ASTContext &Context, QualType T,
497 ExprValueKind VK, CastKind Kind, Expr *Op,
498 const CXXCastPath *Path,
499 TypeSourceInfo *Written, SourceLocation L,
500 SourceLocation RParenLoc,
501 SourceRange AngleBrackets);
502
503 static CXXDynamicCastExpr *CreateEmpty(const ASTContext &Context,
504 unsigned pathSize);
505
506 bool isAlwaysNull() const;
507
508 static bool classof(const Stmt *T) {
509 return T->getStmtClass() == CXXDynamicCastExprClass;
510 }
511};
512
513/// A C++ @c reinterpret_cast expression (C++ [expr.reinterpret.cast]).
514///
515/// This expression node represents a reinterpret cast, e.g.,
516/// @c reinterpret_cast<int>(VoidPtr).
517///
518/// A reinterpret_cast provides a differently-typed view of a value but
519/// (in Clang, as in most C++ implementations) performs no actual work at
520/// run time.
521class CXXReinterpretCastExpr final
522 : public CXXNamedCastExpr,
523 private llvm::TrailingObjects<CXXReinterpretCastExpr,
524 CXXBaseSpecifier *> {
525 CXXReinterpretCastExpr(QualType ty, ExprValueKind vk, CastKind kind, Expr *op,
526 unsigned pathSize, TypeSourceInfo *writtenTy,
527 SourceLocation l, SourceLocation RParenLoc,
528 SourceRange AngleBrackets)
529 : CXXNamedCastExpr(CXXReinterpretCastExprClass, ty, vk, kind, op,
530 pathSize, /*HasFPFeatures*/ false, writtenTy, l,
531 RParenLoc, AngleBrackets) {}
532
533 CXXReinterpretCastExpr(EmptyShell Empty, unsigned pathSize)
534 : CXXNamedCastExpr(CXXReinterpretCastExprClass, Empty, pathSize,
535 /*HasFPFeatures*/ false) {}
536
537public:
538 friend class CastExpr;
539 friend TrailingObjects;
540
541 static CXXReinterpretCastExpr *Create(const ASTContext &Context, QualType T,
542 ExprValueKind VK, CastKind Kind,
543 Expr *Op, const CXXCastPath *Path,
544 TypeSourceInfo *WrittenTy, SourceLocation L,
545 SourceLocation RParenLoc,
546 SourceRange AngleBrackets);
547 static CXXReinterpretCastExpr *CreateEmpty(const ASTContext &Context,
548 unsigned pathSize);
549
550 static bool classof(const Stmt *T) {
551 return T->getStmtClass() == CXXReinterpretCastExprClass;
552 }
553};
554
555/// A C++ \c const_cast expression (C++ [expr.const.cast]).
556///
557/// This expression node represents a const cast, e.g.,
558/// \c const_cast<char*>(PtrToConstChar).
559///
560/// A const_cast can remove type qualifiers but does not change the underlying
561/// value.
562class CXXConstCastExpr final
563 : public CXXNamedCastExpr,
564 private llvm::TrailingObjects<CXXConstCastExpr, CXXBaseSpecifier *> {
565 CXXConstCastExpr(QualType ty, ExprValueKind VK, Expr *op,
566 TypeSourceInfo *writtenTy, SourceLocation l,
567 SourceLocation RParenLoc, SourceRange AngleBrackets)
568 : CXXNamedCastExpr(CXXConstCastExprClass, ty, VK, CK_NoOp, op, 0,
569 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
570 AngleBrackets) {}
571
572 explicit CXXConstCastExpr(EmptyShell Empty)
573 : CXXNamedCastExpr(CXXConstCastExprClass, Empty, 0,
574 /*HasFPFeatures*/ false) {}
575
576public:
577 friend class CastExpr;
578 friend TrailingObjects;
579
580 static CXXConstCastExpr *Create(const ASTContext &Context, QualType T,
581 ExprValueKind VK, Expr *Op,
582 TypeSourceInfo *WrittenTy, SourceLocation L,
583 SourceLocation RParenLoc,
584 SourceRange AngleBrackets);
585 static CXXConstCastExpr *CreateEmpty(const ASTContext &Context);
586
587 static bool classof(const Stmt *T) {
588 return T->getStmtClass() == CXXConstCastExprClass;
589 }
590};
591
592/// A C++ addrspace_cast expression (currently only enabled for OpenCL).
593///
594/// This expression node represents a cast between pointers to objects in
595/// different address spaces e.g.,
596/// \c addrspace_cast<global int*>(PtrToGenericInt).
597///
598/// A addrspace_cast can cast address space type qualifiers but does not change
599/// the underlying value.
600class CXXAddrspaceCastExpr final
601 : public CXXNamedCastExpr,
602 private llvm::TrailingObjects<CXXAddrspaceCastExpr, CXXBaseSpecifier *> {
603 CXXAddrspaceCastExpr(QualType ty, ExprValueKind VK, CastKind Kind, Expr *op,
604 TypeSourceInfo *writtenTy, SourceLocation l,
605 SourceLocation RParenLoc, SourceRange AngleBrackets)
606 : CXXNamedCastExpr(CXXAddrspaceCastExprClass, ty, VK, Kind, op, 0,
607 /*HasFPFeatures*/ false, writtenTy, l, RParenLoc,
608 AngleBrackets) {}
609
610 explicit CXXAddrspaceCastExpr(EmptyShell Empty)
611 : CXXNamedCastExpr(CXXAddrspaceCastExprClass, Empty, 0,
612 /*HasFPFeatures*/ false) {}
613
614public:
615 friend class CastExpr;
616 friend TrailingObjects;
617
618 static CXXAddrspaceCastExpr *
619 Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind,
620 Expr *Op, TypeSourceInfo *WrittenTy, SourceLocation L,
621 SourceLocation RParenLoc, SourceRange AngleBrackets);
622 static CXXAddrspaceCastExpr *CreateEmpty(const ASTContext &Context);
623
624 static bool classof(const Stmt *T) {
625 return T->getStmtClass() == CXXAddrspaceCastExprClass;
626 }
627};
628
629/// A call to a literal operator (C++11 [over.literal])
630/// written as a user-defined literal (C++11 [lit.ext]).
631///
632/// Represents a user-defined literal, e.g. "foo"_bar or 1.23_xyz. While this
633/// is semantically equivalent to a normal call, this AST node provides better
634/// information about the syntactic representation of the literal.
635///
636/// Since literal operators are never found by ADL and can only be declared at
637/// namespace scope, a user-defined literal is never dependent.
638class UserDefinedLiteral final : public CallExpr {
639 friend class ASTStmtReader;
640 friend class ASTStmtWriter;
641
642 /// The location of a ud-suffix within the literal.
643 SourceLocation UDSuffixLoc;
644
645 // UserDefinedLiteral has some trailing objects belonging
646 // to CallExpr. See CallExpr for the details.
647
648 UserDefinedLiteral(Expr *Fn, ArrayRef<Expr *> Args, QualType Ty,
649 ExprValueKind VK, SourceLocation LitEndLoc,
650 SourceLocation SuffixLoc, FPOptionsOverride FPFeatures);
651
652 UserDefinedLiteral(unsigned NumArgs, bool HasFPFeatures, EmptyShell Empty);
653
654public:
655 static UserDefinedLiteral *Create(const ASTContext &Ctx, Expr *Fn,
656 ArrayRef<Expr *> Args, QualType Ty,
657 ExprValueKind VK, SourceLocation LitEndLoc,
658 SourceLocation SuffixLoc,
659 FPOptionsOverride FPFeatures);
660
661 static UserDefinedLiteral *CreateEmpty(const ASTContext &Ctx,
662 unsigned NumArgs, bool HasFPOptions,
663 EmptyShell Empty);
664
665 /// The kind of literal operator which is invoked.
666 enum LiteralOperatorKind {
667 /// Raw form: operator "" X (const char *)
668 LOK_Raw,
669
670 /// Raw form: operator "" X<cs...> ()
671 LOK_Template,
672
673 /// operator "" X (unsigned long long)
674 LOK_Integer,
675
676 /// operator "" X (long double)
677 LOK_Floating,
678
679 /// operator "" X (const CharT *, size_t)
680 LOK_String,
681
682 /// operator "" X (CharT)
683 LOK_Character
684 };
685
686 /// Returns the kind of literal operator invocation
687 /// which this expression represents.
688 LiteralOperatorKind getLiteralOperatorKind() const;
689
690 /// If this is not a raw user-defined literal, get the
691 /// underlying cooked literal (representing the literal with the suffix
692 /// removed).
693 Expr *getCookedLiteral();
694 const Expr *getCookedLiteral() const {
695 return const_cast<UserDefinedLiteral*>(this)->getCookedLiteral();
696 }
697
698 SourceLocation getBeginLoc() const {
699 if (getLiteralOperatorKind() == LOK_Template)
700 return getRParenLoc();
701 return getArg(0)->getBeginLoc();
702 }
703
704 SourceLocation getEndLoc() const { return getRParenLoc(); }
705
706 /// Returns the location of a ud-suffix in the expression.
707 ///
708 /// For a string literal, there may be multiple identical suffixes. This
709 /// returns the first.
710 SourceLocation getUDSuffixLoc() const { return UDSuffixLoc; }
711
712 /// Returns the ud-suffix specified for this literal.
713 const IdentifierInfo *getUDSuffix() const;
714
715 static bool classof(const Stmt *S) {
716 return S->getStmtClass() == UserDefinedLiteralClass;
717 }
718};
719
720/// A boolean literal, per ([C++ lex.bool] Boolean literals).
721class CXXBoolLiteralExpr : public Expr {
722public:
723 CXXBoolLiteralExpr(bool Val, QualType Ty, SourceLocation Loc)
724 : Expr(CXXBoolLiteralExprClass, Ty, VK_PRValue, OK_Ordinary) {
725 CXXBoolLiteralExprBits.Value = Val;
726 CXXBoolLiteralExprBits.Loc = Loc;
727 setDependence(ExprDependence::None);
728 }
729
730 explicit CXXBoolLiteralExpr(EmptyShell Empty)
731 : Expr(CXXBoolLiteralExprClass, Empty) {}
732
733 bool getValue() const { return CXXBoolLiteralExprBits.Value; }
734 void setValue(bool V) { CXXBoolLiteralExprBits.Value = V; }
735
736 SourceLocation getBeginLoc() const { return getLocation(); }
737 SourceLocation getEndLoc() const { return getLocation(); }
738
739 SourceLocation getLocation() const { return CXXBoolLiteralExprBits.Loc; }
740 void setLocation(SourceLocation L) { CXXBoolLiteralExprBits.Loc = L; }
741
742 static bool classof(const Stmt *T) {
743 return T->getStmtClass() == CXXBoolLiteralExprClass;
744 }
745
746 // Iterators
747 child_range children() {
748 return child_range(child_iterator(), child_iterator());
749 }
750
751 const_child_range children() const {
752 return const_child_range(const_child_iterator(), const_child_iterator());
753 }
754};
755
756/// The null pointer literal (C++11 [lex.nullptr])
757///
758/// Introduced in C++11, the only literal of type \c nullptr_t is \c nullptr.
759class CXXNullPtrLiteralExpr : public Expr {
760public:
761 CXXNullPtrLiteralExpr(QualType Ty, SourceLocation Loc)
762 : Expr(CXXNullPtrLiteralExprClass, Ty, VK_PRValue, OK_Ordinary) {
763 CXXNullPtrLiteralExprBits.Loc = Loc;
764 setDependence(ExprDependence::None);
765 }
766
767 explicit CXXNullPtrLiteralExpr(EmptyShell Empty)
768 : Expr(CXXNullPtrLiteralExprClass, Empty) {}
769
770 SourceLocation getBeginLoc() const { return getLocation(); }
771 SourceLocation getEndLoc() const { return getLocation(); }
772
773 SourceLocation getLocation() const { return CXXNullPtrLiteralExprBits.Loc; }
774 void setLocation(SourceLocation L) { CXXNullPtrLiteralExprBits.Loc = L; }
775
776 static bool classof(const Stmt *T) {
777 return T->getStmtClass() == CXXNullPtrLiteralExprClass;
778 }
779
780 child_range children() {
781 return child_range(child_iterator(), child_iterator());
782 }
783
784 const_child_range children() const {
785 return const_child_range(const_child_iterator(), const_child_iterator());
786 }
787};
788
789/// Implicit construction of a std::initializer_list<T> object from an
790/// array temporary within list-initialization (C++11 [dcl.init.list]p5).
791class CXXStdInitializerListExpr : public Expr {
792 Stmt *SubExpr = nullptr;
793
794 CXXStdInitializerListExpr(EmptyShell Empty)
795 : Expr(CXXStdInitializerListExprClass, Empty) {}
796
797public:
798 friend class ASTReader;
799 friend class ASTStmtReader;
800
801 CXXStdInitializerListExpr(QualType Ty, Expr *SubExpr)
802 : Expr(CXXStdInitializerListExprClass, Ty, VK_PRValue, OK_Ordinary),
803 SubExpr(SubExpr) {
804 setDependence(computeDependence(this));
805 }
806
807 Expr *getSubExpr() { return static_cast<Expr*>(SubExpr); }
808 const Expr *getSubExpr() const { return static_cast<const Expr*>(SubExpr); }
809
810 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
811 return SubExpr->getBeginLoc();
812 }
813
814 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
815 return SubExpr->getEndLoc();
816 }
817
818 /// Retrieve the source range of the expression.
819 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
820 return SubExpr->getSourceRange();
821 }
822
823 static bool classof(const Stmt *S) {
824 return S->getStmtClass() == CXXStdInitializerListExprClass;
825 }
826
827 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
828
829 const_child_range children() const {
830 return const_child_range(&SubExpr, &SubExpr + 1);
831 }
832};
833
834/// A C++ \c typeid expression (C++ [expr.typeid]), which gets
835/// the \c type_info that corresponds to the supplied type, or the (possibly
836/// dynamic) type of the supplied expression.
837///
838/// This represents code like \c typeid(int) or \c typeid(*objPtr)
839class CXXTypeidExpr : public Expr {
840 friend class ASTStmtReader;
841
842private:
843 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
844 SourceRange Range;
845
846public:
847 CXXTypeidExpr(QualType Ty, TypeSourceInfo *Operand, SourceRange R)
848 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
849 Range(R) {
850 setDependence(computeDependence(this));
851 }
852
853 CXXTypeidExpr(QualType Ty, Expr *Operand, SourceRange R)
854 : Expr(CXXTypeidExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
855 Range(R) {
856 setDependence(computeDependence(this));
857 }
858
859 CXXTypeidExpr(EmptyShell Empty, bool isExpr)
860 : Expr(CXXTypeidExprClass, Empty) {
861 if (isExpr)
862 Operand = (Expr*)nullptr;
863 else
864 Operand = (TypeSourceInfo*)nullptr;
865 }
866
867 /// Determine whether this typeid has a type operand which is potentially
868 /// evaluated, per C++11 [expr.typeid]p3.
869 bool isPotentiallyEvaluated() const;
870
871 /// Best-effort check if the expression operand refers to a most derived
872 /// object. This is not a strong guarantee.
873 bool isMostDerived(ASTContext &Context) const;
874
875 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
876
877 /// Retrieves the type operand of this typeid() expression after
878 /// various required adjustments (removing reference types, cv-qualifiers).
879 QualType getTypeOperand(ASTContext &Context) const;
880
881 /// Retrieve source information for the type operand.
882 TypeSourceInfo *getTypeOperandSourceInfo() const {
883 assert(isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)")(static_cast <bool> (isTypeOperand() && "Cannot call getTypeOperand for typeid(expr)"
) ? void (0) : __assert_fail ("isTypeOperand() && \"Cannot call getTypeOperand for typeid(expr)\""
, "clang/include/clang/AST/ExprCXX.h", 883, __extension__ __PRETTY_FUNCTION__
))
;
884 return Operand.get<TypeSourceInfo *>();
885 }
886 Expr *getExprOperand() const {
887 assert(!isTypeOperand() && "Cannot call getExprOperand for typeid(type)")(static_cast <bool> (!isTypeOperand() && "Cannot call getExprOperand for typeid(type)"
) ? void (0) : __assert_fail ("!isTypeOperand() && \"Cannot call getExprOperand for typeid(type)\""
, "clang/include/clang/AST/ExprCXX.h", 887, __extension__ __PRETTY_FUNCTION__
))
;
888 return static_cast<Expr*>(Operand.get<Stmt *>());
889 }
890
891 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
892 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
893 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
894 void setSourceRange(SourceRange R) { Range = R; }
895
896 static bool classof(const Stmt *T) {
897 return T->getStmtClass() == CXXTypeidExprClass;
898 }
899
900 // Iterators
901 child_range children() {
902 if (isTypeOperand())
903 return child_range(child_iterator(), child_iterator());
904 auto **begin = reinterpret_cast<Stmt **>(&Operand);
905 return child_range(begin, begin + 1);
906 }
907
908 const_child_range children() const {
909 if (isTypeOperand())
910 return const_child_range(const_child_iterator(), const_child_iterator());
911
912 auto **begin =
913 reinterpret_cast<Stmt **>(&const_cast<CXXTypeidExpr *>(this)->Operand);
914 return const_child_range(begin, begin + 1);
915 }
916};
917
918/// A member reference to an MSPropertyDecl.
919///
920/// This expression always has pseudo-object type, and therefore it is
921/// typically not encountered in a fully-typechecked expression except
922/// within the syntactic form of a PseudoObjectExpr.
923class MSPropertyRefExpr : public Expr {
924 Expr *BaseExpr;
925 MSPropertyDecl *TheDecl;
926 SourceLocation MemberLoc;
927 bool IsArrow;
928 NestedNameSpecifierLoc QualifierLoc;
929
930public:
931 friend class ASTStmtReader;
932
933 MSPropertyRefExpr(Expr *baseExpr, MSPropertyDecl *decl, bool isArrow,
934 QualType ty, ExprValueKind VK,
935 NestedNameSpecifierLoc qualifierLoc, SourceLocation nameLoc)
936 : Expr(MSPropertyRefExprClass, ty, VK, OK_Ordinary), BaseExpr(baseExpr),
937 TheDecl(decl), MemberLoc(nameLoc), IsArrow(isArrow),
938 QualifierLoc(qualifierLoc) {
939 setDependence(computeDependence(this));
940 }
941
942 MSPropertyRefExpr(EmptyShell Empty) : Expr(MSPropertyRefExprClass, Empty) {}
943
944 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
945 return SourceRange(getBeginLoc(), getEndLoc());
946 }
947
948 bool isImplicitAccess() const {
949 return getBaseExpr() && getBaseExpr()->isImplicitCXXThis();
950 }
951
952 SourceLocation getBeginLoc() const {
953 if (!isImplicitAccess())
954 return BaseExpr->getBeginLoc();
955 else if (QualifierLoc)
956 return QualifierLoc.getBeginLoc();
957 else
958 return MemberLoc;
959 }
960
961 SourceLocation getEndLoc() const { return getMemberLoc(); }
962
963 child_range children() {
964 return child_range((Stmt**)&BaseExpr, (Stmt**)&BaseExpr + 1);
965 }
966
967 const_child_range children() const {
968 auto Children = const_cast<MSPropertyRefExpr *>(this)->children();
969 return const_child_range(Children.begin(), Children.end());
970 }
971
972 static bool classof(const Stmt *T) {
973 return T->getStmtClass() == MSPropertyRefExprClass;
974 }
975
976 Expr *getBaseExpr() const { return BaseExpr; }
977 MSPropertyDecl *getPropertyDecl() const { return TheDecl; }
978 bool isArrow() const { return IsArrow; }
979 SourceLocation getMemberLoc() const { return MemberLoc; }
980 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
981};
982
983/// MS property subscript expression.
984/// MSVC supports 'property' attribute and allows to apply it to the
985/// declaration of an empty array in a class or structure definition.
986/// For example:
987/// \code
988/// __declspec(property(get=GetX, put=PutX)) int x[];
989/// \endcode
990/// The above statement indicates that x[] can be used with one or more array
991/// indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b), and
992/// p->x[a][b] = i will be turned into p->PutX(a, b, i).
993/// This is a syntactic pseudo-object expression.
994class MSPropertySubscriptExpr : public Expr {
995 friend class ASTStmtReader;
996
997 enum { BASE_EXPR, IDX_EXPR, NUM_SUBEXPRS = 2 };
998
999 Stmt *SubExprs[NUM_SUBEXPRS];
1000 SourceLocation RBracketLoc;
1001
1002 void setBase(Expr *Base) { SubExprs[BASE_EXPR] = Base; }
1003 void setIdx(Expr *Idx) { SubExprs[IDX_EXPR] = Idx; }
1004
1005public:
1006 MSPropertySubscriptExpr(Expr *Base, Expr *Idx, QualType Ty, ExprValueKind VK,
1007 ExprObjectKind OK, SourceLocation RBracketLoc)
1008 : Expr(MSPropertySubscriptExprClass, Ty, VK, OK),
1009 RBracketLoc(RBracketLoc) {
1010 SubExprs[BASE_EXPR] = Base;
1011 SubExprs[IDX_EXPR] = Idx;
1012 setDependence(computeDependence(this));
1013 }
1014
1015 /// Create an empty array subscript expression.
1016 explicit MSPropertySubscriptExpr(EmptyShell Shell)
1017 : Expr(MSPropertySubscriptExprClass, Shell) {}
1018
1019 Expr *getBase() { return cast<Expr>(SubExprs[BASE_EXPR]); }
1020 const Expr *getBase() const { return cast<Expr>(SubExprs[BASE_EXPR]); }
1021
1022 Expr *getIdx() { return cast<Expr>(SubExprs[IDX_EXPR]); }
1023 const Expr *getIdx() const { return cast<Expr>(SubExprs[IDX_EXPR]); }
1024
1025 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1026 return getBase()->getBeginLoc();
1027 }
1028
1029 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RBracketLoc; }
1030
1031 SourceLocation getRBracketLoc() const { return RBracketLoc; }
1032 void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
1033
1034 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
1035 return getBase()->getExprLoc();
1036 }
1037
1038 static bool classof(const Stmt *T) {
1039 return T->getStmtClass() == MSPropertySubscriptExprClass;
1040 }
1041
1042 // Iterators
1043 child_range children() {
1044 return child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
1045 }
1046
1047 const_child_range children() const {
1048 return const_child_range(&SubExprs[0], &SubExprs[0] + NUM_SUBEXPRS);
1049 }
1050};
1051
1052/// A Microsoft C++ @c __uuidof expression, which gets
1053/// the _GUID that corresponds to the supplied type or expression.
1054///
1055/// This represents code like @c __uuidof(COMTYPE) or @c __uuidof(*comPtr)
1056class CXXUuidofExpr : public Expr {
1057 friend class ASTStmtReader;
1058
1059private:
1060 llvm::PointerUnion<Stmt *, TypeSourceInfo *> Operand;
1061 MSGuidDecl *Guid;
1062 SourceRange Range;
1063
1064public:
1065 CXXUuidofExpr(QualType Ty, TypeSourceInfo *Operand, MSGuidDecl *Guid,
1066 SourceRange R)
1067 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
1068 Guid(Guid), Range(R) {
1069 setDependence(computeDependence(this));
1070 }
1071
1072 CXXUuidofExpr(QualType Ty, Expr *Operand, MSGuidDecl *Guid, SourceRange R)
1073 : Expr(CXXUuidofExprClass, Ty, VK_LValue, OK_Ordinary), Operand(Operand),
1074 Guid(Guid), Range(R) {
1075 setDependence(computeDependence(this));
1076 }
1077
1078 CXXUuidofExpr(EmptyShell Empty, bool isExpr)
1079 : Expr(CXXUuidofExprClass, Empty) {
1080 if (isExpr)
1081 Operand = (Expr*)nullptr;
1082 else
1083 Operand = (TypeSourceInfo*)nullptr;
1084 }
1085
1086 bool isTypeOperand() const { return Operand.is<TypeSourceInfo *>(); }
1087
1088 /// Retrieves the type operand of this __uuidof() expression after
1089 /// various required adjustments (removing reference types, cv-qualifiers).
1090 QualType getTypeOperand(ASTContext &Context) const;
1091
1092 /// Retrieve source information for the type operand.
1093 TypeSourceInfo *getTypeOperandSourceInfo() const {
1094 assert(isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)")(static_cast <bool> (isTypeOperand() && "Cannot call getTypeOperand for __uuidof(expr)"
) ? void (0) : __assert_fail ("isTypeOperand() && \"Cannot call getTypeOperand for __uuidof(expr)\""
, "clang/include/clang/AST/ExprCXX.h", 1094, __extension__ __PRETTY_FUNCTION__
))
;
1095 return Operand.get<TypeSourceInfo *>();
1096 }
1097 Expr *getExprOperand() const {
1098 assert(!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)")(static_cast <bool> (!isTypeOperand() && "Cannot call getExprOperand for __uuidof(type)"
) ? void (0) : __assert_fail ("!isTypeOperand() && \"Cannot call getExprOperand for __uuidof(type)\""
, "clang/include/clang/AST/ExprCXX.h", 1098, __extension__ __PRETTY_FUNCTION__
))
;
1099 return static_cast<Expr*>(Operand.get<Stmt *>());
1100 }
1101
1102 MSGuidDecl *getGuidDecl() const { return Guid; }
1103
1104 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
1105 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
1106 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
1107 void setSourceRange(SourceRange R) { Range = R; }
1108
1109 static bool classof(const Stmt *T) {
1110 return T->getStmtClass() == CXXUuidofExprClass;
1111 }
1112
1113 // Iterators
1114 child_range children() {
1115 if (isTypeOperand())
1116 return child_range(child_iterator(), child_iterator());
1117 auto **begin = reinterpret_cast<Stmt **>(&Operand);
1118 return child_range(begin, begin + 1);
1119 }
1120
1121 const_child_range children() const {
1122 if (isTypeOperand())
1123 return const_child_range(const_child_iterator(), const_child_iterator());
1124 auto **begin =
1125 reinterpret_cast<Stmt **>(&const_cast<CXXUuidofExpr *>(this)->Operand);
1126 return const_child_range(begin, begin + 1);
1127 }
1128};
1129
1130/// Represents the \c this expression in C++.
1131///
1132/// This is a pointer to the object on which the current member function is
1133/// executing (C++ [expr.prim]p3). Example:
1134///
1135/// \code
1136/// class Foo {
1137/// public:
1138/// void bar();
1139/// void test() { this->bar(); }
1140/// };
1141/// \endcode
1142class CXXThisExpr : public Expr {
1143public:
1144 CXXThisExpr(SourceLocation L, QualType Ty, bool IsImplicit)
1145 : Expr(CXXThisExprClass, Ty, VK_PRValue, OK_Ordinary) {
1146 CXXThisExprBits.IsImplicit = IsImplicit;
1147 CXXThisExprBits.Loc = L;
1148 setDependence(computeDependence(this));
1149 }
1150
1151 CXXThisExpr(EmptyShell Empty) : Expr(CXXThisExprClass, Empty) {}
1152
1153 SourceLocation getLocation() const { return CXXThisExprBits.Loc; }
1154 void setLocation(SourceLocation L) { CXXThisExprBits.Loc = L; }
1155
1156 SourceLocation getBeginLoc() const { return getLocation(); }
1157 SourceLocation getEndLoc() const { return getLocation(); }
1158
1159 bool isImplicit() const { return CXXThisExprBits.IsImplicit; }
1160 void setImplicit(bool I) { CXXThisExprBits.IsImplicit = I; }
1161
1162 static bool classof(const Stmt *T) {
1163 return T->getStmtClass() == CXXThisExprClass;
1164 }
1165
1166 // Iterators
1167 child_range children() {
1168 return child_range(child_iterator(), child_iterator());
1169 }
1170
1171 const_child_range children() const {
1172 return const_child_range(const_child_iterator(), const_child_iterator());
1173 }
1174};
1175
1176/// A C++ throw-expression (C++ [except.throw]).
1177///
1178/// This handles 'throw' (for re-throwing the current exception) and
1179/// 'throw' assignment-expression. When assignment-expression isn't
1180/// present, Op will be null.
1181class CXXThrowExpr : public Expr {
1182 friend class ASTStmtReader;
1183
1184 /// The optional expression in the throw statement.
1185 Stmt *Operand;
1186
1187public:
1188 // \p Ty is the void type which is used as the result type of the
1189 // expression. The \p Loc is the location of the throw keyword.
1190 // \p Operand is the expression in the throw statement, and can be
1191 // null if not present.
1192 CXXThrowExpr(Expr *Operand, QualType Ty, SourceLocation Loc,
1193 bool IsThrownVariableInScope)
1194 : Expr(CXXThrowExprClass, Ty, VK_PRValue, OK_Ordinary), Operand(Operand) {
1195 CXXThrowExprBits.ThrowLoc = Loc;
1196 CXXThrowExprBits.IsThrownVariableInScope = IsThrownVariableInScope;
1197 setDependence(computeDependence(this));
1198 }
1199 CXXThrowExpr(EmptyShell Empty) : Expr(CXXThrowExprClass, Empty) {}
1200
1201 const Expr *getSubExpr() const { return cast_or_null<Expr>(Operand); }
1202 Expr *getSubExpr() { return cast_or_null<Expr>(Operand); }
1203
1204 SourceLocation getThrowLoc() const { return CXXThrowExprBits.ThrowLoc; }
1205
1206 /// Determines whether the variable thrown by this expression (if any!)
1207 /// is within the innermost try block.
1208 ///
1209 /// This information is required to determine whether the NRVO can apply to
1210 /// this variable.
1211 bool isThrownVariableInScope() const {
1212 return CXXThrowExprBits.IsThrownVariableInScope;
1213 }
1214
1215 SourceLocation getBeginLoc() const { return getThrowLoc(); }
1216 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1217 if (!getSubExpr())
1218 return getThrowLoc();
1219 return getSubExpr()->getEndLoc();
1220 }
1221
1222 static bool classof(const Stmt *T) {
1223 return T->getStmtClass() == CXXThrowExprClass;
1224 }
1225
1226 // Iterators
1227 child_range children() {
1228 return child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1229 }
1230
1231 const_child_range children() const {
1232 return const_child_range(&Operand, Operand ? &Operand + 1 : &Operand);
1233 }
1234};
1235
1236/// A default argument (C++ [dcl.fct.default]).
1237///
1238/// This wraps up a function call argument that was created from the
1239/// corresponding parameter's default argument, when the call did not
1240/// explicitly supply arguments for all of the parameters.
1241class CXXDefaultArgExpr final : public Expr {
1242 friend class ASTStmtReader;
1243
1244 /// The parameter whose default is being used.
1245 ParmVarDecl *Param;
1246
1247 /// The context where the default argument expression was used.
1248 DeclContext *UsedContext;
1249
1250 CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *Param,
1251 DeclContext *UsedContext)
1252 : Expr(SC,
1253 Param->hasUnparsedDefaultArg()
1254 ? Param->getType().getNonReferenceType()
1255 : Param->getDefaultArg()->getType(),
1256 Param->getDefaultArg()->getValueKind(),
1257 Param->getDefaultArg()->getObjectKind()),
1258 Param(Param), UsedContext(UsedContext) {
1259 CXXDefaultArgExprBits.Loc = Loc;
1260 setDependence(computeDependence(this));
1261 }
1262
1263public:
1264 CXXDefaultArgExpr(EmptyShell Empty) : Expr(CXXDefaultArgExprClass, Empty) {}
1265
1266 // \p Param is the parameter whose default argument is used by this
1267 // expression.
1268 static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
1269 ParmVarDecl *Param,
1270 DeclContext *UsedContext) {
1271 return new (C)
1272 CXXDefaultArgExpr(CXXDefaultArgExprClass, Loc, Param, UsedContext);
1273 }
1274
1275 // Retrieve the parameter that the argument was created from.
1276 const ParmVarDecl *getParam() const { return Param; }
1277 ParmVarDecl *getParam() { return Param; }
1278
1279 // Retrieve the actual argument to the function call.
1280 const Expr *getExpr() const { return getParam()->getDefaultArg(); }
1281 Expr *getExpr() { return getParam()->getDefaultArg(); }
1282
1283 const DeclContext *getUsedContext() const { return UsedContext; }
1284 DeclContext *getUsedContext() { return UsedContext; }
1285
1286 /// Retrieve the location where this default argument was actually used.
1287 SourceLocation getUsedLocation() const { return CXXDefaultArgExprBits.Loc; }
1288
1289 /// Default argument expressions have no representation in the
1290 /// source, so they have an empty source range.
1291 SourceLocation getBeginLoc() const { return SourceLocation(); }
1292 SourceLocation getEndLoc() const { return SourceLocation(); }
1293
1294 SourceLocation getExprLoc() const { return getUsedLocation(); }
1295
1296 static bool classof(const Stmt *T) {
1297 return T->getStmtClass() == CXXDefaultArgExprClass;
1298 }
1299
1300 // Iterators
1301 child_range children() {
1302 return child_range(child_iterator(), child_iterator());
1303 }
1304
1305 const_child_range children() const {
1306 return const_child_range(const_child_iterator(), const_child_iterator());
1307 }
1308};
1309
1310/// A use of a default initializer in a constructor or in aggregate
1311/// initialization.
1312///
1313/// This wraps a use of a C++ default initializer (technically,
1314/// a brace-or-equal-initializer for a non-static data member) when it
1315/// is implicitly used in a mem-initializer-list in a constructor
1316/// (C++11 [class.base.init]p8) or in aggregate initialization
1317/// (C++1y [dcl.init.aggr]p7).
1318class CXXDefaultInitExpr : public Expr {
1319 friend class ASTReader;
1320 friend class ASTStmtReader;
1321
1322 /// The field whose default is being used.
1323 FieldDecl *Field;
1324
1325 /// The context where the default initializer expression was used.
1326 DeclContext *UsedContext;
1327
1328 CXXDefaultInitExpr(const ASTContext &Ctx, SourceLocation Loc,
1329 FieldDecl *Field, QualType Ty, DeclContext *UsedContext);
1330
1331 CXXDefaultInitExpr(EmptyShell Empty) : Expr(CXXDefaultInitExprClass, Empty) {}
1332
1333public:
1334 /// \p Field is the non-static data member whose default initializer is used
1335 /// by this expression.
1336 static CXXDefaultInitExpr *Create(const ASTContext &Ctx, SourceLocation Loc,
1337 FieldDecl *Field, DeclContext *UsedContext) {
1338 return new (Ctx) CXXDefaultInitExpr(Ctx, Loc, Field, Field->getType(), UsedContext);
1339 }
1340
1341 /// Get the field whose initializer will be used.
1342 FieldDecl *getField() { return Field; }
1343 const FieldDecl *getField() const { return Field; }
1344
1345 /// Get the initialization expression that will be used.
1346 const Expr *getExpr() const {
1347 assert(Field->getInClassInitializer() && "initializer hasn't been parsed")(static_cast <bool> (Field->getInClassInitializer() &&
"initializer hasn't been parsed") ? void (0) : __assert_fail
("Field->getInClassInitializer() && \"initializer hasn't been parsed\""
, "clang/include/clang/AST/ExprCXX.h", 1347, __extension__ __PRETTY_FUNCTION__
))
;
1348 return Field->getInClassInitializer();
1349 }
1350 Expr *getExpr() {
1351 assert(Field->getInClassInitializer() && "initializer hasn't been parsed")(static_cast <bool> (Field->getInClassInitializer() &&
"initializer hasn't been parsed") ? void (0) : __assert_fail
("Field->getInClassInitializer() && \"initializer hasn't been parsed\""
, "clang/include/clang/AST/ExprCXX.h", 1351, __extension__ __PRETTY_FUNCTION__
))
;
1352 return Field->getInClassInitializer();
1353 }
1354
1355 const DeclContext *getUsedContext() const { return UsedContext; }
1356 DeclContext *getUsedContext() { return UsedContext; }
1357
1358 /// Retrieve the location where this default initializer expression was
1359 /// actually used.
1360 SourceLocation getUsedLocation() const { return getBeginLoc(); }
1361
1362 SourceLocation getBeginLoc() const { return CXXDefaultInitExprBits.Loc; }
1363 SourceLocation getEndLoc() const { return CXXDefaultInitExprBits.Loc; }
1364
1365 static bool classof(const Stmt *T) {
1366 return T->getStmtClass() == CXXDefaultInitExprClass;
1367 }
1368
1369 // Iterators
1370 child_range children() {
1371 return child_range(child_iterator(), child_iterator());
1372 }
1373
1374 const_child_range children() const {
1375 return const_child_range(const_child_iterator(), const_child_iterator());
1376 }
1377};
1378
1379/// Represents a C++ temporary.
1380class CXXTemporary {
1381 /// The destructor that needs to be called.
1382 const CXXDestructorDecl *Destructor;
1383
1384 explicit CXXTemporary(const CXXDestructorDecl *destructor)
1385 : Destructor(destructor) {}
1386
1387public:
1388 static CXXTemporary *Create(const ASTContext &C,
1389 const CXXDestructorDecl *Destructor);
1390
1391 const CXXDestructorDecl *getDestructor() const { return Destructor; }
1392
1393 void setDestructor(const CXXDestructorDecl *Dtor) {
1394 Destructor = Dtor;
1395 }
1396};
1397
1398/// Represents binding an expression to a temporary.
1399///
1400/// This ensures the destructor is called for the temporary. It should only be
1401/// needed for non-POD, non-trivially destructable class types. For example:
1402///
1403/// \code
1404/// struct S {
1405/// S() { } // User defined constructor makes S non-POD.
1406/// ~S() { } // User defined destructor makes it non-trivial.
1407/// };
1408/// void test() {
1409/// const S &s_ref = S(); // Requires a CXXBindTemporaryExpr.
1410/// }
1411/// \endcode
1412class CXXBindTemporaryExpr : public Expr {
1413 CXXTemporary *Temp = nullptr;
1414 Stmt *SubExpr = nullptr;
1415
1416 CXXBindTemporaryExpr(CXXTemporary *temp, Expr *SubExpr)
1417 : Expr(CXXBindTemporaryExprClass, SubExpr->getType(), VK_PRValue,
1418 OK_Ordinary),
1419 Temp(temp), SubExpr(SubExpr) {
1420 setDependence(computeDependence(this));
1421 }
1422
1423public:
1424 CXXBindTemporaryExpr(EmptyShell Empty)
1425 : Expr(CXXBindTemporaryExprClass, Empty) {}
1426
1427 static CXXBindTemporaryExpr *Create(const ASTContext &C, CXXTemporary *Temp,
1428 Expr* SubExpr);
1429
1430 CXXTemporary *getTemporary() { return Temp; }
1431 const CXXTemporary *getTemporary() const { return Temp; }
1432 void setTemporary(CXXTemporary *T) { Temp = T; }
1433
1434 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1435 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1436 void setSubExpr(Expr *E) { SubExpr = E; }
1437
1438 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1439 return SubExpr->getBeginLoc();
1440 }
1441
1442 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1443 return SubExpr->getEndLoc();
1444 }
1445
1446 // Implement isa/cast/dyncast/etc.
1447 static bool classof(const Stmt *T) {
1448 return T->getStmtClass() == CXXBindTemporaryExprClass;
1449 }
1450
1451 // Iterators
1452 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
1453
1454 const_child_range children() const {
1455 return const_child_range(&SubExpr, &SubExpr + 1);
1456 }
1457};
1458
1459/// Represents a call to a C++ constructor.
1460class CXXConstructExpr : public Expr {
1461 friend class ASTStmtReader;
1462
1463public:
1464 enum ConstructionKind {
1465 CK_Complete,
1466 CK_NonVirtualBase,
1467 CK_VirtualBase,
1468 CK_Delegating
1469 };
1470
1471private:
1472 /// A pointer to the constructor which will be ultimately called.
1473 CXXConstructorDecl *Constructor;
1474
1475 SourceRange ParenOrBraceRange;
1476
1477 /// The number of arguments.
1478 unsigned NumArgs;
1479
1480 // We would like to stash the arguments of the constructor call after
1481 // CXXConstructExpr. However CXXConstructExpr is used as a base class of
1482 // CXXTemporaryObjectExpr which makes the use of llvm::TrailingObjects
1483 // impossible.
1484 //
1485 // Instead we manually stash the trailing object after the full object
1486 // containing CXXConstructExpr (that is either CXXConstructExpr or
1487 // CXXTemporaryObjectExpr).
1488 //
1489 // The trailing objects are:
1490 //
1491 // * An array of getNumArgs() "Stmt *" for the arguments of the
1492 // constructor call.
1493
1494 /// Return a pointer to the start of the trailing arguments.
1495 /// Defined just after CXXTemporaryObjectExpr.
1496 inline Stmt **getTrailingArgs();
1497 const Stmt *const *getTrailingArgs() const {
1498 return const_cast<CXXConstructExpr *>(this)->getTrailingArgs();
1499 }
1500
1501protected:
1502 /// Build a C++ construction expression.
1503 CXXConstructExpr(StmtClass SC, QualType Ty, SourceLocation Loc,
1504 CXXConstructorDecl *Ctor, bool Elidable,
1505 ArrayRef<Expr *> Args, bool HadMultipleCandidates,
1506 bool ListInitialization, bool StdInitListInitialization,
1507 bool ZeroInitialization, ConstructionKind ConstructKind,
1508 SourceRange ParenOrBraceRange);
1509
1510 /// Build an empty C++ construction expression.
1511 CXXConstructExpr(StmtClass SC, EmptyShell Empty, unsigned NumArgs);
1512
1513 /// Return the size in bytes of the trailing objects. Used by
1514 /// CXXTemporaryObjectExpr to allocate the right amount of storage.
1515 static unsigned sizeOfTrailingObjects(unsigned NumArgs) {
1516 return NumArgs * sizeof(Stmt *);
1517 }
1518
1519public:
1520 /// Create a C++ construction expression.
1521 static CXXConstructExpr *
1522 Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc,
1523 CXXConstructorDecl *Ctor, bool Elidable, ArrayRef<Expr *> Args,
1524 bool HadMultipleCandidates, bool ListInitialization,
1525 bool StdInitListInitialization, bool ZeroInitialization,
1526 ConstructionKind ConstructKind, SourceRange ParenOrBraceRange);
1527
1528 /// Create an empty C++ construction expression.
1529 static CXXConstructExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs);
1530
1531 /// Get the constructor that this expression will (ultimately) call.
1532 CXXConstructorDecl *getConstructor() const { return Constructor; }
1533
1534 SourceLocation getLocation() const { return CXXConstructExprBits.Loc; }
1535 void setLocation(SourceLocation Loc) { CXXConstructExprBits.Loc = Loc; }
1536
1537 /// Whether this construction is elidable.
1538 bool isElidable() const { return CXXConstructExprBits.Elidable; }
1539 void setElidable(bool E) { CXXConstructExprBits.Elidable = E; }
1540
1541 /// Whether the referred constructor was resolved from
1542 /// an overloaded set having size greater than 1.
1543 bool hadMultipleCandidates() const {
1544 return CXXConstructExprBits.HadMultipleCandidates;
1545 }
1546 void setHadMultipleCandidates(bool V) {
1547 CXXConstructExprBits.HadMultipleCandidates = V;
1548 }
1549
1550 /// Whether this constructor call was written as list-initialization.
1551 bool isListInitialization() const {
1552 return CXXConstructExprBits.ListInitialization;
1553 }
1554 void setListInitialization(bool V) {
1555 CXXConstructExprBits.ListInitialization = V;
1556 }
1557
1558 /// Whether this constructor call was written as list-initialization,
1559 /// but was interpreted as forming a std::initializer_list<T> from the list
1560 /// and passing that as a single constructor argument.
1561 /// See C++11 [over.match.list]p1 bullet 1.
1562 bool isStdInitListInitialization() const {
1563 return CXXConstructExprBits.StdInitListInitialization;
1564 }
1565 void setStdInitListInitialization(bool V) {
1566 CXXConstructExprBits.StdInitListInitialization = V;
1567 }
1568
1569 /// Whether this construction first requires
1570 /// zero-initialization before the initializer is called.
1571 bool requiresZeroInitialization() const {
1572 return CXXConstructExprBits.ZeroInitialization;
1573 }
1574 void setRequiresZeroInitialization(bool ZeroInit) {
1575 CXXConstructExprBits.ZeroInitialization = ZeroInit;
1576 }
1577
1578 /// Determine whether this constructor is actually constructing
1579 /// a base class (rather than a complete object).
1580 ConstructionKind getConstructionKind() const {
1581 return static_cast<ConstructionKind>(CXXConstructExprBits.ConstructionKind);
1582 }
1583 void setConstructionKind(ConstructionKind CK) {
1584 CXXConstructExprBits.ConstructionKind = CK;
1585 }
1586
1587 using arg_iterator = ExprIterator;
1588 using const_arg_iterator = ConstExprIterator;
1589 using arg_range = llvm::iterator_range<arg_iterator>;
1590 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
1591
1592 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
1593 const_arg_range arguments() const {
1594 return const_arg_range(arg_begin(), arg_end());
1595 }
1596
1597 arg_iterator arg_begin() { return getTrailingArgs(); }
1598 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
1599 const_arg_iterator arg_begin() const { return getTrailingArgs(); }
1600 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
1601
1602 Expr **getArgs() { return reinterpret_cast<Expr **>(getTrailingArgs()); }
1603 const Expr *const *getArgs() const {
1604 return reinterpret_cast<const Expr *const *>(getTrailingArgs());
1605 }
1606
1607 /// Return the number of arguments to the constructor call.
1608 unsigned getNumArgs() const { return NumArgs; }
1609
1610 /// Return the specified argument.
1611 Expr *getArg(unsigned Arg) {
1612 assert(Arg < getNumArgs() && "Arg access out of range!")(static_cast <bool> (Arg < getNumArgs() && "Arg access out of range!"
) ? void (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "clang/include/clang/AST/ExprCXX.h", 1612, __extension__ __PRETTY_FUNCTION__
))
;
1613 return getArgs()[Arg];
1614 }
1615 const Expr *getArg(unsigned Arg) const {
1616 assert(Arg < getNumArgs() && "Arg access out of range!")(static_cast <bool> (Arg < getNumArgs() && "Arg access out of range!"
) ? void (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "clang/include/clang/AST/ExprCXX.h", 1616, __extension__ __PRETTY_FUNCTION__
))
;
1617 return getArgs()[Arg];
1618 }
1619
1620 /// Set the specified argument.
1621 void setArg(unsigned Arg, Expr *ArgExpr) {
1622 assert(Arg < getNumArgs() && "Arg access out of range!")(static_cast <bool> (Arg < getNumArgs() && "Arg access out of range!"
) ? void (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "clang/include/clang/AST/ExprCXX.h", 1622, __extension__ __PRETTY_FUNCTION__
))
;
1623 getArgs()[Arg] = ArgExpr;
1624 }
1625
1626 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1627 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1628 SourceRange getParenOrBraceRange() const { return ParenOrBraceRange; }
1629 void setParenOrBraceRange(SourceRange Range) { ParenOrBraceRange = Range; }
1630
1631 static bool classof(const Stmt *T) {
1632 return T->getStmtClass() == CXXConstructExprClass ||
1633 T->getStmtClass() == CXXTemporaryObjectExprClass;
1634 }
1635
1636 // Iterators
1637 child_range children() {
1638 return child_range(getTrailingArgs(), getTrailingArgs() + getNumArgs());
1639 }
1640
1641 const_child_range children() const {
1642 auto Children = const_cast<CXXConstructExpr *>(this)->children();
1643 return const_child_range(Children.begin(), Children.end());
1644 }
1645};
1646
1647/// Represents a call to an inherited base class constructor from an
1648/// inheriting constructor. This call implicitly forwards the arguments from
1649/// the enclosing context (an inheriting constructor) to the specified inherited
1650/// base class constructor.
1651class CXXInheritedCtorInitExpr : public Expr {
1652private:
1653 CXXConstructorDecl *Constructor = nullptr;
1654
1655 /// The location of the using declaration.
1656 SourceLocation Loc;
1657
1658 /// Whether this is the construction of a virtual base.
1659 unsigned ConstructsVirtualBase : 1;
1660
1661 /// Whether the constructor is inherited from a virtual base class of the
1662 /// class that we construct.
1663 unsigned InheritedFromVirtualBase : 1;
1664
1665public:
1666 friend class ASTStmtReader;
1667
1668 /// Construct a C++ inheriting construction expression.
1669 CXXInheritedCtorInitExpr(SourceLocation Loc, QualType T,
1670 CXXConstructorDecl *Ctor, bool ConstructsVirtualBase,
1671 bool InheritedFromVirtualBase)
1672 : Expr(CXXInheritedCtorInitExprClass, T, VK_PRValue, OK_Ordinary),
1673 Constructor(Ctor), Loc(Loc),
1674 ConstructsVirtualBase(ConstructsVirtualBase),
1675 InheritedFromVirtualBase(InheritedFromVirtualBase) {
1676 assert(!T->isDependentType())(static_cast <bool> (!T->isDependentType()) ? void (
0) : __assert_fail ("!T->isDependentType()", "clang/include/clang/AST/ExprCXX.h"
, 1676, __extension__ __PRETTY_FUNCTION__))
;
1677 setDependence(ExprDependence::None);
1678 }
1679
1680 /// Construct an empty C++ inheriting construction expression.
1681 explicit CXXInheritedCtorInitExpr(EmptyShell Empty)
1682 : Expr(CXXInheritedCtorInitExprClass, Empty),
1683 ConstructsVirtualBase(false), InheritedFromVirtualBase(false) {}
1684
1685 /// Get the constructor that this expression will call.
1686 CXXConstructorDecl *getConstructor() const { return Constructor; }
1687
1688 /// Determine whether this constructor is actually constructing
1689 /// a base class (rather than a complete object).
1690 bool constructsVBase() const { return ConstructsVirtualBase; }
1691 CXXConstructExpr::ConstructionKind getConstructionKind() const {
1692 return ConstructsVirtualBase ? CXXConstructExpr::CK_VirtualBase
1693 : CXXConstructExpr::CK_NonVirtualBase;
1694 }
1695
1696 /// Determine whether the inherited constructor is inherited from a
1697 /// virtual base of the object we construct. If so, we are not responsible
1698 /// for calling the inherited constructor (the complete object constructor
1699 /// does that), and so we don't need to pass any arguments.
1700 bool inheritedFromVBase() const { return InheritedFromVirtualBase; }
1701
1702 SourceLocation getLocation() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1703 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1704 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1705
1706 static bool classof(const Stmt *T) {
1707 return T->getStmtClass() == CXXInheritedCtorInitExprClass;
1708 }
1709
1710 child_range children() {
1711 return child_range(child_iterator(), child_iterator());
1712 }
1713
1714 const_child_range children() const {
1715 return const_child_range(const_child_iterator(), const_child_iterator());
1716 }
1717};
1718
1719/// Represents an explicit C++ type conversion that uses "functional"
1720/// notation (C++ [expr.type.conv]).
1721///
1722/// Example:
1723/// \code
1724/// x = int(0.5);
1725/// \endcode
1726class CXXFunctionalCastExpr final
1727 : public ExplicitCastExpr,
1728 private llvm::TrailingObjects<CXXFunctionalCastExpr, CXXBaseSpecifier *,
1729 FPOptionsOverride> {
1730 SourceLocation LParenLoc;
1731 SourceLocation RParenLoc;
1732
1733 CXXFunctionalCastExpr(QualType ty, ExprValueKind VK,
1734 TypeSourceInfo *writtenTy, CastKind kind,
1735 Expr *castExpr, unsigned pathSize,
1736 FPOptionsOverride FPO, SourceLocation lParenLoc,
1737 SourceLocation rParenLoc)
1738 : ExplicitCastExpr(CXXFunctionalCastExprClass, ty, VK, kind, castExpr,
1739 pathSize, FPO.requiresTrailingStorage(), writtenTy),
1740 LParenLoc(lParenLoc), RParenLoc(rParenLoc) {
1741 if (hasStoredFPFeatures())
1742 *getTrailingFPFeatures() = FPO;
1743 }
1744
1745 explicit CXXFunctionalCastExpr(EmptyShell Shell, unsigned PathSize,
1746 bool HasFPFeatures)
1747 : ExplicitCastExpr(CXXFunctionalCastExprClass, Shell, PathSize,
1748 HasFPFeatures) {}
1749
1750 unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
1751 return path_size();
1752 }
1753
1754public:
1755 friend class CastExpr;
1756 friend TrailingObjects;
1757
1758 static CXXFunctionalCastExpr *
1759 Create(const ASTContext &Context, QualType T, ExprValueKind VK,
1760 TypeSourceInfo *Written, CastKind Kind, Expr *Op,
1761 const CXXCastPath *Path, FPOptionsOverride FPO, SourceLocation LPLoc,
1762 SourceLocation RPLoc);
1763 static CXXFunctionalCastExpr *
1764 CreateEmpty(const ASTContext &Context, unsigned PathSize, bool HasFPFeatures);
1765
1766 SourceLocation getLParenLoc() const { return LParenLoc; }
1767 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
1768 SourceLocation getRParenLoc() const { return RParenLoc; }
1769 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
1770
1771 /// Determine whether this expression models list-initialization.
1772 bool isListInitialization() const { return LParenLoc.isInvalid(); }
1773
1774 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1775 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1776
1777 static bool classof(const Stmt *T) {
1778 return T->getStmtClass() == CXXFunctionalCastExprClass;
1779 }
1780};
1781
1782/// Represents a C++ functional cast expression that builds a
1783/// temporary object.
1784///
1785/// This expression type represents a C++ "functional" cast
1786/// (C++[expr.type.conv]) with N != 1 arguments that invokes a
1787/// constructor to build a temporary object. With N == 1 arguments the
1788/// functional cast expression will be represented by CXXFunctionalCastExpr.
1789/// Example:
1790/// \code
1791/// struct X { X(int, float); }
1792///
1793/// X create_X() {
1794/// return X(1, 3.14f); // creates a CXXTemporaryObjectExpr
1795/// };
1796/// \endcode
1797class CXXTemporaryObjectExpr final : public CXXConstructExpr {
1798 friend class ASTStmtReader;
1799
1800 // CXXTemporaryObjectExpr has some trailing objects belonging
1801 // to CXXConstructExpr. See the comment inside CXXConstructExpr
1802 // for more details.
1803
1804 TypeSourceInfo *TSI;
1805
1806 CXXTemporaryObjectExpr(CXXConstructorDecl *Cons, QualType Ty,
1807 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1808 SourceRange ParenOrBraceRange,
1809 bool HadMultipleCandidates, bool ListInitialization,
1810 bool StdInitListInitialization,
1811 bool ZeroInitialization);
1812
1813 CXXTemporaryObjectExpr(EmptyShell Empty, unsigned NumArgs);
1814
1815public:
1816 static CXXTemporaryObjectExpr *
1817 Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty,
1818 TypeSourceInfo *TSI, ArrayRef<Expr *> Args,
1819 SourceRange ParenOrBraceRange, bool HadMultipleCandidates,
1820 bool ListInitialization, bool StdInitListInitialization,
1821 bool ZeroInitialization);
1822
1823 static CXXTemporaryObjectExpr *CreateEmpty(const ASTContext &Ctx,
1824 unsigned NumArgs);
1825
1826 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
1827
1828 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1829 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1830
1831 static bool classof(const Stmt *T) {
1832 return T->getStmtClass() == CXXTemporaryObjectExprClass;
1833 }
1834};
1835
1836Stmt **CXXConstructExpr::getTrailingArgs() {
1837 if (auto *E = dyn_cast<CXXTemporaryObjectExpr>(this))
1838 return reinterpret_cast<Stmt **>(E + 1);
1839 assert((getStmtClass() == CXXConstructExprClass) &&(static_cast <bool> ((getStmtClass() == CXXConstructExprClass
) && "Unexpected class deriving from CXXConstructExpr!"
) ? void (0) : __assert_fail ("(getStmtClass() == CXXConstructExprClass) && \"Unexpected class deriving from CXXConstructExpr!\""
, "clang/include/clang/AST/ExprCXX.h", 1840, __extension__ __PRETTY_FUNCTION__
))
1840 "Unexpected class deriving from CXXConstructExpr!")(static_cast <bool> ((getStmtClass() == CXXConstructExprClass
) && "Unexpected class deriving from CXXConstructExpr!"
) ? void (0) : __assert_fail ("(getStmtClass() == CXXConstructExprClass) && \"Unexpected class deriving from CXXConstructExpr!\""
, "clang/include/clang/AST/ExprCXX.h", 1840, __extension__ __PRETTY_FUNCTION__
))
;
1841 return reinterpret_cast<Stmt **>(this + 1);
1842}
1843
1844/// A C++ lambda expression, which produces a function object
1845/// (of unspecified type) that can be invoked later.
1846///
1847/// Example:
1848/// \code
1849/// void low_pass_filter(std::vector<double> &values, double cutoff) {
1850/// values.erase(std::remove_if(values.begin(), values.end(),
1851/// [=](double value) { return value > cutoff; });
1852/// }
1853/// \endcode
1854///
1855/// C++11 lambda expressions can capture local variables, either by copying
1856/// the values of those local variables at the time the function
1857/// object is constructed (not when it is called!) or by holding a
1858/// reference to the local variable. These captures can occur either
1859/// implicitly or can be written explicitly between the square
1860/// brackets ([...]) that start the lambda expression.
1861///
1862/// C++1y introduces a new form of "capture" called an init-capture that
1863/// includes an initializing expression (rather than capturing a variable),
1864/// and which can never occur implicitly.
1865class LambdaExpr final : public Expr,
1866 private llvm::TrailingObjects<LambdaExpr, Stmt *> {
1867 // LambdaExpr has some data stored in LambdaExprBits.
1868
1869 /// The source range that covers the lambda introducer ([...]).
1870 SourceRange IntroducerRange;
1871
1872 /// The source location of this lambda's capture-default ('=' or '&').
1873 SourceLocation CaptureDefaultLoc;
1874
1875 /// The location of the closing brace ('}') that completes
1876 /// the lambda.
1877 ///
1878 /// The location of the brace is also available by looking up the
1879 /// function call operator in the lambda class. However, it is
1880 /// stored here to improve the performance of getSourceRange(), and
1881 /// to avoid having to deserialize the function call operator from a
1882 /// module file just to determine the source range.
1883 SourceLocation ClosingBrace;
1884
1885 /// Construct a lambda expression.
1886 LambdaExpr(QualType T, SourceRange IntroducerRange,
1887 LambdaCaptureDefault CaptureDefault,
1888 SourceLocation CaptureDefaultLoc, bool ExplicitParams,
1889 bool ExplicitResultType, ArrayRef<Expr *> CaptureInits,
1890 SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack);
1891
1892 /// Construct an empty lambda expression.
1893 LambdaExpr(EmptyShell Empty, unsigned NumCaptures);
1894
1895 Stmt **getStoredStmts() { return getTrailingObjects<Stmt *>(); }
1896 Stmt *const *getStoredStmts() const { return getTrailingObjects<Stmt *>(); }
1897
1898 void initBodyIfNeeded() const;
1899
1900public:
1901 friend class ASTStmtReader;
1902 friend class ASTStmtWriter;
1903 friend TrailingObjects;
1904
1905 /// Construct a new lambda expression.
1906 static LambdaExpr *
1907 Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange,
1908 LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc,
1909 bool ExplicitParams, bool ExplicitResultType,
1910 ArrayRef<Expr *> CaptureInits, SourceLocation ClosingBrace,
1911 bool ContainsUnexpandedParameterPack);
1912
1913 /// Construct a new lambda expression that will be deserialized from
1914 /// an external source.
1915 static LambdaExpr *CreateDeserialized(const ASTContext &C,
1916 unsigned NumCaptures);
1917
1918 /// Determine the default capture kind for this lambda.
1919 LambdaCaptureDefault getCaptureDefault() const {
1920 return static_cast<LambdaCaptureDefault>(LambdaExprBits.CaptureDefault);
1921 }
1922
1923 /// Retrieve the location of this lambda's capture-default, if any.
1924 SourceLocation getCaptureDefaultLoc() const { return CaptureDefaultLoc; }
1925
1926 /// Determine whether one of this lambda's captures is an init-capture.
1927 bool isInitCapture(const LambdaCapture *Capture) const;
1928
1929 /// An iterator that walks over the captures of the lambda,
1930 /// both implicit and explicit.
1931 using capture_iterator = const LambdaCapture *;
1932
1933 /// An iterator over a range of lambda captures.
1934 using capture_range = llvm::iterator_range<capture_iterator>;
1935
1936 /// Retrieve this lambda's captures.
1937 capture_range captures() const;
1938
1939 /// Retrieve an iterator pointing to the first lambda capture.
1940 capture_iterator capture_begin() const;
1941
1942 /// Retrieve an iterator pointing past the end of the
1943 /// sequence of lambda captures.
1944 capture_iterator capture_end() const;
1945
1946 /// Determine the number of captures in this lambda.
1947 unsigned capture_size() const { return LambdaExprBits.NumCaptures; }
1948
1949 /// Retrieve this lambda's explicit captures.
1950 capture_range explicit_captures() const;
1951
1952 /// Retrieve an iterator pointing to the first explicit
1953 /// lambda capture.
1954 capture_iterator explicit_capture_begin() const;
1955
1956 /// Retrieve an iterator pointing past the end of the sequence of
1957 /// explicit lambda captures.
1958 capture_iterator explicit_capture_end() const;
1959
1960 /// Retrieve this lambda's implicit captures.
1961 capture_range implicit_captures() const;
1962
1963 /// Retrieve an iterator pointing to the first implicit
1964 /// lambda capture.
1965 capture_iterator implicit_capture_begin() const;
1966
1967 /// Retrieve an iterator pointing past the end of the sequence of
1968 /// implicit lambda captures.
1969 capture_iterator implicit_capture_end() const;
1970
1971 /// Iterator that walks over the capture initialization
1972 /// arguments.
1973 using capture_init_iterator = Expr **;
1974
1975 /// Const iterator that walks over the capture initialization
1976 /// arguments.
1977 /// FIXME: This interface is prone to being used incorrectly.
1978 using const_capture_init_iterator = Expr *const *;
1979
1980 /// Retrieve the initialization expressions for this lambda's captures.
1981 llvm::iterator_range<capture_init_iterator> capture_inits() {
1982 return llvm::make_range(capture_init_begin(), capture_init_end());
1983 }
1984
1985 /// Retrieve the initialization expressions for this lambda's captures.
1986 llvm::iterator_range<const_capture_init_iterator> capture_inits() const {
1987 return llvm::make_range(capture_init_begin(), capture_init_end());
1988 }
1989
1990 /// Retrieve the first initialization argument for this
1991 /// lambda expression (which initializes the first capture field).
1992 capture_init_iterator capture_init_begin() {
1993 return reinterpret_cast<Expr **>(getStoredStmts());
1994 }
1995
1996 /// Retrieve the first initialization argument for this
1997 /// lambda expression (which initializes the first capture field).
1998 const_capture_init_iterator capture_init_begin() const {
1999 return reinterpret_cast<Expr *const *>(getStoredStmts());
2000 }
2001
2002 /// Retrieve the iterator pointing one past the last
2003 /// initialization argument for this lambda expression.
2004 capture_init_iterator capture_init_end() {
2005 return capture_init_begin() + capture_size();
2006 }
2007
2008 /// Retrieve the iterator pointing one past the last
2009 /// initialization argument for this lambda expression.
2010 const_capture_init_iterator capture_init_end() const {
2011 return capture_init_begin() + capture_size();
2012 }
2013
2014 /// Retrieve the source range covering the lambda introducer,
2015 /// which contains the explicit capture list surrounded by square
2016 /// brackets ([...]).
2017 SourceRange getIntroducerRange() const { return IntroducerRange; }
2018
2019 /// Retrieve the class that corresponds to the lambda.
2020 ///
2021 /// This is the "closure type" (C++1y [expr.prim.lambda]), and stores the
2022 /// captures in its fields and provides the various operations permitted
2023 /// on a lambda (copying, calling).
2024 CXXRecordDecl *getLambdaClass() const;
2025
2026 /// Retrieve the function call operator associated with this
2027 /// lambda expression.
2028 CXXMethodDecl *getCallOperator() const;
2029
2030 /// Retrieve the function template call operator associated with this
2031 /// lambda expression.
2032 FunctionTemplateDecl *getDependentCallOperator() const;
2033
2034 /// If this is a generic lambda expression, retrieve the template
2035 /// parameter list associated with it, or else return null.
2036 TemplateParameterList *getTemplateParameterList() const;
2037
2038 /// Get the template parameters were explicitly specified (as opposed to being
2039 /// invented by use of an auto parameter).
2040 ArrayRef<NamedDecl *> getExplicitTemplateParameters() const;
2041
2042 /// Get the trailing requires clause, if any.
2043 Expr *getTrailingRequiresClause() const;
2044
2045 /// Whether this is a generic lambda.
2046 bool isGenericLambda() const { return getTemplateParameterList(); }
2047
2048 /// Retrieve the body of the lambda. This will be most of the time
2049 /// a \p CompoundStmt, but can also be \p CoroutineBodyStmt wrapping
2050 /// a \p CompoundStmt. Note that unlike functions, lambda-expressions
2051 /// cannot have a function-try-block.
2052 Stmt *getBody() const;
2053
2054 /// Retrieve the \p CompoundStmt representing the body of the lambda.
2055 /// This is a convenience function for callers who do not need
2056 /// to handle node(s) which may wrap a \p CompoundStmt.
2057 const CompoundStmt *getCompoundStmtBody() const;
2058 CompoundStmt *getCompoundStmtBody() {
2059 const auto *ConstThis = this;
2060 return const_cast<CompoundStmt *>(ConstThis->getCompoundStmtBody());
2061 }
2062
2063 /// Determine whether the lambda is mutable, meaning that any
2064 /// captures values can be modified.
2065 bool isMutable() const;
2066
2067 /// Determine whether this lambda has an explicit parameter
2068 /// list vs. an implicit (empty) parameter list.
2069 bool hasExplicitParameters() const { return LambdaExprBits.ExplicitParams; }
2070
2071 /// Whether this lambda had its result type explicitly specified.
2072 bool hasExplicitResultType() const {
2073 return LambdaExprBits.ExplicitResultType;
2074 }
2075
2076 static bool classof(const Stmt *T) {
2077 return T->getStmtClass() == LambdaExprClass;
2078 }
2079
2080 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2081 return IntroducerRange.getBegin();
2082 }
2083
2084 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return ClosingBrace; }
2085
2086 /// Includes the captures and the body of the lambda.
2087 child_range children();
2088 const_child_range children() const;
2089};
2090
2091/// An expression "T()" which creates a value-initialized rvalue of type
2092/// T, which is a non-class type. See (C++98 [5.2.3p2]).
2093class CXXScalarValueInitExpr : public Expr {
2094 friend class ASTStmtReader;
2095
2096 TypeSourceInfo *TypeInfo;
2097
2098public:
2099 /// Create an explicitly-written scalar-value initialization
2100 /// expression.
2101 CXXScalarValueInitExpr(QualType Type, TypeSourceInfo *TypeInfo,
2102 SourceLocation RParenLoc)
2103 : Expr(CXXScalarValueInitExprClass, Type, VK_PRValue, OK_Ordinary),
2104 TypeInfo(TypeInfo) {
2105 CXXScalarValueInitExprBits.RParenLoc = RParenLoc;
2106 setDependence(computeDependence(this));
2107 }
2108
2109 explicit CXXScalarValueInitExpr(EmptyShell Shell)
2110 : Expr(CXXScalarValueInitExprClass, Shell) {}
2111
2112 TypeSourceInfo *getTypeSourceInfo() const {
2113 return TypeInfo;
2114 }
2115
2116 SourceLocation getRParenLoc() const {
2117 return CXXScalarValueInitExprBits.RParenLoc;
2118 }
2119
2120 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
2121 SourceLocation getEndLoc() const { return getRParenLoc(); }
2122
2123 static bool classof(const Stmt *T) {
2124 return T->getStmtClass() == CXXScalarValueInitExprClass;
2125 }
2126
2127 // Iterators
2128 child_range children() {
2129 return child_range(child_iterator(), child_iterator());
2130 }
2131
2132 const_child_range children() const {
2133 return const_child_range(const_child_iterator(), const_child_iterator());
2134 }
2135};
2136
2137/// Represents a new-expression for memory allocation and constructor
2138/// calls, e.g: "new CXXNewExpr(foo)".
2139class CXXNewExpr final
2140 : public Expr,
2141 private llvm::TrailingObjects<CXXNewExpr, Stmt *, SourceRange> {
2142 friend class ASTStmtReader;
2143 friend class ASTStmtWriter;
2144 friend TrailingObjects;
2145
2146 /// Points to the allocation function used.
2147 FunctionDecl *OperatorNew;
2148
2149 /// Points to the deallocation function used in case of error. May be null.
2150 FunctionDecl *OperatorDelete;
2151
2152 /// The allocated type-source information, as written in the source.
2153 TypeSourceInfo *AllocatedTypeInfo;
2154
2155 /// Range of the entire new expression.
2156 SourceRange Range;
2157
2158 /// Source-range of a paren-delimited initializer.
2159 SourceRange DirectInitRange;
2160
2161 // CXXNewExpr is followed by several optional trailing objects.
2162 // They are in order:
2163 //
2164 // * An optional "Stmt *" for the array size expression.
2165 // Present if and ony if isArray().
2166 //
2167 // * An optional "Stmt *" for the init expression.
2168 // Present if and only if hasInitializer().
2169 //
2170 // * An array of getNumPlacementArgs() "Stmt *" for the placement new
2171 // arguments, if any.
2172 //
2173 // * An optional SourceRange for the range covering the parenthesized type-id
2174 // if the allocated type was expressed as a parenthesized type-id.
2175 // Present if and only if isParenTypeId().
2176 unsigned arraySizeOffset() const { return 0; }
2177 unsigned initExprOffset() const { return arraySizeOffset() + isArray(); }
2178 unsigned placementNewArgsOffset() const {
2179 return initExprOffset() + hasInitializer();
2180 }
2181
2182 unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
2183 return isArray() + hasInitializer() + getNumPlacementArgs();
2184 }
2185
2186 unsigned numTrailingObjects(OverloadToken<SourceRange>) const {
2187 return isParenTypeId();
2188 }
2189
2190public:
2191 enum InitializationStyle {
2192 /// New-expression has no initializer as written.
2193 NoInit,
2194
2195 /// New-expression has a C++98 paren-delimited initializer.
2196 CallInit,
2197
2198 /// New-expression has a C++11 list-initializer.
2199 ListInit
2200 };
2201
2202private:
2203 /// Build a c++ new expression.
2204 CXXNewExpr(bool IsGlobalNew, FunctionDecl *OperatorNew,
2205 FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
2206 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
2207 SourceRange TypeIdParens, Optional<Expr *> ArraySize,
2208 InitializationStyle InitializationStyle, Expr *Initializer,
2209 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2210 SourceRange DirectInitRange);
2211
2212 /// Build an empty c++ new expression.
2213 CXXNewExpr(EmptyShell Empty, bool IsArray, unsigned NumPlacementArgs,
2214 bool IsParenTypeId);
2215
2216public:
2217 /// Create a c++ new expression.
2218 static CXXNewExpr *
2219 Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew,
2220 FunctionDecl *OperatorDelete, bool ShouldPassAlignment,
2221 bool UsualArrayDeleteWantsSize, ArrayRef<Expr *> PlacementArgs,
2222 SourceRange TypeIdParens, Optional<Expr *> ArraySize,
2223 InitializationStyle InitializationStyle, Expr *Initializer,
2224 QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range,
2225 SourceRange DirectInitRange);
2226
2227 /// Create an empty c++ new expression.
2228 static CXXNewExpr *CreateEmpty(const ASTContext &Ctx, bool IsArray,
2229 bool HasInit, unsigned NumPlacementArgs,
2230 bool IsParenTypeId);
2231
2232 QualType getAllocatedType() const {
2233 return getType()->castAs<PointerType>()->getPointeeType();
2234 }
2235
2236 TypeSourceInfo *getAllocatedTypeSourceInfo() const {
2237 return AllocatedTypeInfo;
2238 }
2239
2240 /// True if the allocation result needs to be null-checked.
2241 ///
2242 /// C++11 [expr.new]p13:
2243 /// If the allocation function returns null, initialization shall
2244 /// not be done, the deallocation function shall not be called,
2245 /// and the value of the new-expression shall be null.
2246 ///
2247 /// C++ DR1748:
2248 /// If the allocation function is a reserved placement allocation
2249 /// function that returns null, the behavior is undefined.
2250 ///
2251 /// An allocation function is not allowed to return null unless it
2252 /// has a non-throwing exception-specification. The '03 rule is
2253 /// identical except that the definition of a non-throwing
2254 /// exception specification is just "is it throw()?".
2255 bool shouldNullCheckAllocation() const;
2256
2257 FunctionDecl *getOperatorNew() const { return OperatorNew; }
2258 void setOperatorNew(FunctionDecl *D) { OperatorNew = D; }
2259 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2260 void setOperatorDelete(FunctionDecl *D) { OperatorDelete = D; }
2261
2262 bool isArray() const { return CXXNewExprBits.IsArray; }
2263
2264 /// This might return None even if isArray() returns true,
2265 /// since there might not be an array size expression.
2266 /// If the result is not-None, it will never wrap a nullptr.
2267 Optional<Expr *> getArraySize() {
2268 if (!isArray())
2269 return None;
2270
2271 if (auto *Result =
2272 cast_or_null<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()]))
2273 return Result;
2274
2275 return None;
2276 }
2277
2278 /// This might return None even if isArray() returns true,
2279 /// since there might not be an array size expression.
2280 /// If the result is not-None, it will never wrap a nullptr.
2281 Optional<const Expr *> getArraySize() const {
2282 if (!isArray())
2283 return None;
2284
2285 if (auto *Result =
2286 cast_or_null<Expr>(getTrailingObjects<Stmt *>()[arraySizeOffset()]))
2287 return Result;
2288
2289 return None;
2290 }
2291
2292 unsigned getNumPlacementArgs() const {
2293 return CXXNewExprBits.NumPlacementArgs;
2294 }
2295
2296 Expr **getPlacementArgs() {
2297 return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>() +
2298 placementNewArgsOffset());
2299 }
2300
2301 Expr *getPlacementArg(unsigned I) {
2302 assert((I < getNumPlacementArgs()) && "Index out of range!")(static_cast <bool> ((I < getNumPlacementArgs()) &&
"Index out of range!") ? void (0) : __assert_fail ("(I < getNumPlacementArgs()) && \"Index out of range!\""
, "clang/include/clang/AST/ExprCXX.h", 2302, __extension__ __PRETTY_FUNCTION__
))
;
2303 return getPlacementArgs()[I];
2304 }
2305 const Expr *getPlacementArg(unsigned I) const {
2306 return const_cast<CXXNewExpr *>(this)->getPlacementArg(I);
2307 }
2308
2309 bool isParenTypeId() const { return CXXNewExprBits.IsParenTypeId; }
2310 SourceRange getTypeIdParens() const {
2311 return isParenTypeId() ? getTrailingObjects<SourceRange>()[0]
2312 : SourceRange();
2313 }
2314
2315 bool isGlobalNew() const { return CXXNewExprBits.IsGlobalNew; }
2316
2317 /// Whether this new-expression has any initializer at all.
2318 bool hasInitializer() const {
2319 return CXXNewExprBits.StoredInitializationStyle > 0;
2320 }
2321
2322 /// The kind of initializer this new-expression has.
2323 InitializationStyle getInitializationStyle() const {
2324 if (CXXNewExprBits.StoredInitializationStyle == 0)
2325 return NoInit;
2326 return static_cast<InitializationStyle>(
2327 CXXNewExprBits.StoredInitializationStyle - 1);
2328 }
2329
2330 /// The initializer of this new-expression.
2331 Expr *getInitializer() {
2332 return hasInitializer()
2333 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2334 : nullptr;
2335 }
2336 const Expr *getInitializer() const {
2337 return hasInitializer()
2338 ? cast<Expr>(getTrailingObjects<Stmt *>()[initExprOffset()])
2339 : nullptr;
2340 }
2341
2342 /// Returns the CXXConstructExpr from this new-expression, or null.
2343 const CXXConstructExpr *getConstructExpr() const {
2344 return dyn_cast_or_null<CXXConstructExpr>(getInitializer());
2345 }
2346
2347 /// Indicates whether the required alignment should be implicitly passed to
2348 /// the allocation function.
2349 bool passAlignment() const { return CXXNewExprBits.ShouldPassAlignment; }
2350
2351 /// Answers whether the usual array deallocation function for the
2352 /// allocated type expects the size of the allocation as a
2353 /// parameter.
2354 bool doesUsualArrayDeleteWantSize() const {
2355 return CXXNewExprBits.UsualArrayDeleteWantsSize;
2356 }
2357
2358 using arg_iterator = ExprIterator;
2359 using const_arg_iterator = ConstExprIterator;
2360
2361 llvm::iterator_range<arg_iterator> placement_arguments() {
2362 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2363 }
2364
2365 llvm::iterator_range<const_arg_iterator> placement_arguments() const {
2366 return llvm::make_range(placement_arg_begin(), placement_arg_end());
2367 }
2368
2369 arg_iterator placement_arg_begin() {
2370 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2371 }
2372 arg_iterator placement_arg_end() {
2373 return placement_arg_begin() + getNumPlacementArgs();
2374 }
2375 const_arg_iterator placement_arg_begin() const {
2376 return getTrailingObjects<Stmt *>() + placementNewArgsOffset();
2377 }
2378 const_arg_iterator placement_arg_end() const {
2379 return placement_arg_begin() + getNumPlacementArgs();
2380 }
2381
2382 using raw_arg_iterator = Stmt **;
2383
2384 raw_arg_iterator raw_arg_begin() { return getTrailingObjects<Stmt *>(); }
2385 raw_arg_iterator raw_arg_end() {
2386 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2387 }
2388 const_arg_iterator raw_arg_begin() const {
2389 return getTrailingObjects<Stmt *>();
2390 }
2391 const_arg_iterator raw_arg_end() const {
2392 return raw_arg_begin() + numTrailingObjects(OverloadToken<Stmt *>());
2393 }
2394
2395 SourceLocation getBeginLoc() const { return Range.getBegin(); }
2396 SourceLocation getEndLoc() const { return Range.getEnd(); }
2397
2398 SourceRange getDirectInitRange() const { return DirectInitRange; }
2399 SourceRange getSourceRange() const { return Range; }
2400
2401 static bool classof(const Stmt *T) {
2402 return T->getStmtClass() == CXXNewExprClass;
2403 }
2404
2405 // Iterators
2406 child_range children() { return child_range(raw_arg_begin(), raw_arg_end()); }
2407
2408 const_child_range children() const {
2409 return const_child_range(const_cast<CXXNewExpr *>(this)->children());
2410 }
2411};
2412
2413/// Represents a \c delete expression for memory deallocation and
2414/// destructor calls, e.g. "delete[] pArray".
2415class CXXDeleteExpr : public Expr {
2416 friend class ASTStmtReader;
2417
2418 /// Points to the operator delete overload that is used. Could be a member.
2419 FunctionDecl *OperatorDelete = nullptr;
2420
2421 /// The pointer expression to be deleted.
2422 Stmt *Argument = nullptr;
2423
2424public:
2425 CXXDeleteExpr(QualType Ty, bool GlobalDelete, bool ArrayForm,
2426 bool ArrayFormAsWritten, bool UsualArrayDeleteWantsSize,
2427 FunctionDecl *OperatorDelete, Expr *Arg, SourceLocation Loc)
2428 : Expr(CXXDeleteExprClass, Ty, VK_PRValue, OK_Ordinary),
2429 OperatorDelete(OperatorDelete), Argument(Arg) {
2430 CXXDeleteExprBits.GlobalDelete = GlobalDelete;
2431 CXXDeleteExprBits.ArrayForm = ArrayForm;
2432 CXXDeleteExprBits.ArrayFormAsWritten = ArrayFormAsWritten;
2433 CXXDeleteExprBits.UsualArrayDeleteWantsSize = UsualArrayDeleteWantsSize;
2434 CXXDeleteExprBits.Loc = Loc;
2435 setDependence(computeDependence(this));
2436 }
2437
2438 explicit CXXDeleteExpr(EmptyShell Shell) : Expr(CXXDeleteExprClass, Shell) {}
2439
2440 bool isGlobalDelete() const { return CXXDeleteExprBits.GlobalDelete; }
2441 bool isArrayForm() const { return CXXDeleteExprBits.ArrayForm; }
2442 bool isArrayFormAsWritten() const {
2443 return CXXDeleteExprBits.ArrayFormAsWritten;
2444 }
2445
2446 /// Answers whether the usual array deallocation function for the
2447 /// allocated type expects the size of the allocation as a
2448 /// parameter. This can be true even if the actual deallocation
2449 /// function that we're using doesn't want a size.
2450 bool doesUsualArrayDeleteWantSize() const {
2451 return CXXDeleteExprBits.UsualArrayDeleteWantsSize;
2452 }
2453
2454 FunctionDecl *getOperatorDelete() const { return OperatorDelete; }
2455
2456 Expr *getArgument() { return cast<Expr>(Argument); }
2457 const Expr *getArgument() const { return cast<Expr>(Argument); }
2458
2459 /// Retrieve the type being destroyed.
2460 ///
2461 /// If the type being destroyed is a dependent type which may or may not
2462 /// be a pointer, return an invalid type.
2463 QualType getDestroyedType() const;
2464
2465 SourceLocation getBeginLoc() const { return CXXDeleteExprBits.Loc; }
2466 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2467 return Argument->getEndLoc();
2468 }
2469
2470 static bool classof(const Stmt *T) {
2471 return T->getStmtClass() == CXXDeleteExprClass;
2472 }
2473
2474 // Iterators
2475 child_range children() { return child_range(&Argument, &Argument + 1); }
2476
2477 const_child_range children() const {
2478 return const_child_range(&Argument, &Argument + 1);
2479 }
2480};
2481
2482/// Stores the type being destroyed by a pseudo-destructor expression.
2483class PseudoDestructorTypeStorage {
2484 /// Either the type source information or the name of the type, if
2485 /// it couldn't be resolved due to type-dependence.
2486 llvm::PointerUnion<TypeSourceInfo *, IdentifierInfo *> Type;
2487
2488 /// The starting source location of the pseudo-destructor type.
2489 SourceLocation Location;
2490
2491public:
2492 PseudoDestructorTypeStorage() = default;
2493
2494 PseudoDestructorTypeStorage(IdentifierInfo *II, SourceLocation Loc)
2495 : Type(II), Location(Loc) {}
2496
2497 PseudoDestructorTypeStorage(TypeSourceInfo *Info);
2498
2499 TypeSourceInfo *getTypeSourceInfo() const {
2500 return Type.dyn_cast<TypeSourceInfo *>();
2501 }
2502
2503 IdentifierInfo *getIdentifier() const {
2504 return Type.dyn_cast<IdentifierInfo *>();
2505 }
2506
2507 SourceLocation getLocation() const { return Location; }
2508};
2509
2510/// Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
2511///
2512/// A pseudo-destructor is an expression that looks like a member access to a
2513/// destructor of a scalar type, except that scalar types don't have
2514/// destructors. For example:
2515///
2516/// \code
2517/// typedef int T;
2518/// void f(int *p) {
2519/// p->T::~T();
2520/// }
2521/// \endcode
2522///
2523/// Pseudo-destructors typically occur when instantiating templates such as:
2524///
2525/// \code
2526/// template<typename T>
2527/// void destroy(T* ptr) {
2528/// ptr->T::~T();
2529/// }
2530/// \endcode
2531///
2532/// for scalar types. A pseudo-destructor expression has no run-time semantics
2533/// beyond evaluating the base expression.
2534class CXXPseudoDestructorExpr : public Expr {
2535 friend class ASTStmtReader;
2536
2537 /// The base expression (that is being destroyed).
2538 Stmt *Base = nullptr;
2539
2540 /// Whether the operator was an arrow ('->'); otherwise, it was a
2541 /// period ('.').
2542 bool IsArrow : 1;
2543
2544 /// The location of the '.' or '->' operator.
2545 SourceLocation OperatorLoc;
2546
2547 /// The nested-name-specifier that follows the operator, if present.
2548 NestedNameSpecifierLoc QualifierLoc;
2549
2550 /// The type that precedes the '::' in a qualified pseudo-destructor
2551 /// expression.
2552 TypeSourceInfo *ScopeType = nullptr;
2553
2554 /// The location of the '::' in a qualified pseudo-destructor
2555 /// expression.
2556 SourceLocation ColonColonLoc;
2557
2558 /// The location of the '~'.
2559 SourceLocation TildeLoc;
2560
2561 /// The type being destroyed, or its name if we were unable to
2562 /// resolve the name.
2563 PseudoDestructorTypeStorage DestroyedType;
2564
2565public:
2566 CXXPseudoDestructorExpr(const ASTContext &Context,
2567 Expr *Base, bool isArrow, SourceLocation OperatorLoc,
2568 NestedNameSpecifierLoc QualifierLoc,
2569 TypeSourceInfo *ScopeType,
2570 SourceLocation ColonColonLoc,
2571 SourceLocation TildeLoc,
2572 PseudoDestructorTypeStorage DestroyedType);
2573
2574 explicit CXXPseudoDestructorExpr(EmptyShell Shell)
2575 : Expr(CXXPseudoDestructorExprClass, Shell), IsArrow(false) {}
2576
2577 Expr *getBase() const { return cast<Expr>(Base); }
2578
2579 /// Determines whether this member expression actually had
2580 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2581 /// x->Base::foo.
2582 bool hasQualifier() const { return QualifierLoc.hasQualifier(); }
2583
2584 /// Retrieves the nested-name-specifier that qualifies the type name,
2585 /// with source-location information.
2586 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
2587
2588 /// If the member name was qualified, retrieves the
2589 /// nested-name-specifier that precedes the member name. Otherwise, returns
2590 /// null.
2591 NestedNameSpecifier *getQualifier() const {
2592 return QualifierLoc.getNestedNameSpecifier();
2593 }
2594
2595 /// Determine whether this pseudo-destructor expression was written
2596 /// using an '->' (otherwise, it used a '.').
2597 bool isArrow() const { return IsArrow; }
2598
2599 /// Retrieve the location of the '.' or '->' operator.
2600 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2601
2602 /// Retrieve the scope type in a qualified pseudo-destructor
2603 /// expression.
2604 ///
2605 /// Pseudo-destructor expressions can have extra qualification within them
2606 /// that is not part of the nested-name-specifier, e.g., \c p->T::~T().
2607 /// Here, if the object type of the expression is (or may be) a scalar type,
2608 /// \p T may also be a scalar type and, therefore, cannot be part of a
2609 /// nested-name-specifier. It is stored as the "scope type" of the pseudo-
2610 /// destructor expression.
2611 TypeSourceInfo *getScopeTypeInfo() const { return ScopeType; }
2612
2613 /// Retrieve the location of the '::' in a qualified pseudo-destructor
2614 /// expression.
2615 SourceLocation getColonColonLoc() const { return ColonColonLoc; }
2616
2617 /// Retrieve the location of the '~'.
2618 SourceLocation getTildeLoc() const { return TildeLoc; }
2619
2620 /// Retrieve the source location information for the type
2621 /// being destroyed.
2622 ///
2623 /// This type-source information is available for non-dependent
2624 /// pseudo-destructor expressions and some dependent pseudo-destructor
2625 /// expressions. Returns null if we only have the identifier for a
2626 /// dependent pseudo-destructor expression.
2627 TypeSourceInfo *getDestroyedTypeInfo() const {
2628 return DestroyedType.getTypeSourceInfo();
2629 }
2630
2631 /// In a dependent pseudo-destructor expression for which we do not
2632 /// have full type information on the destroyed type, provides the name
2633 /// of the destroyed type.
2634 IdentifierInfo *getDestroyedTypeIdentifier() const {
2635 return DestroyedType.getIdentifier();
2636 }
2637
2638 /// Retrieve the type being destroyed.
2639 QualType getDestroyedType() const;
2640
2641 /// Retrieve the starting location of the type being destroyed.
2642 SourceLocation getDestroyedTypeLoc() const {
2643 return DestroyedType.getLocation();
2644 }
2645
2646 /// Set the name of destroyed type for a dependent pseudo-destructor
2647 /// expression.
2648 void setDestroyedType(IdentifierInfo *II, SourceLocation Loc) {
2649 DestroyedType = PseudoDestructorTypeStorage(II, Loc);
2650 }
2651
2652 /// Set the destroyed type.
2653 void setDestroyedType(TypeSourceInfo *Info) {
2654 DestroyedType = PseudoDestructorTypeStorage(Info);
2655 }
2656
2657 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2658 return Base->getBeginLoc();
2659 }
2660 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
2661
2662 static bool classof(const Stmt *T) {
2663 return T->getStmtClass() == CXXPseudoDestructorExprClass;
2664 }
2665
2666 // Iterators
2667 child_range children() { return child_range(&Base, &Base + 1); }
2668
2669 const_child_range children() const {
2670 return const_child_range(&Base, &Base + 1);
2671 }
2672};
2673
2674/// A type trait used in the implementation of various C++11 and
2675/// Library TR1 trait templates.
2676///
2677/// \code
2678/// __is_pod(int) == true
2679/// __is_enum(std::string) == false
2680/// __is_trivially_constructible(vector<int>, int*, int*)
2681/// \endcode
2682class TypeTraitExpr final
2683 : public Expr,
2684 private llvm::TrailingObjects<TypeTraitExpr, TypeSourceInfo *> {
2685 /// The location of the type trait keyword.
2686 SourceLocation Loc;
2687
2688 /// The location of the closing parenthesis.
2689 SourceLocation RParenLoc;
2690
2691 // Note: The TypeSourceInfos for the arguments are allocated after the
2692 // TypeTraitExpr.
2693
2694 TypeTraitExpr(QualType T, SourceLocation Loc, TypeTrait Kind,
2695 ArrayRef<TypeSourceInfo *> Args,
2696 SourceLocation RParenLoc,
2697 bool Value);
2698
2699 TypeTraitExpr(EmptyShell Empty) : Expr(TypeTraitExprClass, Empty) {}
2700
2701 size_t numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
2702 return getNumArgs();
2703 }
2704
2705public:
2706 friend class ASTStmtReader;
2707 friend class ASTStmtWriter;
2708 friend TrailingObjects;
2709
2710 /// Create a new type trait expression.
2711 static TypeTraitExpr *Create(const ASTContext &C, QualType T,
2712 SourceLocation Loc, TypeTrait Kind,
2713 ArrayRef<TypeSourceInfo *> Args,
2714 SourceLocation RParenLoc,
2715 bool Value);
2716
2717 static TypeTraitExpr *CreateDeserialized(const ASTContext &C,
2718 unsigned NumArgs);
2719
2720 /// Determine which type trait this expression uses.
2721 TypeTrait getTrait() const {
2722 return static_cast<TypeTrait>(TypeTraitExprBits.Kind);
2723 }
2724
2725 bool getValue() const {
2726 assert(!isValueDependent())(static_cast <bool> (!isValueDependent()) ? void (0) : __assert_fail
("!isValueDependent()", "clang/include/clang/AST/ExprCXX.h",
2726, __extension__ __PRETTY_FUNCTION__))
;
2727 return TypeTraitExprBits.Value;
2728 }
2729
2730 /// Determine the number of arguments to this type trait.
2731 unsigned getNumArgs() const { return TypeTraitExprBits.NumArgs; }
2732
2733 /// Retrieve the Ith argument.
2734 TypeSourceInfo *getArg(unsigned I) const {
2735 assert(I < getNumArgs() && "Argument out-of-range")(static_cast <bool> (I < getNumArgs() && "Argument out-of-range"
) ? void (0) : __assert_fail ("I < getNumArgs() && \"Argument out-of-range\""
, "clang/include/clang/AST/ExprCXX.h", 2735, __extension__ __PRETTY_FUNCTION__
))
;
2736 return getArgs()[I];
2737 }
2738
2739 /// Retrieve the argument types.
2740 ArrayRef<TypeSourceInfo *> getArgs() const {
2741 return llvm::makeArrayRef(getTrailingObjects<TypeSourceInfo *>(),
2742 getNumArgs());
2743 }
2744
2745 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2746 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2747
2748 static bool classof(const Stmt *T) {
2749 return T->getStmtClass() == TypeTraitExprClass;
2750 }
2751
2752 // Iterators
2753 child_range children() {
2754 return child_range(child_iterator(), child_iterator());
2755 }
2756
2757 const_child_range children() const {
2758 return const_child_range(const_child_iterator(), const_child_iterator());
2759 }
2760};
2761
2762/// An Embarcadero array type trait, as used in the implementation of
2763/// __array_rank and __array_extent.
2764///
2765/// Example:
2766/// \code
2767/// __array_rank(int[10][20]) == 2
2768/// __array_extent(int, 1) == 20
2769/// \endcode
2770class ArrayTypeTraitExpr : public Expr {
2771 /// The trait. An ArrayTypeTrait enum in MSVC compat unsigned.
2772 unsigned ATT : 2;
2773
2774 /// The value of the type trait. Unspecified if dependent.
2775 uint64_t Value = 0;
2776
2777 /// The array dimension being queried, or -1 if not used.
2778 Expr *Dimension;
2779
2780 /// The location of the type trait keyword.
2781 SourceLocation Loc;
2782
2783 /// The location of the closing paren.
2784 SourceLocation RParen;
2785
2786 /// The type being queried.
2787 TypeSourceInfo *QueriedType = nullptr;
2788
2789public:
2790 friend class ASTStmtReader;
2791
2792 ArrayTypeTraitExpr(SourceLocation loc, ArrayTypeTrait att,
2793 TypeSourceInfo *queried, uint64_t value, Expr *dimension,
2794 SourceLocation rparen, QualType ty)
2795 : Expr(ArrayTypeTraitExprClass, ty, VK_PRValue, OK_Ordinary), ATT(att),
2796 Value(value), Dimension(dimension), Loc(loc), RParen(rparen),
2797 QueriedType(queried) {
2798 assert(att <= ATT_Last && "invalid enum value!")(static_cast <bool> (att <= ATT_Last && "invalid enum value!"
) ? void (0) : __assert_fail ("att <= ATT_Last && \"invalid enum value!\""
, "clang/include/clang/AST/ExprCXX.h", 2798, __extension__ __PRETTY_FUNCTION__
))
;
2799 assert(static_cast<unsigned>(att) == ATT && "ATT overflow!")(static_cast <bool> (static_cast<unsigned>(att) ==
ATT && "ATT overflow!") ? void (0) : __assert_fail (
"static_cast<unsigned>(att) == ATT && \"ATT overflow!\""
, "clang/include/clang/AST/ExprCXX.h", 2799, __extension__ __PRETTY_FUNCTION__
))
;
2800 setDependence(computeDependence(this));
2801 }
2802
2803 explicit ArrayTypeTraitExpr(EmptyShell Empty)
2804 : Expr(ArrayTypeTraitExprClass, Empty), ATT(0) {}
2805
2806 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2807 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParen; }
2808
2809 ArrayTypeTrait getTrait() const { return static_cast<ArrayTypeTrait>(ATT); }
2810
2811 QualType getQueriedType() const { return QueriedType->getType(); }
2812
2813 TypeSourceInfo *getQueriedTypeSourceInfo() const { return QueriedType; }
2814
2815 uint64_t getValue() const { assert(!isTypeDependent())(static_cast <bool> (!isTypeDependent()) ? void (0) : __assert_fail
("!isTypeDependent()", "clang/include/clang/AST/ExprCXX.h", 2815
, __extension__ __PRETTY_FUNCTION__))
; return Value; }
2816
2817 Expr *getDimensionExpression() const { return Dimension; }
2818
2819 static bool classof(const Stmt *T) {
2820 return T->getStmtClass() == ArrayTypeTraitExprClass;
2821 }
2822
2823 // Iterators
2824 child_range children() {
2825 return child_range(child_iterator(), child_iterator());
2826 }
2827
2828 const_child_range children() const {
2829 return const_child_range(const_child_iterator(), const_child_iterator());
2830 }
2831};
2832
2833/// An expression trait intrinsic.
2834///
2835/// Example:
2836/// \code
2837/// __is_lvalue_expr(std::cout) == true
2838/// __is_lvalue_expr(1) == false
2839/// \endcode
2840class ExpressionTraitExpr : public Expr {
2841 /// The trait. A ExpressionTrait enum in MSVC compatible unsigned.
2842 unsigned ET : 31;
2843
2844 /// The value of the type trait. Unspecified if dependent.
2845 unsigned Value : 1;
2846
2847 /// The location of the type trait keyword.
2848 SourceLocation Loc;
2849
2850 /// The location of the closing paren.
2851 SourceLocation RParen;
2852
2853 /// The expression being queried.
2854 Expr* QueriedExpression = nullptr;
2855
2856public:
2857 friend class ASTStmtReader;
2858
2859 ExpressionTraitExpr(SourceLocation loc, ExpressionTrait et, Expr *queried,
2860 bool value, SourceLocation rparen, QualType resultType)
2861 : Expr(ExpressionTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
2862 ET(et), Value(value), Loc(loc), RParen(rparen),
2863 QueriedExpression(queried) {
2864 assert(et <= ET_Last && "invalid enum value!")(static_cast <bool> (et <= ET_Last && "invalid enum value!"
) ? void (0) : __assert_fail ("et <= ET_Last && \"invalid enum value!\""
, "clang/include/clang/AST/ExprCXX.h", 2864, __extension__ __PRETTY_FUNCTION__
))
;
2865 assert(static_cast<unsigned>(et) == ET && "ET overflow!")(static_cast <bool> (static_cast<unsigned>(et) ==
ET && "ET overflow!") ? void (0) : __assert_fail ("static_cast<unsigned>(et) == ET && \"ET overflow!\""
, "clang/include/clang/AST/ExprCXX.h", 2865, __extension__ __PRETTY_FUNCTION__
))
;
2866 setDependence(computeDependence(this));
2867 }
2868
2869 explicit ExpressionTraitExpr(EmptyShell Empty)
2870 : Expr(ExpressionTraitExprClass, Empty), ET(0), Value(false) {}
2871
2872 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
2873 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParen; }
2874
2875 ExpressionTrait getTrait() const { return static_cast<ExpressionTrait>(ET); }
2876
2877 Expr *getQueriedExpression() const { return QueriedExpression; }
2878
2879 bool getValue() const { return Value; }
2880
2881 static bool classof(const Stmt *T) {
2882 return T->getStmtClass() == ExpressionTraitExprClass;
2883 }
2884
2885 // Iterators
2886 child_range children() {
2887 return child_range(child_iterator(), child_iterator());
2888 }
2889
2890 const_child_range children() const {
2891 return const_child_range(const_child_iterator(), const_child_iterator());
2892 }
2893};
2894
2895/// A reference to an overloaded function set, either an
2896/// \c UnresolvedLookupExpr or an \c UnresolvedMemberExpr.
2897class OverloadExpr : public Expr {
2898 friend class ASTStmtReader;
2899 friend class ASTStmtWriter;
2900
2901 /// The common name of these declarations.
2902 DeclarationNameInfo NameInfo;
2903
2904 /// The nested-name-specifier that qualifies the name, if any.
2905 NestedNameSpecifierLoc QualifierLoc;
2906
2907protected:
2908 OverloadExpr(StmtClass SC, const ASTContext &Context,
2909 NestedNameSpecifierLoc QualifierLoc,
2910 SourceLocation TemplateKWLoc,
2911 const DeclarationNameInfo &NameInfo,
2912 const TemplateArgumentListInfo *TemplateArgs,
2913 UnresolvedSetIterator Begin, UnresolvedSetIterator End,
2914 bool KnownDependent, bool KnownInstantiationDependent,
2915 bool KnownContainsUnexpandedParameterPack);
2916
2917 OverloadExpr(StmtClass SC, EmptyShell Empty, unsigned NumResults,
2918 bool HasTemplateKWAndArgsInfo);
2919
2920 /// Return the results. Defined after UnresolvedMemberExpr.
2921 inline DeclAccessPair *getTrailingResults();
2922 const DeclAccessPair *getTrailingResults() const {
2923 return const_cast<OverloadExpr *>(this)->getTrailingResults();
2924 }
2925
2926 /// Return the optional template keyword and arguments info.
2927 /// Defined after UnresolvedMemberExpr.
2928 inline ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo();
2929 const ASTTemplateKWAndArgsInfo *getTrailingASTTemplateKWAndArgsInfo() const {
2930 return const_cast<OverloadExpr *>(this)
2931 ->getTrailingASTTemplateKWAndArgsInfo();
2932 }
2933
2934 /// Return the optional template arguments. Defined after
2935 /// UnresolvedMemberExpr.
2936 inline TemplateArgumentLoc *getTrailingTemplateArgumentLoc();
2937 const TemplateArgumentLoc *getTrailingTemplateArgumentLoc() const {
2938 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
2939 }
2940
2941 bool hasTemplateKWAndArgsInfo() const {
2942 return OverloadExprBits.HasTemplateKWAndArgsInfo;
2943 }
2944
2945public:
2946 struct FindResult {
2947 OverloadExpr *Expression;
2948 bool IsAddressOfOperand;
2949 bool HasFormOfMemberPointer;
2950 };
2951
2952 /// Finds the overloaded expression in the given expression \p E of
2953 /// OverloadTy.
2954 ///
2955 /// \return the expression (which must be there) and true if it has
2956 /// the particular form of a member pointer expression
2957 static FindResult find(Expr *E) {
2958 assert(E->getType()->isSpecificBuiltinType(BuiltinType::Overload))(static_cast <bool> (E->getType()->isSpecificBuiltinType
(BuiltinType::Overload)) ? void (0) : __assert_fail ("E->getType()->isSpecificBuiltinType(BuiltinType::Overload)"
, "clang/include/clang/AST/ExprCXX.h", 2958, __extension__ __PRETTY_FUNCTION__
))
;
2959
2960 FindResult Result;
2961
2962 E = E->IgnoreParens();
2963 if (isa<UnaryOperator>(E)) {
2964 assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf)(static_cast <bool> (cast<UnaryOperator>(E)->getOpcode
() == UO_AddrOf) ? void (0) : __assert_fail ("cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf"
, "clang/include/clang/AST/ExprCXX.h", 2964, __extension__ __PRETTY_FUNCTION__
))
;
2965 E = cast<UnaryOperator>(E)->getSubExpr();
2966 auto *Ovl = cast<OverloadExpr>(E->IgnoreParens());
2967
2968 Result.HasFormOfMemberPointer = (E == Ovl && Ovl->getQualifier());
2969 Result.IsAddressOfOperand = true;
2970 Result.Expression = Ovl;
2971 } else {
2972 Result.HasFormOfMemberPointer = false;
2973 Result.IsAddressOfOperand = false;
2974 Result.Expression = cast<OverloadExpr>(E);
2975 }
2976
2977 return Result;
2978 }
2979
2980 /// Gets the naming class of this lookup, if any.
2981 /// Defined after UnresolvedMemberExpr.
2982 inline CXXRecordDecl *getNamingClass();
2983 const CXXRecordDecl *getNamingClass() const {
2984 return const_cast<OverloadExpr *>(this)->getNamingClass();
2985 }
2986
2987 using decls_iterator = UnresolvedSetImpl::iterator;
2988
2989 decls_iterator decls_begin() const {
2990 return UnresolvedSetIterator(getTrailingResults());
2991 }
2992 decls_iterator decls_end() const {
2993 return UnresolvedSetIterator(getTrailingResults() + getNumDecls());
2994 }
2995 llvm::iterator_range<decls_iterator> decls() const {
2996 return llvm::make_range(decls_begin(), decls_end());
2997 }
2998
2999 /// Gets the number of declarations in the unresolved set.
3000 unsigned getNumDecls() const { return OverloadExprBits.NumResults; }
3001
3002 /// Gets the full name info.
3003 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
3004
3005 /// Gets the name looked up.
3006 DeclarationName getName() const { return NameInfo.getName(); }
3007
3008 /// Gets the location of the name.
3009 SourceLocation getNameLoc() const { return NameInfo.getLoc(); }
3010
3011 /// Fetches the nested-name qualifier, if one was given.
3012 NestedNameSpecifier *getQualifier() const {
3013 return QualifierLoc.getNestedNameSpecifier();
3014 }
3015
3016 /// Fetches the nested-name qualifier with source-location
3017 /// information, if one was given.
3018 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3019
3020 /// Retrieve the location of the template keyword preceding
3021 /// this name, if any.
3022 SourceLocation getTemplateKeywordLoc() const {
3023 if (!hasTemplateKWAndArgsInfo())
3024 return SourceLocation();
3025 return getTrailingASTTemplateKWAndArgsInfo()->TemplateKWLoc;
3026 }
3027
3028 /// Retrieve the location of the left angle bracket starting the
3029 /// explicit template argument list following the name, if any.
3030 SourceLocation getLAngleLoc() const {
3031 if (!hasTemplateKWAndArgsInfo())
3032 return SourceLocation();
3033 return getTrailingASTTemplateKWAndArgsInfo()->LAngleLoc;
3034 }
3035
3036 /// Retrieve the location of the right angle bracket ending the
3037 /// explicit template argument list following the name, if any.
3038 SourceLocation getRAngleLoc() const {
3039 if (!hasTemplateKWAndArgsInfo())
3040 return SourceLocation();
3041 return getTrailingASTTemplateKWAndArgsInfo()->RAngleLoc;
3042 }
3043
3044 /// Determines whether the name was preceded by the template keyword.
3045 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3046
3047 /// Determines whether this expression had explicit template arguments.
3048 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3049
3050 TemplateArgumentLoc const *getTemplateArgs() const {
3051 if (!hasExplicitTemplateArgs())
3052 return nullptr;
3053 return const_cast<OverloadExpr *>(this)->getTrailingTemplateArgumentLoc();
3054 }
3055
3056 unsigned getNumTemplateArgs() const {
3057 if (!hasExplicitTemplateArgs())
3058 return 0;
3059
3060 return getTrailingASTTemplateKWAndArgsInfo()->NumTemplateArgs;
3061 }
3062
3063 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3064 return {getTemplateArgs(), getNumTemplateArgs()};
3065 }
3066
3067 /// Copies the template arguments into the given structure.
3068 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3069 if (hasExplicitTemplateArgs())
3070 getTrailingASTTemplateKWAndArgsInfo()->copyInto(getTemplateArgs(), List);
3071 }
3072
3073 static bool classof(const Stmt *T) {
3074 return T->getStmtClass() == UnresolvedLookupExprClass ||
3075 T->getStmtClass() == UnresolvedMemberExprClass;
3076 }
3077};
3078
3079/// A reference to a name which we were able to look up during
3080/// parsing but could not resolve to a specific declaration.
3081///
3082/// This arises in several ways:
3083/// * we might be waiting for argument-dependent lookup;
3084/// * the name might resolve to an overloaded function;
3085/// and eventually:
3086/// * the lookup might have included a function template.
3087///
3088/// These never include UnresolvedUsingValueDecls, which are always class
3089/// members and therefore appear only in UnresolvedMemberLookupExprs.
3090class UnresolvedLookupExpr final
3091 : public OverloadExpr,
3092 private llvm::TrailingObjects<UnresolvedLookupExpr, DeclAccessPair,
3093 ASTTemplateKWAndArgsInfo,
3094 TemplateArgumentLoc> {
3095 friend class ASTStmtReader;
3096 friend class OverloadExpr;
3097 friend TrailingObjects;
3098
3099 /// The naming class (C++ [class.access.base]p5) of the lookup, if
3100 /// any. This can generally be recalculated from the context chain,
3101 /// but that can be fairly expensive for unqualified lookups.
3102 CXXRecordDecl *NamingClass;
3103
3104 // UnresolvedLookupExpr is followed by several trailing objects.
3105 // They are in order:
3106 //
3107 // * An array of getNumResults() DeclAccessPair for the results. These are
3108 // undesugared, which is to say, they may include UsingShadowDecls.
3109 // Access is relative to the naming class.
3110 //
3111 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3112 // template keyword and arguments. Present if and only if
3113 // hasTemplateKWAndArgsInfo().
3114 //
3115 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
3116 // location information for the explicitly specified template arguments.
3117
3118 UnresolvedLookupExpr(const ASTContext &Context, CXXRecordDecl *NamingClass,
3119 NestedNameSpecifierLoc QualifierLoc,
3120 SourceLocation TemplateKWLoc,
3121 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3122 bool Overloaded,
3123 const TemplateArgumentListInfo *TemplateArgs,
3124 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3125
3126 UnresolvedLookupExpr(EmptyShell Empty, unsigned NumResults,
3127 bool HasTemplateKWAndArgsInfo);
3128
3129 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3130 return getNumDecls();
3131 }
3132
3133 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3134 return hasTemplateKWAndArgsInfo();
3135 }
3136
3137public:
3138 static UnresolvedLookupExpr *
3139 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
3140 NestedNameSpecifierLoc QualifierLoc,
3141 const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
3142 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3143
3144 static UnresolvedLookupExpr *
3145 Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
3146 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3147 const DeclarationNameInfo &NameInfo, bool RequiresADL,
3148 const TemplateArgumentListInfo *Args, UnresolvedSetIterator Begin,
3149 UnresolvedSetIterator End);
3150
3151 static UnresolvedLookupExpr *CreateEmpty(const ASTContext &Context,
3152 unsigned NumResults,
3153 bool HasTemplateKWAndArgsInfo,
3154 unsigned NumTemplateArgs);
3155
3156 /// True if this declaration should be extended by
3157 /// argument-dependent lookup.
3158 bool requiresADL() const { return UnresolvedLookupExprBits.RequiresADL; }
3159
3160 /// True if this lookup is overloaded.
3161 bool isOverloaded() const { return UnresolvedLookupExprBits.Overloaded; }
3162
3163 /// Gets the 'naming class' (in the sense of C++0x
3164 /// [class.access.base]p5) of the lookup. This is the scope
3165 /// that was looked in to find these results.
3166 CXXRecordDecl *getNamingClass() { return NamingClass; }
3167 const CXXRecordDecl *getNamingClass() const { return NamingClass; }
3168
3169 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3170 if (NestedNameSpecifierLoc l = getQualifierLoc())
3171 return l.getBeginLoc();
3172 return getNameInfo().getBeginLoc();
3173 }
3174
3175 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3176 if (hasExplicitTemplateArgs())
3177 return getRAngleLoc();
3178 return getNameInfo().getEndLoc();
3179 }
3180
3181 child_range children() {
3182 return child_range(child_iterator(), child_iterator());
3183 }
3184
3185 const_child_range children() const {
3186 return const_child_range(const_child_iterator(), const_child_iterator());
3187 }
3188
3189 static bool classof(const Stmt *T) {
3190 return T->getStmtClass() == UnresolvedLookupExprClass;
3191 }
3192};
3193
3194/// A qualified reference to a name whose declaration cannot
3195/// yet be resolved.
3196///
3197/// DependentScopeDeclRefExpr is similar to DeclRefExpr in that
3198/// it expresses a reference to a declaration such as
3199/// X<T>::value. The difference, however, is that an
3200/// DependentScopeDeclRefExpr node is used only within C++ templates when
3201/// the qualification (e.g., X<T>::) refers to a dependent type. In
3202/// this case, X<T>::value cannot resolve to a declaration because the
3203/// declaration will differ from one instantiation of X<T> to the
3204/// next. Therefore, DependentScopeDeclRefExpr keeps track of the
3205/// qualifier (X<T>::) and the name of the entity being referenced
3206/// ("value"). Such expressions will instantiate to a DeclRefExpr once the
3207/// declaration can be found.
3208class DependentScopeDeclRefExpr final
3209 : public Expr,
3210 private llvm::TrailingObjects<DependentScopeDeclRefExpr,
3211 ASTTemplateKWAndArgsInfo,
3212 TemplateArgumentLoc> {
3213 friend class ASTStmtReader;
3214 friend class ASTStmtWriter;
3215 friend TrailingObjects;
3216
3217 /// The nested-name-specifier that qualifies this unresolved
3218 /// declaration name.
3219 NestedNameSpecifierLoc QualifierLoc;
3220
3221 /// The name of the entity we will be referencing.
3222 DeclarationNameInfo NameInfo;
3223
3224 DependentScopeDeclRefExpr(QualType Ty, NestedNameSpecifierLoc QualifierLoc,
3225 SourceLocation TemplateKWLoc,
3226 const DeclarationNameInfo &NameInfo,
3227 const TemplateArgumentListInfo *Args);
3228
3229 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3230 return hasTemplateKWAndArgsInfo();
3231 }
3232
3233 bool hasTemplateKWAndArgsInfo() const {
3234 return DependentScopeDeclRefExprBits.HasTemplateKWAndArgsInfo;
3235 }
3236
3237public:
3238 static DependentScopeDeclRefExpr *
3239 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
3240 SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo,
3241 const TemplateArgumentListInfo *TemplateArgs);
3242
3243 static DependentScopeDeclRefExpr *CreateEmpty(const ASTContext &Context,
3244 bool HasTemplateKWAndArgsInfo,
3245 unsigned NumTemplateArgs);
3246
3247 /// Retrieve the name that this expression refers to.
3248 const DeclarationNameInfo &getNameInfo() const { return NameInfo; }
3249
3250 /// Retrieve the name that this expression refers to.
3251 DeclarationName getDeclName() const { return NameInfo.getName(); }
3252
3253 /// Retrieve the location of the name within the expression.
3254 ///
3255 /// For example, in "X<T>::value" this is the location of "value".
3256 SourceLocation getLocation() const { return NameInfo.getLoc(); }
3257
3258 /// Retrieve the nested-name-specifier that qualifies the
3259 /// name, with source location information.
3260 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3261
3262 /// Retrieve the nested-name-specifier that qualifies this
3263 /// declaration.
3264 NestedNameSpecifier *getQualifier() const {
3265 return QualifierLoc.getNestedNameSpecifier();
3266 }
3267
3268 /// Retrieve the location of the template keyword preceding
3269 /// this name, if any.
3270 SourceLocation getTemplateKeywordLoc() const {
3271 if (!hasTemplateKWAndArgsInfo())
3272 return SourceLocation();
3273 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3274 }
3275
3276 /// Retrieve the location of the left angle bracket starting the
3277 /// explicit template argument list following the name, if any.
3278 SourceLocation getLAngleLoc() const {
3279 if (!hasTemplateKWAndArgsInfo())
3280 return SourceLocation();
3281 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3282 }
3283
3284 /// Retrieve the location of the right angle bracket ending the
3285 /// explicit template argument list following the name, if any.
3286 SourceLocation getRAngleLoc() const {
3287 if (!hasTemplateKWAndArgsInfo())
3288 return SourceLocation();
3289 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3290 }
3291
3292 /// Determines whether the name was preceded by the template keyword.
3293 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3294
3295 /// Determines whether this lookup had explicit template arguments.
3296 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3297
3298 /// Copies the template arguments (if present) into the given
3299 /// structure.
3300 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3301 if (hasExplicitTemplateArgs())
3302 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3303 getTrailingObjects<TemplateArgumentLoc>(), List);
3304 }
3305
3306 TemplateArgumentLoc const *getTemplateArgs() const {
3307 if (!hasExplicitTemplateArgs())
3308 return nullptr;
3309
3310 return getTrailingObjects<TemplateArgumentLoc>();
3311 }
3312
3313 unsigned getNumTemplateArgs() const {
3314 if (!hasExplicitTemplateArgs())
3315 return 0;
3316
3317 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3318 }
3319
3320 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3321 return {getTemplateArgs(), getNumTemplateArgs()};
3322 }
3323
3324 /// Note: getBeginLoc() is the start of the whole DependentScopeDeclRefExpr,
3325 /// and differs from getLocation().getStart().
3326 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3327 return QualifierLoc.getBeginLoc();
3328 }
3329
3330 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3331 if (hasExplicitTemplateArgs())
3332 return getRAngleLoc();
3333 return getLocation();
3334 }
3335
3336 static bool classof(const Stmt *T) {
3337 return T->getStmtClass() == DependentScopeDeclRefExprClass;
3338 }
3339
3340 child_range children() {
3341 return child_range(child_iterator(), child_iterator());
3342 }
3343
3344 const_child_range children() const {
3345 return const_child_range(const_child_iterator(), const_child_iterator());
3346 }
3347};
3348
3349/// Represents an expression -- generally a full-expression -- that
3350/// introduces cleanups to be run at the end of the sub-expression's
3351/// evaluation. The most common source of expression-introduced
3352/// cleanups is temporary objects in C++, but several other kinds of
3353/// expressions can create cleanups, including basically every
3354/// call in ARC that returns an Objective-C pointer.
3355///
3356/// This expression also tracks whether the sub-expression contains a
3357/// potentially-evaluated block literal. The lifetime of a block
3358/// literal is the extent of the enclosing scope.
3359class ExprWithCleanups final
3360 : public FullExpr,
3361 private llvm::TrailingObjects<
3362 ExprWithCleanups,
3363 llvm::PointerUnion<BlockDecl *, CompoundLiteralExpr *>> {
3364public:
3365 /// The type of objects that are kept in the cleanup.
3366 /// It's useful to remember the set of blocks and block-scoped compound
3367 /// literals; we could also remember the set of temporaries, but there's
3368 /// currently no need.
3369 using CleanupObject = llvm::PointerUnion<BlockDecl *, CompoundLiteralExpr *>;
3370
3371private:
3372 friend class ASTStmtReader;
3373 friend TrailingObjects;
3374
3375 ExprWithCleanups(EmptyShell, unsigned NumObjects);
3376 ExprWithCleanups(Expr *SubExpr, bool CleanupsHaveSideEffects,
3377 ArrayRef<CleanupObject> Objects);
3378
3379public:
3380 static ExprWithCleanups *Create(const ASTContext &C, EmptyShell empty,
3381 unsigned numObjects);
3382
3383 static ExprWithCleanups *Create(const ASTContext &C, Expr *subexpr,
3384 bool CleanupsHaveSideEffects,
3385 ArrayRef<CleanupObject> objects);
3386
3387 ArrayRef<CleanupObject> getObjects() const {
3388 return llvm::makeArrayRef(getTrailingObjects<CleanupObject>(),
3389 getNumObjects());
3390 }
3391
3392 unsigned getNumObjects() const { return ExprWithCleanupsBits.NumObjects; }
3393
3394 CleanupObject getObject(unsigned i) const {
3395 assert(i < getNumObjects() && "Index out of range")(static_cast <bool> (i < getNumObjects() && "Index out of range"
) ? void (0) : __assert_fail ("i < getNumObjects() && \"Index out of range\""
, "clang/include/clang/AST/ExprCXX.h", 3395, __extension__ __PRETTY_FUNCTION__
))
;
3396 return getObjects()[i];
3397 }
3398
3399 bool cleanupsHaveSideEffects() const {
3400 return ExprWithCleanupsBits.CleanupsHaveSideEffects;
3401 }
3402
3403 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3404 return SubExpr->getBeginLoc();
3405 }
3406
3407 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3408 return SubExpr->getEndLoc();
3409 }
3410
3411 // Implement isa/cast/dyncast/etc.
3412 static bool classof(const Stmt *T) {
3413 return T->getStmtClass() == ExprWithCleanupsClass;
3414 }
3415
3416 // Iterators
3417 child_range children() { return child_range(&SubExpr, &SubExpr + 1); }
3418
3419 const_child_range children() const {
3420 return const_child_range(&SubExpr, &SubExpr + 1);
3421 }
3422};
3423
3424/// Describes an explicit type conversion that uses functional
3425/// notion but could not be resolved because one or more arguments are
3426/// type-dependent.
3427///
3428/// The explicit type conversions expressed by
3429/// CXXUnresolvedConstructExpr have the form <tt>T(a1, a2, ..., aN)</tt>,
3430/// where \c T is some type and \c a1, \c a2, ..., \c aN are values, and
3431/// either \c T is a dependent type or one or more of the <tt>a</tt>'s is
3432/// type-dependent. For example, this would occur in a template such
3433/// as:
3434///
3435/// \code
3436/// template<typename T, typename A1>
3437/// inline T make_a(const A1& a1) {
3438/// return T(a1);
3439/// }
3440/// \endcode
3441///
3442/// When the returned expression is instantiated, it may resolve to a
3443/// constructor call, conversion function call, or some kind of type
3444/// conversion.
3445class CXXUnresolvedConstructExpr final
3446 : public Expr,
3447 private llvm::TrailingObjects<CXXUnresolvedConstructExpr, Expr *> {
3448 friend class ASTStmtReader;
3449 friend TrailingObjects;
3450
3451 /// The type being constructed.
3452 TypeSourceInfo *TSI;
3453
3454 /// The location of the left parentheses ('(').
3455 SourceLocation LParenLoc;
3456
3457 /// The location of the right parentheses (')').
3458 SourceLocation RParenLoc;
3459
3460 CXXUnresolvedConstructExpr(QualType T, TypeSourceInfo *TSI,
3461 SourceLocation LParenLoc, ArrayRef<Expr *> Args,
3462 SourceLocation RParenLoc);
3463
3464 CXXUnresolvedConstructExpr(EmptyShell Empty, unsigned NumArgs)
3465 : Expr(CXXUnresolvedConstructExprClass, Empty), TSI(nullptr) {
3466 CXXUnresolvedConstructExprBits.NumArgs = NumArgs;
3467 }
3468
3469public:
3470 static CXXUnresolvedConstructExpr *Create(const ASTContext &Context,
3471 QualType T, TypeSourceInfo *TSI,
3472 SourceLocation LParenLoc,
3473 ArrayRef<Expr *> Args,
3474 SourceLocation RParenLoc);
3475
3476 static CXXUnresolvedConstructExpr *CreateEmpty(const ASTContext &Context,
3477 unsigned NumArgs);
3478
3479 /// Retrieve the type that is being constructed, as specified
3480 /// in the source code.
3481 QualType getTypeAsWritten() const { return TSI->getType(); }
3482
3483 /// Retrieve the type source information for the type being
3484 /// constructed.
3485 TypeSourceInfo *getTypeSourceInfo() const { return TSI; }
3486
3487 /// Retrieve the location of the left parentheses ('(') that
3488 /// precedes the argument list.
3489 SourceLocation getLParenLoc() const { return LParenLoc; }
3490 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3491
3492 /// Retrieve the location of the right parentheses (')') that
3493 /// follows the argument list.
3494 SourceLocation getRParenLoc() const { return RParenLoc; }
3495 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3496
3497 /// Determine whether this expression models list-initialization.
3498 /// If so, there will be exactly one subexpression, which will be
3499 /// an InitListExpr.
3500 bool isListInitialization() const { return LParenLoc.isInvalid(); }
3501
3502 /// Retrieve the number of arguments.
3503 unsigned getNumArgs() const { return CXXUnresolvedConstructExprBits.NumArgs; }
3504
3505 using arg_iterator = Expr **;
3506 using arg_range = llvm::iterator_range<arg_iterator>;
3507
3508 arg_iterator arg_begin() { return getTrailingObjects<Expr *>(); }
3509 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3510 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3511
3512 using const_arg_iterator = const Expr* const *;
3513 using const_arg_range = llvm::iterator_range<const_arg_iterator>;
3514
3515 const_arg_iterator arg_begin() const { return getTrailingObjects<Expr *>(); }
3516 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3517 const_arg_range arguments() const {
3518 return const_arg_range(arg_begin(), arg_end());
3519 }
3520
3521 Expr *getArg(unsigned I) {
3522 assert(I < getNumArgs() && "Argument index out-of-range")(static_cast <bool> (I < getNumArgs() && "Argument index out-of-range"
) ? void (0) : __assert_fail ("I < getNumArgs() && \"Argument index out-of-range\""
, "clang/include/clang/AST/ExprCXX.h", 3522, __extension__ __PRETTY_FUNCTION__
))
;
3523 return arg_begin()[I];
3524 }
3525
3526 const Expr *getArg(unsigned I) const {
3527 assert(I < getNumArgs() && "Argument index out-of-range")(static_cast <bool> (I < getNumArgs() && "Argument index out-of-range"
) ? void (0) : __assert_fail ("I < getNumArgs() && \"Argument index out-of-range\""
, "clang/include/clang/AST/ExprCXX.h", 3527, __extension__ __PRETTY_FUNCTION__
))
;
3528 return arg_begin()[I];
3529 }
3530
3531 void setArg(unsigned I, Expr *E) {
3532 assert(I < getNumArgs() && "Argument index out-of-range")(static_cast <bool> (I < getNumArgs() && "Argument index out-of-range"
) ? void (0) : __assert_fail ("I < getNumArgs() && \"Argument index out-of-range\""
, "clang/include/clang/AST/ExprCXX.h", 3532, __extension__ __PRETTY_FUNCTION__
))
;
3533 arg_begin()[I] = E;
3534 }
3535
3536 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
3537 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3538 if (!RParenLoc.isValid() && getNumArgs() > 0)
3539 return getArg(getNumArgs() - 1)->getEndLoc();
3540 return RParenLoc;
3541 }
3542
3543 static bool classof(const Stmt *T) {
3544 return T->getStmtClass() == CXXUnresolvedConstructExprClass;
3545 }
3546
3547 // Iterators
3548 child_range children() {
3549 auto **begin = reinterpret_cast<Stmt **>(arg_begin());
3550 return child_range(begin, begin + getNumArgs());
3551 }
3552
3553 const_child_range children() const {
3554 auto **begin = reinterpret_cast<Stmt **>(
3555 const_cast<CXXUnresolvedConstructExpr *>(this)->arg_begin());
3556 return const_child_range(begin, begin + getNumArgs());
3557 }
3558};
3559
3560/// Represents a C++ member access expression where the actual
3561/// member referenced could not be resolved because the base
3562/// expression or the member name was dependent.
3563///
3564/// Like UnresolvedMemberExprs, these can be either implicit or
3565/// explicit accesses. It is only possible to get one of these with
3566/// an implicit access if a qualifier is provided.
3567class CXXDependentScopeMemberExpr final
3568 : public Expr,
3569 private llvm::TrailingObjects<CXXDependentScopeMemberExpr,
3570 ASTTemplateKWAndArgsInfo,
3571 TemplateArgumentLoc, NamedDecl *> {
3572 friend class ASTStmtReader;
3573 friend class ASTStmtWriter;
3574 friend TrailingObjects;
3575
3576 /// The expression for the base pointer or class reference,
3577 /// e.g., the \c x in x.f. Can be null in implicit accesses.
3578 Stmt *Base;
3579
3580 /// The type of the base expression. Never null, even for
3581 /// implicit accesses.
3582 QualType BaseType;
3583
3584 /// The nested-name-specifier that precedes the member name, if any.
3585 /// FIXME: This could be in principle store as a trailing object.
3586 /// However the performance impact of doing so should be investigated first.
3587 NestedNameSpecifierLoc QualifierLoc;
3588
3589 /// The member to which this member expression refers, which
3590 /// can be name, overloaded operator, or destructor.
3591 ///
3592 /// FIXME: could also be a template-id
3593 DeclarationNameInfo MemberNameInfo;
3594
3595 // CXXDependentScopeMemberExpr is followed by several trailing objects,
3596 // some of which optional. They are in order:
3597 //
3598 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3599 // template keyword and arguments. Present if and only if
3600 // hasTemplateKWAndArgsInfo().
3601 //
3602 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing location
3603 // information for the explicitly specified template arguments.
3604 //
3605 // * An optional NamedDecl *. In a qualified member access expression such
3606 // as t->Base::f, this member stores the resolves of name lookup in the
3607 // context of the member access expression, to be used at instantiation
3608 // time. Present if and only if hasFirstQualifierFoundInScope().
3609
3610 bool hasTemplateKWAndArgsInfo() const {
3611 return CXXDependentScopeMemberExprBits.HasTemplateKWAndArgsInfo;
3612 }
3613
3614 bool hasFirstQualifierFoundInScope() const {
3615 return CXXDependentScopeMemberExprBits.HasFirstQualifierFoundInScope;
3616 }
3617
3618 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3619 return hasTemplateKWAndArgsInfo();
3620 }
3621
3622 unsigned numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
3623 return getNumTemplateArgs();
3624 }
3625
3626 unsigned numTrailingObjects(OverloadToken<NamedDecl *>) const {
3627 return hasFirstQualifierFoundInScope();
3628 }
3629
3630 CXXDependentScopeMemberExpr(const ASTContext &Ctx, Expr *Base,
3631 QualType BaseType, bool IsArrow,
3632 SourceLocation OperatorLoc,
3633 NestedNameSpecifierLoc QualifierLoc,
3634 SourceLocation TemplateKWLoc,
3635 NamedDecl *FirstQualifierFoundInScope,
3636 DeclarationNameInfo MemberNameInfo,
3637 const TemplateArgumentListInfo *TemplateArgs);
3638
3639 CXXDependentScopeMemberExpr(EmptyShell Empty, bool HasTemplateKWAndArgsInfo,
3640 bool HasFirstQualifierFoundInScope);
3641
3642public:
3643 static CXXDependentScopeMemberExpr *
3644 Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow,
3645 SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc,
3646 SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope,
3647 DeclarationNameInfo MemberNameInfo,
3648 const TemplateArgumentListInfo *TemplateArgs);
3649
3650 static CXXDependentScopeMemberExpr *
3651 CreateEmpty(const ASTContext &Ctx, bool HasTemplateKWAndArgsInfo,
3652 unsigned NumTemplateArgs, bool HasFirstQualifierFoundInScope);
3653
3654 /// True if this is an implicit access, i.e. one in which the
3655 /// member being accessed was not written in the source. The source
3656 /// location of the operator is invalid in this case.
3657 bool isImplicitAccess() const {
3658 if (!Base)
3659 return true;
3660 return cast<Expr>(Base)->isImplicitCXXThis();
3661 }
3662
3663 /// Retrieve the base object of this member expressions,
3664 /// e.g., the \c x in \c x.m.
3665 Expr *getBase() const {
3666 assert(!isImplicitAccess())(static_cast <bool> (!isImplicitAccess()) ? void (0) : __assert_fail
("!isImplicitAccess()", "clang/include/clang/AST/ExprCXX.h",
3666, __extension__ __PRETTY_FUNCTION__))
;
3667 return cast<Expr>(Base);
3668 }
3669
3670 QualType getBaseType() const { return BaseType; }
3671
3672 /// Determine whether this member expression used the '->'
3673 /// operator; otherwise, it used the '.' operator.
3674 bool isArrow() const { return CXXDependentScopeMemberExprBits.IsArrow; }
3675
3676 /// Retrieve the location of the '->' or '.' operator.
3677 SourceLocation getOperatorLoc() const {
3678 return CXXDependentScopeMemberExprBits.OperatorLoc;
3679 }
3680
3681 /// Retrieve the nested-name-specifier that qualifies the member name.
3682 NestedNameSpecifier *getQualifier() const {
3683 return QualifierLoc.getNestedNameSpecifier();
3684 }
3685
3686 /// Retrieve the nested-name-specifier that qualifies the member
3687 /// name, with source location information.
3688 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3689
3690 /// Retrieve the first part of the nested-name-specifier that was
3691 /// found in the scope of the member access expression when the member access
3692 /// was initially parsed.
3693 ///
3694 /// This function only returns a useful result when member access expression
3695 /// uses a qualified member name, e.g., "x.Base::f". Here, the declaration
3696 /// returned by this function describes what was found by unqualified name
3697 /// lookup for the identifier "Base" within the scope of the member access
3698 /// expression itself. At template instantiation time, this information is
3699 /// combined with the results of name lookup into the type of the object
3700 /// expression itself (the class type of x).
3701 NamedDecl *getFirstQualifierFoundInScope() const {
3702 if (!hasFirstQualifierFoundInScope())
3703 return nullptr;
3704 return *getTrailingObjects<NamedDecl *>();
3705 }
3706
3707 /// Retrieve the name of the member that this expression refers to.
3708 const DeclarationNameInfo &getMemberNameInfo() const {
3709 return MemberNameInfo;
3710 }
3711
3712 /// Retrieve the name of the member that this expression refers to.
3713 DeclarationName getMember() const { return MemberNameInfo.getName(); }
3714
3715 // Retrieve the location of the name of the member that this
3716 // expression refers to.
3717 SourceLocation getMemberLoc() const { return MemberNameInfo.getLoc(); }
3718
3719 /// Retrieve the location of the template keyword preceding the
3720 /// member name, if any.
3721 SourceLocation getTemplateKeywordLoc() const {
3722 if (!hasTemplateKWAndArgsInfo())
3723 return SourceLocation();
3724 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3725 }
3726
3727 /// Retrieve the location of the left angle bracket starting the
3728 /// explicit template argument list following the member name, if any.
3729 SourceLocation getLAngleLoc() const {
3730 if (!hasTemplateKWAndArgsInfo())
3731 return SourceLocation();
3732 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3733 }
3734
3735 /// Retrieve the location of the right angle bracket ending the
3736 /// explicit template argument list following the member name, if any.
3737 SourceLocation getRAngleLoc() const {
3738 if (!hasTemplateKWAndArgsInfo())
3739 return SourceLocation();
3740 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3741 }
3742
3743 /// Determines whether the member name was preceded by the template keyword.
3744 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3745
3746 /// Determines whether this member expression actually had a C++
3747 /// template argument list explicitly specified, e.g., x.f<int>.
3748 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3749
3750 /// Copies the template arguments (if present) into the given
3751 /// structure.
3752 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3753 if (hasExplicitTemplateArgs())
3754 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3755 getTrailingObjects<TemplateArgumentLoc>(), List);
3756 }
3757
3758 /// Retrieve the template arguments provided as part of this
3759 /// template-id.
3760 const TemplateArgumentLoc *getTemplateArgs() const {
3761 if (!hasExplicitTemplateArgs())
3762 return nullptr;
3763
3764 return getTrailingObjects<TemplateArgumentLoc>();
3765 }
3766
3767 /// Retrieve the number of template arguments provided as part of this
3768 /// template-id.
3769 unsigned getNumTemplateArgs() const {
3770 if (!hasExplicitTemplateArgs())
3771 return 0;
3772
3773 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3774 }
3775
3776 ArrayRef<TemplateArgumentLoc> template_arguments() const {
3777 return {getTemplateArgs(), getNumTemplateArgs()};
3778 }
3779
3780 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3781 if (!isImplicitAccess())
3782 return Base->getBeginLoc();
3783 if (getQualifier())
3784 return getQualifierLoc().getBeginLoc();
3785 return MemberNameInfo.getBeginLoc();
3786 }
3787
3788 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3789 if (hasExplicitTemplateArgs())
3790 return getRAngleLoc();
3791 return MemberNameInfo.getEndLoc();
3792 }
3793
3794 static bool classof(const Stmt *T) {
3795 return T->getStmtClass() == CXXDependentScopeMemberExprClass;
3796 }
3797
3798 // Iterators
3799 child_range children() {
3800 if (isImplicitAccess())
3801 return child_range(child_iterator(), child_iterator());
3802 return child_range(&Base, &Base + 1);
3803 }
3804
3805 const_child_range children() const {
3806 if (isImplicitAccess())
3807 return const_child_range(const_child_iterator(), const_child_iterator());
3808 return const_child_range(&Base, &Base + 1);
3809 }
3810};
3811
3812/// Represents a C++ member access expression for which lookup
3813/// produced a set of overloaded functions.
3814///
3815/// The member access may be explicit or implicit:
3816/// \code
3817/// struct A {
3818/// int a, b;
3819/// int explicitAccess() { return this->a + this->A::b; }
3820/// int implicitAccess() { return a + A::b; }
3821/// };
3822/// \endcode
3823///
3824/// In the final AST, an explicit access always becomes a MemberExpr.
3825/// An implicit access may become either a MemberExpr or a
3826/// DeclRefExpr, depending on whether the member is static.
3827class UnresolvedMemberExpr final
3828 : public OverloadExpr,
3829 private llvm::TrailingObjects<UnresolvedMemberExpr, DeclAccessPair,
3830 ASTTemplateKWAndArgsInfo,
3831 TemplateArgumentLoc> {
3832 friend class ASTStmtReader;
3833 friend class OverloadExpr;
3834 friend TrailingObjects;
3835
3836 /// The expression for the base pointer or class reference,
3837 /// e.g., the \c x in x.f.
3838 ///
3839 /// This can be null if this is an 'unbased' member expression.
3840 Stmt *Base;
3841
3842 /// The type of the base expression; never null.
3843 QualType BaseType;
3844
3845 /// The location of the '->' or '.' operator.
3846 SourceLocation OperatorLoc;
3847
3848 // UnresolvedMemberExpr is followed by several trailing objects.
3849 // They are in order:
3850 //
3851 // * An array of getNumResults() DeclAccessPair for the results. These are
3852 // undesugared, which is to say, they may include UsingShadowDecls.
3853 // Access is relative to the naming class.
3854 //
3855 // * An optional ASTTemplateKWAndArgsInfo for the explicitly specified
3856 // template keyword and arguments. Present if and only if
3857 // hasTemplateKWAndArgsInfo().
3858 //
3859 // * An array of getNumTemplateArgs() TemplateArgumentLoc containing
3860 // location information for the explicitly specified template arguments.
3861
3862 UnresolvedMemberExpr(const ASTContext &Context, bool HasUnresolvedUsing,
3863 Expr *Base, QualType BaseType, bool IsArrow,
3864 SourceLocation OperatorLoc,
3865 NestedNameSpecifierLoc QualifierLoc,
3866 SourceLocation TemplateKWLoc,
3867 const DeclarationNameInfo &MemberNameInfo,
3868 const TemplateArgumentListInfo *TemplateArgs,
3869 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3870
3871 UnresolvedMemberExpr(EmptyShell Empty, unsigned NumResults,
3872 bool HasTemplateKWAndArgsInfo);
3873
3874 unsigned numTrailingObjects(OverloadToken<DeclAccessPair>) const {
3875 return getNumDecls();
3876 }
3877
3878 unsigned numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3879 return hasTemplateKWAndArgsInfo();
3880 }
3881
3882public:
3883 static UnresolvedMemberExpr *
3884 Create(const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base,
3885 QualType BaseType, bool IsArrow, SourceLocation OperatorLoc,
3886 NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
3887 const DeclarationNameInfo &MemberNameInfo,
3888 const TemplateArgumentListInfo *TemplateArgs,
3889 UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3890
3891 static UnresolvedMemberExpr *CreateEmpty(const ASTContext &Context,
3892 unsigned NumResults,
3893 bool HasTemplateKWAndArgsInfo,
3894 unsigned NumTemplateArgs);
3895
3896 /// True if this is an implicit access, i.e., one in which the
3897 /// member being accessed was not written in the source.
3898 ///
3899 /// The source location of the operator is invalid in this case.
3900 bool isImplicitAccess() const;
3901
3902 /// Retrieve the base object of this member expressions,
3903 /// e.g., the \c x in \c x.m.
3904 Expr *getBase() {
3905 assert(!isImplicitAccess())(static_cast <bool> (!isImplicitAccess()) ? void (0) : __assert_fail
("!isImplicitAccess()", "clang/include/clang/AST/ExprCXX.h",
3905, __extension__ __PRETTY_FUNCTION__))
;
3906 return cast<Expr>(Base);
3907 }
3908 const Expr *getBase() const {
3909 assert(!isImplicitAccess())(static_cast <bool> (!isImplicitAccess()) ? void (0) : __assert_fail
("!isImplicitAccess()", "clang/include/clang/AST/ExprCXX.h",
3909, __extension__ __PRETTY_FUNCTION__))
;
3910 return cast<Expr>(Base);
3911 }
3912
3913 QualType getBaseType() const { return BaseType; }
3914
3915 /// Determine whether the lookup results contain an unresolved using
3916 /// declaration.
3917 bool hasUnresolvedUsing() const {
3918 return UnresolvedMemberExprBits.HasUnresolvedUsing;
3919 }
3920
3921 /// Determine whether this member expression used the '->'
3922 /// operator; otherwise, it used the '.' operator.
3923 bool isArrow() const { return UnresolvedMemberExprBits.IsArrow; }
3924
3925 /// Retrieve the location of the '->' or '.' operator.
3926 SourceLocation getOperatorLoc() const { return OperatorLoc; }
3927
3928 /// Retrieve the naming class of this lookup.
3929 CXXRecordDecl *getNamingClass();
3930 const CXXRecordDecl *getNamingClass() const {
3931 return const_cast<UnresolvedMemberExpr *>(this)->getNamingClass();
3932 }
3933
3934 /// Retrieve the full name info for the member that this expression
3935 /// refers to.
3936 const DeclarationNameInfo &getMemberNameInfo() const { return getNameInfo(); }
3937
3938 /// Retrieve the name of the member that this expression refers to.
3939 DeclarationName getMemberName() const { return getName(); }
3940
3941 /// Retrieve the location of the name of the member that this
3942 /// expression refers to.
3943 SourceLocation getMemberLoc() const { return getNameLoc(); }
3944
3945 /// Return the preferred location (the member name) for the arrow when
3946 /// diagnosing a problem with this expression.
3947 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return getMemberLoc(); }
3948
3949 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3950 if (!isImplicitAccess())
3951 return Base->getBeginLoc();
3952 if (NestedNameSpecifierLoc l = getQualifierLoc())
3953 return l.getBeginLoc();
3954 return getMemberNameInfo().getBeginLoc();
3955 }
3956
3957 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3958 if (hasExplicitTemplateArgs())
3959 return getRAngleLoc();
3960 return getMemberNameInfo().getEndLoc();
3961 }
3962
3963 static bool classof(const Stmt *T) {
3964 return T->getStmtClass() == UnresolvedMemberExprClass;
3965 }
3966
3967 // Iterators
3968 child_range children() {
3969 if (isImplicitAccess())
3970 return child_range(child_iterator(), child_iterator());
3971 return child_range(&Base, &Base + 1);
3972 }
3973
3974 const_child_range children() const {
3975 if (isImplicitAccess())
3976 return const_child_range(const_child_iterator(), const_child_iterator());
3977 return const_child_range(&Base, &Base + 1);
3978 }
3979};
3980
3981DeclAccessPair *OverloadExpr::getTrailingResults() {
3982 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3983 return ULE->getTrailingObjects<DeclAccessPair>();
3984 return cast<UnresolvedMemberExpr>(this)->getTrailingObjects<DeclAccessPair>();
3985}
3986
3987ASTTemplateKWAndArgsInfo *OverloadExpr::getTrailingASTTemplateKWAndArgsInfo() {
3988 if (!hasTemplateKWAndArgsInfo())
3989 return nullptr;
3990
3991 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3992 return ULE->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
3993 return cast<UnresolvedMemberExpr>(this)
3994 ->getTrailingObjects<ASTTemplateKWAndArgsInfo>();
3995}
3996
3997TemplateArgumentLoc *OverloadExpr::getTrailingTemplateArgumentLoc() {
3998 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
3999 return ULE->getTrailingObjects<TemplateArgumentLoc>();
4000 return cast<UnresolvedMemberExpr>(this)
4001 ->getTrailingObjects<TemplateArgumentLoc>();
4002}
4003
4004CXXRecordDecl *OverloadExpr::getNamingClass() {
4005 if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(this))
4006 return ULE->getNamingClass();
4007 return cast<UnresolvedMemberExpr>(this)->getNamingClass();
4008}
4009
4010/// Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
4011///
4012/// The noexcept expression tests whether a given expression might throw. Its
4013/// result is a boolean constant.
4014class CXXNoexceptExpr : public Expr {
4015 friend class ASTStmtReader;
4016
4017 Stmt *Operand;
4018 SourceRange Range;
4019
4020public:
4021 CXXNoexceptExpr(QualType Ty, Expr *Operand, CanThrowResult Val,
4022 SourceLocation Keyword, SourceLocation RParen)
4023 : Expr(CXXNoexceptExprClass, Ty, VK_PRValue, OK_Ordinary),
4024 Operand(Operand), Range(Keyword, RParen) {
4025 CXXNoexceptExprBits.Value = Val == CT_Cannot;
4026 setDependence(computeDependence(this, Val));
4027 }
4028
4029 CXXNoexceptExpr(EmptyShell Empty) : Expr(CXXNoexceptExprClass, Empty) {}
4030
4031 Expr *getOperand() const { return static_cast<Expr *>(Operand); }
4032
4033 SourceLocation getBeginLoc() const { return Range.getBegin(); }
4034 SourceLocation getEndLoc() const { return Range.getEnd(); }
4035 SourceRange getSourceRange() const { return Range; }
4036
4037 bool getValue() const { return CXXNoexceptExprBits.Value; }
4038
4039 static bool classof(const Stmt *T) {
4040 return T->getStmtClass() == CXXNoexceptExprClass;
4041 }
4042
4043 // Iterators
4044 child_range children() { return child_range(&Operand, &Operand + 1); }
4045
4046 const_child_range children() const {
4047 return const_child_range(&Operand, &Operand + 1);
4048 }
4049};
4050
4051/// Represents a C++11 pack expansion that produces a sequence of
4052/// expressions.
4053///
4054/// A pack expansion expression contains a pattern (which itself is an
4055/// expression) followed by an ellipsis. For example:
4056///
4057/// \code
4058/// template<typename F, typename ...Types>
4059/// void forward(F f, Types &&...args) {
4060/// f(static_cast<Types&&>(args)...);
4061/// }
4062/// \endcode
4063///
4064/// Here, the argument to the function object \c f is a pack expansion whose
4065/// pattern is \c static_cast<Types&&>(args). When the \c forward function
4066/// template is instantiated, the pack expansion will instantiate to zero or
4067/// or more function arguments to the function object \c f.
4068class PackExpansionExpr : public Expr {
4069 friend class ASTStmtReader;
4070 friend class ASTStmtWriter;
4071
4072 SourceLocation EllipsisLoc;
4073
4074 /// The number of expansions that will be produced by this pack
4075 /// expansion expression, if known.
4076 ///
4077 /// When zero, the number of expansions is not known. Otherwise, this value
4078 /// is the number of expansions + 1.
4079 unsigned NumExpansions;
4080
4081 Stmt *Pattern;
4082
4083public:
4084 PackExpansionExpr(QualType T, Expr *Pattern, SourceLocation EllipsisLoc,
4085 Optional<unsigned> NumExpansions)
4086 : Expr(PackExpansionExprClass, T, Pattern->getValueKind(),
4087 Pattern->getObjectKind()),
4088 EllipsisLoc(EllipsisLoc),
4089 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0),
4090 Pattern(Pattern) {
4091 setDependence(computeDependence(this));
4092 }
4093
4094 PackExpansionExpr(EmptyShell Empty) : Expr(PackExpansionExprClass, Empty) {}
4095
4096 /// Retrieve the pattern of the pack expansion.
4097 Expr *getPattern() { return reinterpret_cast<Expr *>(Pattern); }
4098
4099 /// Retrieve the pattern of the pack expansion.
4100 const Expr *getPattern() const { return reinterpret_cast<Expr *>(Pattern); }
4101
4102 /// Retrieve the location of the ellipsis that describes this pack
4103 /// expansion.
4104 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
4105
4106 /// Determine the number of expansions that will be produced when
4107 /// this pack expansion is instantiated, if already known.
4108 Optional<unsigned> getNumExpansions() const {
4109 if (NumExpansions)
4110 return NumExpansions - 1;
4111
4112 return None;
4113 }
4114
4115 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
4116 return Pattern->getBeginLoc();
4117 }
4118
4119 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return EllipsisLoc; }
4120
4121 static bool classof(const Stmt *T) {
4122 return T->getStmtClass() == PackExpansionExprClass;
4123 }
4124
4125 // Iterators
4126 child_range children() {
4127 return child_range(&Pattern, &Pattern + 1);
4128 }
4129
4130 const_child_range children() const {
4131 return const_child_range(&Pattern, &Pattern + 1);
4132 }
4133};
4134
4135/// Represents an expression that computes the length of a parameter
4136/// pack.
4137///
4138/// \code
4139/// template<typename ...Types>
4140/// struct count {
4141/// static const unsigned value = sizeof...(Types);
4142/// };
4143/// \endcode
4144class SizeOfPackExpr final
4145 : public Expr,
4146 private llvm::TrailingObjects<SizeOfPackExpr, TemplateArgument> {
4147 friend class ASTStmtReader;
4148 friend class ASTStmtWriter;
4149 friend TrailingObjects;
4150
4151 /// The location of the \c sizeof keyword.
4152 SourceLocation OperatorLoc;
4153
4154 /// The location of the name of the parameter pack.
4155 SourceLocation PackLoc;
4156
4157 /// The location of the closing parenthesis.
4158 SourceLocation RParenLoc;
4159
4160 /// The length of the parameter pack, if known.
4161 ///
4162 /// When this expression is not value-dependent, this is the length of
4163 /// the pack. When the expression was parsed rather than instantiated
4164 /// (and thus is value-dependent), this is zero.
4165 ///
4166 /// After partial substitution into a sizeof...(X) expression (for instance,
4167 /// within an alias template or during function template argument deduction),
4168 /// we store a trailing array of partially-substituted TemplateArguments,
4169 /// and this is the length of that array.
4170 unsigned Length;
4171
4172 /// The parameter pack.
4173 NamedDecl *Pack = nullptr;
4174
4175 /// Create an expression that computes the length of
4176 /// the given parameter pack.
4177 SizeOfPackExpr(QualType SizeType, SourceLocation OperatorLoc, NamedDecl *Pack,
4178 SourceLocation PackLoc, SourceLocation RParenLoc,
4179 Optional<unsigned> Length,
4180 ArrayRef<TemplateArgument> PartialArgs)
4181 : Expr(SizeOfPackExprClass, SizeType, VK_PRValue, OK_Ordinary),
4182 OperatorLoc(OperatorLoc), PackLoc(PackLoc), RParenLoc(RParenLoc),
4183 Length(Length ? *Length : PartialArgs.size()), Pack(Pack) {
4184 assert((!Length || PartialArgs.empty()) &&(static_cast <bool> ((!Length || PartialArgs.empty()) &&
"have partial args for non-dependent sizeof... expression") ?
void (0) : __assert_fail ("(!Length || PartialArgs.empty()) && \"have partial args for non-dependent sizeof... expression\""
, "clang/include/clang/AST/ExprCXX.h", 4185, __extension__ __PRETTY_FUNCTION__
))
4185 "have partial args for non-dependent sizeof... expression")(static_cast <bool> ((!Length || PartialArgs.empty()) &&
"have partial args for non-dependent sizeof... expression") ?
void (0) : __assert_fail ("(!Length || PartialArgs.empty()) && \"have partial args for non-dependent sizeof... expression\""
, "clang/include/clang/AST/ExprCXX.h", 4185, __extension__ __PRETTY_FUNCTION__
))
;
4186 auto *Args = getTrailingObjects<TemplateArgument>();
4187 std::uninitialized_copy(PartialArgs.begin(), PartialArgs.end(), Args);
4188 setDependence(Length ? ExprDependence::None
4189 : ExprDependence::ValueInstantiation);
4190 }
4191
4192 /// Create an empty expression.
4193 SizeOfPackExpr(EmptyShell Empty, unsigned NumPartialArgs)
4194 : Expr(SizeOfPackExprClass, Empty), Length(NumPartialArgs) {}
4195
4196public:
4197 static SizeOfPackExpr *Create(ASTContext &Context, SourceLocation OperatorLoc,
4198 NamedDecl *Pack, SourceLocation PackLoc,
4199 SourceLocation RParenLoc,
4200 Optional<unsigned> Length = None,
4201 ArrayRef<TemplateArgument> PartialArgs = None);
4202 static SizeOfPackExpr *CreateDeserialized(ASTContext &Context,
4203 unsigned NumPartialArgs);
4204
4205 /// Determine the location of the 'sizeof' keyword.
4206 SourceLocation getOperatorLoc() const { return OperatorLoc; }
4207
4208 /// Determine the location of the parameter pack.
4209 SourceLocation getPackLoc() const { return PackLoc; }
4210
4211 /// Determine the location of the right parenthesis.
4212 SourceLocation getRParenLoc() const { return RParenLoc; }
4213
4214 /// Retrieve the parameter pack.
4215 NamedDecl *getPack() const { return Pack; }
4216
4217 /// Retrieve the length of the parameter pack.
4218 ///
4219 /// This routine may only be invoked when the expression is not
4220 /// value-dependent.
4221 unsigned getPackLength() const {
4222 assert(!isValueDependent() &&(static_cast <bool> (!isValueDependent() && "Cannot get the length of a value-dependent pack size expression"
) ? void (0) : __assert_fail ("!isValueDependent() && \"Cannot get the length of a value-dependent pack size expression\""
, "clang/include/clang/AST/ExprCXX.h", 4223, __extension__ __PRETTY_FUNCTION__
))
4223 "Cannot get the length of a value-dependent pack size expression")(static_cast <bool> (!isValueDependent() && "Cannot get the length of a value-dependent pack size expression"
) ? void (0) : __assert_fail ("!isValueDependent() && \"Cannot get the length of a value-dependent pack size expression\""
, "clang/include/clang/AST/ExprCXX.h", 4223, __extension__ __PRETTY_FUNCTION__
))
;
4224 return Length;
4225 }
4226
4227 /// Determine whether this represents a partially-substituted sizeof...
4228 /// expression, such as is produced for:
4229 ///
4230 /// template<typename ...Ts> using X = int[sizeof...(Ts)];
4231 /// template<typename ...Us> void f(X<Us..., 1, 2, 3, Us...>);
4232 bool isPartiallySubstituted() const {
4233 return isValueDependent() && Length;
4234 }
4235
4236 /// Get
4237 ArrayRef<TemplateArgument> getPartialArguments() const {
4238 assert(isPartiallySubstituted())(static_cast <bool> (isPartiallySubstituted()) ? void (
0) : __assert_fail ("isPartiallySubstituted()", "clang/include/clang/AST/ExprCXX.h"
, 4238, __extension__ __PRETTY_FUNCTION__))
;
4239 const auto *Args = getTrailingObjects<TemplateArgument>();
4240 return llvm::makeArrayRef(Args, Args + Length);
4241 }
4242
4243 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; }
4244 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4245
4246 static bool classof(const Stmt *T) {
4247 return T->getStmtClass() == SizeOfPackExprClass;
4248 }
4249
4250 // Iterators
4251 child_range children() {
4252 return child_range(child_iterator(), child_iterator());
4253 }
4254
4255 const_child_range children() const {
4256 return const_child_range(const_child_iterator(), const_child_iterator());
4257 }
4258};
4259
4260/// Represents a reference to a non-type template parameter
4261/// that has been substituted with a template argument.
4262class SubstNonTypeTemplateParmExpr : public Expr {
4263 friend class ASTReader;
4264 friend class ASTStmtReader;
4265
4266 /// The replaced parameter and a flag indicating if it was a reference
4267 /// parameter. For class NTTPs, we can't determine that based on the value
4268 /// category alone.
4269 llvm::PointerIntPair<NonTypeTemplateParmDecl*, 1, bool> ParamAndRef;
4270
4271 /// The replacement expression.
4272 Stmt *Replacement;
4273
4274 explicit SubstNonTypeTemplateParmExpr(EmptyShell Empty)
4275 : Expr(SubstNonTypeTemplateParmExprClass, Empty) {}
4276
4277public:
4278 SubstNonTypeTemplateParmExpr(QualType Ty, ExprValueKind ValueKind,
4279 SourceLocation Loc,
4280 NonTypeTemplateParmDecl *Param, bool RefParam,
4281 Expr *Replacement)
4282 : Expr(SubstNonTypeTemplateParmExprClass, Ty, ValueKind, OK_Ordinary),
4283 ParamAndRef(Param, RefParam), Replacement(Replacement) {
4284 SubstNonTypeTemplateParmExprBits.NameLoc = Loc;
4285 setDependence(computeDependence(this));
4286 }
4287
4288 SourceLocation getNameLoc() const {
4289 return SubstNonTypeTemplateParmExprBits.NameLoc;
4290 }
4291 SourceLocation getBeginLoc() const { return getNameLoc(); }
4292 SourceLocation getEndLoc() const { return getNameLoc(); }
4293
4294 Expr *getReplacement() const { return cast<Expr>(Replacement); }
4295
4296 NonTypeTemplateParmDecl *getParameter() const {
4297 return ParamAndRef.getPointer();
4298 }
4299
4300 bool isReferenceParameter() const { return ParamAndRef.getInt(); }
4301
4302 /// Determine the substituted type of the template parameter.
4303 QualType getParameterType(const ASTContext &Ctx) const;
4304
4305 static bool classof(const Stmt *s) {
4306 return s->getStmtClass() == SubstNonTypeTemplateParmExprClass;
4307 }
4308
4309 // Iterators
4310 child_range children() { return child_range(&Replacement, &Replacement + 1); }
4311
4312 const_child_range children() const {
4313 return const_child_range(&Replacement, &Replacement + 1);
4314 }
4315};
4316
4317/// Represents a reference to a non-type template parameter pack that
4318/// has been substituted with a non-template argument pack.
4319///
4320/// When a pack expansion in the source code contains multiple parameter packs
4321/// and those parameter packs correspond to different levels of template
4322/// parameter lists, this node is used to represent a non-type template
4323/// parameter pack from an outer level, which has already had its argument pack
4324/// substituted but that still lives within a pack expansion that itself
4325/// could not be instantiated. When actually performing a substitution into
4326/// that pack expansion (e.g., when all template parameters have corresponding
4327/// arguments), this type will be replaced with the appropriate underlying
4328/// expression at the current pack substitution index.
4329class SubstNonTypeTemplateParmPackExpr : public Expr {
4330 friend class ASTReader;
4331 friend class ASTStmtReader;
4332
4333 /// The non-type template parameter pack itself.
4334 NonTypeTemplateParmDecl *Param;
4335
4336 /// A pointer to the set of template arguments that this
4337 /// parameter pack is instantiated with.
4338 const TemplateArgument *Arguments;
4339
4340 /// The number of template arguments in \c Arguments.
4341 unsigned NumArguments;
4342
4343 /// The location of the non-type template parameter pack reference.
4344 SourceLocation NameLoc;
4345
4346 explicit SubstNonTypeTemplateParmPackExpr(EmptyShell Empty)
4347 : Expr(SubstNonTypeTemplateParmPackExprClass, Empty) {}
4348
4349public:
4350 SubstNonTypeTemplateParmPackExpr(QualType T,
4351 ExprValueKind ValueKind,
4352 NonTypeTemplateParmDecl *Param,
4353 SourceLocation NameLoc,
4354 const TemplateArgument &ArgPack);
4355
4356 /// Retrieve the non-type template parameter pack being substituted.
4357 NonTypeTemplateParmDecl *getParameterPack() const { return Param; }
4358
4359 /// Retrieve the location of the parameter pack name.
4360 SourceLocation getParameterPackLocation() const { return NameLoc; }
4361
4362 /// Retrieve the template argument pack containing the substituted
4363 /// template arguments.
4364 TemplateArgument getArgumentPack() const;
4365
4366 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return NameLoc; }
4367 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return NameLoc; }
4368
4369 static bool classof(const Stmt *T) {
4370 return T->getStmtClass() == SubstNonTypeTemplateParmPackExprClass;
4371 }
4372
4373 // Iterators
4374 child_range children() {
4375 return child_range(child_iterator(), child_iterator());
4376 }
4377
4378 const_child_range children() const {
4379 return const_child_range(const_child_iterator(), const_child_iterator());
4380 }
4381};
4382
4383/// Represents a reference to a function parameter pack or init-capture pack
4384/// that has been substituted but not yet expanded.
4385///
4386/// When a pack expansion contains multiple parameter packs at different levels,
4387/// this node is used to represent a function parameter pack at an outer level
4388/// which we have already substituted to refer to expanded parameters, but where
4389/// the containing pack expansion cannot yet be expanded.
4390///
4391/// \code
4392/// template<typename...Ts> struct S {
4393/// template<typename...Us> auto f(Ts ...ts) -> decltype(g(Us(ts)...));
4394/// };
4395/// template struct S<int, int>;
4396/// \endcode
4397class FunctionParmPackExpr final
4398 : public Expr,
4399 private llvm::TrailingObjects<FunctionParmPackExpr, VarDecl *> {
4400 friend class ASTReader;
4401 friend class ASTStmtReader;
4402 friend TrailingObjects;
4403
4404 /// The function parameter pack which was referenced.
4405 VarDecl *ParamPack;
4406
4407 /// The location of the function parameter pack reference.
4408 SourceLocation NameLoc;
4409
4410 /// The number of expansions of this pack.
4411 unsigned NumParameters;
4412
4413 FunctionParmPackExpr(QualType T, VarDecl *ParamPack,
4414 SourceLocation NameLoc, unsigned NumParams,
4415 VarDecl *const *Params);
4416
4417public:
4418 static FunctionParmPackExpr *Create(const ASTContext &Context, QualType T,
4419 VarDecl *ParamPack,
4420 SourceLocation NameLoc,
4421 ArrayRef<VarDecl *> Params);
4422 static FunctionParmPackExpr *CreateEmpty(const ASTContext &Context,
4423 unsigned NumParams);
4424
4425 /// Get the parameter pack which this expression refers to.
4426 VarDecl *getParameterPack() const { return ParamPack; }
4427
4428 /// Get the location of the parameter pack.
4429 SourceLocation getParameterPackLocation() const { return NameLoc; }
4430
4431 /// Iterators over the parameters which the parameter pack expanded
4432 /// into.
4433 using iterator = VarDecl * const *;
4434 iterator begin() const { return getTrailingObjects<VarDecl *>(); }
4435 iterator end() const { return begin() + NumParameters; }
4436
4437 /// Get the number of parameters in this parameter pack.
4438 unsigned getNumExpansions() const { return NumParameters; }
4439
4440 /// Get an expansion of the parameter pack by index.
4441 VarDecl *getExpansion(unsigned I) const { return begin()[I]; }
4442
4443 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return NameLoc; }
4444 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return NameLoc; }
4445
4446 static bool classof(const Stmt *T) {
4447 return T->getStmtClass() == FunctionParmPackExprClass;
4448 }
4449
4450 child_range children() {
4451 return child_range(child_iterator(), child_iterator());
4452 }
4453
4454 const_child_range children() const {
4455 return const_child_range(const_child_iterator(), const_child_iterator());
4456 }
4457};
4458
4459/// Represents a prvalue temporary that is written into memory so that
4460/// a reference can bind to it.
4461///
4462/// Prvalue expressions are materialized when they need to have an address
4463/// in memory for a reference to bind to. This happens when binding a
4464/// reference to the result of a conversion, e.g.,
4465///
4466/// \code
4467/// const int &r = 1.0;
4468/// \endcode
4469///
4470/// Here, 1.0 is implicitly converted to an \c int. That resulting \c int is
4471/// then materialized via a \c MaterializeTemporaryExpr, and the reference
4472/// binds to the temporary. \c MaterializeTemporaryExprs are always glvalues
4473/// (either an lvalue or an xvalue, depending on the kind of reference binding
4474/// to it), maintaining the invariant that references always bind to glvalues.
4475///
4476/// Reference binding and copy-elision can both extend the lifetime of a
4477/// temporary. When either happens, the expression will also track the
4478/// declaration which is responsible for the lifetime extension.
4479class MaterializeTemporaryExpr : public Expr {
4480private:
4481 friend class ASTStmtReader;
4482 friend class ASTStmtWriter;
4483
4484 llvm::PointerUnion<Stmt *, LifetimeExtendedTemporaryDecl *> State;
4485
4486public:
4487 MaterializeTemporaryExpr(QualType T, Expr *Temporary,
4488 bool BoundToLvalueReference,
4489 LifetimeExtendedTemporaryDecl *MTD = nullptr);
4490
4491 MaterializeTemporaryExpr(EmptyShell Empty)
4492 : Expr(MaterializeTemporaryExprClass, Empty) {}
4493
4494 /// Retrieve the temporary-generating subexpression whose value will
4495 /// be materialized into a glvalue.
4496 Expr *getSubExpr() const {
4497 return cast<Expr>(
4498 State.is<Stmt *>()
4499 ? State.get<Stmt *>()
4500 : State.get<LifetimeExtendedTemporaryDecl *>()->getTemporaryExpr());
4501 }
4502
4503 /// Retrieve the storage duration for the materialized temporary.
4504 StorageDuration getStorageDuration() const {
4505 return State.is<Stmt *>() ? SD_FullExpression
4506 : State.get<LifetimeExtendedTemporaryDecl *>()
4507 ->getStorageDuration();
4508 }
4509
4510 /// Get the storage for the constant value of a materialized temporary
4511 /// of static storage duration.
4512 APValue *getOrCreateValue(bool MayCreate) const {
4513 assert(State.is<LifetimeExtendedTemporaryDecl *>() &&(static_cast <bool> (State.is<LifetimeExtendedTemporaryDecl
*>() && "the temporary has not been lifetime extended"
) ? void (0) : __assert_fail ("State.is<LifetimeExtendedTemporaryDecl *>() && \"the temporary has not been lifetime extended\""
, "clang/include/clang/AST/ExprCXX.h", 4514, __extension__ __PRETTY_FUNCTION__
))
4514 "the temporary has not been lifetime extended")(static_cast <bool> (State.is<LifetimeExtendedTemporaryDecl
*>() && "the temporary has not been lifetime extended"
) ? void (0) : __assert_fail ("State.is<LifetimeExtendedTemporaryDecl *>() && \"the temporary has not been lifetime extended\""
, "clang/include/clang/AST/ExprCXX.h", 4514, __extension__ __PRETTY_FUNCTION__
))
;
4515 return State.get<LifetimeExtendedTemporaryDecl *>()->getOrCreateValue(
4516 MayCreate);
4517 }
4518
4519 LifetimeExtendedTemporaryDecl *getLifetimeExtendedTemporaryDecl() {
4520 return State.dyn_cast<LifetimeExtendedTemporaryDecl *>();
4521 }
4522 const LifetimeExtendedTemporaryDecl *
4523 getLifetimeExtendedTemporaryDecl() const {
4524 return State.dyn_cast<LifetimeExtendedTemporaryDecl *>();
4525 }
4526
4527 /// Get the declaration which triggered the lifetime-extension of this
4528 /// temporary, if any.
4529 ValueDecl *getExtendingDecl() {
4530 return State.is<Stmt *>() ? nullptr
4531 : State.get<LifetimeExtendedTemporaryDecl *>()
4532 ->getExtendingDecl();
4533 }
4534 const ValueDecl *getExtendingDecl() const {
4535 return const_cast<MaterializeTemporaryExpr *>(this)->getExtendingDecl();
4536 }
4537
4538 void setExtendingDecl(ValueDecl *ExtendedBy, unsigned ManglingNumber);
4539
4540 unsigned getManglingNumber() const {
4541 return State.is<Stmt *>() ? 0
4542 : State.get<LifetimeExtendedTemporaryDecl *>()
4543 ->getManglingNumber();
4544 }
4545
4546 /// Determine whether this materialized temporary is bound to an
4547 /// lvalue reference; otherwise, it's bound to an rvalue reference.
4548 bool isBoundToLvalueReference() const { return isLValue(); }
4549
4550 /// Determine whether this temporary object is usable in constant
4551 /// expressions, as specified in C++20 [expr.const]p4.
4552 bool isUsableInConstantExpressions(const ASTContext &Context) const;
4553
4554 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
4555 return getSubExpr()->getBeginLoc();
4556 }
4557
4558 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4559 return getSubExpr()->getEndLoc();
4560 }
4561
4562 static bool classof(const Stmt *T) {
4563 return T->getStmtClass() == MaterializeTemporaryExprClass;
4564 }
4565
4566 // Iterators
4567 child_range children() {
4568 return State.is<Stmt *>()
4569 ? child_range(State.getAddrOfPtr1(), State.getAddrOfPtr1() + 1)
4570 : State.get<LifetimeExtendedTemporaryDecl *>()->childrenExpr();
4571 }
4572
4573 const_child_range children() const {
4574 return State.is<Stmt *>()
4575 ? const_child_range(State.getAddrOfPtr1(),
4576 State.getAddrOfPtr1() + 1)
4577 : const_cast<const LifetimeExtendedTemporaryDecl *>(
4578 State.get<LifetimeExtendedTemporaryDecl *>())
4579 ->childrenExpr();
4580 }
4581};
4582
4583/// Represents a folding of a pack over an operator.
4584///
4585/// This expression is always dependent and represents a pack expansion of the
4586/// forms:
4587///
4588/// ( expr op ... )
4589/// ( ... op expr )
4590/// ( expr op ... op expr )
4591class CXXFoldExpr : public Expr {
4592 friend class ASTStmtReader;
4593 friend class ASTStmtWriter;
4594
4595 enum SubExpr { Callee, LHS, RHS, Count };
4596
4597 SourceLocation LParenLoc;
4598 SourceLocation EllipsisLoc;
4599 SourceLocation RParenLoc;
4600 // When 0, the number of expansions is not known. Otherwise, this is one more
4601 // than the number of expansions.
4602 unsigned NumExpansions;
4603 Stmt *SubExprs[SubExpr::Count];
4604 BinaryOperatorKind Opcode;
4605
4606public:
4607 CXXFoldExpr(QualType T, UnresolvedLookupExpr *Callee,
4608 SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Opcode,
4609 SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc,
4610 Optional<unsigned> NumExpansions)
4611 : Expr(CXXFoldExprClass, T, VK_PRValue, OK_Ordinary),
4612 LParenLoc(LParenLoc), EllipsisLoc(EllipsisLoc), RParenLoc(RParenLoc),
4613 NumExpansions(NumExpansions ? *NumExpansions + 1 : 0), Opcode(Opcode) {
4614 SubExprs[SubExpr::Callee] = Callee;
4615 SubExprs[SubExpr::LHS] = LHS;
4616 SubExprs[SubExpr::RHS] = RHS;
4617 setDependence(computeDependence(this));
4618 }
4619
4620 CXXFoldExpr(EmptyShell Empty) : Expr(CXXFoldExprClass, Empty) {}
4621
4622 UnresolvedLookupExpr *getCallee() const {
4623 return static_cast<UnresolvedLookupExpr *>(SubExprs[SubExpr::Callee]);
4624 }
4625 Expr *getLHS() const { return static_cast<Expr*>(SubExprs[SubExpr::LHS]); }
4626 Expr *getRHS() const { return static_cast<Expr*>(SubExprs[SubExpr::RHS]); }
4627
4628 /// Does this produce a right-associated sequence of operators?
4629 bool isRightFold() const {
4630 return getLHS() && getLHS()->containsUnexpandedParameterPack();
4631 }
4632
4633 /// Does this produce a left-associated sequence of operators?
4634 bool isLeftFold() const { return !isRightFold(); }
4635
4636 /// Get the pattern, that is, the operand that contains an unexpanded pack.
4637 Expr *getPattern() const { return isLeftFold() ? getRHS() : getLHS(); }
4638
4639 /// Get the operand that doesn't contain a pack, for a binary fold.
4640 Expr *getInit() const { return isLeftFold() ? getLHS() : getRHS(); }
4641
4642 SourceLocation getLParenLoc() const { return LParenLoc; }
4643 SourceLocation getRParenLoc() const { return RParenLoc; }
4644 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
4645 BinaryOperatorKind getOperator() const { return Opcode; }
4646
4647 Optional<unsigned> getNumExpansions() const {
4648 if (NumExpansions)
4649 return NumExpansions - 1;
4650 return None;
4651 }
4652
4653 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
4654 if (LParenLoc.isValid())
4655 return LParenLoc;
4656 if (isLeftFold())
4657 return getEllipsisLoc();
4658 return getLHS()->getBeginLoc();
4659 }
4660
4661 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4662 if (RParenLoc.isValid())
4663 return RParenLoc;
4664 if (isRightFold())
4665 return getEllipsisLoc();
4666 return getRHS()->getEndLoc();
4667 }
4668
4669 static bool classof(const Stmt *T) {
4670 return T->getStmtClass() == CXXFoldExprClass;
4671 }
4672
4673 // Iterators
4674 child_range children() {
4675 return child_range(SubExprs, SubExprs + SubExpr::Count);
4676 }
4677
4678 const_child_range children() const {
4679 return const_child_range(SubExprs, SubExprs + SubExpr::Count);
4680 }
4681};
4682
4683/// Represents an expression that might suspend coroutine execution;
4684/// either a co_await or co_yield expression.
4685///
4686/// Evaluation of this expression first evaluates its 'ready' expression. If
4687/// that returns 'false':
4688/// -- execution of the coroutine is suspended
4689/// -- the 'suspend' expression is evaluated
4690/// -- if the 'suspend' expression returns 'false', the coroutine is
4691/// resumed
4692/// -- otherwise, control passes back to the resumer.
4693/// If the coroutine is not suspended, or when it is resumed, the 'resume'
4694/// expression is evaluated, and its result is the result of the overall
4695/// expression.
4696class CoroutineSuspendExpr : public Expr {
4697 friend class ASTStmtReader;
4698
4699 SourceLocation KeywordLoc;
4700
4701 enum SubExpr { Common, Ready, Suspend, Resume, Count };
4702
4703 Stmt *SubExprs[SubExpr::Count];
4704 OpaqueValueExpr *OpaqueValue = nullptr;
4705
4706public:
4707 CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, Expr *Common,
4708 Expr *Ready, Expr *Suspend, Expr *Resume,
4709 OpaqueValueExpr *OpaqueValue)
4710 : Expr(SC, Resume->getType(), Resume->getValueKind(),
40
Called C++ object pointer is null
4711 Resume->getObjectKind()),
4712 KeywordLoc(KeywordLoc), OpaqueValue(OpaqueValue) {
4713 SubExprs[SubExpr::Common] = Common;
4714 SubExprs[SubExpr::Ready] = Ready;
4715 SubExprs[SubExpr::Suspend] = Suspend;
4716 SubExprs[SubExpr::Resume] = Resume;
4717 setDependence(computeDependence(this));
4718 }
4719
4720 CoroutineSuspendExpr(StmtClass SC, SourceLocation KeywordLoc, QualType Ty,
4721 Expr *Common)
4722 : Expr(SC, Ty, VK_PRValue, OK_Ordinary), KeywordLoc(KeywordLoc) {
4723 assert(Common->isTypeDependent() && Ty->isDependentType() &&(static_cast <bool> (Common->isTypeDependent() &&
Ty->isDependentType() && "wrong constructor for non-dependent co_await/co_yield expression"
) ? void (0) : __assert_fail ("Common->isTypeDependent() && Ty->isDependentType() && \"wrong constructor for non-dependent co_await/co_yield expression\""
, "clang/include/clang/AST/ExprCXX.h", 4724, __extension__ __PRETTY_FUNCTION__
))
4724 "wrong constructor for non-dependent co_await/co_yield expression")(static_cast <bool> (Common->isTypeDependent() &&
Ty->isDependentType() && "wrong constructor for non-dependent co_await/co_yield expression"
) ? void (0) : __assert_fail ("Common->isTypeDependent() && Ty->isDependentType() && \"wrong constructor for non-dependent co_await/co_yield expression\""
, "clang/include/clang/AST/ExprCXX.h", 4724, __extension__ __PRETTY_FUNCTION__
))
;
4725 SubExprs[SubExpr::Common] = Common;
4726 SubExprs[SubExpr::Ready] = nullptr;
4727 SubExprs[SubExpr::Suspend] = nullptr;
4728 SubExprs[SubExpr::Resume] = nullptr;
4729 setDependence(computeDependence(this));
4730 }
4731
4732 CoroutineSuspendExpr(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4733 SubExprs[SubExpr::Common] = nullptr;
4734 SubExprs[SubExpr::Ready] = nullptr;
4735 SubExprs[SubExpr::Suspend] = nullptr;
4736 SubExprs[SubExpr::Resume] = nullptr;
4737 }
4738
4739 SourceLocation getKeywordLoc() const { return KeywordLoc; }
4740
4741 Expr *getCommonExpr() const {
4742 return static_cast<Expr*>(SubExprs[SubExpr::Common]);
4743 }
4744
4745 /// getOpaqueValue - Return the opaque value placeholder.
4746 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4747
4748 Expr *getReadyExpr() const {
4749 return static_cast<Expr*>(SubExprs[SubExpr::Ready]);
4750 }
4751
4752 Expr *getSuspendExpr() const {
4753 return static_cast<Expr*>(SubExprs[SubExpr::Suspend]);
4754 }
4755
4756 Expr *getResumeExpr() const {
4757 return static_cast<Expr*>(SubExprs[SubExpr::Resume]);
4758 }
4759
4760 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return KeywordLoc; }
4761
4762 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4763 return getCommonExpr()->getEndLoc();
4764 }
4765
4766 child_range children() {
4767 return child_range(SubExprs, SubExprs + SubExpr::Count);
4768 }
4769
4770 const_child_range children() const {
4771 return const_child_range(SubExprs, SubExprs + SubExpr::Count);
4772 }
4773
4774 static bool classof(const Stmt *T) {
4775 return T->getStmtClass() == CoawaitExprClass ||
4776 T->getStmtClass() == CoyieldExprClass;
4777 }
4778};
4779
4780/// Represents a 'co_await' expression.
4781class CoawaitExpr : public CoroutineSuspendExpr {
4782 friend class ASTStmtReader;
4783
4784public:
4785 CoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand, Expr *Ready,
4786 Expr *Suspend, Expr *Resume, OpaqueValueExpr *OpaqueValue,
4787 bool IsImplicit = false)
4788 : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Operand, Ready,
4789 Suspend, Resume, OpaqueValue) {
4790 CoawaitBits.IsImplicit = IsImplicit;
4791 }
4792
4793 CoawaitExpr(SourceLocation CoawaitLoc, QualType Ty, Expr *Operand,
4794 bool IsImplicit = false)
4795 : CoroutineSuspendExpr(CoawaitExprClass, CoawaitLoc, Ty, Operand) {
4796 CoawaitBits.IsImplicit = IsImplicit;
4797 }
4798
4799 CoawaitExpr(EmptyShell Empty)
4800 : CoroutineSuspendExpr(CoawaitExprClass, Empty) {}
4801
4802 Expr *getOperand() const {
4803 // FIXME: Dig out the actual operand or store it.
4804 return getCommonExpr();
4805 }
4806
4807 bool isImplicit() const { return CoawaitBits.IsImplicit; }
4808 void setIsImplicit(bool value = true) { CoawaitBits.IsImplicit = value; }
4809
4810 static bool classof(const Stmt *T) {
4811 return T->getStmtClass() == CoawaitExprClass;
4812 }
4813};
4814
4815/// Represents a 'co_await' expression while the type of the promise
4816/// is dependent.
4817class DependentCoawaitExpr : public Expr {
4818 friend class ASTStmtReader;
4819
4820 SourceLocation KeywordLoc;
4821 Stmt *SubExprs[2];
4822
4823public:
4824 DependentCoawaitExpr(SourceLocation KeywordLoc, QualType Ty, Expr *Op,
4825 UnresolvedLookupExpr *OpCoawait)
4826 : Expr(DependentCoawaitExprClass, Ty, VK_PRValue, OK_Ordinary),
4827 KeywordLoc(KeywordLoc) {
4828 // NOTE: A co_await expression is dependent on the coroutines promise
4829 // type and may be dependent even when the `Op` expression is not.
4830 assert(Ty->isDependentType() &&(static_cast <bool> (Ty->isDependentType() &&
"wrong constructor for non-dependent co_await/co_yield expression"
) ? void (0) : __assert_fail ("Ty->isDependentType() && \"wrong constructor for non-dependent co_await/co_yield expression\""
, "clang/include/clang/AST/ExprCXX.h", 4831, __extension__ __PRETTY_FUNCTION__
))
4831 "wrong constructor for non-dependent co_await/co_yield expression")(static_cast <bool> (Ty->isDependentType() &&
"wrong constructor for non-dependent co_await/co_yield expression"
) ? void (0) : __assert_fail ("Ty->isDependentType() && \"wrong constructor for non-dependent co_await/co_yield expression\""
, "clang/include/clang/AST/ExprCXX.h", 4831, __extension__ __PRETTY_FUNCTION__
))
;
4832 SubExprs[0] = Op;
4833 SubExprs[1] = OpCoawait;
4834 setDependence(computeDependence(this));
4835 }
4836
4837 DependentCoawaitExpr(EmptyShell Empty)
4838 : Expr(DependentCoawaitExprClass, Empty) {}
4839
4840 Expr *getOperand() const { return cast<Expr>(SubExprs[0]); }
4841
4842 UnresolvedLookupExpr *getOperatorCoawaitLookup() const {
4843 return cast<UnresolvedLookupExpr>(SubExprs[1]);
4844 }
4845
4846 SourceLocation getKeywordLoc() const { return KeywordLoc; }
4847
4848 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return KeywordLoc; }
4849
4850 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
4851 return getOperand()->getEndLoc();
4852 }
4853
4854 child_range children() { return child_range(SubExprs, SubExprs + 2); }
4855
4856 const_child_range children() const {
4857 return const_child_range(SubExprs, SubExprs + 2);
4858 }
4859
4860 static bool classof(const Stmt *T) {
4861 return T->getStmtClass() == DependentCoawaitExprClass;
4862 }
4863};
4864
4865/// Represents a 'co_yield' expression.
4866class CoyieldExpr : public CoroutineSuspendExpr {
4867 friend class ASTStmtReader;
4868
4869public:
4870 CoyieldExpr(SourceLocation CoyieldLoc, Expr *Operand, Expr *Ready,
4871 Expr *Suspend, Expr *Resume, OpaqueValueExpr *OpaqueValue)
4872 : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Operand, Ready,
39
Calling constructor for 'CoroutineSuspendExpr'
4873 Suspend, Resume, OpaqueValue) {}
38
Passing null pointer value via 6th parameter 'Resume'
4874 CoyieldExpr(SourceLocation CoyieldLoc, QualType Ty, Expr *Operand)
4875 : CoroutineSuspendExpr(CoyieldExprClass, CoyieldLoc, Ty, Operand) {}
4876 CoyieldExpr(EmptyShell Empty)
4877 : CoroutineSuspendExpr(CoyieldExprClass, Empty) {}
4878
4879 Expr *getOperand() const {
4880 // FIXME: Dig out the actual operand or store it.
4881 return getCommonExpr();
4882 }
4883
4884 static bool classof(const Stmt *T) {
4885 return T->getStmtClass() == CoyieldExprClass;
4886 }
4887};
4888
4889/// Represents a C++2a __builtin_bit_cast(T, v) expression. Used to implement
4890/// std::bit_cast. These can sometimes be evaluated as part of a constant
4891/// expression, but otherwise CodeGen to a simple memcpy in general.
4892class BuiltinBitCastExpr final
4893 : public ExplicitCastExpr,
4894 private llvm::TrailingObjects<BuiltinBitCastExpr, CXXBaseSpecifier *> {
4895 friend class ASTStmtReader;
4896 friend class CastExpr;
4897 friend TrailingObjects;
4898
4899 SourceLocation KWLoc;
4900 SourceLocation RParenLoc;
4901
4902public:
4903 BuiltinBitCastExpr(QualType T, ExprValueKind VK, CastKind CK, Expr *SrcExpr,
4904 TypeSourceInfo *DstType, SourceLocation KWLoc,
4905 SourceLocation RParenLoc)
4906 : ExplicitCastExpr(BuiltinBitCastExprClass, T, VK, CK, SrcExpr, 0, false,
4907 DstType),
4908 KWLoc(KWLoc), RParenLoc(RParenLoc) {}
4909 BuiltinBitCastExpr(EmptyShell Empty)
4910 : ExplicitCastExpr(BuiltinBitCastExprClass, Empty, 0, false) {}
4911
4912 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return KWLoc; }
4913 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
4914
4915 static bool classof(const Stmt *T) {
4916 return T->getStmtClass() == BuiltinBitCastExprClass;
4917 }
4918};
4919
4920} // namespace clang
4921
4922#endif // LLVM_CLANG_AST_EXPRCXX_H