1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for expressions.
11 //===----------------------------------------------------------------------===//
13 #include "TreeTransform.h"
14 #include "UsedDeclVisitor.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Designator.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExprOpenMP.h"
28 #include "clang/AST/OperationKinds.h"
29 #include "clang/AST/ParentMapContext.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/Type.h"
32 #include "clang/AST/TypeLoc.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/DiagnosticSema.h"
35 #include "clang/Basic/PartialDiagnostic.h"
36 #include "clang/Basic/SourceManager.h"
37 #include "clang/Basic/Specifiers.h"
38 #include "clang/Basic/TargetInfo.h"
39 #include "clang/Lex/LiteralSupport.h"
40 #include "clang/Lex/Preprocessor.h"
41 #include "clang/Sema/AnalysisBasedWarnings.h"
42 #include "clang/Sema/DeclSpec.h"
43 #include "clang/Sema/DelayedDiagnostic.h"
44 #include "clang/Sema/Initialization.h"
45 #include "clang/Sema/Lookup.h"
46 #include "clang/Sema/Overload.h"
47 #include "clang/Sema/ParsedTemplate.h"
48 #include "clang/Sema/Scope.h"
49 #include "clang/Sema/ScopeInfo.h"
50 #include "clang/Sema/SemaFixItUtils.h"
51 #include "clang/Sema/SemaInternal.h"
52 #include "clang/Sema/Template.h"
53 #include "llvm/ADT/STLExtras.h"
54 #include "llvm/ADT/StringExtras.h"
55 #include "llvm/Support/Casting.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/TypeSize.h"
61 using namespace clang
;
64 /// Determine whether the use of this declaration is valid, without
65 /// emitting diagnostics.
66 bool Sema::CanUseDecl(NamedDecl
*D
, bool TreatUnavailableAsInvalid
) {
67 // See if this is an auto-typed variable whose initializer we are parsing.
68 if (ParsingInitForAutoVars
.count(D
))
71 // See if this is a deleted function.
72 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
76 // If the function has a deduced return type, and we can't deduce it,
77 // then we can't use it either.
78 if (getLangOpts().CPlusPlus14
&& FD
->getReturnType()->isUndeducedType() &&
79 DeduceReturnType(FD
, SourceLocation(), /*Diagnose*/ false))
82 // See if this is an aligned allocation/deallocation function that is
84 if (TreatUnavailableAsInvalid
&&
85 isUnavailableAlignedAllocationFunction(*FD
))
89 // See if this function is unavailable.
90 if (TreatUnavailableAsInvalid
&& D
->getAvailability() == AR_Unavailable
&&
91 cast
<Decl
>(CurContext
)->getAvailability() != AR_Unavailable
)
94 if (isa
<UnresolvedUsingIfExistsDecl
>(D
))
100 static void DiagnoseUnusedOfDecl(Sema
&S
, NamedDecl
*D
, SourceLocation Loc
) {
101 // Warn if this is used but marked unused.
102 if (const auto *A
= D
->getAttr
<UnusedAttr
>()) {
103 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
104 // should diagnose them.
105 if (A
->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused
&&
106 A
->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused
) {
107 const Decl
*DC
= cast_or_null
<Decl
>(S
.getCurObjCLexicalContext());
108 if (DC
&& !DC
->hasAttr
<UnusedAttr
>())
109 S
.Diag(Loc
, diag::warn_used_but_marked_unused
) << D
;
114 /// Emit a note explaining that this function is deleted.
115 void Sema::NoteDeletedFunction(FunctionDecl
*Decl
) {
116 assert(Decl
&& Decl
->isDeleted());
118 if (Decl
->isDefaulted()) {
119 // If the method was explicitly defaulted, point at that declaration.
120 if (!Decl
->isImplicit())
121 Diag(Decl
->getLocation(), diag::note_implicitly_deleted
);
123 // Try to diagnose why this special member function was implicitly
124 // deleted. This might fail, if that reason no longer applies.
125 DiagnoseDeletedDefaultedFunction(Decl
);
129 auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(Decl
);
130 if (Ctor
&& Ctor
->isInheritingConstructor())
131 return NoteDeletedInheritingConstructor(Ctor
);
133 Diag(Decl
->getLocation(), diag::note_availability_specified_here
)
137 /// Determine whether a FunctionDecl was ever declared with an
138 /// explicit storage class.
139 static bool hasAnyExplicitStorageClass(const FunctionDecl
*D
) {
140 for (auto *I
: D
->redecls()) {
141 if (I
->getStorageClass() != SC_None
)
147 /// Check whether we're in an extern inline function and referring to a
148 /// variable or function with internal linkage (C11 6.7.4p3).
150 /// This is only a warning because we used to silently accept this code, but
151 /// in many cases it will not behave correctly. This is not enabled in C++ mode
152 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
153 /// and so while there may still be user mistakes, most of the time we can't
154 /// prove that there are errors.
155 static void diagnoseUseOfInternalDeclInInlineFunction(Sema
&S
,
157 SourceLocation Loc
) {
158 // This is disabled under C++; there are too many ways for this to fire in
159 // contexts where the warning is a false positive, or where it is technically
160 // correct but benign.
161 if (S
.getLangOpts().CPlusPlus
)
164 // Check if this is an inlined function or method.
165 FunctionDecl
*Current
= S
.getCurFunctionDecl();
168 if (!Current
->isInlined())
170 if (!Current
->isExternallyVisible())
173 // Check if the decl has internal linkage.
174 if (D
->getFormalLinkage() != InternalLinkage
)
177 // Downgrade from ExtWarn to Extension if
178 // (1) the supposedly external inline function is in the main file,
179 // and probably won't be included anywhere else.
180 // (2) the thing we're referencing is a pure function.
181 // (3) the thing we're referencing is another inline function.
182 // This last can give us false negatives, but it's better than warning on
183 // wrappers for simple C library functions.
184 const FunctionDecl
*UsedFn
= dyn_cast
<FunctionDecl
>(D
);
185 bool DowngradeWarning
= S
.getSourceManager().isInMainFile(Loc
);
186 if (!DowngradeWarning
&& UsedFn
)
187 DowngradeWarning
= UsedFn
->isInlined() || UsedFn
->hasAttr
<ConstAttr
>();
189 S
.Diag(Loc
, DowngradeWarning
? diag::ext_internal_in_extern_inline_quiet
190 : diag::ext_internal_in_extern_inline
)
191 << /*IsVar=*/!UsedFn
<< D
;
193 S
.MaybeSuggestAddingStaticToDecl(Current
);
195 S
.Diag(D
->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at
)
199 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl
*Cur
) {
200 const FunctionDecl
*First
= Cur
->getFirstDecl();
202 // Suggest "static" on the function, if possible.
203 if (!hasAnyExplicitStorageClass(First
)) {
204 SourceLocation DeclBegin
= First
->getSourceRange().getBegin();
205 Diag(DeclBegin
, diag::note_convert_inline_to_static
)
206 << Cur
<< FixItHint::CreateInsertion(DeclBegin
, "static ");
210 /// Determine whether the use of this declaration is valid, and
211 /// emit any corresponding diagnostics.
213 /// This routine diagnoses various problems with referencing
214 /// declarations that can occur when using a declaration. For example,
215 /// it might warn if a deprecated or unavailable declaration is being
216 /// used, or produce an error (and return true) if a C++0x deleted
217 /// function is being used.
219 /// \returns true if there was an error (this declaration cannot be
220 /// referenced), false otherwise.
222 bool Sema::DiagnoseUseOfDecl(NamedDecl
*D
, ArrayRef
<SourceLocation
> Locs
,
223 const ObjCInterfaceDecl
*UnknownObjCClass
,
224 bool ObjCPropertyAccess
,
225 bool AvoidPartialAvailabilityChecks
,
226 ObjCInterfaceDecl
*ClassReceiver
,
227 bool SkipTrailingRequiresClause
) {
228 SourceLocation Loc
= Locs
.front();
229 if (getLangOpts().CPlusPlus
&& isa
<FunctionDecl
>(D
)) {
230 // If there were any diagnostics suppressed by template argument deduction,
232 auto Pos
= SuppressedDiagnostics
.find(D
->getCanonicalDecl());
233 if (Pos
!= SuppressedDiagnostics
.end()) {
234 for (const PartialDiagnosticAt
&Suppressed
: Pos
->second
)
235 Diag(Suppressed
.first
, Suppressed
.second
);
237 // Clear out the list of suppressed diagnostics, so that we don't emit
238 // them again for this specialization. However, we don't obsolete this
239 // entry from the table, because we want to avoid ever emitting these
240 // diagnostics again.
244 // C++ [basic.start.main]p3:
245 // The function 'main' shall not be used within a program.
246 if (cast
<FunctionDecl
>(D
)->isMain())
247 Diag(Loc
, diag::ext_main_used
);
249 diagnoseUnavailableAlignedAllocation(*cast
<FunctionDecl
>(D
), Loc
);
252 // See if this is an auto-typed variable whose initializer we are parsing.
253 if (ParsingInitForAutoVars
.count(D
)) {
254 if (isa
<BindingDecl
>(D
)) {
255 Diag(Loc
, diag::err_binding_cannot_appear_in_own_initializer
)
258 Diag(Loc
, diag::err_auto_variable_cannot_appear_in_own_initializer
)
259 << D
->getDeclName() << cast
<VarDecl
>(D
)->getType();
264 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
265 // See if this is a deleted function.
266 if (FD
->isDeleted()) {
267 auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(FD
);
268 if (Ctor
&& Ctor
->isInheritingConstructor())
269 Diag(Loc
, diag::err_deleted_inherited_ctor_use
)
271 << Ctor
->getInheritedConstructor().getConstructor()->getParent();
273 Diag(Loc
, diag::err_deleted_function_use
);
274 NoteDeletedFunction(FD
);
279 // A program that refers explicitly or implicitly to a function with a
280 // trailing requires-clause whose constraint-expression is not satisfied,
281 // other than to declare it, is ill-formed. [...]
283 // See if this is a function with constraints that need to be satisfied.
284 // Check this before deducing the return type, as it might instantiate the
286 if (!SkipTrailingRequiresClause
&& FD
->getTrailingRequiresClause()) {
287 ConstraintSatisfaction Satisfaction
;
288 if (CheckFunctionConstraints(FD
, Satisfaction
, Loc
,
289 /*ForOverloadResolution*/ true))
290 // A diagnostic will have already been generated (non-constant
291 // constraint expression, for example)
293 if (!Satisfaction
.IsSatisfied
) {
295 diag::err_reference_to_function_with_unsatisfied_constraints
)
297 DiagnoseUnsatisfiedConstraint(Satisfaction
);
302 // If the function has a deduced return type, and we can't deduce it,
303 // then we can't use it either.
304 if (getLangOpts().CPlusPlus14
&& FD
->getReturnType()->isUndeducedType() &&
305 DeduceReturnType(FD
, Loc
))
308 if (getLangOpts().CUDA
&& !CheckCUDACall(Loc
, FD
))
311 if (getLangOpts().SYCLIsDevice
&& !checkSYCLDeviceFunction(Loc
, FD
))
315 if (auto *MD
= dyn_cast
<CXXMethodDecl
>(D
)) {
316 // Lambdas are only default-constructible or assignable in C++2a onwards.
317 if (MD
->getParent()->isLambda() &&
318 ((isa
<CXXConstructorDecl
>(MD
) &&
319 cast
<CXXConstructorDecl
>(MD
)->isDefaultConstructor()) ||
320 MD
->isCopyAssignmentOperator() || MD
->isMoveAssignmentOperator())) {
321 Diag(Loc
, diag::warn_cxx17_compat_lambda_def_ctor_assign
)
322 << !isa
<CXXConstructorDecl
>(MD
);
326 auto getReferencedObjCProp
= [](const NamedDecl
*D
) ->
327 const ObjCPropertyDecl
* {
328 if (const auto *MD
= dyn_cast
<ObjCMethodDecl
>(D
))
329 return MD
->findPropertyDecl();
332 if (const ObjCPropertyDecl
*ObjCPDecl
= getReferencedObjCProp(D
)) {
333 if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl
, Loc
))
335 } else if (diagnoseArgIndependentDiagnoseIfAttrs(D
, Loc
)) {
339 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
340 // Only the variables omp_in and omp_out are allowed in the combiner.
341 // Only the variables omp_priv and omp_orig are allowed in the
342 // initializer-clause.
343 auto *DRD
= dyn_cast
<OMPDeclareReductionDecl
>(CurContext
);
344 if (LangOpts
.OpenMP
&& DRD
&& !CurContext
->containsDecl(D
) &&
346 Diag(Loc
, diag::err_omp_wrong_var_in_declare_reduction
)
347 << getCurFunction()->HasOMPDeclareReductionCombiner
;
348 Diag(D
->getLocation(), diag::note_entity_declared_at
) << D
;
352 // [OpenMP 5.0], 2.19.7.3. declare mapper Directive, Restrictions
353 // List-items in map clauses on this construct may only refer to the declared
354 // variable var and entities that could be referenced by a procedure defined
355 // at the same location.
356 // [OpenMP 5.2] Also allow iterator declared variables.
357 if (LangOpts
.OpenMP
&& isa
<VarDecl
>(D
) &&
358 !isOpenMPDeclareMapperVarDeclAllowed(cast
<VarDecl
>(D
))) {
359 Diag(Loc
, diag::err_omp_declare_mapper_wrong_var
)
360 << getOpenMPDeclareMapperVarName();
361 Diag(D
->getLocation(), diag::note_entity_declared_at
) << D
;
365 if (const auto *EmptyD
= dyn_cast
<UnresolvedUsingIfExistsDecl
>(D
)) {
366 Diag(Loc
, diag::err_use_of_empty_using_if_exists
);
367 Diag(EmptyD
->getLocation(), diag::note_empty_using_if_exists_here
);
371 DiagnoseAvailabilityOfDecl(D
, Locs
, UnknownObjCClass
, ObjCPropertyAccess
,
372 AvoidPartialAvailabilityChecks
, ClassReceiver
);
374 DiagnoseUnusedOfDecl(*this, D
, Loc
);
376 diagnoseUseOfInternalDeclInInlineFunction(*this, D
, Loc
);
378 if (auto *VD
= dyn_cast
<ValueDecl
>(D
))
379 checkTypeSupport(VD
->getType(), Loc
, VD
);
381 if (LangOpts
.SYCLIsDevice
|| (LangOpts
.OpenMP
&& LangOpts
.OpenMPIsDevice
)) {
382 if (!Context
.getTargetInfo().isTLSSupported())
383 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
384 if (VD
->getTLSKind() != VarDecl::TLS_None
)
385 targetDiag(*Locs
.begin(), diag::err_thread_unsupported
);
388 if (isa
<ParmVarDecl
>(D
) && isa
<RequiresExprBodyDecl
>(D
->getDeclContext()) &&
389 !isUnevaluatedContext()) {
390 // C++ [expr.prim.req.nested] p3
391 // A local parameter shall only appear as an unevaluated operand
392 // (Clause 8) within the constraint-expression.
393 Diag(Loc
, diag::err_requires_expr_parameter_referenced_in_evaluated_context
)
395 Diag(D
->getLocation(), diag::note_entity_declared_at
) << D
;
402 /// DiagnoseSentinelCalls - This routine checks whether a call or
403 /// message-send is to a declaration with the sentinel attribute, and
404 /// if so, it checks that the requirements of the sentinel are
406 void Sema::DiagnoseSentinelCalls(NamedDecl
*D
, SourceLocation Loc
,
407 ArrayRef
<Expr
*> Args
) {
408 const SentinelAttr
*attr
= D
->getAttr
<SentinelAttr
>();
412 // The number of formal parameters of the declaration.
413 unsigned numFormalParams
;
415 // The kind of declaration. This is also an index into a %select in
417 enum CalleeType
{ CT_Function
, CT_Method
, CT_Block
} calleeType
;
419 if (ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
420 numFormalParams
= MD
->param_size();
421 calleeType
= CT_Method
;
422 } else if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
423 numFormalParams
= FD
->param_size();
424 calleeType
= CT_Function
;
425 } else if (isa
<VarDecl
>(D
)) {
426 QualType type
= cast
<ValueDecl
>(D
)->getType();
427 const FunctionType
*fn
= nullptr;
428 if (const PointerType
*ptr
= type
->getAs
<PointerType
>()) {
429 fn
= ptr
->getPointeeType()->getAs
<FunctionType
>();
431 calleeType
= CT_Function
;
432 } else if (const BlockPointerType
*ptr
= type
->getAs
<BlockPointerType
>()) {
433 fn
= ptr
->getPointeeType()->castAs
<FunctionType
>();
434 calleeType
= CT_Block
;
439 if (const FunctionProtoType
*proto
= dyn_cast
<FunctionProtoType
>(fn
)) {
440 numFormalParams
= proto
->getNumParams();
448 // "nullPos" is the number of formal parameters at the end which
449 // effectively count as part of the variadic arguments. This is
450 // useful if you would prefer to not have *any* formal parameters,
451 // but the language forces you to have at least one.
452 unsigned nullPos
= attr
->getNullPos();
453 assert((nullPos
== 0 || nullPos
== 1) && "invalid null position on sentinel");
454 numFormalParams
= (nullPos
> numFormalParams
? 0 : numFormalParams
- nullPos
);
456 // The number of arguments which should follow the sentinel.
457 unsigned numArgsAfterSentinel
= attr
->getSentinel();
459 // If there aren't enough arguments for all the formal parameters,
460 // the sentinel, and the args after the sentinel, complain.
461 if (Args
.size() < numFormalParams
+ numArgsAfterSentinel
+ 1) {
462 Diag(Loc
, diag::warn_not_enough_argument
) << D
->getDeclName();
463 Diag(D
->getLocation(), diag::note_sentinel_here
) << int(calleeType
);
467 // Otherwise, find the sentinel expression.
468 Expr
*sentinelExpr
= Args
[Args
.size() - numArgsAfterSentinel
- 1];
469 if (!sentinelExpr
) return;
470 if (sentinelExpr
->isValueDependent()) return;
471 if (Context
.isSentinelNullExpr(sentinelExpr
)) return;
473 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
474 // or 'NULL' if those are actually defined in the context. Only use
475 // 'nil' for ObjC methods, where it's much more likely that the
476 // variadic arguments form a list of object pointers.
477 SourceLocation MissingNilLoc
= getLocForEndOfToken(sentinelExpr
->getEndLoc());
478 std::string NullValue
;
479 if (calleeType
== CT_Method
&& PP
.isMacroDefined("nil"))
481 else if (getLangOpts().CPlusPlus11
)
482 NullValue
= "nullptr";
483 else if (PP
.isMacroDefined("NULL"))
486 NullValue
= "(void*) 0";
488 if (MissingNilLoc
.isInvalid())
489 Diag(Loc
, diag::warn_missing_sentinel
) << int(calleeType
);
491 Diag(MissingNilLoc
, diag::warn_missing_sentinel
)
493 << FixItHint::CreateInsertion(MissingNilLoc
, ", " + NullValue
);
494 Diag(D
->getLocation(), diag::note_sentinel_here
) << int(calleeType
);
497 SourceRange
Sema::getExprRange(Expr
*E
) const {
498 return E
? E
->getSourceRange() : SourceRange();
501 //===----------------------------------------------------------------------===//
502 // Standard Promotions and Conversions
503 //===----------------------------------------------------------------------===//
505 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
506 ExprResult
Sema::DefaultFunctionArrayConversion(Expr
*E
, bool Diagnose
) {
507 // Handle any placeholder expressions which made it here.
508 if (E
->hasPlaceholderType()) {
509 ExprResult result
= CheckPlaceholderExpr(E
);
510 if (result
.isInvalid()) return ExprError();
514 QualType Ty
= E
->getType();
515 assert(!Ty
.isNull() && "DefaultFunctionArrayConversion - missing type");
517 if (Ty
->isFunctionType()) {
518 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenCasts()))
519 if (auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl()))
520 if (!checkAddressOfFunctionIsAvailable(FD
, Diagnose
, E
->getExprLoc()))
523 E
= ImpCastExprToType(E
, Context
.getPointerType(Ty
),
524 CK_FunctionToPointerDecay
).get();
525 } else if (Ty
->isArrayType()) {
526 // In C90 mode, arrays only promote to pointers if the array expression is
527 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
528 // type 'array of type' is converted to an expression that has type 'pointer
529 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
530 // that has type 'array of type' ...". The relevant change is "an lvalue"
531 // (C90) to "an expression" (C99).
534 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
535 // T" can be converted to an rvalue of type "pointer to T".
537 if (getLangOpts().C99
|| getLangOpts().CPlusPlus
|| E
->isLValue()) {
538 ExprResult Res
= ImpCastExprToType(E
, Context
.getArrayDecayedType(Ty
),
539 CK_ArrayToPointerDecay
);
548 static void CheckForNullPointerDereference(Sema
&S
, Expr
*E
) {
549 // Check to see if we are dereferencing a null pointer. If so,
550 // and if not volatile-qualified, this is undefined behavior that the
551 // optimizer will delete, so warn about it. People sometimes try to use this
552 // to get a deterministic trap and are surprised by clang's behavior. This
553 // only handles the pattern "*null", which is a very syntactic check.
554 const auto *UO
= dyn_cast
<UnaryOperator
>(E
->IgnoreParenCasts());
555 if (UO
&& UO
->getOpcode() == UO_Deref
&&
556 UO
->getSubExpr()->getType()->isPointerType()) {
558 UO
->getSubExpr()->getType()->getPointeeType().getAddressSpace();
559 if ((!isTargetAddressSpace(AS
) ||
560 (isTargetAddressSpace(AS
) && toTargetAddressSpace(AS
) == 0)) &&
561 UO
->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
562 S
.Context
, Expr::NPC_ValueDependentIsNotNull
) &&
563 !UO
->getType().isVolatileQualified()) {
564 S
.DiagRuntimeBehavior(UO
->getOperatorLoc(), UO
,
565 S
.PDiag(diag::warn_indirection_through_null
)
566 << UO
->getSubExpr()->getSourceRange());
567 S
.DiagRuntimeBehavior(UO
->getOperatorLoc(), UO
,
568 S
.PDiag(diag::note_indirection_through_null
));
573 static void DiagnoseDirectIsaAccess(Sema
&S
, const ObjCIvarRefExpr
*OIRE
,
574 SourceLocation AssignLoc
,
576 const ObjCIvarDecl
*IV
= OIRE
->getDecl();
580 DeclarationName MemberName
= IV
->getDeclName();
581 IdentifierInfo
*Member
= MemberName
.getAsIdentifierInfo();
582 if (!Member
|| !Member
->isStr("isa"))
585 const Expr
*Base
= OIRE
->getBase();
586 QualType BaseType
= Base
->getType();
588 BaseType
= BaseType
->getPointeeType();
589 if (const ObjCObjectType
*OTy
= BaseType
->getAs
<ObjCObjectType
>())
590 if (ObjCInterfaceDecl
*IDecl
= OTy
->getInterface()) {
591 ObjCInterfaceDecl
*ClassDeclared
= nullptr;
592 ObjCIvarDecl
*IV
= IDecl
->lookupInstanceVariable(Member
, ClassDeclared
);
593 if (!ClassDeclared
->getSuperClass()
594 && (*ClassDeclared
->ivar_begin()) == IV
) {
596 NamedDecl
*ObjectSetClass
=
597 S
.LookupSingleName(S
.TUScope
,
598 &S
.Context
.Idents
.get("object_setClass"),
599 SourceLocation(), S
.LookupOrdinaryName
);
600 if (ObjectSetClass
) {
601 SourceLocation RHSLocEnd
= S
.getLocForEndOfToken(RHS
->getEndLoc());
602 S
.Diag(OIRE
->getExprLoc(), diag::warn_objc_isa_assign
)
603 << FixItHint::CreateInsertion(OIRE
->getBeginLoc(),
605 << FixItHint::CreateReplacement(
606 SourceRange(OIRE
->getOpLoc(), AssignLoc
), ",")
607 << FixItHint::CreateInsertion(RHSLocEnd
, ")");
610 S
.Diag(OIRE
->getLocation(), diag::warn_objc_isa_assign
);
612 NamedDecl
*ObjectGetClass
=
613 S
.LookupSingleName(S
.TUScope
,
614 &S
.Context
.Idents
.get("object_getClass"),
615 SourceLocation(), S
.LookupOrdinaryName
);
617 S
.Diag(OIRE
->getExprLoc(), diag::warn_objc_isa_use
)
618 << FixItHint::CreateInsertion(OIRE
->getBeginLoc(),
620 << FixItHint::CreateReplacement(
621 SourceRange(OIRE
->getOpLoc(), OIRE
->getEndLoc()), ")");
623 S
.Diag(OIRE
->getLocation(), diag::warn_objc_isa_use
);
625 S
.Diag(IV
->getLocation(), diag::note_ivar_decl
);
630 ExprResult
Sema::DefaultLvalueConversion(Expr
*E
) {
631 // Handle any placeholder expressions which made it here.
632 if (E
->hasPlaceholderType()) {
633 ExprResult result
= CheckPlaceholderExpr(E
);
634 if (result
.isInvalid()) return ExprError();
638 // C++ [conv.lval]p1:
639 // A glvalue of a non-function, non-array type T can be
640 // converted to a prvalue.
641 if (!E
->isGLValue()) return E
;
643 QualType T
= E
->getType();
644 assert(!T
.isNull() && "r-value conversion on typeless expression?");
646 // lvalue-to-rvalue conversion cannot be applied to function or array types.
647 if (T
->isFunctionType() || T
->isArrayType())
650 // We don't want to throw lvalue-to-rvalue casts on top of
651 // expressions of certain types in C++.
652 if (getLangOpts().CPlusPlus
&&
653 (E
->getType() == Context
.OverloadTy
||
654 T
->isDependentType() ||
658 // The C standard is actually really unclear on this point, and
659 // DR106 tells us what the result should be but not why. It's
660 // generally best to say that void types just doesn't undergo
661 // lvalue-to-rvalue at all. Note that expressions of unqualified
662 // 'void' type are never l-values, but qualified void can be.
666 // OpenCL usually rejects direct accesses to values of 'half' type.
667 if (getLangOpts().OpenCL
&&
668 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
670 Diag(E
->getExprLoc(), diag::err_opencl_half_load_store
)
675 CheckForNullPointerDereference(*this, E
);
676 if (const ObjCIsaExpr
*OISA
= dyn_cast
<ObjCIsaExpr
>(E
->IgnoreParenCasts())) {
677 NamedDecl
*ObjectGetClass
= LookupSingleName(TUScope
,
678 &Context
.Idents
.get("object_getClass"),
679 SourceLocation(), LookupOrdinaryName
);
681 Diag(E
->getExprLoc(), diag::warn_objc_isa_use
)
682 << FixItHint::CreateInsertion(OISA
->getBeginLoc(), "object_getClass(")
683 << FixItHint::CreateReplacement(
684 SourceRange(OISA
->getOpLoc(), OISA
->getIsaMemberLoc()), ")");
686 Diag(E
->getExprLoc(), diag::warn_objc_isa_use
);
688 else if (const ObjCIvarRefExpr
*OIRE
=
689 dyn_cast
<ObjCIvarRefExpr
>(E
->IgnoreParenCasts()))
690 DiagnoseDirectIsaAccess(*this, OIRE
, SourceLocation(), /* Expr*/nullptr);
692 // C++ [conv.lval]p1:
693 // [...] If T is a non-class type, the type of the prvalue is the
694 // cv-unqualified version of T. Otherwise, the type of the
698 // If the lvalue has qualified type, the value has the unqualified
699 // version of the type of the lvalue; otherwise, the value has the
700 // type of the lvalue.
701 if (T
.hasQualifiers())
702 T
= T
.getUnqualifiedType();
704 // Under the MS ABI, lock down the inheritance model now.
705 if (T
->isMemberPointerType() &&
706 Context
.getTargetInfo().getCXXABI().isMicrosoft())
707 (void)isCompleteType(E
->getExprLoc(), T
);
709 ExprResult Res
= CheckLValueToRValueConversionOperand(E
);
714 // Loading a __weak object implicitly retains the value, so we need a cleanup to
716 if (E
->getType().getObjCLifetime() == Qualifiers::OCL_Weak
)
717 Cleanup
.setExprNeedsCleanups(true);
719 if (E
->getType().isDestructedType() == QualType::DK_nontrivial_c_struct
)
720 Cleanup
.setExprNeedsCleanups(true);
722 // C++ [conv.lval]p3:
723 // If T is cv std::nullptr_t, the result is a null pointer constant.
724 CastKind CK
= T
->isNullPtrType() ? CK_NullToPointer
: CK_LValueToRValue
;
725 Res
= ImplicitCastExpr::Create(Context
, T
, CK
, E
, nullptr, VK_PRValue
,
726 CurFPFeatureOverrides());
729 // ... if the lvalue has atomic type, the value has the non-atomic version
730 // of the type of the lvalue ...
731 if (const AtomicType
*Atomic
= T
->getAs
<AtomicType
>()) {
732 T
= Atomic
->getValueType().getUnqualifiedType();
733 Res
= ImplicitCastExpr::Create(Context
, T
, CK_AtomicToNonAtomic
, Res
.get(),
734 nullptr, VK_PRValue
, FPOptionsOverride());
740 ExprResult
Sema::DefaultFunctionArrayLvalueConversion(Expr
*E
, bool Diagnose
) {
741 ExprResult Res
= DefaultFunctionArrayConversion(E
, Diagnose
);
744 Res
= DefaultLvalueConversion(Res
.get());
750 /// CallExprUnaryConversions - a special case of an unary conversion
751 /// performed on a function designator of a call expression.
752 ExprResult
Sema::CallExprUnaryConversions(Expr
*E
) {
753 QualType Ty
= E
->getType();
755 // Only do implicit cast for a function type, but not for a pointer
757 if (Ty
->isFunctionType()) {
758 Res
= ImpCastExprToType(E
, Context
.getPointerType(Ty
),
759 CK_FunctionToPointerDecay
);
763 Res
= DefaultLvalueConversion(Res
.get());
769 /// UsualUnaryConversions - Performs various conversions that are common to most
770 /// operators (C99 6.3). The conversions of array and function types are
771 /// sometimes suppressed. For example, the array->pointer conversion doesn't
772 /// apply if the array is an argument to the sizeof or address (&) operators.
773 /// In these instances, this routine should *not* be called.
774 ExprResult
Sema::UsualUnaryConversions(Expr
*E
) {
775 // First, convert to an r-value.
776 ExprResult Res
= DefaultFunctionArrayLvalueConversion(E
);
781 QualType Ty
= E
->getType();
782 assert(!Ty
.isNull() && "UsualUnaryConversions - missing type");
784 LangOptions::FPEvalMethodKind EvalMethod
= CurFPFeatures
.getFPEvalMethod();
785 if (EvalMethod
!= LangOptions::FEM_Source
&& Ty
->isFloatingType() &&
786 (getLangOpts().getFPEvalMethod() !=
787 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine
||
788 PP
.getLastFPEvalPragmaLocation().isValid())) {
789 switch (EvalMethod
) {
791 llvm_unreachable("Unrecognized float evaluation method");
793 case LangOptions::FEM_UnsetOnCommandLine
:
794 llvm_unreachable("Float evaluation method should be set by now");
796 case LangOptions::FEM_Double
:
797 if (Context
.getFloatingTypeOrder(Context
.DoubleTy
, Ty
) > 0)
798 // Widen the expression to double.
799 return Ty
->isComplexType()
800 ? ImpCastExprToType(E
,
801 Context
.getComplexType(Context
.DoubleTy
),
802 CK_FloatingComplexCast
)
803 : ImpCastExprToType(E
, Context
.DoubleTy
, CK_FloatingCast
);
805 case LangOptions::FEM_Extended
:
806 if (Context
.getFloatingTypeOrder(Context
.LongDoubleTy
, Ty
) > 0)
807 // Widen the expression to long double.
808 return Ty
->isComplexType()
810 E
, Context
.getComplexType(Context
.LongDoubleTy
),
811 CK_FloatingComplexCast
)
812 : ImpCastExprToType(E
, Context
.LongDoubleTy
,
818 // Half FP have to be promoted to float unless it is natively supported
819 if (Ty
->isHalfType() && !getLangOpts().NativeHalfType
)
820 return ImpCastExprToType(Res
.get(), Context
.FloatTy
, CK_FloatingCast
);
822 // Try to perform integral promotions if the object has a theoretically
824 if (Ty
->isIntegralOrUnscopedEnumerationType()) {
827 // The following may be used in an expression wherever an int or
828 // unsigned int may be used:
829 // - an object or expression with an integer type whose integer
830 // conversion rank is less than or equal to the rank of int
832 // - A bit-field of type _Bool, int, signed int, or unsigned int.
834 // If an int can represent all values of the original type, the
835 // value is converted to an int; otherwise, it is converted to an
836 // unsigned int. These are called the integer promotions. All
837 // other types are unchanged by the integer promotions.
839 QualType PTy
= Context
.isPromotableBitField(E
);
841 E
= ImpCastExprToType(E
, PTy
, CK_IntegralCast
).get();
844 if (Context
.isPromotableIntegerType(Ty
)) {
845 QualType PT
= Context
.getPromotedIntegerType(Ty
);
846 E
= ImpCastExprToType(E
, PT
, CK_IntegralCast
).get();
853 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
854 /// do not have a prototype. Arguments that have type float or __fp16
855 /// are promoted to double. All other argument types are converted by
856 /// UsualUnaryConversions().
857 ExprResult
Sema::DefaultArgumentPromotion(Expr
*E
) {
858 QualType Ty
= E
->getType();
859 assert(!Ty
.isNull() && "DefaultArgumentPromotion - missing type");
861 ExprResult Res
= UsualUnaryConversions(E
);
866 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
867 // promote to double.
868 // Note that default argument promotion applies only to float (and
869 // half/fp16); it does not apply to _Float16.
870 const BuiltinType
*BTy
= Ty
->getAs
<BuiltinType
>();
871 if (BTy
&& (BTy
->getKind() == BuiltinType::Half
||
872 BTy
->getKind() == BuiltinType::Float
)) {
873 if (getLangOpts().OpenCL
&&
874 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
875 if (BTy
->getKind() == BuiltinType::Half
) {
876 E
= ImpCastExprToType(E
, Context
.FloatTy
, CK_FloatingCast
).get();
879 E
= ImpCastExprToType(E
, Context
.DoubleTy
, CK_FloatingCast
).get();
883 getLangOpts().getExtendIntArgs() ==
884 LangOptions::ExtendArgsKind::ExtendTo64
&&
885 Context
.getTargetInfo().supportsExtendIntArgs() && Ty
->isIntegerType() &&
886 Context
.getTypeSizeInChars(BTy
) <
887 Context
.getTypeSizeInChars(Context
.LongLongTy
)) {
888 E
= (Ty
->isUnsignedIntegerType())
889 ? ImpCastExprToType(E
, Context
.UnsignedLongLongTy
, CK_IntegralCast
)
891 : ImpCastExprToType(E
, Context
.LongLongTy
, CK_IntegralCast
).get();
892 assert(8 == Context
.getTypeSizeInChars(Context
.LongLongTy
).getQuantity() &&
893 "Unexpected typesize for LongLongTy");
896 // C++ performs lvalue-to-rvalue conversion as a default argument
897 // promotion, even on class types, but note:
898 // C++11 [conv.lval]p2:
899 // When an lvalue-to-rvalue conversion occurs in an unevaluated
900 // operand or a subexpression thereof the value contained in the
901 // referenced object is not accessed. Otherwise, if the glvalue
902 // has a class type, the conversion copy-initializes a temporary
903 // of type T from the glvalue and the result of the conversion
904 // is a prvalue for the temporary.
905 // FIXME: add some way to gate this entire thing for correctness in
906 // potentially potentially evaluated contexts.
907 if (getLangOpts().CPlusPlus
&& E
->isGLValue() && !isUnevaluatedContext()) {
908 ExprResult Temp
= PerformCopyInitialization(
909 InitializedEntity::InitializeTemporary(E
->getType()),
911 if (Temp
.isInvalid())
919 /// Determine the degree of POD-ness for an expression.
920 /// Incomplete types are considered POD, since this check can be performed
921 /// when we're in an unevaluated context.
922 Sema::VarArgKind
Sema::isValidVarArgType(const QualType
&Ty
) {
923 if (Ty
->isIncompleteType()) {
924 // C++11 [expr.call]p7:
925 // After these conversions, if the argument does not have arithmetic,
926 // enumeration, pointer, pointer to member, or class type, the program
929 // Since we've already performed array-to-pointer and function-to-pointer
930 // decay, the only such type in C++ is cv void. This also handles
931 // initializer lists as variadic arguments.
932 if (Ty
->isVoidType())
935 if (Ty
->isObjCObjectType())
940 if (Ty
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
943 if (Ty
.isCXX98PODType(Context
))
946 // C++11 [expr.call]p7:
947 // Passing a potentially-evaluated argument of class type (Clause 9)
948 // having a non-trivial copy constructor, a non-trivial move constructor,
949 // or a non-trivial destructor, with no corresponding parameter,
950 // is conditionally-supported with implementation-defined semantics.
951 if (getLangOpts().CPlusPlus11
&& !Ty
->isDependentType())
952 if (CXXRecordDecl
*Record
= Ty
->getAsCXXRecordDecl())
953 if (!Record
->hasNonTrivialCopyConstructor() &&
954 !Record
->hasNonTrivialMoveConstructor() &&
955 !Record
->hasNonTrivialDestructor())
956 return VAK_ValidInCXX11
;
958 if (getLangOpts().ObjCAutoRefCount
&& Ty
->isObjCLifetimeType())
961 if (Ty
->isObjCObjectType())
964 if (getLangOpts().MSVCCompat
)
965 return VAK_MSVCUndefined
;
967 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
968 // permitted to reject them. We should consider doing so.
969 return VAK_Undefined
;
972 void Sema::checkVariadicArgument(const Expr
*E
, VariadicCallType CT
) {
973 // Don't allow one to pass an Objective-C interface to a vararg.
974 const QualType
&Ty
= E
->getType();
975 VarArgKind VAK
= isValidVarArgType(Ty
);
977 // Complain about passing non-POD types through varargs.
979 case VAK_ValidInCXX11
:
981 E
->getBeginLoc(), nullptr,
982 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg
) << Ty
<< CT
);
985 if (Ty
->isRecordType()) {
986 // This is unlikely to be what the user intended. If the class has a
987 // 'c_str' member function, the user probably meant to call that.
988 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
989 PDiag(diag::warn_pass_class_arg_to_vararg
)
990 << Ty
<< CT
<< hasCStrMethod(E
) << ".c_str()");
995 case VAK_MSVCUndefined
:
996 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
997 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg
)
998 << getLangOpts().CPlusPlus11
<< Ty
<< CT
);
1002 if (Ty
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
1003 Diag(E
->getBeginLoc(),
1004 diag::err_cannot_pass_non_trivial_c_struct_to_vararg
)
1006 else if (Ty
->isObjCObjectType())
1007 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
1008 PDiag(diag::err_cannot_pass_objc_interface_to_vararg
)
1011 Diag(E
->getBeginLoc(), diag::err_cannot_pass_to_vararg
)
1012 << isa
<InitListExpr
>(E
) << Ty
<< CT
;
1017 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1018 /// will create a trap if the resulting type is not a POD type.
1019 ExprResult
Sema::DefaultVariadicArgumentPromotion(Expr
*E
, VariadicCallType CT
,
1020 FunctionDecl
*FDecl
) {
1021 if (const BuiltinType
*PlaceholderTy
= E
->getType()->getAsPlaceholderType()) {
1022 // Strip the unbridged-cast placeholder expression off, if applicable.
1023 if (PlaceholderTy
->getKind() == BuiltinType::ARCUnbridgedCast
&&
1024 (CT
== VariadicMethod
||
1025 (FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>()))) {
1026 E
= stripARCUnbridgedCast(E
);
1028 // Otherwise, do normal placeholder checking.
1030 ExprResult ExprRes
= CheckPlaceholderExpr(E
);
1031 if (ExprRes
.isInvalid())
1037 ExprResult ExprRes
= DefaultArgumentPromotion(E
);
1038 if (ExprRes
.isInvalid())
1041 // Copy blocks to the heap.
1042 if (ExprRes
.get()->getType()->isBlockPointerType())
1043 maybeExtendBlockObject(ExprRes
);
1047 // Diagnostics regarding non-POD argument types are
1048 // emitted along with format string checking in Sema::CheckFunctionCall().
1049 if (isValidVarArgType(E
->getType()) == VAK_Undefined
) {
1050 // Turn this into a trap.
1052 SourceLocation TemplateKWLoc
;
1054 Name
.setIdentifier(PP
.getIdentifierInfo("__builtin_trap"),
1056 ExprResult TrapFn
= ActOnIdExpression(TUScope
, SS
, TemplateKWLoc
, Name
,
1057 /*HasTrailingLParen=*/true,
1058 /*IsAddressOfOperand=*/false);
1059 if (TrapFn
.isInvalid())
1062 ExprResult Call
= BuildCallExpr(TUScope
, TrapFn
.get(), E
->getBeginLoc(),
1063 std::nullopt
, E
->getEndLoc());
1064 if (Call
.isInvalid())
1068 ActOnBinOp(TUScope
, E
->getBeginLoc(), tok::comma
, Call
.get(), E
);
1069 if (Comma
.isInvalid())
1074 if (!getLangOpts().CPlusPlus
&&
1075 RequireCompleteType(E
->getExprLoc(), E
->getType(),
1076 diag::err_call_incomplete_argument
))
1082 /// Converts an integer to complex float type. Helper function of
1083 /// UsualArithmeticConversions()
1085 /// \return false if the integer expression is an integer type and is
1086 /// successfully converted to the complex type.
1087 static bool handleIntegerToComplexFloatConversion(Sema
&S
, ExprResult
&IntExpr
,
1088 ExprResult
&ComplexExpr
,
1092 if (IntTy
->isComplexType() || IntTy
->isRealFloatingType()) return true;
1093 if (SkipCast
) return false;
1094 if (IntTy
->isIntegerType()) {
1095 QualType fpTy
= ComplexTy
->castAs
<ComplexType
>()->getElementType();
1096 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), fpTy
, CK_IntegralToFloating
);
1097 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), ComplexTy
,
1098 CK_FloatingRealToComplex
);
1100 assert(IntTy
->isComplexIntegerType());
1101 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), ComplexTy
,
1102 CK_IntegralComplexToFloatingComplex
);
1107 // This handles complex/complex, complex/float, or float/complex.
1108 // When both operands are complex, the shorter operand is converted to the
1109 // type of the longer, and that is the type of the result. This corresponds
1110 // to what is done when combining two real floating-point operands.
1111 // The fun begins when size promotion occur across type domains.
1112 // From H&S 6.3.4: When one operand is complex and the other is a real
1113 // floating-point type, the less precise type is converted, within it's
1114 // real or complex domain, to the precision of the other type. For example,
1115 // when combining a "long double" with a "double _Complex", the
1116 // "double _Complex" is promoted to "long double _Complex".
1117 static QualType
handleComplexFloatConversion(Sema
&S
, ExprResult
&Shorter
,
1118 QualType ShorterType
,
1119 QualType LongerType
,
1120 bool PromotePrecision
) {
1121 bool LongerIsComplex
= isa
<ComplexType
>(LongerType
.getCanonicalType());
1123 LongerIsComplex
? LongerType
: S
.Context
.getComplexType(LongerType
);
1125 if (PromotePrecision
) {
1126 if (isa
<ComplexType
>(ShorterType
.getCanonicalType())) {
1128 S
.ImpCastExprToType(Shorter
.get(), Result
, CK_FloatingComplexCast
);
1130 if (LongerIsComplex
)
1131 LongerType
= LongerType
->castAs
<ComplexType
>()->getElementType();
1132 Shorter
= S
.ImpCastExprToType(Shorter
.get(), LongerType
, CK_FloatingCast
);
1138 /// Handle arithmetic conversion with complex types. Helper function of
1139 /// UsualArithmeticConversions()
1140 static QualType
handleComplexConversion(Sema
&S
, ExprResult
&LHS
,
1141 ExprResult
&RHS
, QualType LHSType
,
1142 QualType RHSType
, bool IsCompAssign
) {
1143 // if we have an integer operand, the result is the complex type.
1144 if (!handleIntegerToComplexFloatConversion(S
, RHS
, LHS
, RHSType
, LHSType
,
1145 /*SkipCast=*/false))
1147 if (!handleIntegerToComplexFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
1148 /*SkipCast=*/IsCompAssign
))
1151 // Compute the rank of the two types, regardless of whether they are complex.
1152 int Order
= S
.Context
.getFloatingTypeOrder(LHSType
, RHSType
);
1154 // Promote the precision of the LHS if not an assignment.
1155 return handleComplexFloatConversion(S
, LHS
, LHSType
, RHSType
,
1156 /*PromotePrecision=*/!IsCompAssign
);
1157 // Promote the precision of the RHS unless it is already the same as the LHS.
1158 return handleComplexFloatConversion(S
, RHS
, RHSType
, LHSType
,
1159 /*PromotePrecision=*/Order
> 0);
1162 /// Handle arithmetic conversion from integer to float. Helper function
1163 /// of UsualArithmeticConversions()
1164 static QualType
handleIntToFloatConversion(Sema
&S
, ExprResult
&FloatExpr
,
1165 ExprResult
&IntExpr
,
1166 QualType FloatTy
, QualType IntTy
,
1167 bool ConvertFloat
, bool ConvertInt
) {
1168 if (IntTy
->isIntegerType()) {
1170 // Convert intExpr to the lhs floating point type.
1171 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), FloatTy
,
1172 CK_IntegralToFloating
);
1176 // Convert both sides to the appropriate complex float.
1177 assert(IntTy
->isComplexIntegerType());
1178 QualType result
= S
.Context
.getComplexType(FloatTy
);
1180 // _Complex int -> _Complex float
1182 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), result
,
1183 CK_IntegralComplexToFloatingComplex
);
1185 // float -> _Complex float
1187 FloatExpr
= S
.ImpCastExprToType(FloatExpr
.get(), result
,
1188 CK_FloatingRealToComplex
);
1193 /// Handle arithmethic conversion with floating point types. Helper
1194 /// function of UsualArithmeticConversions()
1195 static QualType
handleFloatConversion(Sema
&S
, ExprResult
&LHS
,
1196 ExprResult
&RHS
, QualType LHSType
,
1197 QualType RHSType
, bool IsCompAssign
) {
1198 bool LHSFloat
= LHSType
->isRealFloatingType();
1199 bool RHSFloat
= RHSType
->isRealFloatingType();
1201 // N1169 4.1.4: If one of the operands has a floating type and the other
1202 // operand has a fixed-point type, the fixed-point operand
1203 // is converted to the floating type [...]
1204 if (LHSType
->isFixedPointType() || RHSType
->isFixedPointType()) {
1206 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSType
, CK_FixedPointToFloating
);
1207 else if (!IsCompAssign
)
1208 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSType
, CK_FixedPointToFloating
);
1209 return LHSFloat
? LHSType
: RHSType
;
1212 // If we have two real floating types, convert the smaller operand
1213 // to the bigger result.
1214 if (LHSFloat
&& RHSFloat
) {
1215 int order
= S
.Context
.getFloatingTypeOrder(LHSType
, RHSType
);
1217 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSType
, CK_FloatingCast
);
1221 assert(order
< 0 && "illegal float comparison");
1223 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSType
, CK_FloatingCast
);
1228 // Half FP has to be promoted to float unless it is natively supported
1229 if (LHSType
->isHalfType() && !S
.getLangOpts().NativeHalfType
)
1230 LHSType
= S
.Context
.FloatTy
;
1232 return handleIntToFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
1233 /*ConvertFloat=*/!IsCompAssign
,
1234 /*ConvertInt=*/ true);
1237 return handleIntToFloatConversion(S
, RHS
, LHS
, RHSType
, LHSType
,
1238 /*ConvertFloat=*/ true,
1239 /*ConvertInt=*/!IsCompAssign
);
1242 /// Diagnose attempts to convert between __float128, __ibm128 and
1243 /// long double if there is no support for such conversion.
1244 /// Helper function of UsualArithmeticConversions().
1245 static bool unsupportedTypeConversion(const Sema
&S
, QualType LHSType
,
1247 // No issue if either is not a floating point type.
1248 if (!LHSType
->isFloatingType() || !RHSType
->isFloatingType())
1251 // No issue if both have the same 128-bit float semantics.
1252 auto *LHSComplex
= LHSType
->getAs
<ComplexType
>();
1253 auto *RHSComplex
= RHSType
->getAs
<ComplexType
>();
1255 QualType LHSElem
= LHSComplex
? LHSComplex
->getElementType() : LHSType
;
1256 QualType RHSElem
= RHSComplex
? RHSComplex
->getElementType() : RHSType
;
1258 const llvm::fltSemantics
&LHSSem
= S
.Context
.getFloatTypeSemantics(LHSElem
);
1259 const llvm::fltSemantics
&RHSSem
= S
.Context
.getFloatTypeSemantics(RHSElem
);
1261 if ((&LHSSem
!= &llvm::APFloat::PPCDoubleDouble() ||
1262 &RHSSem
!= &llvm::APFloat::IEEEquad()) &&
1263 (&LHSSem
!= &llvm::APFloat::IEEEquad() ||
1264 &RHSSem
!= &llvm::APFloat::PPCDoubleDouble()))
1270 typedef ExprResult
PerformCastFn(Sema
&S
, Expr
*operand
, QualType toType
);
1273 /// These helper callbacks are placed in an anonymous namespace to
1274 /// permit their use as function template parameters.
1275 ExprResult
doIntegralCast(Sema
&S
, Expr
*op
, QualType toType
) {
1276 return S
.ImpCastExprToType(op
, toType
, CK_IntegralCast
);
1279 ExprResult
doComplexIntegralCast(Sema
&S
, Expr
*op
, QualType toType
) {
1280 return S
.ImpCastExprToType(op
, S
.Context
.getComplexType(toType
),
1281 CK_IntegralComplexCast
);
1285 /// Handle integer arithmetic conversions. Helper function of
1286 /// UsualArithmeticConversions()
1287 template <PerformCastFn doLHSCast
, PerformCastFn doRHSCast
>
1288 static QualType
handleIntegerConversion(Sema
&S
, ExprResult
&LHS
,
1289 ExprResult
&RHS
, QualType LHSType
,
1290 QualType RHSType
, bool IsCompAssign
) {
1291 // The rules for this case are in C99 6.3.1.8
1292 int order
= S
.Context
.getIntegerTypeOrder(LHSType
, RHSType
);
1293 bool LHSSigned
= LHSType
->hasSignedIntegerRepresentation();
1294 bool RHSSigned
= RHSType
->hasSignedIntegerRepresentation();
1295 if (LHSSigned
== RHSSigned
) {
1296 // Same signedness; use the higher-ranked type
1298 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1300 } else if (!IsCompAssign
)
1301 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1303 } else if (order
!= (LHSSigned
? 1 : -1)) {
1304 // The unsigned type has greater than or equal rank to the
1305 // signed type, so use the unsigned type
1307 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1309 } else if (!IsCompAssign
)
1310 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1312 } else if (S
.Context
.getIntWidth(LHSType
) != S
.Context
.getIntWidth(RHSType
)) {
1313 // The two types are different widths; if we are here, that
1314 // means the signed type is larger than the unsigned type, so
1315 // use the signed type.
1317 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1319 } else if (!IsCompAssign
)
1320 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1323 // The signed type is higher-ranked than the unsigned type,
1324 // but isn't actually any bigger (like unsigned int and long
1325 // on most 32-bit systems). Use the unsigned type corresponding
1326 // to the signed type.
1328 S
.Context
.getCorrespondingUnsignedType(LHSSigned
? LHSType
: RHSType
);
1329 RHS
= (*doRHSCast
)(S
, RHS
.get(), result
);
1331 LHS
= (*doLHSCast
)(S
, LHS
.get(), result
);
1336 /// Handle conversions with GCC complex int extension. Helper function
1337 /// of UsualArithmeticConversions()
1338 static QualType
handleComplexIntConversion(Sema
&S
, ExprResult
&LHS
,
1339 ExprResult
&RHS
, QualType LHSType
,
1341 bool IsCompAssign
) {
1342 const ComplexType
*LHSComplexInt
= LHSType
->getAsComplexIntegerType();
1343 const ComplexType
*RHSComplexInt
= RHSType
->getAsComplexIntegerType();
1345 if (LHSComplexInt
&& RHSComplexInt
) {
1346 QualType LHSEltType
= LHSComplexInt
->getElementType();
1347 QualType RHSEltType
= RHSComplexInt
->getElementType();
1348 QualType ScalarType
=
1349 handleIntegerConversion
<doComplexIntegralCast
, doComplexIntegralCast
>
1350 (S
, LHS
, RHS
, LHSEltType
, RHSEltType
, IsCompAssign
);
1352 return S
.Context
.getComplexType(ScalarType
);
1355 if (LHSComplexInt
) {
1356 QualType LHSEltType
= LHSComplexInt
->getElementType();
1357 QualType ScalarType
=
1358 handleIntegerConversion
<doComplexIntegralCast
, doIntegralCast
>
1359 (S
, LHS
, RHS
, LHSEltType
, RHSType
, IsCompAssign
);
1360 QualType ComplexType
= S
.Context
.getComplexType(ScalarType
);
1361 RHS
= S
.ImpCastExprToType(RHS
.get(), ComplexType
,
1362 CK_IntegralRealToComplex
);
1367 assert(RHSComplexInt
);
1369 QualType RHSEltType
= RHSComplexInt
->getElementType();
1370 QualType ScalarType
=
1371 handleIntegerConversion
<doIntegralCast
, doComplexIntegralCast
>
1372 (S
, LHS
, RHS
, LHSType
, RHSEltType
, IsCompAssign
);
1373 QualType ComplexType
= S
.Context
.getComplexType(ScalarType
);
1376 LHS
= S
.ImpCastExprToType(LHS
.get(), ComplexType
,
1377 CK_IntegralRealToComplex
);
1381 /// Return the rank of a given fixed point or integer type. The value itself
1382 /// doesn't matter, but the values must be increasing with proper increasing
1383 /// rank as described in N1169 4.1.1.
1384 static unsigned GetFixedPointRank(QualType Ty
) {
1385 const auto *BTy
= Ty
->getAs
<BuiltinType
>();
1386 assert(BTy
&& "Expected a builtin type.");
1388 switch (BTy
->getKind()) {
1389 case BuiltinType::ShortFract
:
1390 case BuiltinType::UShortFract
:
1391 case BuiltinType::SatShortFract
:
1392 case BuiltinType::SatUShortFract
:
1394 case BuiltinType::Fract
:
1395 case BuiltinType::UFract
:
1396 case BuiltinType::SatFract
:
1397 case BuiltinType::SatUFract
:
1399 case BuiltinType::LongFract
:
1400 case BuiltinType::ULongFract
:
1401 case BuiltinType::SatLongFract
:
1402 case BuiltinType::SatULongFract
:
1404 case BuiltinType::ShortAccum
:
1405 case BuiltinType::UShortAccum
:
1406 case BuiltinType::SatShortAccum
:
1407 case BuiltinType::SatUShortAccum
:
1409 case BuiltinType::Accum
:
1410 case BuiltinType::UAccum
:
1411 case BuiltinType::SatAccum
:
1412 case BuiltinType::SatUAccum
:
1414 case BuiltinType::LongAccum
:
1415 case BuiltinType::ULongAccum
:
1416 case BuiltinType::SatLongAccum
:
1417 case BuiltinType::SatULongAccum
:
1420 if (BTy
->isInteger())
1422 llvm_unreachable("Unexpected fixed point or integer type");
1426 /// handleFixedPointConversion - Fixed point operations between fixed
1427 /// point types and integers or other fixed point types do not fall under
1428 /// usual arithmetic conversion since these conversions could result in loss
1429 /// of precsision (N1169 4.1.4). These operations should be calculated with
1430 /// the full precision of their result type (N1169 4.1.6.2.1).
1431 static QualType
handleFixedPointConversion(Sema
&S
, QualType LHSTy
,
1433 assert((LHSTy
->isFixedPointType() || RHSTy
->isFixedPointType()) &&
1434 "Expected at least one of the operands to be a fixed point type");
1435 assert((LHSTy
->isFixedPointOrIntegerType() ||
1436 RHSTy
->isFixedPointOrIntegerType()) &&
1437 "Special fixed point arithmetic operation conversions are only "
1438 "applied to ints or other fixed point types");
1440 // If one operand has signed fixed-point type and the other operand has
1441 // unsigned fixed-point type, then the unsigned fixed-point operand is
1442 // converted to its corresponding signed fixed-point type and the resulting
1443 // type is the type of the converted operand.
1444 if (RHSTy
->isSignedFixedPointType() && LHSTy
->isUnsignedFixedPointType())
1445 LHSTy
= S
.Context
.getCorrespondingSignedFixedPointType(LHSTy
);
1446 else if (RHSTy
->isUnsignedFixedPointType() && LHSTy
->isSignedFixedPointType())
1447 RHSTy
= S
.Context
.getCorrespondingSignedFixedPointType(RHSTy
);
1449 // The result type is the type with the highest rank, whereby a fixed-point
1450 // conversion rank is always greater than an integer conversion rank; if the
1451 // type of either of the operands is a saturating fixedpoint type, the result
1452 // type shall be the saturating fixed-point type corresponding to the type
1453 // with the highest rank; the resulting value is converted (taking into
1454 // account rounding and overflow) to the precision of the resulting type.
1455 // Same ranks between signed and unsigned types are resolved earlier, so both
1456 // types are either signed or both unsigned at this point.
1457 unsigned LHSTyRank
= GetFixedPointRank(LHSTy
);
1458 unsigned RHSTyRank
= GetFixedPointRank(RHSTy
);
1460 QualType ResultTy
= LHSTyRank
> RHSTyRank
? LHSTy
: RHSTy
;
1462 if (LHSTy
->isSaturatedFixedPointType() || RHSTy
->isSaturatedFixedPointType())
1463 ResultTy
= S
.Context
.getCorrespondingSaturatedType(ResultTy
);
1468 /// Check that the usual arithmetic conversions can be performed on this pair of
1469 /// expressions that might be of enumeration type.
1470 static void checkEnumArithmeticConversions(Sema
&S
, Expr
*LHS
, Expr
*RHS
,
1472 Sema::ArithConvKind ACK
) {
1473 // C++2a [expr.arith.conv]p1:
1474 // If one operand is of enumeration type and the other operand is of a
1475 // different enumeration type or a floating-point type, this behavior is
1476 // deprecated ([depr.arith.conv.enum]).
1478 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1479 // Eventually we will presumably reject these cases (in C++23 onwards?).
1480 QualType L
= LHS
->getType(), R
= RHS
->getType();
1481 bool LEnum
= L
->isUnscopedEnumerationType(),
1482 REnum
= R
->isUnscopedEnumerationType();
1483 bool IsCompAssign
= ACK
== Sema::ACK_CompAssign
;
1484 if ((!IsCompAssign
&& LEnum
&& R
->isFloatingType()) ||
1485 (REnum
&& L
->isFloatingType())) {
1486 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus20
1487 ? diag::warn_arith_conv_enum_float_cxx20
1488 : diag::warn_arith_conv_enum_float
)
1489 << LHS
->getSourceRange() << RHS
->getSourceRange()
1490 << (int)ACK
<< LEnum
<< L
<< R
;
1491 } else if (!IsCompAssign
&& LEnum
&& REnum
&&
1492 !S
.Context
.hasSameUnqualifiedType(L
, R
)) {
1494 if (!L
->castAs
<EnumType
>()->getDecl()->hasNameForLinkage() ||
1495 !R
->castAs
<EnumType
>()->getDecl()->hasNameForLinkage()) {
1496 // If either enumeration type is unnamed, it's less likely that the
1497 // user cares about this, but this situation is still deprecated in
1498 // C++2a. Use a different warning group.
1499 DiagID
= S
.getLangOpts().CPlusPlus20
1500 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1501 : diag::warn_arith_conv_mixed_anon_enum_types
;
1502 } else if (ACK
== Sema::ACK_Conditional
) {
1503 // Conditional expressions are separated out because they have
1504 // historically had a different warning flag.
1505 DiagID
= S
.getLangOpts().CPlusPlus20
1506 ? diag::warn_conditional_mixed_enum_types_cxx20
1507 : diag::warn_conditional_mixed_enum_types
;
1508 } else if (ACK
== Sema::ACK_Comparison
) {
1509 // Comparison expressions are separated out because they have
1510 // historically had a different warning flag.
1511 DiagID
= S
.getLangOpts().CPlusPlus20
1512 ? diag::warn_comparison_mixed_enum_types_cxx20
1513 : diag::warn_comparison_mixed_enum_types
;
1515 DiagID
= S
.getLangOpts().CPlusPlus20
1516 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1517 : diag::warn_arith_conv_mixed_enum_types
;
1519 S
.Diag(Loc
, DiagID
) << LHS
->getSourceRange() << RHS
->getSourceRange()
1520 << (int)ACK
<< L
<< R
;
1524 /// UsualArithmeticConversions - Performs various conversions that are common to
1525 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1526 /// routine returns the first non-arithmetic type found. The client is
1527 /// responsible for emitting appropriate error diagnostics.
1528 QualType
Sema::UsualArithmeticConversions(ExprResult
&LHS
, ExprResult
&RHS
,
1530 ArithConvKind ACK
) {
1531 checkEnumArithmeticConversions(*this, LHS
.get(), RHS
.get(), Loc
, ACK
);
1533 if (ACK
!= ACK_CompAssign
) {
1534 LHS
= UsualUnaryConversions(LHS
.get());
1535 if (LHS
.isInvalid())
1539 RHS
= UsualUnaryConversions(RHS
.get());
1540 if (RHS
.isInvalid())
1543 // For conversion purposes, we ignore any qualifiers.
1544 // For example, "const float" and "float" are equivalent.
1545 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
1546 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
1548 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1549 if (const AtomicType
*AtomicLHS
= LHSType
->getAs
<AtomicType
>())
1550 LHSType
= AtomicLHS
->getValueType();
1552 // If both types are identical, no conversion is needed.
1553 if (Context
.hasSameType(LHSType
, RHSType
))
1554 return Context
.getCommonSugaredType(LHSType
, RHSType
);
1556 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1557 // The caller can deal with this (e.g. pointer + int).
1558 if (!LHSType
->isArithmeticType() || !RHSType
->isArithmeticType())
1561 // Apply unary and bitfield promotions to the LHS's type.
1562 QualType LHSUnpromotedType
= LHSType
;
1563 if (Context
.isPromotableIntegerType(LHSType
))
1564 LHSType
= Context
.getPromotedIntegerType(LHSType
);
1565 QualType LHSBitfieldPromoteTy
= Context
.isPromotableBitField(LHS
.get());
1566 if (!LHSBitfieldPromoteTy
.isNull())
1567 LHSType
= LHSBitfieldPromoteTy
;
1568 if (LHSType
!= LHSUnpromotedType
&& ACK
!= ACK_CompAssign
)
1569 LHS
= ImpCastExprToType(LHS
.get(), LHSType
, CK_IntegralCast
);
1571 // If both types are identical, no conversion is needed.
1572 if (Context
.hasSameType(LHSType
, RHSType
))
1573 return Context
.getCommonSugaredType(LHSType
, RHSType
);
1575 // At this point, we have two different arithmetic types.
1577 // Diagnose attempts to convert between __ibm128, __float128 and long double
1578 // where such conversions currently can't be handled.
1579 if (unsupportedTypeConversion(*this, LHSType
, RHSType
))
1582 // Handle complex types first (C99 6.3.1.8p1).
1583 if (LHSType
->isComplexType() || RHSType
->isComplexType())
1584 return handleComplexConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1585 ACK
== ACK_CompAssign
);
1587 // Now handle "real" floating types (i.e. float, double, long double).
1588 if (LHSType
->isRealFloatingType() || RHSType
->isRealFloatingType())
1589 return handleFloatConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1590 ACK
== ACK_CompAssign
);
1592 // Handle GCC complex int extension.
1593 if (LHSType
->isComplexIntegerType() || RHSType
->isComplexIntegerType())
1594 return handleComplexIntConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1595 ACK
== ACK_CompAssign
);
1597 if (LHSType
->isFixedPointType() || RHSType
->isFixedPointType())
1598 return handleFixedPointConversion(*this, LHSType
, RHSType
);
1600 // Finally, we have two differing integer types.
1601 return handleIntegerConversion
<doIntegralCast
, doIntegralCast
>
1602 (*this, LHS
, RHS
, LHSType
, RHSType
, ACK
== ACK_CompAssign
);
1605 //===----------------------------------------------------------------------===//
1606 // Semantic Analysis for various Expression Types
1607 //===----------------------------------------------------------------------===//
1611 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc
,
1612 SourceLocation DefaultLoc
,
1613 SourceLocation RParenLoc
,
1614 Expr
*ControllingExpr
,
1615 ArrayRef
<ParsedType
> ArgTypes
,
1616 ArrayRef
<Expr
*> ArgExprs
) {
1617 unsigned NumAssocs
= ArgTypes
.size();
1618 assert(NumAssocs
== ArgExprs
.size());
1620 TypeSourceInfo
**Types
= new TypeSourceInfo
*[NumAssocs
];
1621 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1623 (void) GetTypeFromParser(ArgTypes
[i
], &Types
[i
]);
1629 CreateGenericSelectionExpr(KeyLoc
, DefaultLoc
, RParenLoc
, ControllingExpr
,
1630 llvm::ArrayRef(Types
, NumAssocs
), ArgExprs
);
1636 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc
,
1637 SourceLocation DefaultLoc
,
1638 SourceLocation RParenLoc
,
1639 Expr
*ControllingExpr
,
1640 ArrayRef
<TypeSourceInfo
*> Types
,
1641 ArrayRef
<Expr
*> Exprs
) {
1642 unsigned NumAssocs
= Types
.size();
1643 assert(NumAssocs
== Exprs
.size());
1645 // Decay and strip qualifiers for the controlling expression type, and handle
1646 // placeholder type replacement. See committee discussion from WG14 DR423.
1648 EnterExpressionEvaluationContext
Unevaluated(
1649 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
1650 ExprResult R
= DefaultFunctionArrayLvalueConversion(ControllingExpr
);
1653 ControllingExpr
= R
.get();
1656 bool TypeErrorFound
= false,
1657 IsResultDependent
= ControllingExpr
->isTypeDependent(),
1658 ContainsUnexpandedParameterPack
1659 = ControllingExpr
->containsUnexpandedParameterPack();
1661 // The controlling expression is an unevaluated operand, so side effects are
1662 // likely unintended.
1663 if (!inTemplateInstantiation() && !IsResultDependent
&&
1664 ControllingExpr
->HasSideEffects(Context
, false))
1665 Diag(ControllingExpr
->getExprLoc(),
1666 diag::warn_side_effects_unevaluated_context
);
1668 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1669 if (Exprs
[i
]->containsUnexpandedParameterPack())
1670 ContainsUnexpandedParameterPack
= true;
1673 if (Types
[i
]->getType()->containsUnexpandedParameterPack())
1674 ContainsUnexpandedParameterPack
= true;
1676 if (Types
[i
]->getType()->isDependentType()) {
1677 IsResultDependent
= true;
1679 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1680 // complete object type other than a variably modified type."
1682 if (Types
[i
]->getType()->isIncompleteType())
1683 D
= diag::err_assoc_type_incomplete
;
1684 else if (!Types
[i
]->getType()->isObjectType())
1685 D
= diag::err_assoc_type_nonobject
;
1686 else if (Types
[i
]->getType()->isVariablyModifiedType())
1687 D
= diag::err_assoc_type_variably_modified
;
1689 // Because the controlling expression undergoes lvalue conversion,
1690 // array conversion, and function conversion, an association which is
1691 // of array type, function type, or is qualified can never be
1692 // reached. We will warn about this so users are less surprised by
1693 // the unreachable association. However, we don't have to handle
1694 // function types; that's not an object type, so it's handled above.
1696 // The logic is somewhat different for C++ because C++ has different
1697 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1698 // If T is a non-class type, the type of the prvalue is the cv-
1699 // unqualified version of T. Otherwise, the type of the prvalue is T.
1700 // The result of these rules is that all qualified types in an
1701 // association in C are unreachable, and in C++, only qualified non-
1702 // class types are unreachable.
1703 unsigned Reason
= 0;
1704 QualType QT
= Types
[i
]->getType();
1705 if (QT
->isArrayType())
1707 else if (QT
.hasQualifiers() &&
1708 (!LangOpts
.CPlusPlus
|| !QT
->isRecordType()))
1712 Diag(Types
[i
]->getTypeLoc().getBeginLoc(),
1713 diag::warn_unreachable_association
)
1714 << QT
<< (Reason
- 1);
1718 Diag(Types
[i
]->getTypeLoc().getBeginLoc(), D
)
1719 << Types
[i
]->getTypeLoc().getSourceRange()
1720 << Types
[i
]->getType();
1721 TypeErrorFound
= true;
1724 // C11 6.5.1.1p2 "No two generic associations in the same generic
1725 // selection shall specify compatible types."
1726 for (unsigned j
= i
+1; j
< NumAssocs
; ++j
)
1727 if (Types
[j
] && !Types
[j
]->getType()->isDependentType() &&
1728 Context
.typesAreCompatible(Types
[i
]->getType(),
1729 Types
[j
]->getType())) {
1730 Diag(Types
[j
]->getTypeLoc().getBeginLoc(),
1731 diag::err_assoc_compatible_types
)
1732 << Types
[j
]->getTypeLoc().getSourceRange()
1733 << Types
[j
]->getType()
1734 << Types
[i
]->getType();
1735 Diag(Types
[i
]->getTypeLoc().getBeginLoc(),
1736 diag::note_compat_assoc
)
1737 << Types
[i
]->getTypeLoc().getSourceRange()
1738 << Types
[i
]->getType();
1739 TypeErrorFound
= true;
1747 // If we determined that the generic selection is result-dependent, don't
1748 // try to compute the result expression.
1749 if (IsResultDependent
)
1750 return GenericSelectionExpr::Create(Context
, KeyLoc
, ControllingExpr
, Types
,
1751 Exprs
, DefaultLoc
, RParenLoc
,
1752 ContainsUnexpandedParameterPack
);
1754 SmallVector
<unsigned, 1> CompatIndices
;
1755 unsigned DefaultIndex
= -1U;
1756 // Look at the canonical type of the controlling expression in case it was a
1757 // deduced type like __auto_type. However, when issuing diagnostics, use the
1758 // type the user wrote in source rather than the canonical one.
1759 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1762 else if (Context
.typesAreCompatible(
1763 ControllingExpr
->getType().getCanonicalType(),
1764 Types
[i
]->getType()))
1765 CompatIndices
.push_back(i
);
1768 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1769 // type compatible with at most one of the types named in its generic
1770 // association list."
1771 if (CompatIndices
.size() > 1) {
1772 // We strip parens here because the controlling expression is typically
1773 // parenthesized in macro definitions.
1774 ControllingExpr
= ControllingExpr
->IgnoreParens();
1775 Diag(ControllingExpr
->getBeginLoc(), diag::err_generic_sel_multi_match
)
1776 << ControllingExpr
->getSourceRange() << ControllingExpr
->getType()
1777 << (unsigned)CompatIndices
.size();
1778 for (unsigned I
: CompatIndices
) {
1779 Diag(Types
[I
]->getTypeLoc().getBeginLoc(),
1780 diag::note_compat_assoc
)
1781 << Types
[I
]->getTypeLoc().getSourceRange()
1782 << Types
[I
]->getType();
1787 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1788 // its controlling expression shall have type compatible with exactly one of
1789 // the types named in its generic association list."
1790 if (DefaultIndex
== -1U && CompatIndices
.size() == 0) {
1791 // We strip parens here because the controlling expression is typically
1792 // parenthesized in macro definitions.
1793 ControllingExpr
= ControllingExpr
->IgnoreParens();
1794 Diag(ControllingExpr
->getBeginLoc(), diag::err_generic_sel_no_match
)
1795 << ControllingExpr
->getSourceRange() << ControllingExpr
->getType();
1799 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1800 // type name that is compatible with the type of the controlling expression,
1801 // then the result expression of the generic selection is the expression
1802 // in that generic association. Otherwise, the result expression of the
1803 // generic selection is the expression in the default generic association."
1804 unsigned ResultIndex
=
1805 CompatIndices
.size() ? CompatIndices
[0] : DefaultIndex
;
1807 return GenericSelectionExpr::Create(
1808 Context
, KeyLoc
, ControllingExpr
, Types
, Exprs
, DefaultLoc
, RParenLoc
,
1809 ContainsUnexpandedParameterPack
, ResultIndex
);
1812 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1813 /// location of the token and the offset of the ud-suffix within it.
1814 static SourceLocation
getUDSuffixLoc(Sema
&S
, SourceLocation TokLoc
,
1816 return Lexer::AdvanceToTokenCharacter(TokLoc
, Offset
, S
.getSourceManager(),
1820 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1821 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1822 static ExprResult
BuildCookedLiteralOperatorCall(Sema
&S
, Scope
*Scope
,
1823 IdentifierInfo
*UDSuffix
,
1824 SourceLocation UDSuffixLoc
,
1825 ArrayRef
<Expr
*> Args
,
1826 SourceLocation LitEndLoc
) {
1827 assert(Args
.size() <= 2 && "too many arguments for literal operator");
1830 for (unsigned ArgIdx
= 0; ArgIdx
!= Args
.size(); ++ArgIdx
) {
1831 ArgTy
[ArgIdx
] = Args
[ArgIdx
]->getType();
1832 if (ArgTy
[ArgIdx
]->isArrayType())
1833 ArgTy
[ArgIdx
] = S
.Context
.getArrayDecayedType(ArgTy
[ArgIdx
]);
1836 DeclarationName OpName
=
1837 S
.Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
1838 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
1839 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
1841 LookupResult
R(S
, OpName
, UDSuffixLoc
, Sema::LookupOrdinaryName
);
1842 if (S
.LookupLiteralOperator(Scope
, R
, llvm::ArrayRef(ArgTy
, Args
.size()),
1843 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1844 /*AllowStringTemplatePack*/ false,
1845 /*DiagnoseMissing*/ true) == Sema::LOLR_Error
)
1848 return S
.BuildLiteralOperatorCall(R
, OpNameInfo
, Args
, LitEndLoc
);
1851 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1852 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1853 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1854 /// multiple tokens. However, the common case is that StringToks points to one
1858 Sema::ActOnStringLiteral(ArrayRef
<Token
> StringToks
, Scope
*UDLScope
) {
1859 assert(!StringToks
.empty() && "Must have at least one string!");
1861 StringLiteralParser
Literal(StringToks
, PP
);
1862 if (Literal
.hadError
)
1865 SmallVector
<SourceLocation
, 4> StringTokLocs
;
1866 for (const Token
&Tok
: StringToks
)
1867 StringTokLocs
.push_back(Tok
.getLocation());
1869 QualType CharTy
= Context
.CharTy
;
1870 StringLiteral::StringKind Kind
= StringLiteral::Ordinary
;
1871 if (Literal
.isWide()) {
1872 CharTy
= Context
.getWideCharType();
1873 Kind
= StringLiteral::Wide
;
1874 } else if (Literal
.isUTF8()) {
1875 if (getLangOpts().Char8
)
1876 CharTy
= Context
.Char8Ty
;
1877 Kind
= StringLiteral::UTF8
;
1878 } else if (Literal
.isUTF16()) {
1879 CharTy
= Context
.Char16Ty
;
1880 Kind
= StringLiteral::UTF16
;
1881 } else if (Literal
.isUTF32()) {
1882 CharTy
= Context
.Char32Ty
;
1883 Kind
= StringLiteral::UTF32
;
1884 } else if (Literal
.isPascal()) {
1885 CharTy
= Context
.UnsignedCharTy
;
1888 // Warn on initializing an array of char from a u8 string literal; this
1889 // becomes ill-formed in C++2a.
1890 if (getLangOpts().CPlusPlus
&& !getLangOpts().CPlusPlus20
&&
1891 !getLangOpts().Char8
&& Kind
== StringLiteral::UTF8
) {
1892 Diag(StringTokLocs
.front(), diag::warn_cxx20_compat_utf8_string
);
1894 // Create removals for all 'u8' prefixes in the string literal(s). This
1895 // ensures C++2a compatibility (but may change the program behavior when
1896 // built by non-Clang compilers for which the execution character set is
1897 // not always UTF-8).
1898 auto RemovalDiag
= PDiag(diag::note_cxx20_compat_utf8_string_remove_u8
);
1899 SourceLocation RemovalDiagLoc
;
1900 for (const Token
&Tok
: StringToks
) {
1901 if (Tok
.getKind() == tok::utf8_string_literal
) {
1902 if (RemovalDiagLoc
.isInvalid())
1903 RemovalDiagLoc
= Tok
.getLocation();
1904 RemovalDiag
<< FixItHint::CreateRemoval(CharSourceRange::getCharRange(
1906 Lexer::AdvanceToTokenCharacter(Tok
.getLocation(), 2,
1907 getSourceManager(), getLangOpts())));
1910 Diag(RemovalDiagLoc
, RemovalDiag
);
1914 Context
.getStringLiteralArrayType(CharTy
, Literal
.GetNumStringChars());
1916 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1917 StringLiteral
*Lit
= StringLiteral::Create(Context
, Literal
.GetString(),
1918 Kind
, Literal
.Pascal
, StrTy
,
1920 StringTokLocs
.size());
1921 if (Literal
.getUDSuffix().empty())
1924 // We're building a user-defined literal.
1925 IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
1926 SourceLocation UDSuffixLoc
=
1927 getUDSuffixLoc(*this, StringTokLocs
[Literal
.getUDSuffixToken()],
1928 Literal
.getUDSuffixOffset());
1930 // Make sure we're allowed user-defined literals here.
1932 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_string_udl
));
1934 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1935 // operator "" X (str, len)
1936 QualType SizeType
= Context
.getSizeType();
1938 DeclarationName OpName
=
1939 Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
1940 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
1941 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
1943 QualType ArgTy
[] = {
1944 Context
.getArrayDecayedType(StrTy
), SizeType
1947 LookupResult
R(*this, OpName
, UDSuffixLoc
, LookupOrdinaryName
);
1948 switch (LookupLiteralOperator(UDLScope
, R
, ArgTy
,
1949 /*AllowRaw*/ false, /*AllowTemplate*/ true,
1950 /*AllowStringTemplatePack*/ true,
1951 /*DiagnoseMissing*/ true, Lit
)) {
1954 llvm::APInt
Len(Context
.getIntWidth(SizeType
), Literal
.GetNumStringChars());
1955 IntegerLiteral
*LenArg
= IntegerLiteral::Create(Context
, Len
, SizeType
,
1957 Expr
*Args
[] = { Lit
, LenArg
};
1959 return BuildLiteralOperatorCall(R
, OpNameInfo
, Args
, StringTokLocs
.back());
1962 case LOLR_Template
: {
1963 TemplateArgumentListInfo ExplicitArgs
;
1964 TemplateArgument
Arg(Lit
);
1965 TemplateArgumentLocInfo
ArgInfo(Lit
);
1966 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
1967 return BuildLiteralOperatorCall(R
, OpNameInfo
, std::nullopt
,
1968 StringTokLocs
.back(), &ExplicitArgs
);
1971 case LOLR_StringTemplatePack
: {
1972 TemplateArgumentListInfo ExplicitArgs
;
1974 unsigned CharBits
= Context
.getIntWidth(CharTy
);
1975 bool CharIsUnsigned
= CharTy
->isUnsignedIntegerType();
1976 llvm::APSInt
Value(CharBits
, CharIsUnsigned
);
1978 TemplateArgument
TypeArg(CharTy
);
1979 TemplateArgumentLocInfo
TypeArgInfo(Context
.getTrivialTypeSourceInfo(CharTy
));
1980 ExplicitArgs
.addArgument(TemplateArgumentLoc(TypeArg
, TypeArgInfo
));
1982 for (unsigned I
= 0, N
= Lit
->getLength(); I
!= N
; ++I
) {
1983 Value
= Lit
->getCodeUnit(I
);
1984 TemplateArgument
Arg(Context
, Value
, CharTy
);
1985 TemplateArgumentLocInfo ArgInfo
;
1986 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
1988 return BuildLiteralOperatorCall(R
, OpNameInfo
, std::nullopt
,
1989 StringTokLocs
.back(), &ExplicitArgs
);
1992 case LOLR_ErrorNoDiagnostic
:
1993 llvm_unreachable("unexpected literal operator lookup result");
1997 llvm_unreachable("unexpected literal operator lookup result");
2001 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2003 const CXXScopeSpec
*SS
) {
2004 DeclarationNameInfo
NameInfo(D
->getDeclName(), Loc
);
2005 return BuildDeclRefExpr(D
, Ty
, VK
, NameInfo
, SS
);
2009 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2010 const DeclarationNameInfo
&NameInfo
,
2011 const CXXScopeSpec
*SS
, NamedDecl
*FoundD
,
2012 SourceLocation TemplateKWLoc
,
2013 const TemplateArgumentListInfo
*TemplateArgs
) {
2014 NestedNameSpecifierLoc NNS
=
2015 SS
? SS
->getWithLocInContext(Context
) : NestedNameSpecifierLoc();
2016 return BuildDeclRefExpr(D
, Ty
, VK
, NameInfo
, NNS
, FoundD
, TemplateKWLoc
,
2020 // CUDA/HIP: Check whether a captured reference variable is referencing a
2021 // host variable in a device or host device lambda.
2022 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema
&S
,
2024 if (!S
.getLangOpts().CUDA
|| !VD
->hasInit())
2026 assert(VD
->getType()->isReferenceType());
2028 // Check whether the reference variable is referencing a host variable.
2029 auto *DRE
= dyn_cast
<DeclRefExpr
>(VD
->getInit());
2032 auto *Referee
= dyn_cast
<VarDecl
>(DRE
->getDecl());
2033 if (!Referee
|| !Referee
->hasGlobalStorage() ||
2034 Referee
->hasAttr
<CUDADeviceAttr
>())
2037 // Check whether the current function is a device or host device lambda.
2038 // Check whether the reference variable is a capture by getDeclContext()
2039 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2040 auto *MD
= dyn_cast_or_null
<CXXMethodDecl
>(S
.CurContext
);
2041 if (MD
&& MD
->getParent()->isLambda() &&
2042 MD
->getOverloadedOperator() == OO_Call
&& MD
->hasAttr
<CUDADeviceAttr
>() &&
2043 VD
->getDeclContext() != MD
)
2049 NonOdrUseReason
Sema::getNonOdrUseReasonInCurrentContext(ValueDecl
*D
) {
2050 // A declaration named in an unevaluated operand never constitutes an odr-use.
2051 if (isUnevaluatedContext())
2052 return NOUR_Unevaluated
;
2054 // C++2a [basic.def.odr]p4:
2055 // A variable x whose name appears as a potentially-evaluated expression e
2056 // is odr-used by e unless [...] x is a reference that is usable in
2057 // constant expressions.
2059 // If a reference variable referencing a host variable is captured in a
2060 // device or host device lambda, the value of the referee must be copied
2061 // to the capture and the reference variable must be treated as odr-use
2062 // since the value of the referee is not known at compile time and must
2063 // be loaded from the captured.
2064 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2065 if (VD
->getType()->isReferenceType() &&
2066 !(getLangOpts().OpenMP
&& isOpenMPCapturedDecl(D
)) &&
2067 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD
) &&
2068 VD
->isUsableInConstantExpressions(Context
))
2069 return NOUR_Constant
;
2072 // All remaining non-variable cases constitute an odr-use. For variables, we
2073 // need to wait and see how the expression is used.
2077 /// BuildDeclRefExpr - Build an expression that references a
2078 /// declaration that does not require a closure capture.
2080 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2081 const DeclarationNameInfo
&NameInfo
,
2082 NestedNameSpecifierLoc NNS
, NamedDecl
*FoundD
,
2083 SourceLocation TemplateKWLoc
,
2084 const TemplateArgumentListInfo
*TemplateArgs
) {
2085 bool RefersToCapturedVariable
= isa
<VarDecl
, BindingDecl
>(D
) &&
2086 NeedToCaptureVariable(D
, NameInfo
.getLoc());
2088 DeclRefExpr
*E
= DeclRefExpr::Create(
2089 Context
, NNS
, TemplateKWLoc
, D
, RefersToCapturedVariable
, NameInfo
, Ty
,
2090 VK
, FoundD
, TemplateArgs
, getNonOdrUseReasonInCurrentContext(D
));
2091 MarkDeclRefReferenced(E
);
2093 // C++ [except.spec]p17:
2094 // An exception-specification is considered to be needed when:
2095 // - in an expression, the function is the unique lookup result or
2096 // the selected member of a set of overloaded functions.
2098 // We delay doing this until after we've built the function reference and
2099 // marked it as used so that:
2100 // a) if the function is defaulted, we get errors from defining it before /
2101 // instead of errors from computing its exception specification, and
2102 // b) if the function is a defaulted comparison, we can use the body we
2103 // build when defining it as input to the exception specification
2104 // computation rather than computing a new body.
2105 if (auto *FPT
= Ty
->getAs
<FunctionProtoType
>()) {
2106 if (isUnresolvedExceptionSpec(FPT
->getExceptionSpecType())) {
2107 if (auto *NewFPT
= ResolveExceptionSpec(NameInfo
.getLoc(), FPT
))
2108 E
->setType(Context
.getQualifiedType(NewFPT
, Ty
.getQualifiers()));
2112 if (getLangOpts().ObjCWeak
&& isa
<VarDecl
>(D
) &&
2113 Ty
.getObjCLifetime() == Qualifiers::OCL_Weak
&& !isUnevaluatedContext() &&
2114 !Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
, E
->getBeginLoc()))
2115 getCurFunction()->recordUseOfWeak(E
);
2117 FieldDecl
*FD
= dyn_cast
<FieldDecl
>(D
);
2118 if (IndirectFieldDecl
*IFD
= dyn_cast
<IndirectFieldDecl
>(D
))
2119 FD
= IFD
->getAnonField();
2121 UnusedPrivateFields
.remove(FD
);
2122 // Just in case we're building an illegal pointer-to-member.
2123 if (FD
->isBitField())
2124 E
->setObjectKind(OK_BitField
);
2127 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2128 // designates a bit-field.
2129 if (auto *BD
= dyn_cast
<BindingDecl
>(D
))
2130 if (auto *BE
= BD
->getBinding())
2131 E
->setObjectKind(BE
->getObjectKind());
2136 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2137 /// possibly a list of template arguments.
2139 /// If this produces template arguments, it is permitted to call
2140 /// DecomposeTemplateName.
2142 /// This actually loses a lot of source location information for
2143 /// non-standard name kinds; we should consider preserving that in
2146 Sema::DecomposeUnqualifiedId(const UnqualifiedId
&Id
,
2147 TemplateArgumentListInfo
&Buffer
,
2148 DeclarationNameInfo
&NameInfo
,
2149 const TemplateArgumentListInfo
*&TemplateArgs
) {
2150 if (Id
.getKind() == UnqualifiedIdKind::IK_TemplateId
) {
2151 Buffer
.setLAngleLoc(Id
.TemplateId
->LAngleLoc
);
2152 Buffer
.setRAngleLoc(Id
.TemplateId
->RAngleLoc
);
2154 ASTTemplateArgsPtr
TemplateArgsPtr(Id
.TemplateId
->getTemplateArgs(),
2155 Id
.TemplateId
->NumArgs
);
2156 translateTemplateArguments(TemplateArgsPtr
, Buffer
);
2158 TemplateName TName
= Id
.TemplateId
->Template
.get();
2159 SourceLocation TNameLoc
= Id
.TemplateId
->TemplateNameLoc
;
2160 NameInfo
= Context
.getNameForTemplate(TName
, TNameLoc
);
2161 TemplateArgs
= &Buffer
;
2163 NameInfo
= GetNameFromUnqualifiedId(Id
);
2164 TemplateArgs
= nullptr;
2168 static void emitEmptyLookupTypoDiagnostic(
2169 const TypoCorrection
&TC
, Sema
&SemaRef
, const CXXScopeSpec
&SS
,
2170 DeclarationName Typo
, SourceLocation TypoLoc
, ArrayRef
<Expr
*> Args
,
2171 unsigned DiagnosticID
, unsigned DiagnosticSuggestID
) {
2173 SS
.isEmpty() ? nullptr : SemaRef
.computeDeclContext(SS
, false);
2175 // Emit a special diagnostic for failed member lookups.
2176 // FIXME: computing the declaration context might fail here (?)
2178 SemaRef
.Diag(TypoLoc
, diag::err_no_member
) << Typo
<< Ctx
2181 SemaRef
.Diag(TypoLoc
, DiagnosticID
) << Typo
;
2185 std::string CorrectedStr
= TC
.getAsString(SemaRef
.getLangOpts());
2186 bool DroppedSpecifier
=
2187 TC
.WillReplaceSpecifier() && Typo
.getAsString() == CorrectedStr
;
2188 unsigned NoteID
= TC
.getCorrectionDeclAs
<ImplicitParamDecl
>()
2189 ? diag::note_implicit_param_decl
2190 : diag::note_previous_decl
;
2192 SemaRef
.diagnoseTypo(TC
, SemaRef
.PDiag(DiagnosticSuggestID
) << Typo
,
2193 SemaRef
.PDiag(NoteID
));
2195 SemaRef
.diagnoseTypo(TC
, SemaRef
.PDiag(diag::err_no_member_suggest
)
2196 << Typo
<< Ctx
<< DroppedSpecifier
2198 SemaRef
.PDiag(NoteID
));
2201 /// Diagnose a lookup that found results in an enclosing class during error
2202 /// recovery. This usually indicates that the results were found in a dependent
2203 /// base class that could not be searched as part of a template definition.
2204 /// Always issues a diagnostic (though this may be only a warning in MS
2205 /// compatibility mode).
2207 /// Return \c true if the error is unrecoverable, or \c false if the caller
2208 /// should attempt to recover using these lookup results.
2209 bool Sema::DiagnoseDependentMemberLookup(LookupResult
&R
) {
2210 // During a default argument instantiation the CurContext points
2211 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2212 // function parameter list, hence add an explicit check.
2213 bool isDefaultArgument
=
2214 !CodeSynthesisContexts
.empty() &&
2215 CodeSynthesisContexts
.back().Kind
==
2216 CodeSynthesisContext::DefaultFunctionArgumentInstantiation
;
2217 CXXMethodDecl
*CurMethod
= dyn_cast
<CXXMethodDecl
>(CurContext
);
2218 bool isInstance
= CurMethod
&& CurMethod
->isInstance() &&
2219 R
.getNamingClass() == CurMethod
->getParent() &&
2222 // There are two ways we can find a class-scope declaration during template
2223 // instantiation that we did not find in the template definition: if it is a
2224 // member of a dependent base class, or if it is declared after the point of
2225 // use in the same class. Distinguish these by comparing the class in which
2226 // the member was found to the naming class of the lookup.
2227 unsigned DiagID
= diag::err_found_in_dependent_base
;
2228 unsigned NoteID
= diag::note_member_declared_at
;
2229 if (R
.getRepresentativeDecl()->getDeclContext()->Equals(R
.getNamingClass())) {
2230 DiagID
= getLangOpts().MSVCCompat
? diag::ext_found_later_in_class
2231 : diag::err_found_later_in_class
;
2232 } else if (getLangOpts().MSVCCompat
) {
2233 DiagID
= diag::ext_found_in_dependent_base
;
2234 NoteID
= diag::note_dependent_member_use
;
2238 // Give a code modification hint to insert 'this->'.
2239 Diag(R
.getNameLoc(), DiagID
)
2240 << R
.getLookupName()
2241 << FixItHint::CreateInsertion(R
.getNameLoc(), "this->");
2242 CheckCXXThisCapture(R
.getNameLoc());
2244 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2245 // they're not shadowed).
2246 Diag(R
.getNameLoc(), DiagID
) << R
.getLookupName();
2249 for (NamedDecl
*D
: R
)
2250 Diag(D
->getLocation(), NoteID
);
2252 // Return true if we are inside a default argument instantiation
2253 // and the found name refers to an instance member function, otherwise
2254 // the caller will try to create an implicit member call and this is wrong
2255 // for default arguments.
2257 // FIXME: Is this special case necessary? We could allow the caller to
2259 if (isDefaultArgument
&& ((*R
.begin())->isCXXInstanceMember())) {
2260 Diag(R
.getNameLoc(), diag::err_member_call_without_object
);
2264 // Tell the callee to try to recover.
2268 /// Diagnose an empty lookup.
2270 /// \return false if new lookup candidates were found
2271 bool Sema::DiagnoseEmptyLookup(Scope
*S
, CXXScopeSpec
&SS
, LookupResult
&R
,
2272 CorrectionCandidateCallback
&CCC
,
2273 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
2274 ArrayRef
<Expr
*> Args
, TypoExpr
**Out
) {
2275 DeclarationName Name
= R
.getLookupName();
2277 unsigned diagnostic
= diag::err_undeclared_var_use
;
2278 unsigned diagnostic_suggest
= diag::err_undeclared_var_use_suggest
;
2279 if (Name
.getNameKind() == DeclarationName::CXXOperatorName
||
2280 Name
.getNameKind() == DeclarationName::CXXLiteralOperatorName
||
2281 Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
) {
2282 diagnostic
= diag::err_undeclared_use
;
2283 diagnostic_suggest
= diag::err_undeclared_use_suggest
;
2286 // If the original lookup was an unqualified lookup, fake an
2287 // unqualified lookup. This is useful when (for example) the
2288 // original lookup would not have found something because it was a
2290 DeclContext
*DC
= SS
.isEmpty() ? CurContext
: nullptr;
2292 if (isa
<CXXRecordDecl
>(DC
)) {
2293 LookupQualifiedName(R
, DC
);
2296 // Don't give errors about ambiguities in this lookup.
2297 R
.suppressDiagnostics();
2299 // If there's a best viable function among the results, only mention
2300 // that one in the notes.
2301 OverloadCandidateSet
Candidates(R
.getNameLoc(),
2302 OverloadCandidateSet::CSK_Normal
);
2303 AddOverloadedCallCandidates(R
, ExplicitTemplateArgs
, Args
, Candidates
);
2304 OverloadCandidateSet::iterator Best
;
2305 if (Candidates
.BestViableFunction(*this, R
.getNameLoc(), Best
) ==
2308 R
.addDecl(Best
->FoundDecl
.getDecl(), Best
->FoundDecl
.getAccess());
2312 return DiagnoseDependentMemberLookup(R
);
2318 DC
= DC
->getLookupParent();
2321 // We didn't find anything, so try to correct for a typo.
2322 TypoCorrection Corrected
;
2324 SourceLocation TypoLoc
= R
.getNameLoc();
2325 assert(!ExplicitTemplateArgs
&&
2326 "Diagnosing an empty lookup with explicit template args!");
2327 *Out
= CorrectTypoDelayed(
2328 R
.getLookupNameInfo(), R
.getLookupKind(), S
, &SS
, CCC
,
2329 [=](const TypoCorrection
&TC
) {
2330 emitEmptyLookupTypoDiagnostic(TC
, *this, SS
, Name
, TypoLoc
, Args
,
2331 diagnostic
, diagnostic_suggest
);
2333 nullptr, CTK_ErrorRecovery
);
2337 (Corrected
= CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(),
2338 S
, &SS
, CCC
, CTK_ErrorRecovery
))) {
2339 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
2340 bool DroppedSpecifier
=
2341 Corrected
.WillReplaceSpecifier() && Name
.getAsString() == CorrectedStr
;
2342 R
.setLookupName(Corrected
.getCorrection());
2344 bool AcceptableWithRecovery
= false;
2345 bool AcceptableWithoutRecovery
= false;
2346 NamedDecl
*ND
= Corrected
.getFoundDecl();
2348 if (Corrected
.isOverloaded()) {
2349 OverloadCandidateSet
OCS(R
.getNameLoc(),
2350 OverloadCandidateSet::CSK_Normal
);
2351 OverloadCandidateSet::iterator Best
;
2352 for (NamedDecl
*CD
: Corrected
) {
2353 if (FunctionTemplateDecl
*FTD
=
2354 dyn_cast
<FunctionTemplateDecl
>(CD
))
2355 AddTemplateOverloadCandidate(
2356 FTD
, DeclAccessPair::make(FTD
, AS_none
), ExplicitTemplateArgs
,
2358 else if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(CD
))
2359 if (!ExplicitTemplateArgs
|| ExplicitTemplateArgs
->size() == 0)
2360 AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, AS_none
),
2363 switch (OCS
.BestViableFunction(*this, R
.getNameLoc(), Best
)) {
2365 ND
= Best
->FoundDecl
;
2366 Corrected
.setCorrectionDecl(ND
);
2369 // FIXME: Arbitrarily pick the first declaration for the note.
2370 Corrected
.setCorrectionDecl(ND
);
2375 if (getLangOpts().CPlusPlus
&& ND
->isCXXClassMember()) {
2376 CXXRecordDecl
*Record
= nullptr;
2377 if (Corrected
.getCorrectionSpecifier()) {
2378 const Type
*Ty
= Corrected
.getCorrectionSpecifier()->getAsType();
2379 Record
= Ty
->getAsCXXRecordDecl();
2382 Record
= cast
<CXXRecordDecl
>(
2383 ND
->getDeclContext()->getRedeclContext());
2384 R
.setNamingClass(Record
);
2387 auto *UnderlyingND
= ND
->getUnderlyingDecl();
2388 AcceptableWithRecovery
= isa
<ValueDecl
>(UnderlyingND
) ||
2389 isa
<FunctionTemplateDecl
>(UnderlyingND
);
2390 // FIXME: If we ended up with a typo for a type name or
2391 // Objective-C class name, we're in trouble because the parser
2392 // is in the wrong place to recover. Suggest the typo
2393 // correction, but don't make it a fix-it since we're not going
2394 // to recover well anyway.
2395 AcceptableWithoutRecovery
= isa
<TypeDecl
>(UnderlyingND
) ||
2396 getAsTypeTemplateDecl(UnderlyingND
) ||
2397 isa
<ObjCInterfaceDecl
>(UnderlyingND
);
2399 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2400 // because we aren't able to recover.
2401 AcceptableWithoutRecovery
= true;
2404 if (AcceptableWithRecovery
|| AcceptableWithoutRecovery
) {
2405 unsigned NoteID
= Corrected
.getCorrectionDeclAs
<ImplicitParamDecl
>()
2406 ? diag::note_implicit_param_decl
2407 : diag::note_previous_decl
;
2409 diagnoseTypo(Corrected
, PDiag(diagnostic_suggest
) << Name
,
2410 PDiag(NoteID
), AcceptableWithRecovery
);
2412 diagnoseTypo(Corrected
, PDiag(diag::err_no_member_suggest
)
2413 << Name
<< computeDeclContext(SS
, false)
2414 << DroppedSpecifier
<< SS
.getRange(),
2415 PDiag(NoteID
), AcceptableWithRecovery
);
2417 // Tell the callee whether to try to recover.
2418 return !AcceptableWithRecovery
;
2423 // Emit a special diagnostic for failed member lookups.
2424 // FIXME: computing the declaration context might fail here (?)
2425 if (!SS
.isEmpty()) {
2426 Diag(R
.getNameLoc(), diag::err_no_member
)
2427 << Name
<< computeDeclContext(SS
, false)
2432 // Give up, we can't recover.
2433 Diag(R
.getNameLoc(), diagnostic
) << Name
;
2437 /// In Microsoft mode, if we are inside a template class whose parent class has
2438 /// dependent base classes, and we can't resolve an unqualified identifier, then
2439 /// assume the identifier is a member of a dependent base class. We can only
2440 /// recover successfully in static methods, instance methods, and other contexts
2441 /// where 'this' is available. This doesn't precisely match MSVC's
2442 /// instantiation model, but it's close enough.
2444 recoverFromMSUnqualifiedLookup(Sema
&S
, ASTContext
&Context
,
2445 DeclarationNameInfo
&NameInfo
,
2446 SourceLocation TemplateKWLoc
,
2447 const TemplateArgumentListInfo
*TemplateArgs
) {
2448 // Only try to recover from lookup into dependent bases in static methods or
2449 // contexts where 'this' is available.
2450 QualType ThisType
= S
.getCurrentThisType();
2451 const CXXRecordDecl
*RD
= nullptr;
2452 if (!ThisType
.isNull())
2453 RD
= ThisType
->getPointeeType()->getAsCXXRecordDecl();
2454 else if (auto *MD
= dyn_cast
<CXXMethodDecl
>(S
.CurContext
))
2455 RD
= MD
->getParent();
2456 if (!RD
|| !RD
->hasAnyDependentBases())
2459 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2460 // is available, suggest inserting 'this->' as a fixit.
2461 SourceLocation Loc
= NameInfo
.getLoc();
2462 auto DB
= S
.Diag(Loc
, diag::ext_undeclared_unqual_id_with_dependent_base
);
2463 DB
<< NameInfo
.getName() << RD
;
2465 if (!ThisType
.isNull()) {
2466 DB
<< FixItHint::CreateInsertion(Loc
, "this->");
2467 return CXXDependentScopeMemberExpr::Create(
2468 Context
, /*This=*/nullptr, ThisType
, /*IsArrow=*/true,
2469 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc
,
2470 /*FirstQualifierFoundInScope=*/nullptr, NameInfo
, TemplateArgs
);
2473 // Synthesize a fake NNS that points to the derived class. This will
2474 // perform name lookup during template instantiation.
2477 NestedNameSpecifier::Create(Context
, nullptr, true, RD
->getTypeForDecl());
2478 SS
.MakeTrivial(Context
, NNS
, SourceRange(Loc
, Loc
));
2479 return DependentScopeDeclRefExpr::Create(
2480 Context
, SS
.getWithLocInContext(Context
), TemplateKWLoc
, NameInfo
,
2485 Sema::ActOnIdExpression(Scope
*S
, CXXScopeSpec
&SS
,
2486 SourceLocation TemplateKWLoc
, UnqualifiedId
&Id
,
2487 bool HasTrailingLParen
, bool IsAddressOfOperand
,
2488 CorrectionCandidateCallback
*CCC
,
2489 bool IsInlineAsmIdentifier
, Token
*KeywordReplacement
) {
2490 assert(!(IsAddressOfOperand
&& HasTrailingLParen
) &&
2491 "cannot be direct & operand and have a trailing lparen");
2495 TemplateArgumentListInfo TemplateArgsBuffer
;
2497 // Decompose the UnqualifiedId into the following data.
2498 DeclarationNameInfo NameInfo
;
2499 const TemplateArgumentListInfo
*TemplateArgs
;
2500 DecomposeUnqualifiedId(Id
, TemplateArgsBuffer
, NameInfo
, TemplateArgs
);
2502 DeclarationName Name
= NameInfo
.getName();
2503 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
2504 SourceLocation NameLoc
= NameInfo
.getLoc();
2506 if (II
&& II
->isEditorPlaceholder()) {
2507 // FIXME: When typed placeholders are supported we can create a typed
2508 // placeholder expression node.
2512 // C++ [temp.dep.expr]p3:
2513 // An id-expression is type-dependent if it contains:
2514 // -- an identifier that was declared with a dependent type,
2515 // (note: handled after lookup)
2516 // -- a template-id that is dependent,
2517 // (note: handled in BuildTemplateIdExpr)
2518 // -- a conversion-function-id that specifies a dependent type,
2519 // -- a nested-name-specifier that contains a class-name that
2520 // names a dependent type.
2521 // Determine whether this is a member of an unknown specialization;
2522 // we need to handle these differently.
2523 bool DependentID
= false;
2524 if (Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
&&
2525 Name
.getCXXNameType()->isDependentType()) {
2527 } else if (SS
.isSet()) {
2528 if (DeclContext
*DC
= computeDeclContext(SS
, false)) {
2529 if (RequireCompleteDeclContext(SS
, DC
))
2537 return ActOnDependentIdExpression(SS
, TemplateKWLoc
, NameInfo
,
2538 IsAddressOfOperand
, TemplateArgs
);
2540 // Perform the required lookup.
2541 LookupResult
R(*this, NameInfo
,
2542 (Id
.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam
)
2543 ? LookupObjCImplicitSelfParam
2544 : LookupOrdinaryName
);
2545 if (TemplateKWLoc
.isValid() || TemplateArgs
) {
2546 // Lookup the template name again to correctly establish the context in
2547 // which it was found. This is really unfortunate as we already did the
2548 // lookup to determine that it was a template name in the first place. If
2549 // this becomes a performance hit, we can work harder to preserve those
2550 // results until we get here but it's likely not worth it.
2551 bool MemberOfUnknownSpecialization
;
2552 AssumedTemplateKind AssumedTemplate
;
2553 if (LookupTemplateName(R
, S
, SS
, QualType(), /*EnteringContext=*/false,
2554 MemberOfUnknownSpecialization
, TemplateKWLoc
,
2558 if (MemberOfUnknownSpecialization
||
2559 (R
.getResultKind() == LookupResult::NotFoundInCurrentInstantiation
))
2560 return ActOnDependentIdExpression(SS
, TemplateKWLoc
, NameInfo
,
2561 IsAddressOfOperand
, TemplateArgs
);
2563 bool IvarLookupFollowUp
= II
&& !SS
.isSet() && getCurMethodDecl();
2564 LookupParsedName(R
, S
, &SS
, !IvarLookupFollowUp
);
2566 // If the result might be in a dependent base class, this is a dependent
2568 if (R
.getResultKind() == LookupResult::NotFoundInCurrentInstantiation
)
2569 return ActOnDependentIdExpression(SS
, TemplateKWLoc
, NameInfo
,
2570 IsAddressOfOperand
, TemplateArgs
);
2572 // If this reference is in an Objective-C method, then we need to do
2573 // some special Objective-C lookup, too.
2574 if (IvarLookupFollowUp
) {
2575 ExprResult
E(LookupInObjCMethod(R
, S
, II
, true));
2579 if (Expr
*Ex
= E
.getAs
<Expr
>())
2584 if (R
.isAmbiguous())
2587 // This could be an implicitly declared function reference if the language
2588 // mode allows it as a feature.
2589 if (R
.empty() && HasTrailingLParen
&& II
&&
2590 getLangOpts().implicitFunctionsAllowed()) {
2591 NamedDecl
*D
= ImplicitlyDefineFunction(NameLoc
, *II
, S
);
2592 if (D
) R
.addDecl(D
);
2595 // Determine whether this name might be a candidate for
2596 // argument-dependent lookup.
2597 bool ADL
= UseArgumentDependentLookup(SS
, R
, HasTrailingLParen
);
2599 if (R
.empty() && !ADL
) {
2600 if (SS
.isEmpty() && getLangOpts().MSVCCompat
) {
2601 if (Expr
*E
= recoverFromMSUnqualifiedLookup(*this, Context
, NameInfo
,
2602 TemplateKWLoc
, TemplateArgs
))
2606 // Don't diagnose an empty lookup for inline assembly.
2607 if (IsInlineAsmIdentifier
)
2610 // If this name wasn't predeclared and if this is not a function
2611 // call, diagnose the problem.
2612 TypoExpr
*TE
= nullptr;
2613 DefaultFilterCCC
DefaultValidator(II
, SS
.isValid() ? SS
.getScopeRep()
2615 DefaultValidator
.IsAddressOfOperand
= IsAddressOfOperand
;
2616 assert((!CCC
|| CCC
->IsAddressOfOperand
== IsAddressOfOperand
) &&
2617 "Typo correction callback misconfigured");
2619 // Make sure the callback knows what the typo being diagnosed is.
2620 CCC
->setTypoName(II
);
2622 CCC
->setTypoNNS(SS
.getScopeRep());
2624 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2625 // a template name, but we happen to have always already looked up the name
2626 // before we get here if it must be a template name.
2627 if (DiagnoseEmptyLookup(S
, SS
, R
, CCC
? *CCC
: DefaultValidator
, nullptr,
2628 std::nullopt
, &TE
)) {
2629 if (TE
&& KeywordReplacement
) {
2630 auto &State
= getTypoExprState(TE
);
2631 auto BestTC
= State
.Consumer
->getNextCorrection();
2632 if (BestTC
.isKeyword()) {
2633 auto *II
= BestTC
.getCorrectionAsIdentifierInfo();
2634 if (State
.DiagHandler
)
2635 State
.DiagHandler(BestTC
);
2636 KeywordReplacement
->startToken();
2637 KeywordReplacement
->setKind(II
->getTokenID());
2638 KeywordReplacement
->setIdentifierInfo(II
);
2639 KeywordReplacement
->setLocation(BestTC
.getCorrectionRange().getBegin());
2640 // Clean up the state associated with the TypoExpr, since it has
2641 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2642 clearDelayedTypo(TE
);
2643 // Signal that a correction to a keyword was performed by returning a
2644 // valid-but-null ExprResult.
2645 return (Expr
*)nullptr;
2647 State
.Consumer
->resetCorrectionStream();
2649 return TE
? TE
: ExprError();
2652 assert(!R
.empty() &&
2653 "DiagnoseEmptyLookup returned false but added no results");
2655 // If we found an Objective-C instance variable, let
2656 // LookupInObjCMethod build the appropriate expression to
2657 // reference the ivar.
2658 if (ObjCIvarDecl
*Ivar
= R
.getAsSingle
<ObjCIvarDecl
>()) {
2660 ExprResult
E(LookupInObjCMethod(R
, S
, Ivar
->getIdentifier()));
2661 // In a hopelessly buggy code, Objective-C instance variable
2662 // lookup fails and no expression will be built to reference it.
2663 if (!E
.isInvalid() && !E
.get())
2669 // This is guaranteed from this point on.
2670 assert(!R
.empty() || ADL
);
2672 // Check whether this might be a C++ implicit instance member access.
2673 // C++ [class.mfct.non-static]p3:
2674 // When an id-expression that is not part of a class member access
2675 // syntax and not used to form a pointer to member is used in the
2676 // body of a non-static member function of class X, if name lookup
2677 // resolves the name in the id-expression to a non-static non-type
2678 // member of some class C, the id-expression is transformed into a
2679 // class member access expression using (*this) as the
2680 // postfix-expression to the left of the . operator.
2682 // But we don't actually need to do this for '&' operands if R
2683 // resolved to a function or overloaded function set, because the
2684 // expression is ill-formed if it actually works out to be a
2685 // non-static member function:
2687 // C++ [expr.ref]p4:
2688 // Otherwise, if E1.E2 refers to a non-static member function. . .
2689 // [t]he expression can be used only as the left-hand operand of a
2690 // member function call.
2692 // There are other safeguards against such uses, but it's important
2693 // to get this right here so that we don't end up making a
2694 // spuriously dependent expression if we're inside a dependent
2696 if (!R
.empty() && (*R
.begin())->isCXXClassMember()) {
2697 bool MightBeImplicitMember
;
2698 if (!IsAddressOfOperand
)
2699 MightBeImplicitMember
= true;
2700 else if (!SS
.isEmpty())
2701 MightBeImplicitMember
= false;
2702 else if (R
.isOverloadedResult())
2703 MightBeImplicitMember
= false;
2704 else if (R
.isUnresolvableResult())
2705 MightBeImplicitMember
= true;
2707 MightBeImplicitMember
= isa
<FieldDecl
>(R
.getFoundDecl()) ||
2708 isa
<IndirectFieldDecl
>(R
.getFoundDecl()) ||
2709 isa
<MSPropertyDecl
>(R
.getFoundDecl());
2711 if (MightBeImplicitMember
)
2712 return BuildPossibleImplicitMemberExpr(SS
, TemplateKWLoc
,
2713 R
, TemplateArgs
, S
);
2716 if (TemplateArgs
|| TemplateKWLoc
.isValid()) {
2718 // In C++1y, if this is a variable template id, then check it
2719 // in BuildTemplateIdExpr().
2720 // The single lookup result must be a variable template declaration.
2721 if (Id
.getKind() == UnqualifiedIdKind::IK_TemplateId
&& Id
.TemplateId
&&
2722 Id
.TemplateId
->Kind
== TNK_Var_template
) {
2723 assert(R
.getAsSingle
<VarTemplateDecl
>() &&
2724 "There should only be one declaration found.");
2727 return BuildTemplateIdExpr(SS
, TemplateKWLoc
, R
, ADL
, TemplateArgs
);
2730 return BuildDeclarationNameExpr(SS
, R
, ADL
);
2733 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2734 /// declaration name, generally during template instantiation.
2735 /// There's a large number of things which don't need to be done along
2737 ExprResult
Sema::BuildQualifiedDeclarationNameExpr(
2738 CXXScopeSpec
&SS
, const DeclarationNameInfo
&NameInfo
,
2739 bool IsAddressOfOperand
, const Scope
*S
, TypeSourceInfo
**RecoveryTSI
) {
2740 if (NameInfo
.getName().isDependentName())
2741 return BuildDependentDeclRefExpr(SS
, /*TemplateKWLoc=*/SourceLocation(),
2742 NameInfo
, /*TemplateArgs=*/nullptr);
2744 DeclContext
*DC
= computeDeclContext(SS
, false);
2746 return BuildDependentDeclRefExpr(SS
, /*TemplateKWLoc=*/SourceLocation(),
2747 NameInfo
, /*TemplateArgs=*/nullptr);
2749 if (RequireCompleteDeclContext(SS
, DC
))
2752 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
2753 LookupQualifiedName(R
, DC
);
2755 if (R
.isAmbiguous())
2758 if (R
.getResultKind() == LookupResult::NotFoundInCurrentInstantiation
)
2759 return BuildDependentDeclRefExpr(SS
, /*TemplateKWLoc=*/SourceLocation(),
2760 NameInfo
, /*TemplateArgs=*/nullptr);
2763 // Don't diagnose problems with invalid record decl, the secondary no_member
2764 // diagnostic during template instantiation is likely bogus, e.g. if a class
2765 // is invalid because it's derived from an invalid base class, then missing
2766 // members were likely supposed to be inherited.
2767 if (const auto *CD
= dyn_cast
<CXXRecordDecl
>(DC
))
2768 if (CD
->isInvalidDecl())
2770 Diag(NameInfo
.getLoc(), diag::err_no_member
)
2771 << NameInfo
.getName() << DC
<< SS
.getRange();
2775 if (const TypeDecl
*TD
= R
.getAsSingle
<TypeDecl
>()) {
2776 // Diagnose a missing typename if this resolved unambiguously to a type in
2777 // a dependent context. If we can recover with a type, downgrade this to
2778 // a warning in Microsoft compatibility mode.
2779 unsigned DiagID
= diag::err_typename_missing
;
2780 if (RecoveryTSI
&& getLangOpts().MSVCCompat
)
2781 DiagID
= diag::ext_typename_missing
;
2782 SourceLocation Loc
= SS
.getBeginLoc();
2783 auto D
= Diag(Loc
, DiagID
);
2784 D
<< SS
.getScopeRep() << NameInfo
.getName().getAsString()
2785 << SourceRange(Loc
, NameInfo
.getEndLoc());
2787 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2792 // Only issue the fixit if we're prepared to recover.
2793 D
<< FixItHint::CreateInsertion(Loc
, "typename ");
2795 // Recover by pretending this was an elaborated type.
2796 QualType Ty
= Context
.getTypeDeclType(TD
);
2798 TLB
.pushTypeSpec(Ty
).setNameLoc(NameInfo
.getLoc());
2800 QualType ET
= getElaboratedType(ETK_None
, SS
, Ty
);
2801 ElaboratedTypeLoc QTL
= TLB
.push
<ElaboratedTypeLoc
>(ET
);
2802 QTL
.setElaboratedKeywordLoc(SourceLocation());
2803 QTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
2805 *RecoveryTSI
= TLB
.getTypeSourceInfo(Context
, ET
);
2810 // Defend against this resolving to an implicit member access. We usually
2811 // won't get here if this might be a legitimate a class member (we end up in
2812 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2813 // a pointer-to-member or in an unevaluated context in C++11.
2814 if (!R
.empty() && (*R
.begin())->isCXXClassMember() && !IsAddressOfOperand
)
2815 return BuildPossibleImplicitMemberExpr(SS
,
2816 /*TemplateKWLoc=*/SourceLocation(),
2817 R
, /*TemplateArgs=*/nullptr, S
);
2819 return BuildDeclarationNameExpr(SS
, R
, /* ADL */ false);
2822 /// The parser has read a name in, and Sema has detected that we're currently
2823 /// inside an ObjC method. Perform some additional checks and determine if we
2824 /// should form a reference to an ivar.
2826 /// Ideally, most of this would be done by lookup, but there's
2827 /// actually quite a lot of extra work involved.
2828 DeclResult
Sema::LookupIvarInObjCMethod(LookupResult
&Lookup
, Scope
*S
,
2829 IdentifierInfo
*II
) {
2830 SourceLocation Loc
= Lookup
.getNameLoc();
2831 ObjCMethodDecl
*CurMethod
= getCurMethodDecl();
2833 // Check for error condition which is already reported.
2835 return DeclResult(true);
2837 // There are two cases to handle here. 1) scoped lookup could have failed,
2838 // in which case we should look for an ivar. 2) scoped lookup could have
2839 // found a decl, but that decl is outside the current instance method (i.e.
2840 // a global variable). In these two cases, we do a lookup for an ivar with
2841 // this name, if the lookup sucedes, we replace it our current decl.
2843 // If we're in a class method, we don't normally want to look for
2844 // ivars. But if we don't find anything else, and there's an
2845 // ivar, that's an error.
2846 bool IsClassMethod
= CurMethod
->isClassMethod();
2850 LookForIvars
= true;
2851 else if (IsClassMethod
)
2852 LookForIvars
= false;
2854 LookForIvars
= (Lookup
.isSingleResult() &&
2855 Lookup
.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2856 ObjCInterfaceDecl
*IFace
= nullptr;
2858 IFace
= CurMethod
->getClassInterface();
2859 ObjCInterfaceDecl
*ClassDeclared
;
2860 ObjCIvarDecl
*IV
= nullptr;
2861 if (IFace
&& (IV
= IFace
->lookupInstanceVariable(II
, ClassDeclared
))) {
2862 // Diagnose using an ivar in a class method.
2863 if (IsClassMethod
) {
2864 Diag(Loc
, diag::err_ivar_use_in_class_method
) << IV
->getDeclName();
2865 return DeclResult(true);
2868 // Diagnose the use of an ivar outside of the declaring class.
2869 if (IV
->getAccessControl() == ObjCIvarDecl::Private
&&
2870 !declaresSameEntity(ClassDeclared
, IFace
) &&
2871 !getLangOpts().DebuggerSupport
)
2872 Diag(Loc
, diag::err_private_ivar_access
) << IV
->getDeclName();
2877 } else if (CurMethod
->isInstanceMethod()) {
2878 // We should warn if a local variable hides an ivar.
2879 if (ObjCInterfaceDecl
*IFace
= CurMethod
->getClassInterface()) {
2880 ObjCInterfaceDecl
*ClassDeclared
;
2881 if (ObjCIvarDecl
*IV
= IFace
->lookupInstanceVariable(II
, ClassDeclared
)) {
2882 if (IV
->getAccessControl() != ObjCIvarDecl::Private
||
2883 declaresSameEntity(IFace
, ClassDeclared
))
2884 Diag(Loc
, diag::warn_ivar_use_hidden
) << IV
->getDeclName();
2887 } else if (Lookup
.isSingleResult() &&
2888 Lookup
.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2889 // If accessing a stand-alone ivar in a class method, this is an error.
2890 if (const ObjCIvarDecl
*IV
=
2891 dyn_cast
<ObjCIvarDecl
>(Lookup
.getFoundDecl())) {
2892 Diag(Loc
, diag::err_ivar_use_in_class_method
) << IV
->getDeclName();
2893 return DeclResult(true);
2897 // Didn't encounter an error, didn't find an ivar.
2898 return DeclResult(false);
2901 ExprResult
Sema::BuildIvarRefExpr(Scope
*S
, SourceLocation Loc
,
2903 ObjCMethodDecl
*CurMethod
= getCurMethodDecl();
2904 assert(CurMethod
&& CurMethod
->isInstanceMethod() &&
2905 "should not reference ivar from this context");
2907 ObjCInterfaceDecl
*IFace
= CurMethod
->getClassInterface();
2908 assert(IFace
&& "should not reference ivar from this context");
2910 // If we're referencing an invalid decl, just return this as a silent
2911 // error node. The error diagnostic was already emitted on the decl.
2912 if (IV
->isInvalidDecl())
2915 // Check if referencing a field with __attribute__((deprecated)).
2916 if (DiagnoseUseOfDecl(IV
, Loc
))
2919 // FIXME: This should use a new expr for a direct reference, don't
2920 // turn this into Self->ivar, just return a BareIVarExpr or something.
2921 IdentifierInfo
&II
= Context
.Idents
.get("self");
2922 UnqualifiedId SelfName
;
2923 SelfName
.setImplicitSelfParam(&II
);
2924 CXXScopeSpec SelfScopeSpec
;
2925 SourceLocation TemplateKWLoc
;
2926 ExprResult SelfExpr
=
2927 ActOnIdExpression(S
, SelfScopeSpec
, TemplateKWLoc
, SelfName
,
2928 /*HasTrailingLParen=*/false,
2929 /*IsAddressOfOperand=*/false);
2930 if (SelfExpr
.isInvalid())
2933 SelfExpr
= DefaultLvalueConversion(SelfExpr
.get());
2934 if (SelfExpr
.isInvalid())
2937 MarkAnyDeclReferenced(Loc
, IV
, true);
2939 ObjCMethodFamily MF
= CurMethod
->getMethodFamily();
2940 if (MF
!= OMF_init
&& MF
!= OMF_dealloc
&& MF
!= OMF_finalize
&&
2941 !IvarBacksCurrentMethodAccessor(IFace
, CurMethod
, IV
))
2942 Diag(Loc
, diag::warn_direct_ivar_access
) << IV
->getDeclName();
2944 ObjCIvarRefExpr
*Result
= new (Context
)
2945 ObjCIvarRefExpr(IV
, IV
->getUsageType(SelfExpr
.get()->getType()), Loc
,
2946 IV
->getLocation(), SelfExpr
.get(), true, true);
2948 if (IV
->getType().getObjCLifetime() == Qualifiers::OCL_Weak
) {
2949 if (!isUnevaluatedContext() &&
2950 !Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
, Loc
))
2951 getCurFunction()->recordUseOfWeak(Result
);
2953 if (getLangOpts().ObjCAutoRefCount
&& !isUnevaluatedContext())
2954 if (const BlockDecl
*BD
= CurContext
->getInnermostBlockDecl())
2955 ImplicitlyRetainedSelfLocs
.push_back({Loc
, BD
});
2960 /// The parser has read a name in, and Sema has detected that we're currently
2961 /// inside an ObjC method. Perform some additional checks and determine if we
2962 /// should form a reference to an ivar. If so, build an expression referencing
2965 Sema::LookupInObjCMethod(LookupResult
&Lookup
, Scope
*S
,
2966 IdentifierInfo
*II
, bool AllowBuiltinCreation
) {
2967 // FIXME: Integrate this lookup step into LookupParsedName.
2968 DeclResult Ivar
= LookupIvarInObjCMethod(Lookup
, S
, II
);
2969 if (Ivar
.isInvalid())
2971 if (Ivar
.isUsable())
2972 return BuildIvarRefExpr(S
, Lookup
.getNameLoc(),
2973 cast
<ObjCIvarDecl
>(Ivar
.get()));
2975 if (Lookup
.empty() && II
&& AllowBuiltinCreation
)
2976 LookupBuiltin(Lookup
);
2978 // Sentinel value saying that we didn't do anything special.
2979 return ExprResult(false);
2982 /// Cast a base object to a member's actual type.
2984 /// There are two relevant checks:
2986 /// C++ [class.access.base]p7:
2988 /// If a class member access operator [...] is used to access a non-static
2989 /// data member or non-static member function, the reference is ill-formed if
2990 /// the left operand [...] cannot be implicitly converted to a pointer to the
2991 /// naming class of the right operand.
2993 /// C++ [expr.ref]p7:
2995 /// If E2 is a non-static data member or a non-static member function, the
2996 /// program is ill-formed if the class of which E2 is directly a member is an
2997 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
2999 /// Note that the latter check does not consider access; the access of the
3000 /// "real" base class is checked as appropriate when checking the access of the
3003 Sema::PerformObjectMemberConversion(Expr
*From
,
3004 NestedNameSpecifier
*Qualifier
,
3005 NamedDecl
*FoundDecl
,
3006 NamedDecl
*Member
) {
3007 CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(Member
->getDeclContext());
3011 QualType DestRecordType
;
3013 QualType FromRecordType
;
3014 QualType FromType
= From
->getType();
3015 bool PointerConversions
= false;
3016 if (isa
<FieldDecl
>(Member
)) {
3017 DestRecordType
= Context
.getCanonicalType(Context
.getTypeDeclType(RD
));
3018 auto FromPtrType
= FromType
->getAs
<PointerType
>();
3019 DestRecordType
= Context
.getAddrSpaceQualType(
3020 DestRecordType
, FromPtrType
3021 ? FromType
->getPointeeType().getAddressSpace()
3022 : FromType
.getAddressSpace());
3025 DestType
= Context
.getPointerType(DestRecordType
);
3026 FromRecordType
= FromPtrType
->getPointeeType();
3027 PointerConversions
= true;
3029 DestType
= DestRecordType
;
3030 FromRecordType
= FromType
;
3032 } else if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(Member
)) {
3033 if (Method
->isStatic())
3036 DestType
= Method
->getThisType();
3037 DestRecordType
= DestType
->getPointeeType();
3039 if (FromType
->getAs
<PointerType
>()) {
3040 FromRecordType
= FromType
->getPointeeType();
3041 PointerConversions
= true;
3043 FromRecordType
= FromType
;
3044 DestType
= DestRecordType
;
3047 LangAS FromAS
= FromRecordType
.getAddressSpace();
3048 LangAS DestAS
= DestRecordType
.getAddressSpace();
3049 if (FromAS
!= DestAS
) {
3050 QualType FromRecordTypeWithoutAS
=
3051 Context
.removeAddrSpaceQualType(FromRecordType
);
3052 QualType FromTypeWithDestAS
=
3053 Context
.getAddrSpaceQualType(FromRecordTypeWithoutAS
, DestAS
);
3054 if (PointerConversions
)
3055 FromTypeWithDestAS
= Context
.getPointerType(FromTypeWithDestAS
);
3056 From
= ImpCastExprToType(From
, FromTypeWithDestAS
,
3057 CK_AddressSpaceConversion
, From
->getValueKind())
3061 // No conversion necessary.
3065 if (DestType
->isDependentType() || FromType
->isDependentType())
3068 // If the unqualified types are the same, no conversion is necessary.
3069 if (Context
.hasSameUnqualifiedType(FromRecordType
, DestRecordType
))
3072 SourceRange FromRange
= From
->getSourceRange();
3073 SourceLocation FromLoc
= FromRange
.getBegin();
3075 ExprValueKind VK
= From
->getValueKind();
3077 // C++ [class.member.lookup]p8:
3078 // [...] Ambiguities can often be resolved by qualifying a name with its
3081 // If the member was a qualified name and the qualified referred to a
3082 // specific base subobject type, we'll cast to that intermediate type
3083 // first and then to the object in which the member is declared. That allows
3084 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3086 // class Base { public: int x; };
3087 // class Derived1 : public Base { };
3088 // class Derived2 : public Base { };
3089 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3091 // void VeryDerived::f() {
3092 // x = 17; // error: ambiguous base subobjects
3093 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3095 if (Qualifier
&& Qualifier
->getAsType()) {
3096 QualType QType
= QualType(Qualifier
->getAsType(), 0);
3097 assert(QType
->isRecordType() && "lookup done with non-record type");
3099 QualType QRecordType
= QualType(QType
->castAs
<RecordType
>(), 0);
3101 // In C++98, the qualifier type doesn't actually have to be a base
3102 // type of the object type, in which case we just ignore it.
3103 // Otherwise build the appropriate casts.
3104 if (IsDerivedFrom(FromLoc
, FromRecordType
, QRecordType
)) {
3105 CXXCastPath BasePath
;
3106 if (CheckDerivedToBaseConversion(FromRecordType
, QRecordType
,
3107 FromLoc
, FromRange
, &BasePath
))
3110 if (PointerConversions
)
3111 QType
= Context
.getPointerType(QType
);
3112 From
= ImpCastExprToType(From
, QType
, CK_UncheckedDerivedToBase
,
3113 VK
, &BasePath
).get();
3116 FromRecordType
= QRecordType
;
3118 // If the qualifier type was the same as the destination type,
3120 if (Context
.hasSameUnqualifiedType(FromRecordType
, DestRecordType
))
3125 CXXCastPath BasePath
;
3126 if (CheckDerivedToBaseConversion(FromRecordType
, DestRecordType
,
3127 FromLoc
, FromRange
, &BasePath
,
3128 /*IgnoreAccess=*/true))
3131 return ImpCastExprToType(From
, DestType
, CK_UncheckedDerivedToBase
,
3135 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec
&SS
,
3136 const LookupResult
&R
,
3137 bool HasTrailingLParen
) {
3138 // Only when used directly as the postfix-expression of a call.
3139 if (!HasTrailingLParen
)
3142 // Never if a scope specifier was provided.
3146 // Only in C++ or ObjC++.
3147 if (!getLangOpts().CPlusPlus
)
3150 // Turn off ADL when we find certain kinds of declarations during
3152 for (NamedDecl
*D
: R
) {
3153 // C++0x [basic.lookup.argdep]p3:
3154 // -- a declaration of a class member
3155 // Since using decls preserve this property, we check this on the
3157 if (D
->isCXXClassMember())
3160 // C++0x [basic.lookup.argdep]p3:
3161 // -- a block-scope function declaration that is not a
3162 // using-declaration
3163 // NOTE: we also trigger this for function templates (in fact, we
3164 // don't check the decl type at all, since all other decl types
3165 // turn off ADL anyway).
3166 if (isa
<UsingShadowDecl
>(D
))
3167 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
3168 else if (D
->getLexicalDeclContext()->isFunctionOrMethod())
3171 // C++0x [basic.lookup.argdep]p3:
3172 // -- a declaration that is neither a function or a function
3174 // And also for builtin functions.
3175 if (isa
<FunctionDecl
>(D
)) {
3176 FunctionDecl
*FDecl
= cast
<FunctionDecl
>(D
);
3178 // But also builtin functions.
3179 if (FDecl
->getBuiltinID() && FDecl
->isImplicit())
3181 } else if (!isa
<FunctionTemplateDecl
>(D
))
3189 /// Diagnoses obvious problems with the use of the given declaration
3190 /// as an expression. This is only actually called for lookups that
3191 /// were not overloaded, and it doesn't promise that the declaration
3192 /// will in fact be used.
3193 static bool CheckDeclInExpr(Sema
&S
, SourceLocation Loc
, NamedDecl
*D
,
3194 bool AcceptInvalid
) {
3195 if (D
->isInvalidDecl() && !AcceptInvalid
)
3198 if (isa
<TypedefNameDecl
>(D
)) {
3199 S
.Diag(Loc
, diag::err_unexpected_typedef
) << D
->getDeclName();
3203 if (isa
<ObjCInterfaceDecl
>(D
)) {
3204 S
.Diag(Loc
, diag::err_unexpected_interface
) << D
->getDeclName();
3208 if (isa
<NamespaceDecl
>(D
)) {
3209 S
.Diag(Loc
, diag::err_unexpected_namespace
) << D
->getDeclName();
3216 // Certain multiversion types should be treated as overloaded even when there is
3218 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult
&R
) {
3219 assert(R
.isSingleResult() && "Expected only a single result");
3220 const auto *FD
= dyn_cast
<FunctionDecl
>(R
.getFoundDecl());
3222 (FD
->isCPUDispatchMultiVersion() || FD
->isCPUSpecificMultiVersion());
3225 ExprResult
Sema::BuildDeclarationNameExpr(const CXXScopeSpec
&SS
,
3226 LookupResult
&R
, bool NeedsADL
,
3227 bool AcceptInvalidDecl
) {
3228 // If this is a single, fully-resolved result and we don't need ADL,
3229 // just build an ordinary singleton decl ref.
3230 if (!NeedsADL
&& R
.isSingleResult() &&
3231 !R
.getAsSingle
<FunctionTemplateDecl
>() &&
3232 !ShouldLookupResultBeMultiVersionOverload(R
))
3233 return BuildDeclarationNameExpr(SS
, R
.getLookupNameInfo(), R
.getFoundDecl(),
3234 R
.getRepresentativeDecl(), nullptr,
3237 // We only need to check the declaration if there's exactly one
3238 // result, because in the overloaded case the results can only be
3239 // functions and function templates.
3240 if (R
.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R
) &&
3241 CheckDeclInExpr(*this, R
.getNameLoc(), R
.getFoundDecl(),
3245 // Otherwise, just build an unresolved lookup expression. Suppress
3246 // any lookup-related diagnostics; we'll hash these out later, when
3247 // we've picked a target.
3248 R
.suppressDiagnostics();
3250 UnresolvedLookupExpr
*ULE
3251 = UnresolvedLookupExpr::Create(Context
, R
.getNamingClass(),
3252 SS
.getWithLocInContext(Context
),
3253 R
.getLookupNameInfo(),
3254 NeedsADL
, R
.isOverloadedResult(),
3255 R
.begin(), R
.end());
3260 static void diagnoseUncapturableValueReferenceOrBinding(Sema
&S
,
3264 /// Complete semantic analysis for a reference to the given declaration.
3265 ExprResult
Sema::BuildDeclarationNameExpr(
3266 const CXXScopeSpec
&SS
, const DeclarationNameInfo
&NameInfo
, NamedDecl
*D
,
3267 NamedDecl
*FoundD
, const TemplateArgumentListInfo
*TemplateArgs
,
3268 bool AcceptInvalidDecl
) {
3269 assert(D
&& "Cannot refer to a NULL declaration");
3270 assert(!isa
<FunctionTemplateDecl
>(D
) &&
3271 "Cannot refer unambiguously to a function template");
3273 SourceLocation Loc
= NameInfo
.getLoc();
3274 if (CheckDeclInExpr(*this, Loc
, D
, AcceptInvalidDecl
)) {
3275 // Recovery from invalid cases (e.g. D is an invalid Decl).
3276 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3277 // diagnostics, as invalid decls use int as a fallback type.
3278 return CreateRecoveryExpr(NameInfo
.getBeginLoc(), NameInfo
.getEndLoc(), {});
3281 if (TemplateDecl
*Template
= dyn_cast
<TemplateDecl
>(D
)) {
3282 // Specifically diagnose references to class templates that are missing
3283 // a template argument list.
3284 diagnoseMissingTemplateArguments(TemplateName(Template
), Loc
);
3288 // Make sure that we're referring to a value.
3289 if (!isa
<ValueDecl
, UnresolvedUsingIfExistsDecl
>(D
)) {
3290 Diag(Loc
, diag::err_ref_non_value
) << D
<< SS
.getRange();
3291 Diag(D
->getLocation(), diag::note_declared_at
);
3295 // Check whether this declaration can be used. Note that we suppress
3296 // this check when we're going to perform argument-dependent lookup
3297 // on this function name, because this might not be the function
3298 // that overload resolution actually selects.
3299 if (DiagnoseUseOfDecl(D
, Loc
))
3302 auto *VD
= cast
<ValueDecl
>(D
);
3304 // Only create DeclRefExpr's for valid Decl's.
3305 if (VD
->isInvalidDecl() && !AcceptInvalidDecl
)
3308 // Handle members of anonymous structs and unions. If we got here,
3309 // and the reference is to a class member indirect field, then this
3310 // must be the subject of a pointer-to-member expression.
3311 if (IndirectFieldDecl
*indirectField
= dyn_cast
<IndirectFieldDecl
>(VD
))
3312 if (!indirectField
->isCXXClassMember())
3313 return BuildAnonymousStructUnionMemberReference(SS
, NameInfo
.getLoc(),
3316 QualType type
= VD
->getType();
3319 ExprValueKind valueKind
= VK_PRValue
;
3321 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3322 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3323 // is expanded by some outer '...' in the context of the use.
3324 type
= type
.getNonPackExpansionType();
3326 switch (D
->getKind()) {
3327 // Ignore all the non-ValueDecl kinds.
3328 #define ABSTRACT_DECL(kind)
3329 #define VALUE(type, base)
3330 #define DECL(type, base) case Decl::type:
3331 #include "clang/AST/DeclNodes.inc"
3332 llvm_unreachable("invalid value decl kind");
3334 // These shouldn't make it here.
3335 case Decl::ObjCAtDefsField
:
3336 llvm_unreachable("forming non-member reference to ivar?");
3338 // Enum constants are always r-values and never references.
3339 // Unresolved using declarations are dependent.
3340 case Decl::EnumConstant
:
3341 case Decl::UnresolvedUsingValue
:
3342 case Decl::OMPDeclareReduction
:
3343 case Decl::OMPDeclareMapper
:
3344 valueKind
= VK_PRValue
;
3347 // Fields and indirect fields that got here must be for
3348 // pointer-to-member expressions; we just call them l-values for
3349 // internal consistency, because this subexpression doesn't really
3350 // exist in the high-level semantics.
3352 case Decl::IndirectField
:
3353 case Decl::ObjCIvar
:
3354 assert(getLangOpts().CPlusPlus
&& "building reference to field in C?");
3356 // These can't have reference type in well-formed programs, but
3357 // for internal consistency we do this anyway.
3358 type
= type
.getNonReferenceType();
3359 valueKind
= VK_LValue
;
3362 // Non-type template parameters are either l-values or r-values
3363 // depending on the type.
3364 case Decl::NonTypeTemplateParm
: {
3365 if (const ReferenceType
*reftype
= type
->getAs
<ReferenceType
>()) {
3366 type
= reftype
->getPointeeType();
3367 valueKind
= VK_LValue
; // even if the parameter is an r-value reference
3371 // [expr.prim.id.unqual]p2:
3372 // If the entity is a template parameter object for a template
3373 // parameter of type T, the type of the expression is const T.
3374 // [...] The expression is an lvalue if the entity is a [...] template
3375 // parameter object.
3376 if (type
->isRecordType()) {
3377 type
= type
.getUnqualifiedType().withConst();
3378 valueKind
= VK_LValue
;
3382 // For non-references, we need to strip qualifiers just in case
3383 // the template parameter was declared as 'const int' or whatever.
3384 valueKind
= VK_PRValue
;
3385 type
= type
.getUnqualifiedType();
3390 case Decl::VarTemplateSpecialization
:
3391 case Decl::VarTemplatePartialSpecialization
:
3392 case Decl::Decomposition
:
3393 case Decl::OMPCapturedExpr
:
3394 // In C, "extern void blah;" is valid and is an r-value.
3395 if (!getLangOpts().CPlusPlus
&& !type
.hasQualifiers() &&
3396 type
->isVoidType()) {
3397 valueKind
= VK_PRValue
;
3402 case Decl::ImplicitParam
:
3403 case Decl::ParmVar
: {
3404 // These are always l-values.
3405 valueKind
= VK_LValue
;
3406 type
= type
.getNonReferenceType();
3408 // FIXME: Does the addition of const really only apply in
3409 // potentially-evaluated contexts? Since the variable isn't actually
3410 // captured in an unevaluated context, it seems that the answer is no.
3411 if (!isUnevaluatedContext()) {
3412 QualType CapturedType
= getCapturedDeclRefType(cast
<VarDecl
>(VD
), Loc
);
3413 if (!CapturedType
.isNull())
3414 type
= CapturedType
;
3421 // These are always lvalues.
3422 valueKind
= VK_LValue
;
3423 type
= type
.getNonReferenceType();
3426 case Decl::Function
: {
3427 if (unsigned BID
= cast
<FunctionDecl
>(VD
)->getBuiltinID()) {
3428 if (!Context
.BuiltinInfo
.isDirectlyAddressable(BID
)) {
3429 type
= Context
.BuiltinFnTy
;
3430 valueKind
= VK_PRValue
;
3435 const FunctionType
*fty
= type
->castAs
<FunctionType
>();
3437 // If we're referring to a function with an __unknown_anytype
3438 // result type, make the entire expression __unknown_anytype.
3439 if (fty
->getReturnType() == Context
.UnknownAnyTy
) {
3440 type
= Context
.UnknownAnyTy
;
3441 valueKind
= VK_PRValue
;
3445 // Functions are l-values in C++.
3446 if (getLangOpts().CPlusPlus
) {
3447 valueKind
= VK_LValue
;
3451 // C99 DR 316 says that, if a function type comes from a
3452 // function definition (without a prototype), that type is only
3453 // used for checking compatibility. Therefore, when referencing
3454 // the function, we pretend that we don't have the full function
3456 if (!cast
<FunctionDecl
>(VD
)->hasPrototype() && isa
<FunctionProtoType
>(fty
))
3457 type
= Context
.getFunctionNoProtoType(fty
->getReturnType(),
3460 // Functions are r-values in C.
3461 valueKind
= VK_PRValue
;
3465 case Decl::CXXDeductionGuide
:
3466 llvm_unreachable("building reference to deduction guide");
3468 case Decl::MSProperty
:
3470 case Decl::TemplateParamObject
:
3471 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3472 // capture in OpenMP, or duplicated between host and device?
3473 valueKind
= VK_LValue
;
3476 case Decl::UnnamedGlobalConstant
:
3477 valueKind
= VK_LValue
;
3480 case Decl::CXXMethod
:
3481 // If we're referring to a method with an __unknown_anytype
3482 // result type, make the entire expression __unknown_anytype.
3483 // This should only be possible with a type written directly.
3484 if (const FunctionProtoType
*proto
=
3485 dyn_cast
<FunctionProtoType
>(VD
->getType()))
3486 if (proto
->getReturnType() == Context
.UnknownAnyTy
) {
3487 type
= Context
.UnknownAnyTy
;
3488 valueKind
= VK_PRValue
;
3492 // C++ methods are l-values if static, r-values if non-static.
3493 if (cast
<CXXMethodDecl
>(VD
)->isStatic()) {
3494 valueKind
= VK_LValue
;
3499 case Decl::CXXConversion
:
3500 case Decl::CXXDestructor
:
3501 case Decl::CXXConstructor
:
3502 valueKind
= VK_PRValue
;
3507 BuildDeclRefExpr(VD
, type
, valueKind
, NameInfo
, &SS
, FoundD
,
3508 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs
);
3509 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3510 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3511 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3513 if (VD
->isInvalidDecl() && E
)
3514 return CreateRecoveryExpr(E
->getBeginLoc(), E
->getEndLoc(), {E
});
3518 static void ConvertUTF8ToWideString(unsigned CharByteWidth
, StringRef Source
,
3519 SmallString
<32> &Target
) {
3520 Target
.resize(CharByteWidth
* (Source
.size() + 1));
3521 char *ResultPtr
= &Target
[0];
3522 const llvm::UTF8
*ErrorPtr
;
3524 llvm::ConvertUTF8toWide(CharByteWidth
, Source
, ResultPtr
, ErrorPtr
);
3527 Target
.resize(ResultPtr
- &Target
[0]);
3530 ExprResult
Sema::BuildPredefinedExpr(SourceLocation Loc
,
3531 PredefinedExpr::IdentKind IK
) {
3532 // Pick the current block, lambda, captured statement or function.
3533 Decl
*currentDecl
= nullptr;
3534 if (const BlockScopeInfo
*BSI
= getCurBlock())
3535 currentDecl
= BSI
->TheDecl
;
3536 else if (const LambdaScopeInfo
*LSI
= getCurLambda())
3537 currentDecl
= LSI
->CallOperator
;
3538 else if (const CapturedRegionScopeInfo
*CSI
= getCurCapturedRegion())
3539 currentDecl
= CSI
->TheCapturedDecl
;
3541 currentDecl
= getCurFunctionOrMethodDecl();
3544 Diag(Loc
, diag::ext_predef_outside_function
);
3545 currentDecl
= Context
.getTranslationUnitDecl();
3549 StringLiteral
*SL
= nullptr;
3550 if (cast
<DeclContext
>(currentDecl
)->isDependentContext())
3551 ResTy
= Context
.DependentTy
;
3553 // Pre-defined identifiers are of type char[x], where x is the length of
3555 auto Str
= PredefinedExpr::ComputeName(IK
, currentDecl
);
3556 unsigned Length
= Str
.length();
3558 llvm::APInt
LengthI(32, Length
+ 1);
3559 if (IK
== PredefinedExpr::LFunction
|| IK
== PredefinedExpr::LFuncSig
) {
3561 Context
.adjustStringLiteralBaseType(Context
.WideCharTy
.withConst());
3562 SmallString
<32> RawChars
;
3563 ConvertUTF8ToWideString(Context
.getTypeSizeInChars(ResTy
).getQuantity(),
3565 ResTy
= Context
.getConstantArrayType(ResTy
, LengthI
, nullptr,
3567 /*IndexTypeQuals*/ 0);
3568 SL
= StringLiteral::Create(Context
, RawChars
, StringLiteral::Wide
,
3569 /*Pascal*/ false, ResTy
, Loc
);
3571 ResTy
= Context
.adjustStringLiteralBaseType(Context
.CharTy
.withConst());
3572 ResTy
= Context
.getConstantArrayType(ResTy
, LengthI
, nullptr,
3574 /*IndexTypeQuals*/ 0);
3575 SL
= StringLiteral::Create(Context
, Str
, StringLiteral::Ordinary
,
3576 /*Pascal*/ false, ResTy
, Loc
);
3580 return PredefinedExpr::Create(Context
, Loc
, ResTy
, IK
, SL
);
3583 ExprResult
Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc
,
3584 SourceLocation LParen
,
3585 SourceLocation RParen
,
3586 TypeSourceInfo
*TSI
) {
3587 return SYCLUniqueStableNameExpr::Create(Context
, OpLoc
, LParen
, RParen
, TSI
);
3590 ExprResult
Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc
,
3591 SourceLocation LParen
,
3592 SourceLocation RParen
,
3593 ParsedType ParsedTy
) {
3594 TypeSourceInfo
*TSI
= nullptr;
3595 QualType Ty
= GetTypeFromParser(ParsedTy
, &TSI
);
3600 TSI
= Context
.getTrivialTypeSourceInfo(Ty
, LParen
);
3602 return BuildSYCLUniqueStableNameExpr(OpLoc
, LParen
, RParen
, TSI
);
3605 ExprResult
Sema::ActOnPredefinedExpr(SourceLocation Loc
, tok::TokenKind Kind
) {
3606 PredefinedExpr::IdentKind IK
;
3609 default: llvm_unreachable("Unknown simple primary expr!");
3610 case tok::kw___func__
: IK
= PredefinedExpr::Func
; break; // [C99 6.4.2.2]
3611 case tok::kw___FUNCTION__
: IK
= PredefinedExpr::Function
; break;
3612 case tok::kw___FUNCDNAME__
: IK
= PredefinedExpr::FuncDName
; break; // [MS]
3613 case tok::kw___FUNCSIG__
: IK
= PredefinedExpr::FuncSig
; break; // [MS]
3614 case tok::kw_L__FUNCTION__
: IK
= PredefinedExpr::LFunction
; break; // [MS]
3615 case tok::kw_L__FUNCSIG__
: IK
= PredefinedExpr::LFuncSig
; break; // [MS]
3616 case tok::kw___PRETTY_FUNCTION__
: IK
= PredefinedExpr::PrettyFunction
; break;
3619 return BuildPredefinedExpr(Loc
, IK
);
3622 ExprResult
Sema::ActOnCharacterConstant(const Token
&Tok
, Scope
*UDLScope
) {
3623 SmallString
<16> CharBuffer
;
3624 bool Invalid
= false;
3625 StringRef ThisTok
= PP
.getSpelling(Tok
, CharBuffer
, &Invalid
);
3629 CharLiteralParser
Literal(ThisTok
.begin(), ThisTok
.end(), Tok
.getLocation(),
3631 if (Literal
.hadError())
3635 if (Literal
.isWide())
3636 Ty
= Context
.WideCharTy
; // L'x' -> wchar_t in C and C++.
3637 else if (Literal
.isUTF8() && getLangOpts().C2x
)
3638 Ty
= Context
.UnsignedCharTy
; // u8'x' -> unsigned char in C2x
3639 else if (Literal
.isUTF8() && getLangOpts().Char8
)
3640 Ty
= Context
.Char8Ty
; // u8'x' -> char8_t when it exists.
3641 else if (Literal
.isUTF16())
3642 Ty
= Context
.Char16Ty
; // u'x' -> char16_t in C11 and C++11.
3643 else if (Literal
.isUTF32())
3644 Ty
= Context
.Char32Ty
; // U'x' -> char32_t in C11 and C++11.
3645 else if (!getLangOpts().CPlusPlus
|| Literal
.isMultiChar())
3646 Ty
= Context
.IntTy
; // 'x' -> int in C, 'wxyz' -> int in C++.
3648 Ty
= Context
.CharTy
; // 'x' -> char in C++;
3649 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3651 CharacterLiteral::CharacterKind Kind
= CharacterLiteral::Ascii
;
3652 if (Literal
.isWide())
3653 Kind
= CharacterLiteral::Wide
;
3654 else if (Literal
.isUTF16())
3655 Kind
= CharacterLiteral::UTF16
;
3656 else if (Literal
.isUTF32())
3657 Kind
= CharacterLiteral::UTF32
;
3658 else if (Literal
.isUTF8())
3659 Kind
= CharacterLiteral::UTF8
;
3661 Expr
*Lit
= new (Context
) CharacterLiteral(Literal
.getValue(), Kind
, Ty
,
3664 if (Literal
.getUDSuffix().empty())
3667 // We're building a user-defined literal.
3668 IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
3669 SourceLocation UDSuffixLoc
=
3670 getUDSuffixLoc(*this, Tok
.getLocation(), Literal
.getUDSuffixOffset());
3672 // Make sure we're allowed user-defined literals here.
3674 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_character_udl
));
3676 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3677 // operator "" X (ch)
3678 return BuildCookedLiteralOperatorCall(*this, UDLScope
, UDSuffix
, UDSuffixLoc
,
3679 Lit
, Tok
.getLocation());
3682 ExprResult
Sema::ActOnIntegerConstant(SourceLocation Loc
, uint64_t Val
) {
3683 unsigned IntSize
= Context
.getTargetInfo().getIntWidth();
3684 return IntegerLiteral::Create(Context
, llvm::APInt(IntSize
, Val
),
3685 Context
.IntTy
, Loc
);
3688 static Expr
*BuildFloatingLiteral(Sema
&S
, NumericLiteralParser
&Literal
,
3689 QualType Ty
, SourceLocation Loc
) {
3690 const llvm::fltSemantics
&Format
= S
.Context
.getFloatTypeSemantics(Ty
);
3692 using llvm::APFloat
;
3693 APFloat
Val(Format
);
3695 APFloat::opStatus result
= Literal
.GetFloatValue(Val
);
3697 // Overflow is always an error, but underflow is only an error if
3698 // we underflowed to zero (APFloat reports denormals as underflow).
3699 if ((result
& APFloat::opOverflow
) ||
3700 ((result
& APFloat::opUnderflow
) && Val
.isZero())) {
3701 unsigned diagnostic
;
3702 SmallString
<20> buffer
;
3703 if (result
& APFloat::opOverflow
) {
3704 diagnostic
= diag::warn_float_overflow
;
3705 APFloat::getLargest(Format
).toString(buffer
);
3707 diagnostic
= diag::warn_float_underflow
;
3708 APFloat::getSmallest(Format
).toString(buffer
);
3711 S
.Diag(Loc
, diagnostic
)
3713 << StringRef(buffer
.data(), buffer
.size());
3716 bool isExact
= (result
== APFloat::opOK
);
3717 return FloatingLiteral::Create(S
.Context
, Val
, isExact
, Ty
, Loc
);
3720 bool Sema::CheckLoopHintExpr(Expr
*E
, SourceLocation Loc
) {
3721 assert(E
&& "Invalid expression");
3723 if (E
->isValueDependent())
3726 QualType QT
= E
->getType();
3727 if (!QT
->isIntegerType() || QT
->isBooleanType() || QT
->isCharType()) {
3728 Diag(E
->getExprLoc(), diag::err_pragma_loop_invalid_argument_type
) << QT
;
3732 llvm::APSInt ValueAPS
;
3733 ExprResult R
= VerifyIntegerConstantExpression(E
, &ValueAPS
);
3738 bool ValueIsPositive
= ValueAPS
.isStrictlyPositive();
3739 if (!ValueIsPositive
|| ValueAPS
.getActiveBits() > 31) {
3740 Diag(E
->getExprLoc(), diag::err_pragma_loop_invalid_argument_value
)
3741 << toString(ValueAPS
, 10) << ValueIsPositive
;
3748 ExprResult
Sema::ActOnNumericConstant(const Token
&Tok
, Scope
*UDLScope
) {
3749 // Fast path for a single digit (which is quite common). A single digit
3750 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3751 if (Tok
.getLength() == 1) {
3752 const char Val
= PP
.getSpellingOfSingleCharacterNumericConstant(Tok
);
3753 return ActOnIntegerConstant(Tok
.getLocation(), Val
-'0');
3756 SmallString
<128> SpellingBuffer
;
3757 // NumericLiteralParser wants to overread by one character. Add padding to
3758 // the buffer in case the token is copied to the buffer. If getSpelling()
3759 // returns a StringRef to the memory buffer, it should have a null char at
3760 // the EOF, so it is also safe.
3761 SpellingBuffer
.resize(Tok
.getLength() + 1);
3763 // Get the spelling of the token, which eliminates trigraphs, etc.
3764 bool Invalid
= false;
3765 StringRef TokSpelling
= PP
.getSpelling(Tok
, SpellingBuffer
, &Invalid
);
3769 NumericLiteralParser
Literal(TokSpelling
, Tok
.getLocation(),
3770 PP
.getSourceManager(), PP
.getLangOpts(),
3771 PP
.getTargetInfo(), PP
.getDiagnostics());
3772 if (Literal
.hadError
)
3775 if (Literal
.hasUDSuffix()) {
3776 // We're building a user-defined literal.
3777 IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
3778 SourceLocation UDSuffixLoc
=
3779 getUDSuffixLoc(*this, Tok
.getLocation(), Literal
.getUDSuffixOffset());
3781 // Make sure we're allowed user-defined literals here.
3783 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_numeric_udl
));
3786 if (Literal
.isFloatingLiteral()) {
3787 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3788 // long double, the literal is treated as a call of the form
3789 // operator "" X (f L)
3790 CookedTy
= Context
.LongDoubleTy
;
3792 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3793 // unsigned long long, the literal is treated as a call of the form
3794 // operator "" X (n ULL)
3795 CookedTy
= Context
.UnsignedLongLongTy
;
3798 DeclarationName OpName
=
3799 Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
3800 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
3801 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
3803 SourceLocation TokLoc
= Tok
.getLocation();
3805 // Perform literal operator lookup to determine if we're building a raw
3806 // literal or a cooked one.
3807 LookupResult
R(*this, OpName
, UDSuffixLoc
, LookupOrdinaryName
);
3808 switch (LookupLiteralOperator(UDLScope
, R
, CookedTy
,
3809 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3810 /*AllowStringTemplatePack*/ false,
3811 /*DiagnoseMissing*/ !Literal
.isImaginary
)) {
3812 case LOLR_ErrorNoDiagnostic
:
3813 // Lookup failure for imaginary constants isn't fatal, there's still the
3814 // GNU extension producing _Complex types.
3820 if (Literal
.isFloatingLiteral()) {
3821 Lit
= BuildFloatingLiteral(*this, Literal
, CookedTy
, Tok
.getLocation());
3823 llvm::APInt
ResultVal(Context
.getTargetInfo().getLongLongWidth(), 0);
3824 if (Literal
.GetIntegerValue(ResultVal
))
3825 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
3826 << /* Unsigned */ 1;
3827 Lit
= IntegerLiteral::Create(Context
, ResultVal
, CookedTy
,
3830 return BuildLiteralOperatorCall(R
, OpNameInfo
, Lit
, TokLoc
);
3834 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3835 // literal is treated as a call of the form
3836 // operator "" X ("n")
3837 unsigned Length
= Literal
.getUDSuffixOffset();
3838 QualType StrTy
= Context
.getConstantArrayType(
3839 Context
.adjustStringLiteralBaseType(Context
.CharTy
.withConst()),
3840 llvm::APInt(32, Length
+ 1), nullptr, ArrayType::Normal
, 0);
3842 StringLiteral::Create(Context
, StringRef(TokSpelling
.data(), Length
),
3843 StringLiteral::Ordinary
,
3844 /*Pascal*/ false, StrTy
, &TokLoc
, 1);
3845 return BuildLiteralOperatorCall(R
, OpNameInfo
, Lit
, TokLoc
);
3848 case LOLR_Template
: {
3849 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3850 // template), L is treated as a call fo the form
3851 // operator "" X <'c1', 'c2', ... 'ck'>()
3852 // where n is the source character sequence c1 c2 ... ck.
3853 TemplateArgumentListInfo ExplicitArgs
;
3854 unsigned CharBits
= Context
.getIntWidth(Context
.CharTy
);
3855 bool CharIsUnsigned
= Context
.CharTy
->isUnsignedIntegerType();
3856 llvm::APSInt
Value(CharBits
, CharIsUnsigned
);
3857 for (unsigned I
= 0, N
= Literal
.getUDSuffixOffset(); I
!= N
; ++I
) {
3858 Value
= TokSpelling
[I
];
3859 TemplateArgument
Arg(Context
, Value
, Context
.CharTy
);
3860 TemplateArgumentLocInfo ArgInfo
;
3861 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
3863 return BuildLiteralOperatorCall(R
, OpNameInfo
, std::nullopt
, TokLoc
,
3866 case LOLR_StringTemplatePack
:
3867 llvm_unreachable("unexpected literal operator lookup result");
3873 if (Literal
.isFixedPointLiteral()) {
3876 if (Literal
.isAccum
) {
3877 if (Literal
.isHalf
) {
3878 Ty
= Context
.ShortAccumTy
;
3879 } else if (Literal
.isLong
) {
3880 Ty
= Context
.LongAccumTy
;
3882 Ty
= Context
.AccumTy
;
3884 } else if (Literal
.isFract
) {
3885 if (Literal
.isHalf
) {
3886 Ty
= Context
.ShortFractTy
;
3887 } else if (Literal
.isLong
) {
3888 Ty
= Context
.LongFractTy
;
3890 Ty
= Context
.FractTy
;
3894 if (Literal
.isUnsigned
) Ty
= Context
.getCorrespondingUnsignedType(Ty
);
3896 bool isSigned
= !Literal
.isUnsigned
;
3897 unsigned scale
= Context
.getFixedPointScale(Ty
);
3898 unsigned bit_width
= Context
.getTypeInfo(Ty
).Width
;
3900 llvm::APInt
Val(bit_width
, 0, isSigned
);
3901 bool Overflowed
= Literal
.GetFixedPointValue(Val
, scale
);
3902 bool ValIsZero
= Val
.isZero() && !Overflowed
;
3904 auto MaxVal
= Context
.getFixedPointMax(Ty
).getValue();
3905 if (Literal
.isFract
&& Val
== MaxVal
+ 1 && !ValIsZero
)
3906 // Clause 6.4.4 - The value of a constant shall be in the range of
3907 // representable values for its type, with exception for constants of a
3908 // fract type with a value of exactly 1; such a constant shall denote
3909 // the maximal value for the type.
3911 else if (Val
.ugt(MaxVal
) || Overflowed
)
3912 Diag(Tok
.getLocation(), diag::err_too_large_for_fixed_point
);
3914 Res
= FixedPointLiteral::CreateFromRawInt(Context
, Val
, Ty
,
3915 Tok
.getLocation(), scale
);
3916 } else if (Literal
.isFloatingLiteral()) {
3918 if (Literal
.isHalf
){
3919 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
3920 Ty
= Context
.HalfTy
;
3922 Diag(Tok
.getLocation(), diag::err_half_const_requires_fp16
);
3925 } else if (Literal
.isFloat
)
3926 Ty
= Context
.FloatTy
;
3927 else if (Literal
.isLong
)
3928 Ty
= Context
.LongDoubleTy
;
3929 else if (Literal
.isFloat16
)
3930 Ty
= Context
.Float16Ty
;
3931 else if (Literal
.isFloat128
)
3932 Ty
= Context
.Float128Ty
;
3934 Ty
= Context
.DoubleTy
;
3936 Res
= BuildFloatingLiteral(*this, Literal
, Ty
, Tok
.getLocation());
3938 if (Ty
== Context
.DoubleTy
) {
3939 if (getLangOpts().SinglePrecisionConstants
) {
3940 if (Ty
->castAs
<BuiltinType
>()->getKind() != BuiltinType::Float
) {
3941 Res
= ImpCastExprToType(Res
, Context
.FloatTy
, CK_FloatingCast
).get();
3943 } else if (getLangOpts().OpenCL
&& !getOpenCLOptions().isAvailableOption(
3944 "cl_khr_fp64", getLangOpts())) {
3945 // Impose single-precision float type when cl_khr_fp64 is not enabled.
3946 Diag(Tok
.getLocation(), diag::warn_double_const_requires_fp64
)
3947 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
3948 Res
= ImpCastExprToType(Res
, Context
.FloatTy
, CK_FloatingCast
).get();
3951 } else if (!Literal
.isIntegerLiteral()) {
3956 // 'z/uz' literals are a C++2b feature.
3957 if (Literal
.isSizeT
)
3958 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus
3959 ? getLangOpts().CPlusPlus2b
3960 ? diag::warn_cxx20_compat_size_t_suffix
3961 : diag::ext_cxx2b_size_t_suffix
3962 : diag::err_cxx2b_size_t_suffix
);
3964 // 'wb/uwb' literals are a C2x feature. We support _BitInt as a type in C++,
3965 // but we do not currently support the suffix in C++ mode because it's not
3966 // entirely clear whether WG21 will prefer this suffix to return a library
3967 // type such as std::bit_int instead of returning a _BitInt.
3968 if (Literal
.isBitInt
&& !getLangOpts().CPlusPlus
)
3969 PP
.Diag(Tok
.getLocation(), getLangOpts().C2x
3970 ? diag::warn_c2x_compat_bitint_suffix
3971 : diag::ext_c2x_bitint_suffix
);
3973 // Get the value in the widest-possible width. What is "widest" depends on
3974 // whether the literal is a bit-precise integer or not. For a bit-precise
3975 // integer type, try to scan the source to determine how many bits are
3976 // needed to represent the value. This may seem a bit expensive, but trying
3977 // to get the integer value from an overly-wide APInt is *extremely*
3978 // expensive, so the naive approach of assuming
3979 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
3980 unsigned BitsNeeded
=
3981 Literal
.isBitInt
? llvm::APInt::getSufficientBitsNeeded(
3982 Literal
.getLiteralDigits(), Literal
.getRadix())
3983 : Context
.getTargetInfo().getIntMaxTWidth();
3984 llvm::APInt
ResultVal(BitsNeeded
, 0);
3986 if (Literal
.GetIntegerValue(ResultVal
)) {
3987 // If this value didn't fit into uintmax_t, error and force to ull.
3988 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
3989 << /* Unsigned */ 1;
3990 Ty
= Context
.UnsignedLongLongTy
;
3991 assert(Context
.getTypeSize(Ty
) == ResultVal
.getBitWidth() &&
3992 "long long is not intmax_t?");
3994 // If this value fits into a ULL, try to figure out what else it fits into
3995 // according to the rules of C99 6.4.4.1p5.
3997 // Octal, Hexadecimal, and integers with a U suffix are allowed to
3998 // be an unsigned int.
3999 bool AllowUnsigned
= Literal
.isUnsigned
|| Literal
.getRadix() != 10;
4001 // Check from smallest to largest, picking the smallest type we can.
4004 // Microsoft specific integer suffixes are explicitly sized.
4005 if (Literal
.MicrosoftInteger
) {
4006 if (Literal
.MicrosoftInteger
== 8 && !Literal
.isUnsigned
) {
4008 Ty
= Context
.CharTy
;
4010 Width
= Literal
.MicrosoftInteger
;
4011 Ty
= Context
.getIntTypeForBitwidth(Width
,
4012 /*Signed=*/!Literal
.isUnsigned
);
4016 // Bit-precise integer literals are automagically-sized based on the
4017 // width required by the literal.
4018 if (Literal
.isBitInt
) {
4019 // The signed version has one more bit for the sign value. There are no
4020 // zero-width bit-precise integers, even if the literal value is 0.
4021 Width
= std::max(ResultVal
.getActiveBits(), 1u) +
4022 (Literal
.isUnsigned
? 0u : 1u);
4024 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4025 // and reset the type to the largest supported width.
4026 unsigned int MaxBitIntWidth
=
4027 Context
.getTargetInfo().getMaxBitIntWidth();
4028 if (Width
> MaxBitIntWidth
) {
4029 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
4030 << Literal
.isUnsigned
;
4031 Width
= MaxBitIntWidth
;
4034 // Reset the result value to the smaller APInt and select the correct
4035 // type to be used. Note, we zext even for signed values because the
4036 // literal itself is always an unsigned value (a preceeding - is a
4037 // unary operator, not part of the literal).
4038 ResultVal
= ResultVal
.zextOrTrunc(Width
);
4039 Ty
= Context
.getBitIntType(Literal
.isUnsigned
, Width
);
4042 // Check C++2b size_t literals.
4043 if (Literal
.isSizeT
) {
4044 assert(!Literal
.MicrosoftInteger
&&
4045 "size_t literals can't be Microsoft literals");
4046 unsigned SizeTSize
= Context
.getTargetInfo().getTypeWidth(
4047 Context
.getTargetInfo().getSizeType());
4049 // Does it fit in size_t?
4050 if (ResultVal
.isIntN(SizeTSize
)) {
4051 // Does it fit in ssize_t?
4052 if (!Literal
.isUnsigned
&& ResultVal
[SizeTSize
- 1] == 0)
4053 Ty
= Context
.getSignedSizeType();
4054 else if (AllowUnsigned
)
4055 Ty
= Context
.getSizeType();
4060 if (Ty
.isNull() && !Literal
.isLong
&& !Literal
.isLongLong
&&
4062 // Are int/unsigned possibilities?
4063 unsigned IntSize
= Context
.getTargetInfo().getIntWidth();
4065 // Does it fit in a unsigned int?
4066 if (ResultVal
.isIntN(IntSize
)) {
4067 // Does it fit in a signed int?
4068 if (!Literal
.isUnsigned
&& ResultVal
[IntSize
-1] == 0)
4070 else if (AllowUnsigned
)
4071 Ty
= Context
.UnsignedIntTy
;
4076 // Are long/unsigned long possibilities?
4077 if (Ty
.isNull() && !Literal
.isLongLong
&& !Literal
.isSizeT
) {
4078 unsigned LongSize
= Context
.getTargetInfo().getLongWidth();
4080 // Does it fit in a unsigned long?
4081 if (ResultVal
.isIntN(LongSize
)) {
4082 // Does it fit in a signed long?
4083 if (!Literal
.isUnsigned
&& ResultVal
[LongSize
-1] == 0)
4084 Ty
= Context
.LongTy
;
4085 else if (AllowUnsigned
)
4086 Ty
= Context
.UnsignedLongTy
;
4087 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4089 else if (!getLangOpts().C99
&& !getLangOpts().CPlusPlus11
) {
4090 const unsigned LongLongSize
=
4091 Context
.getTargetInfo().getLongLongWidth();
4092 Diag(Tok
.getLocation(),
4093 getLangOpts().CPlusPlus
4095 ? diag::warn_old_implicitly_unsigned_long_cxx
4096 : /*C++98 UB*/ diag::
4097 ext_old_implicitly_unsigned_long_cxx
4098 : diag::warn_old_implicitly_unsigned_long
)
4099 << (LongLongSize
> LongSize
? /*will have type 'long long'*/ 0
4100 : /*will be ill-formed*/ 1);
4101 Ty
= Context
.UnsignedLongTy
;
4107 // Check long long if needed.
4108 if (Ty
.isNull() && !Literal
.isSizeT
) {
4109 unsigned LongLongSize
= Context
.getTargetInfo().getLongLongWidth();
4111 // Does it fit in a unsigned long long?
4112 if (ResultVal
.isIntN(LongLongSize
)) {
4113 // Does it fit in a signed long long?
4114 // To be compatible with MSVC, hex integer literals ending with the
4115 // LL or i64 suffix are always signed in Microsoft mode.
4116 if (!Literal
.isUnsigned
&& (ResultVal
[LongLongSize
-1] == 0 ||
4117 (getLangOpts().MSVCCompat
&& Literal
.isLongLong
)))
4118 Ty
= Context
.LongLongTy
;
4119 else if (AllowUnsigned
)
4120 Ty
= Context
.UnsignedLongLongTy
;
4121 Width
= LongLongSize
;
4123 // 'long long' is a C99 or C++11 feature, whether the literal
4124 // explicitly specified 'long long' or we needed the extra width.
4125 if (getLangOpts().CPlusPlus
)
4126 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus11
4127 ? diag::warn_cxx98_compat_longlong
4128 : diag::ext_cxx11_longlong
);
4129 else if (!getLangOpts().C99
)
4130 Diag(Tok
.getLocation(), diag::ext_c99_longlong
);
4134 // If we still couldn't decide a type, we either have 'size_t' literal
4135 // that is out of range, or a decimal literal that does not fit in a
4136 // signed long long and has no U suffix.
4138 if (Literal
.isSizeT
)
4139 Diag(Tok
.getLocation(), diag::err_size_t_literal_too_large
)
4140 << Literal
.isUnsigned
;
4142 Diag(Tok
.getLocation(),
4143 diag::ext_integer_literal_too_large_for_signed
);
4144 Ty
= Context
.UnsignedLongLongTy
;
4145 Width
= Context
.getTargetInfo().getLongLongWidth();
4148 if (ResultVal
.getBitWidth() != Width
)
4149 ResultVal
= ResultVal
.trunc(Width
);
4151 Res
= IntegerLiteral::Create(Context
, ResultVal
, Ty
, Tok
.getLocation());
4154 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4155 if (Literal
.isImaginary
) {
4156 Res
= new (Context
) ImaginaryLiteral(Res
,
4157 Context
.getComplexType(Res
->getType()));
4159 Diag(Tok
.getLocation(), diag::ext_imaginary_constant
);
4164 ExprResult
Sema::ActOnParenExpr(SourceLocation L
, SourceLocation R
, Expr
*E
) {
4165 assert(E
&& "ActOnParenExpr() missing expr");
4166 QualType ExprTy
= E
->getType();
4167 if (getLangOpts().ProtectParens
&& CurFPFeatures
.getAllowFPReassociate() &&
4168 !E
->isLValue() && ExprTy
->hasFloatingRepresentation())
4169 return BuildBuiltinCallExpr(R
, Builtin::BI__arithmetic_fence
, E
);
4170 return new (Context
) ParenExpr(L
, R
, E
);
4173 static bool CheckVecStepTraitOperandType(Sema
&S
, QualType T
,
4175 SourceRange ArgRange
) {
4176 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4177 // scalar or vector data type argument..."
4178 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4179 // type (C99 6.2.5p18) or void.
4180 if (!(T
->isArithmeticType() || T
->isVoidType() || T
->isVectorType())) {
4181 S
.Diag(Loc
, diag::err_vecstep_non_scalar_vector_type
)
4186 assert((T
->isVoidType() || !T
->isIncompleteType()) &&
4187 "Scalar types should always be complete");
4191 static bool CheckExtensionTraitOperandType(Sema
&S
, QualType T
,
4193 SourceRange ArgRange
,
4194 UnaryExprOrTypeTrait TraitKind
) {
4195 // Invalid types must be hard errors for SFINAE in C++.
4196 if (S
.LangOpts
.CPlusPlus
)
4200 if (T
->isFunctionType() &&
4201 (TraitKind
== UETT_SizeOf
|| TraitKind
== UETT_AlignOf
||
4202 TraitKind
== UETT_PreferredAlignOf
)) {
4203 // sizeof(function)/alignof(function) is allowed as an extension.
4204 S
.Diag(Loc
, diag::ext_sizeof_alignof_function_type
)
4205 << getTraitSpelling(TraitKind
) << ArgRange
;
4209 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4210 // this is an error (OpenCL v1.1 s6.3.k)
4211 if (T
->isVoidType()) {
4212 unsigned DiagID
= S
.LangOpts
.OpenCL
? diag::err_opencl_sizeof_alignof_type
4213 : diag::ext_sizeof_alignof_void_type
;
4214 S
.Diag(Loc
, DiagID
) << getTraitSpelling(TraitKind
) << ArgRange
;
4221 static bool CheckObjCTraitOperandConstraints(Sema
&S
, QualType T
,
4223 SourceRange ArgRange
,
4224 UnaryExprOrTypeTrait TraitKind
) {
4225 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4226 // runtime doesn't allow it.
4227 if (!S
.LangOpts
.ObjCRuntime
.allowsSizeofAlignof() && T
->isObjCObjectType()) {
4228 S
.Diag(Loc
, diag::err_sizeof_nonfragile_interface
)
4229 << T
<< (TraitKind
== UETT_SizeOf
)
4237 /// Check whether E is a pointer from a decayed array type (the decayed
4238 /// pointer type is equal to T) and emit a warning if it is.
4239 static void warnOnSizeofOnArrayDecay(Sema
&S
, SourceLocation Loc
, QualType T
,
4241 // Don't warn if the operation changed the type.
4242 if (T
!= E
->getType())
4245 // Now look for array decays.
4246 ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
);
4247 if (!ICE
|| ICE
->getCastKind() != CK_ArrayToPointerDecay
)
4250 S
.Diag(Loc
, diag::warn_sizeof_array_decay
) << ICE
->getSourceRange()
4252 << ICE
->getSubExpr()->getType();
4255 /// Check the constraints on expression operands to unary type expression
4256 /// and type traits.
4258 /// Completes any types necessary and validates the constraints on the operand
4259 /// expression. The logic mostly mirrors the type-based overload, but may modify
4260 /// the expression as it completes the type for that expression through template
4261 /// instantiation, etc.
4262 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr
*E
,
4263 UnaryExprOrTypeTrait ExprKind
) {
4264 QualType ExprTy
= E
->getType();
4265 assert(!ExprTy
->isReferenceType());
4267 bool IsUnevaluatedOperand
=
4268 (ExprKind
== UETT_SizeOf
|| ExprKind
== UETT_AlignOf
||
4269 ExprKind
== UETT_PreferredAlignOf
|| ExprKind
== UETT_VecStep
);
4270 if (IsUnevaluatedOperand
) {
4271 ExprResult Result
= CheckUnevaluatedOperand(E
);
4272 if (Result
.isInvalid())
4277 // The operand for sizeof and alignof is in an unevaluated expression context,
4278 // so side effects could result in unintended consequences.
4279 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4280 // used to build SFINAE gadgets.
4281 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4282 if (IsUnevaluatedOperand
&& !inTemplateInstantiation() &&
4283 !E
->isInstantiationDependent() &&
4284 !E
->getType()->isVariableArrayType() &&
4285 E
->HasSideEffects(Context
, false))
4286 Diag(E
->getExprLoc(), diag::warn_side_effects_unevaluated_context
);
4288 if (ExprKind
== UETT_VecStep
)
4289 return CheckVecStepTraitOperandType(*this, ExprTy
, E
->getExprLoc(),
4290 E
->getSourceRange());
4292 // Explicitly list some types as extensions.
4293 if (!CheckExtensionTraitOperandType(*this, ExprTy
, E
->getExprLoc(),
4294 E
->getSourceRange(), ExprKind
))
4297 // 'alignof' applied to an expression only requires the base element type of
4298 // the expression to be complete. 'sizeof' requires the expression's type to
4299 // be complete (and will attempt to complete it if it's an array of unknown
4301 if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
) {
4302 if (RequireCompleteSizedType(
4303 E
->getExprLoc(), Context
.getBaseElementType(E
->getType()),
4304 diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4305 getTraitSpelling(ExprKind
), E
->getSourceRange()))
4308 if (RequireCompleteSizedExprType(
4309 E
, diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4310 getTraitSpelling(ExprKind
), E
->getSourceRange()))
4314 // Completing the expression's type may have changed it.
4315 ExprTy
= E
->getType();
4316 assert(!ExprTy
->isReferenceType());
4318 if (ExprTy
->isFunctionType()) {
4319 Diag(E
->getExprLoc(), diag::err_sizeof_alignof_function_type
)
4320 << getTraitSpelling(ExprKind
) << E
->getSourceRange();
4324 if (CheckObjCTraitOperandConstraints(*this, ExprTy
, E
->getExprLoc(),
4325 E
->getSourceRange(), ExprKind
))
4328 if (ExprKind
== UETT_SizeOf
) {
4329 if (DeclRefExpr
*DeclRef
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParens())) {
4330 if (ParmVarDecl
*PVD
= dyn_cast
<ParmVarDecl
>(DeclRef
->getFoundDecl())) {
4331 QualType OType
= PVD
->getOriginalType();
4332 QualType Type
= PVD
->getType();
4333 if (Type
->isPointerType() && OType
->isArrayType()) {
4334 Diag(E
->getExprLoc(), diag::warn_sizeof_array_param
)
4336 Diag(PVD
->getLocation(), diag::note_declared_at
);
4341 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4342 // decays into a pointer and returns an unintended result. This is most
4343 // likely a typo for "sizeof(array) op x".
4344 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
->IgnoreParens())) {
4345 warnOnSizeofOnArrayDecay(*this, BO
->getOperatorLoc(), BO
->getType(),
4347 warnOnSizeofOnArrayDecay(*this, BO
->getOperatorLoc(), BO
->getType(),
4355 /// Check the constraints on operands to unary expression and type
4358 /// This will complete any types necessary, and validate the various constraints
4359 /// on those operands.
4361 /// The UsualUnaryConversions() function is *not* called by this routine.
4362 /// C99 6.3.2.1p[2-4] all state:
4363 /// Except when it is the operand of the sizeof operator ...
4365 /// C++ [expr.sizeof]p4
4366 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4367 /// standard conversions are not applied to the operand of sizeof.
4369 /// This policy is followed for all of the unary trait expressions.
4370 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType
,
4371 SourceLocation OpLoc
,
4372 SourceRange ExprRange
,
4373 UnaryExprOrTypeTrait ExprKind
) {
4374 if (ExprType
->isDependentType())
4377 // C++ [expr.sizeof]p2:
4378 // When applied to a reference or a reference type, the result
4379 // is the size of the referenced type.
4380 // C++11 [expr.alignof]p3:
4381 // When alignof is applied to a reference type, the result
4382 // shall be the alignment of the referenced type.
4383 if (const ReferenceType
*Ref
= ExprType
->getAs
<ReferenceType
>())
4384 ExprType
= Ref
->getPointeeType();
4386 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4387 // When alignof or _Alignof is applied to an array type, the result
4388 // is the alignment of the element type.
4389 if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
||
4390 ExprKind
== UETT_OpenMPRequiredSimdAlign
)
4391 ExprType
= Context
.getBaseElementType(ExprType
);
4393 if (ExprKind
== UETT_VecStep
)
4394 return CheckVecStepTraitOperandType(*this, ExprType
, OpLoc
, ExprRange
);
4396 // Explicitly list some types as extensions.
4397 if (!CheckExtensionTraitOperandType(*this, ExprType
, OpLoc
, ExprRange
,
4401 if (RequireCompleteSizedType(
4402 OpLoc
, ExprType
, diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4403 getTraitSpelling(ExprKind
), ExprRange
))
4406 if (ExprType
->isFunctionType()) {
4407 Diag(OpLoc
, diag::err_sizeof_alignof_function_type
)
4408 << getTraitSpelling(ExprKind
) << ExprRange
;
4412 if (CheckObjCTraitOperandConstraints(*this, ExprType
, OpLoc
, ExprRange
,
4419 static bool CheckAlignOfExpr(Sema
&S
, Expr
*E
, UnaryExprOrTypeTrait ExprKind
) {
4420 // Cannot know anything else if the expression is dependent.
4421 if (E
->isTypeDependent())
4424 if (E
->getObjectKind() == OK_BitField
) {
4425 S
.Diag(E
->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield
)
4426 << 1 << E
->getSourceRange();
4430 ValueDecl
*D
= nullptr;
4431 Expr
*Inner
= E
->IgnoreParens();
4432 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Inner
)) {
4434 } else if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Inner
)) {
4435 D
= ME
->getMemberDecl();
4438 // If it's a field, require the containing struct to have a
4439 // complete definition so that we can compute the layout.
4441 // This can happen in C++11 onwards, either by naming the member
4442 // in a way that is not transformed into a member access expression
4443 // (in an unevaluated operand, for instance), or by naming the member
4444 // in a trailing-return-type.
4446 // For the record, since __alignof__ on expressions is a GCC
4447 // extension, GCC seems to permit this but always gives the
4448 // nonsensical answer 0.
4450 // We don't really need the layout here --- we could instead just
4451 // directly check for all the appropriate alignment-lowing
4452 // attributes --- but that would require duplicating a lot of
4453 // logic that just isn't worth duplicating for such a marginal
4455 if (FieldDecl
*FD
= dyn_cast_or_null
<FieldDecl
>(D
)) {
4456 // Fast path this check, since we at least know the record has a
4457 // definition if we can find a member of it.
4458 if (!FD
->getParent()->isCompleteDefinition()) {
4459 S
.Diag(E
->getExprLoc(), diag::err_alignof_member_of_incomplete_type
)
4460 << E
->getSourceRange();
4464 // Otherwise, if it's a field, and the field doesn't have
4465 // reference type, then it must have a complete type (or be a
4466 // flexible array member, which we explicitly want to
4467 // white-list anyway), which makes the following checks trivial.
4468 if (!FD
->getType()->isReferenceType())
4472 return S
.CheckUnaryExprOrTypeTraitOperand(E
, ExprKind
);
4475 bool Sema::CheckVecStepExpr(Expr
*E
) {
4476 E
= E
->IgnoreParens();
4478 // Cannot know anything else if the expression is dependent.
4479 if (E
->isTypeDependent())
4482 return CheckUnaryExprOrTypeTraitOperand(E
, UETT_VecStep
);
4485 static void captureVariablyModifiedType(ASTContext
&Context
, QualType T
,
4486 CapturingScopeInfo
*CSI
) {
4487 assert(T
->isVariablyModifiedType());
4488 assert(CSI
!= nullptr);
4490 // We're going to walk down into the type and look for VLA expressions.
4492 const Type
*Ty
= T
.getTypePtr();
4493 switch (Ty
->getTypeClass()) {
4494 #define TYPE(Class, Base)
4495 #define ABSTRACT_TYPE(Class, Base)
4496 #define NON_CANONICAL_TYPE(Class, Base)
4497 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4498 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4499 #include "clang/AST/TypeNodes.inc"
4502 // These types are never variably-modified.
4506 case Type::ExtVector
:
4507 case Type::ConstantMatrix
:
4510 case Type::TemplateSpecialization
:
4511 case Type::ObjCObject
:
4512 case Type::ObjCInterface
:
4513 case Type::ObjCObjectPointer
:
4514 case Type::ObjCTypeParam
:
4517 llvm_unreachable("type class is never variably-modified!");
4518 case Type::Elaborated
:
4519 T
= cast
<ElaboratedType
>(Ty
)->getNamedType();
4521 case Type::Adjusted
:
4522 T
= cast
<AdjustedType
>(Ty
)->getOriginalType();
4525 T
= cast
<DecayedType
>(Ty
)->getPointeeType();
4528 T
= cast
<PointerType
>(Ty
)->getPointeeType();
4530 case Type::BlockPointer
:
4531 T
= cast
<BlockPointerType
>(Ty
)->getPointeeType();
4533 case Type::LValueReference
:
4534 case Type::RValueReference
:
4535 T
= cast
<ReferenceType
>(Ty
)->getPointeeType();
4537 case Type::MemberPointer
:
4538 T
= cast
<MemberPointerType
>(Ty
)->getPointeeType();
4540 case Type::ConstantArray
:
4541 case Type::IncompleteArray
:
4542 // Losing element qualification here is fine.
4543 T
= cast
<ArrayType
>(Ty
)->getElementType();
4545 case Type::VariableArray
: {
4546 // Losing element qualification here is fine.
4547 const VariableArrayType
*VAT
= cast
<VariableArrayType
>(Ty
);
4549 // Unknown size indication requires no size computation.
4550 // Otherwise, evaluate and record it.
4551 auto Size
= VAT
->getSizeExpr();
4552 if (Size
&& !CSI
->isVLATypeCaptured(VAT
) &&
4553 (isa
<CapturedRegionScopeInfo
>(CSI
) || isa
<LambdaScopeInfo
>(CSI
)))
4554 CSI
->addVLATypeCapture(Size
->getExprLoc(), VAT
, Context
.getSizeType());
4556 T
= VAT
->getElementType();
4559 case Type::FunctionProto
:
4560 case Type::FunctionNoProto
:
4561 T
= cast
<FunctionType
>(Ty
)->getReturnType();
4565 case Type::UnaryTransform
:
4566 case Type::Attributed
:
4567 case Type::BTFTagAttributed
:
4568 case Type::SubstTemplateTypeParm
:
4569 case Type::MacroQualified
:
4570 // Keep walking after single level desugaring.
4571 T
= T
.getSingleStepDesugaredType(Context
);
4574 T
= cast
<TypedefType
>(Ty
)->desugar();
4576 case Type::Decltype
:
4577 T
= cast
<DecltypeType
>(Ty
)->desugar();
4580 T
= cast
<UsingType
>(Ty
)->desugar();
4583 case Type::DeducedTemplateSpecialization
:
4584 T
= cast
<DeducedType
>(Ty
)->getDeducedType();
4586 case Type::TypeOfExpr
:
4587 T
= cast
<TypeOfExprType
>(Ty
)->getUnderlyingExpr()->getType();
4590 T
= cast
<AtomicType
>(Ty
)->getValueType();
4593 } while (!T
.isNull() && T
->isVariablyModifiedType());
4596 /// Build a sizeof or alignof expression given a type operand.
4598 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo
*TInfo
,
4599 SourceLocation OpLoc
,
4600 UnaryExprOrTypeTrait ExprKind
,
4605 QualType T
= TInfo
->getType();
4607 if (!T
->isDependentType() &&
4608 CheckUnaryExprOrTypeTraitOperand(T
, OpLoc
, R
, ExprKind
))
4611 if (T
->isVariablyModifiedType() && FunctionScopes
.size() > 1) {
4612 if (auto *TT
= T
->getAs
<TypedefType
>()) {
4613 for (auto I
= FunctionScopes
.rbegin(),
4614 E
= std::prev(FunctionScopes
.rend());
4616 auto *CSI
= dyn_cast
<CapturingScopeInfo
>(*I
);
4619 DeclContext
*DC
= nullptr;
4620 if (auto *LSI
= dyn_cast
<LambdaScopeInfo
>(CSI
))
4621 DC
= LSI
->CallOperator
;
4622 else if (auto *CRSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
))
4623 DC
= CRSI
->TheCapturedDecl
;
4624 else if (auto *BSI
= dyn_cast
<BlockScopeInfo
>(CSI
))
4627 if (DC
->containsDecl(TT
->getDecl()))
4629 captureVariablyModifiedType(Context
, T
, CSI
);
4635 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4636 if (isUnevaluatedContext() && ExprKind
== UETT_SizeOf
&&
4637 TInfo
->getType()->isVariablyModifiedType())
4638 TInfo
= TransformToPotentiallyEvaluated(TInfo
);
4640 return new (Context
) UnaryExprOrTypeTraitExpr(
4641 ExprKind
, TInfo
, Context
.getSizeType(), OpLoc
, R
.getEnd());
4644 /// Build a sizeof or alignof expression given an expression
4647 Sema::CreateUnaryExprOrTypeTraitExpr(Expr
*E
, SourceLocation OpLoc
,
4648 UnaryExprOrTypeTrait ExprKind
) {
4649 ExprResult PE
= CheckPlaceholderExpr(E
);
4655 // Verify that the operand is valid.
4656 bool isInvalid
= false;
4657 if (E
->isTypeDependent()) {
4658 // Delay type-checking for type-dependent expressions.
4659 } else if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
) {
4660 isInvalid
= CheckAlignOfExpr(*this, E
, ExprKind
);
4661 } else if (ExprKind
== UETT_VecStep
) {
4662 isInvalid
= CheckVecStepExpr(E
);
4663 } else if (ExprKind
== UETT_OpenMPRequiredSimdAlign
) {
4664 Diag(E
->getExprLoc(), diag::err_openmp_default_simd_align_expr
);
4666 } else if (E
->refersToBitField()) { // C99 6.5.3.4p1.
4667 Diag(E
->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield
) << 0;
4670 isInvalid
= CheckUnaryExprOrTypeTraitOperand(E
, UETT_SizeOf
);
4676 if (ExprKind
== UETT_SizeOf
&& E
->getType()->isVariableArrayType()) {
4677 PE
= TransformToPotentiallyEvaluated(E
);
4678 if (PE
.isInvalid()) return ExprError();
4682 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4683 return new (Context
) UnaryExprOrTypeTraitExpr(
4684 ExprKind
, E
, Context
.getSizeType(), OpLoc
, E
->getSourceRange().getEnd());
4687 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4688 /// expr and the same for @c alignof and @c __alignof
4689 /// Note that the ArgRange is invalid if isType is false.
4691 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc
,
4692 UnaryExprOrTypeTrait ExprKind
, bool IsType
,
4693 void *TyOrEx
, SourceRange ArgRange
) {
4694 // If error parsing type, ignore.
4695 if (!TyOrEx
) return ExprError();
4698 TypeSourceInfo
*TInfo
;
4699 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx
), &TInfo
);
4700 return CreateUnaryExprOrTypeTraitExpr(TInfo
, OpLoc
, ExprKind
, ArgRange
);
4703 Expr
*ArgEx
= (Expr
*)TyOrEx
;
4704 ExprResult Result
= CreateUnaryExprOrTypeTraitExpr(ArgEx
, OpLoc
, ExprKind
);
4708 static QualType
CheckRealImagOperand(Sema
&S
, ExprResult
&V
, SourceLocation Loc
,
4710 if (V
.get()->isTypeDependent())
4711 return S
.Context
.DependentTy
;
4713 // _Real and _Imag are only l-values for normal l-values.
4714 if (V
.get()->getObjectKind() != OK_Ordinary
) {
4715 V
= S
.DefaultLvalueConversion(V
.get());
4720 // These operators return the element type of a complex type.
4721 if (const ComplexType
*CT
= V
.get()->getType()->getAs
<ComplexType
>())
4722 return CT
->getElementType();
4724 // Otherwise they pass through real integer and floating point types here.
4725 if (V
.get()->getType()->isArithmeticType())
4726 return V
.get()->getType();
4728 // Test for placeholders.
4729 ExprResult PR
= S
.CheckPlaceholderExpr(V
.get());
4730 if (PR
.isInvalid()) return QualType();
4731 if (PR
.get() != V
.get()) {
4733 return CheckRealImagOperand(S
, V
, Loc
, IsReal
);
4736 // Reject anything else.
4737 S
.Diag(Loc
, diag::err_realimag_invalid_type
) << V
.get()->getType()
4738 << (IsReal
? "__real" : "__imag");
4745 Sema::ActOnPostfixUnaryOp(Scope
*S
, SourceLocation OpLoc
,
4746 tok::TokenKind Kind
, Expr
*Input
) {
4747 UnaryOperatorKind Opc
;
4749 default: llvm_unreachable("Unknown unary op!");
4750 case tok::plusplus
: Opc
= UO_PostInc
; break;
4751 case tok::minusminus
: Opc
= UO_PostDec
; break;
4754 // Since this might is a postfix expression, get rid of ParenListExprs.
4755 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, Input
);
4756 if (Result
.isInvalid()) return ExprError();
4757 Input
= Result
.get();
4759 return BuildUnaryOp(S
, OpLoc
, Opc
, Input
);
4762 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4764 /// \return true on error
4765 static bool checkArithmeticOnObjCPointer(Sema
&S
,
4766 SourceLocation opLoc
,
4768 assert(op
->getType()->isObjCObjectPointerType());
4769 if (S
.LangOpts
.ObjCRuntime
.allowsPointerArithmetic() &&
4770 !S
.LangOpts
.ObjCSubscriptingLegacyRuntime
)
4773 S
.Diag(opLoc
, diag::err_arithmetic_nonfragile_interface
)
4774 << op
->getType()->castAs
<ObjCObjectPointerType
>()->getPointeeType()
4775 << op
->getSourceRange();
4779 static bool isMSPropertySubscriptExpr(Sema
&S
, Expr
*Base
) {
4780 auto *BaseNoParens
= Base
->IgnoreParens();
4781 if (auto *MSProp
= dyn_cast
<MSPropertyRefExpr
>(BaseNoParens
))
4782 return MSProp
->getPropertyDecl()->getType()->isArrayType();
4783 return isa
<MSPropertySubscriptExpr
>(BaseNoParens
);
4786 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
4787 // Typically this is DependentTy, but can sometimes be more precise.
4789 // There are cases when we could determine a non-dependent type:
4790 // - LHS and RHS may have non-dependent types despite being type-dependent
4791 // (e.g. unbounded array static members of the current instantiation)
4792 // - one may be a dependent-sized array with known element type
4793 // - one may be a dependent-typed valid index (enum in current instantiation)
4795 // We *always* return a dependent type, in such cases it is DependentTy.
4796 // This avoids creating type-dependent expressions with non-dependent types.
4797 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
4798 static QualType
getDependentArraySubscriptType(Expr
*LHS
, Expr
*RHS
,
4799 const ASTContext
&Ctx
) {
4800 assert(LHS
->isTypeDependent() || RHS
->isTypeDependent());
4801 QualType LTy
= LHS
->getType(), RTy
= RHS
->getType();
4802 QualType Result
= Ctx
.DependentTy
;
4803 if (RTy
->isIntegralOrUnscopedEnumerationType()) {
4804 if (const PointerType
*PT
= LTy
->getAs
<PointerType
>())
4805 Result
= PT
->getPointeeType();
4806 else if (const ArrayType
*AT
= LTy
->getAsArrayTypeUnsafe())
4807 Result
= AT
->getElementType();
4808 } else if (LTy
->isIntegralOrUnscopedEnumerationType()) {
4809 if (const PointerType
*PT
= RTy
->getAs
<PointerType
>())
4810 Result
= PT
->getPointeeType();
4811 else if (const ArrayType
*AT
= RTy
->getAsArrayTypeUnsafe())
4812 Result
= AT
->getElementType();
4814 // Ensure we return a dependent type.
4815 return Result
->isDependentType() ? Result
: Ctx
.DependentTy
;
4818 static bool checkArgsForPlaceholders(Sema
&S
, MultiExprArg args
);
4820 ExprResult
Sema::ActOnArraySubscriptExpr(Scope
*S
, Expr
*base
,
4821 SourceLocation lbLoc
,
4822 MultiExprArg ArgExprs
,
4823 SourceLocation rbLoc
) {
4825 if (base
&& !base
->getType().isNull() &&
4826 base
->hasPlaceholderType(BuiltinType::OMPArraySection
))
4827 return ActOnOMPArraySectionExpr(base
, lbLoc
, ArgExprs
.front(), SourceLocation(),
4828 SourceLocation(), /*Length*/ nullptr,
4829 /*Stride=*/nullptr, rbLoc
);
4831 // Since this might be a postfix expression, get rid of ParenListExprs.
4832 if (isa
<ParenListExpr
>(base
)) {
4833 ExprResult result
= MaybeConvertParenListExprToParenExpr(S
, base
);
4834 if (result
.isInvalid())
4836 base
= result
.get();
4839 // Check if base and idx form a MatrixSubscriptExpr.
4841 // Helper to check for comma expressions, which are not allowed as indices for
4842 // matrix subscript expressions.
4843 auto CheckAndReportCommaError
= [this, base
, rbLoc
](Expr
*E
) {
4844 if (isa
<BinaryOperator
>(E
) && cast
<BinaryOperator
>(E
)->isCommaOp()) {
4845 Diag(E
->getExprLoc(), diag::err_matrix_subscript_comma
)
4846 << SourceRange(base
->getBeginLoc(), rbLoc
);
4851 // The matrix subscript operator ([][])is considered a single operator.
4852 // Separating the index expressions by parenthesis is not allowed.
4853 if (base
->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx
) &&
4854 !isa
<MatrixSubscriptExpr
>(base
)) {
4855 Diag(base
->getExprLoc(), diag::err_matrix_separate_incomplete_index
)
4856 << SourceRange(base
->getBeginLoc(), rbLoc
);
4859 // If the base is a MatrixSubscriptExpr, try to create a new
4860 // MatrixSubscriptExpr.
4861 auto *matSubscriptE
= dyn_cast
<MatrixSubscriptExpr
>(base
);
4862 if (matSubscriptE
) {
4863 assert(ArgExprs
.size() == 1);
4864 if (CheckAndReportCommaError(ArgExprs
.front()))
4867 assert(matSubscriptE
->isIncomplete() &&
4868 "base has to be an incomplete matrix subscript");
4869 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE
->getBase(),
4870 matSubscriptE
->getRowIdx(),
4871 ArgExprs
.front(), rbLoc
);
4874 // Handle any non-overload placeholder types in the base and index
4875 // expressions. We can't handle overloads here because the other
4876 // operand might be an overloadable type, in which case the overload
4877 // resolution for the operator overload should get the first crack
4879 bool IsMSPropertySubscript
= false;
4880 if (base
->getType()->isNonOverloadPlaceholderType()) {
4881 IsMSPropertySubscript
= isMSPropertySubscriptExpr(*this, base
);
4882 if (!IsMSPropertySubscript
) {
4883 ExprResult result
= CheckPlaceholderExpr(base
);
4884 if (result
.isInvalid())
4886 base
= result
.get();
4890 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
4891 if (base
->getType()->isMatrixType()) {
4892 assert(ArgExprs
.size() == 1);
4893 if (CheckAndReportCommaError(ArgExprs
.front()))
4896 return CreateBuiltinMatrixSubscriptExpr(base
, ArgExprs
.front(), nullptr,
4900 if (ArgExprs
.size() == 1 && getLangOpts().CPlusPlus20
) {
4901 Expr
*idx
= ArgExprs
[0];
4902 if ((isa
<BinaryOperator
>(idx
) && cast
<BinaryOperator
>(idx
)->isCommaOp()) ||
4903 (isa
<CXXOperatorCallExpr
>(idx
) &&
4904 cast
<CXXOperatorCallExpr
>(idx
)->getOperator() == OO_Comma
)) {
4905 Diag(idx
->getExprLoc(), diag::warn_deprecated_comma_subscript
)
4906 << SourceRange(base
->getBeginLoc(), rbLoc
);
4910 if (ArgExprs
.size() == 1 &&
4911 ArgExprs
[0]->getType()->isNonOverloadPlaceholderType()) {
4912 ExprResult result
= CheckPlaceholderExpr(ArgExprs
[0]);
4913 if (result
.isInvalid())
4915 ArgExprs
[0] = result
.get();
4917 if (checkArgsForPlaceholders(*this, ArgExprs
))
4921 // Build an unanalyzed expression if either operand is type-dependent.
4922 if (getLangOpts().CPlusPlus
&& ArgExprs
.size() == 1 &&
4923 (base
->isTypeDependent() ||
4924 Expr::hasAnyTypeDependentArguments(ArgExprs
))) {
4925 return new (Context
) ArraySubscriptExpr(
4926 base
, ArgExprs
.front(),
4927 getDependentArraySubscriptType(base
, ArgExprs
.front(), getASTContext()),
4928 VK_LValue
, OK_Ordinary
, rbLoc
);
4931 // MSDN, property (C++)
4932 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4933 // This attribute can also be used in the declaration of an empty array in a
4934 // class or structure definition. For example:
4935 // __declspec(property(get=GetX, put=PutX)) int x[];
4936 // The above statement indicates that x[] can be used with one or more array
4937 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4938 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4939 if (IsMSPropertySubscript
) {
4940 assert(ArgExprs
.size() == 1);
4941 // Build MS property subscript expression if base is MS property reference
4942 // or MS property subscript.
4943 return new (Context
)
4944 MSPropertySubscriptExpr(base
, ArgExprs
.front(), Context
.PseudoObjectTy
,
4945 VK_LValue
, OK_Ordinary
, rbLoc
);
4948 // Use C++ overloaded-operator rules if either operand has record
4949 // type. The spec says to do this if either type is *overloadable*,
4950 // but enum types can't declare subscript operators or conversion
4951 // operators, so there's nothing interesting for overload resolution
4952 // to do if there aren't any record types involved.
4954 // ObjC pointers have their own subscripting logic that is not tied
4955 // to overload resolution and so should not take this path.
4956 if (getLangOpts().CPlusPlus
&& !base
->getType()->isObjCObjectPointerType() &&
4957 ((base
->getType()->isRecordType() ||
4958 (ArgExprs
.size() != 1 || ArgExprs
[0]->getType()->isRecordType())))) {
4959 return CreateOverloadedArraySubscriptExpr(lbLoc
, rbLoc
, base
, ArgExprs
);
4963 CreateBuiltinArraySubscriptExpr(base
, lbLoc
, ArgExprs
.front(), rbLoc
);
4965 if (!Res
.isInvalid() && isa
<ArraySubscriptExpr
>(Res
.get()))
4966 CheckSubscriptAccessOfNoDeref(cast
<ArraySubscriptExpr
>(Res
.get()));
4971 ExprResult
Sema::tryConvertExprToType(Expr
*E
, QualType Ty
) {
4972 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(Ty
);
4973 InitializationKind Kind
=
4974 InitializationKind::CreateCopy(E
->getBeginLoc(), SourceLocation());
4975 InitializationSequence
InitSeq(*this, Entity
, Kind
, E
);
4976 return InitSeq
.Perform(*this, Entity
, Kind
, E
);
4979 ExprResult
Sema::CreateBuiltinMatrixSubscriptExpr(Expr
*Base
, Expr
*RowIdx
,
4981 SourceLocation RBLoc
) {
4982 ExprResult BaseR
= CheckPlaceholderExpr(Base
);
4983 if (BaseR
.isInvalid())
4987 ExprResult RowR
= CheckPlaceholderExpr(RowIdx
);
4988 if (RowR
.isInvalid())
4990 RowIdx
= RowR
.get();
4993 return new (Context
) MatrixSubscriptExpr(
4994 Base
, RowIdx
, ColumnIdx
, Context
.IncompleteMatrixIdxTy
, RBLoc
);
4996 // Build an unanalyzed expression if any of the operands is type-dependent.
4997 if (Base
->isTypeDependent() || RowIdx
->isTypeDependent() ||
4998 ColumnIdx
->isTypeDependent())
4999 return new (Context
) MatrixSubscriptExpr(Base
, RowIdx
, ColumnIdx
,
5000 Context
.DependentTy
, RBLoc
);
5002 ExprResult ColumnR
= CheckPlaceholderExpr(ColumnIdx
);
5003 if (ColumnR
.isInvalid())
5005 ColumnIdx
= ColumnR
.get();
5007 // Check that IndexExpr is an integer expression. If it is a constant
5008 // expression, check that it is less than Dim (= the number of elements in the
5009 // corresponding dimension).
5010 auto IsIndexValid
= [&](Expr
*IndexExpr
, unsigned Dim
,
5011 bool IsColumnIdx
) -> Expr
* {
5012 if (!IndexExpr
->getType()->isIntegerType() &&
5013 !IndexExpr
->isTypeDependent()) {
5014 Diag(IndexExpr
->getBeginLoc(), diag::err_matrix_index_not_integer
)
5019 if (std::optional
<llvm::APSInt
> Idx
=
5020 IndexExpr
->getIntegerConstantExpr(Context
)) {
5021 if ((*Idx
< 0 || *Idx
>= Dim
)) {
5022 Diag(IndexExpr
->getBeginLoc(), diag::err_matrix_index_outside_range
)
5023 << IsColumnIdx
<< Dim
;
5028 ExprResult ConvExpr
=
5029 tryConvertExprToType(IndexExpr
, Context
.getSizeType());
5030 assert(!ConvExpr
.isInvalid() &&
5031 "should be able to convert any integer type to size type");
5032 return ConvExpr
.get();
5035 auto *MTy
= Base
->getType()->getAs
<ConstantMatrixType
>();
5036 RowIdx
= IsIndexValid(RowIdx
, MTy
->getNumRows(), false);
5037 ColumnIdx
= IsIndexValid(ColumnIdx
, MTy
->getNumColumns(), true);
5038 if (!RowIdx
|| !ColumnIdx
)
5041 return new (Context
) MatrixSubscriptExpr(Base
, RowIdx
, ColumnIdx
,
5042 MTy
->getElementType(), RBLoc
);
5045 void Sema::CheckAddressOfNoDeref(const Expr
*E
) {
5046 ExpressionEvaluationContextRecord
&LastRecord
= ExprEvalContexts
.back();
5047 const Expr
*StrippedExpr
= E
->IgnoreParenImpCasts();
5049 // For expressions like `&(*s).b`, the base is recorded and what should be
5051 const MemberExpr
*Member
= nullptr;
5052 while ((Member
= dyn_cast
<MemberExpr
>(StrippedExpr
)) && !Member
->isArrow())
5053 StrippedExpr
= Member
->getBase()->IgnoreParenImpCasts();
5055 LastRecord
.PossibleDerefs
.erase(StrippedExpr
);
5058 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr
*E
) {
5059 if (isUnevaluatedContext())
5062 QualType ResultTy
= E
->getType();
5063 ExpressionEvaluationContextRecord
&LastRecord
= ExprEvalContexts
.back();
5065 // Bail if the element is an array since it is not memory access.
5066 if (isa
<ArrayType
>(ResultTy
))
5069 if (ResultTy
->hasAttr(attr::NoDeref
)) {
5070 LastRecord
.PossibleDerefs
.insert(E
);
5074 // Check if the base type is a pointer to a member access of a struct
5075 // marked with noderef.
5076 const Expr
*Base
= E
->getBase();
5077 QualType BaseTy
= Base
->getType();
5078 if (!(isa
<ArrayType
>(BaseTy
) || isa
<PointerType
>(BaseTy
)))
5079 // Not a pointer access
5082 const MemberExpr
*Member
= nullptr;
5083 while ((Member
= dyn_cast
<MemberExpr
>(Base
->IgnoreParenCasts())) &&
5085 Base
= Member
->getBase();
5087 if (const auto *Ptr
= dyn_cast
<PointerType
>(Base
->getType())) {
5088 if (Ptr
->getPointeeType()->hasAttr(attr::NoDeref
))
5089 LastRecord
.PossibleDerefs
.insert(E
);
5093 ExprResult
Sema::ActOnOMPArraySectionExpr(Expr
*Base
, SourceLocation LBLoc
,
5095 SourceLocation ColonLocFirst
,
5096 SourceLocation ColonLocSecond
,
5097 Expr
*Length
, Expr
*Stride
,
5098 SourceLocation RBLoc
) {
5099 if (Base
->hasPlaceholderType() &&
5100 !Base
->hasPlaceholderType(BuiltinType::OMPArraySection
)) {
5101 ExprResult Result
= CheckPlaceholderExpr(Base
);
5102 if (Result
.isInvalid())
5104 Base
= Result
.get();
5106 if (LowerBound
&& LowerBound
->getType()->isNonOverloadPlaceholderType()) {
5107 ExprResult Result
= CheckPlaceholderExpr(LowerBound
);
5108 if (Result
.isInvalid())
5110 Result
= DefaultLvalueConversion(Result
.get());
5111 if (Result
.isInvalid())
5113 LowerBound
= Result
.get();
5115 if (Length
&& Length
->getType()->isNonOverloadPlaceholderType()) {
5116 ExprResult Result
= CheckPlaceholderExpr(Length
);
5117 if (Result
.isInvalid())
5119 Result
= DefaultLvalueConversion(Result
.get());
5120 if (Result
.isInvalid())
5122 Length
= Result
.get();
5124 if (Stride
&& Stride
->getType()->isNonOverloadPlaceholderType()) {
5125 ExprResult Result
= CheckPlaceholderExpr(Stride
);
5126 if (Result
.isInvalid())
5128 Result
= DefaultLvalueConversion(Result
.get());
5129 if (Result
.isInvalid())
5131 Stride
= Result
.get();
5134 // Build an unanalyzed expression if either operand is type-dependent.
5135 if (Base
->isTypeDependent() ||
5137 (LowerBound
->isTypeDependent() || LowerBound
->isValueDependent())) ||
5138 (Length
&& (Length
->isTypeDependent() || Length
->isValueDependent())) ||
5139 (Stride
&& (Stride
->isTypeDependent() || Stride
->isValueDependent()))) {
5140 return new (Context
) OMPArraySectionExpr(
5141 Base
, LowerBound
, Length
, Stride
, Context
.DependentTy
, VK_LValue
,
5142 OK_Ordinary
, ColonLocFirst
, ColonLocSecond
, RBLoc
);
5145 // Perform default conversions.
5146 QualType OriginalTy
= OMPArraySectionExpr::getBaseOriginalType(Base
);
5148 if (OriginalTy
->isAnyPointerType()) {
5149 ResultTy
= OriginalTy
->getPointeeType();
5150 } else if (OriginalTy
->isArrayType()) {
5151 ResultTy
= OriginalTy
->getAsArrayTypeUnsafe()->getElementType();
5154 Diag(Base
->getExprLoc(), diag::err_omp_typecheck_section_value
)
5155 << Base
->getSourceRange());
5159 auto Res
= PerformOpenMPImplicitIntegerConversion(LowerBound
->getExprLoc(),
5161 if (Res
.isInvalid())
5162 return ExprError(Diag(LowerBound
->getExprLoc(),
5163 diag::err_omp_typecheck_section_not_integer
)
5164 << 0 << LowerBound
->getSourceRange());
5165 LowerBound
= Res
.get();
5167 if (LowerBound
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
5168 LowerBound
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
5169 Diag(LowerBound
->getExprLoc(), diag::warn_omp_section_is_char
)
5170 << 0 << LowerBound
->getSourceRange();
5174 PerformOpenMPImplicitIntegerConversion(Length
->getExprLoc(), Length
);
5175 if (Res
.isInvalid())
5176 return ExprError(Diag(Length
->getExprLoc(),
5177 diag::err_omp_typecheck_section_not_integer
)
5178 << 1 << Length
->getSourceRange());
5181 if (Length
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
5182 Length
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
5183 Diag(Length
->getExprLoc(), diag::warn_omp_section_is_char
)
5184 << 1 << Length
->getSourceRange();
5188 PerformOpenMPImplicitIntegerConversion(Stride
->getExprLoc(), Stride
);
5189 if (Res
.isInvalid())
5190 return ExprError(Diag(Stride
->getExprLoc(),
5191 diag::err_omp_typecheck_section_not_integer
)
5192 << 1 << Stride
->getSourceRange());
5195 if (Stride
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
5196 Stride
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
5197 Diag(Stride
->getExprLoc(), diag::warn_omp_section_is_char
)
5198 << 1 << Stride
->getSourceRange();
5201 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5202 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5203 // type. Note that functions are not objects, and that (in C99 parlance)
5204 // incomplete types are not object types.
5205 if (ResultTy
->isFunctionType()) {
5206 Diag(Base
->getExprLoc(), diag::err_omp_section_function_type
)
5207 << ResultTy
<< Base
->getSourceRange();
5211 if (RequireCompleteType(Base
->getExprLoc(), ResultTy
,
5212 diag::err_omp_section_incomplete_type
, Base
))
5215 if (LowerBound
&& !OriginalTy
->isAnyPointerType()) {
5216 Expr::EvalResult Result
;
5217 if (LowerBound
->EvaluateAsInt(Result
, Context
)) {
5218 // OpenMP 5.0, [2.1.5 Array Sections]
5219 // The array section must be a subset of the original array.
5220 llvm::APSInt LowerBoundValue
= Result
.Val
.getInt();
5221 if (LowerBoundValue
.isNegative()) {
5222 Diag(LowerBound
->getExprLoc(), diag::err_omp_section_not_subset_of_array
)
5223 << LowerBound
->getSourceRange();
5230 Expr::EvalResult Result
;
5231 if (Length
->EvaluateAsInt(Result
, Context
)) {
5232 // OpenMP 5.0, [2.1.5 Array Sections]
5233 // The length must evaluate to non-negative integers.
5234 llvm::APSInt LengthValue
= Result
.Val
.getInt();
5235 if (LengthValue
.isNegative()) {
5236 Diag(Length
->getExprLoc(), diag::err_omp_section_length_negative
)
5237 << toString(LengthValue
, /*Radix=*/10, /*Signed=*/true)
5238 << Length
->getSourceRange();
5242 } else if (ColonLocFirst
.isValid() &&
5243 (OriginalTy
.isNull() || (!OriginalTy
->isConstantArrayType() &&
5244 !OriginalTy
->isVariableArrayType()))) {
5245 // OpenMP 5.0, [2.1.5 Array Sections]
5246 // When the size of the array dimension is not known, the length must be
5247 // specified explicitly.
5248 Diag(ColonLocFirst
, diag::err_omp_section_length_undefined
)
5249 << (!OriginalTy
.isNull() && OriginalTy
->isArrayType());
5254 Expr::EvalResult Result
;
5255 if (Stride
->EvaluateAsInt(Result
, Context
)) {
5256 // OpenMP 5.0, [2.1.5 Array Sections]
5257 // The stride must evaluate to a positive integer.
5258 llvm::APSInt StrideValue
= Result
.Val
.getInt();
5259 if (!StrideValue
.isStrictlyPositive()) {
5260 Diag(Stride
->getExprLoc(), diag::err_omp_section_stride_non_positive
)
5261 << toString(StrideValue
, /*Radix=*/10, /*Signed=*/true)
5262 << Stride
->getSourceRange();
5268 if (!Base
->hasPlaceholderType(BuiltinType::OMPArraySection
)) {
5269 ExprResult Result
= DefaultFunctionArrayLvalueConversion(Base
);
5270 if (Result
.isInvalid())
5272 Base
= Result
.get();
5274 return new (Context
) OMPArraySectionExpr(
5275 Base
, LowerBound
, Length
, Stride
, Context
.OMPArraySectionTy
, VK_LValue
,
5276 OK_Ordinary
, ColonLocFirst
, ColonLocSecond
, RBLoc
);
5279 ExprResult
Sema::ActOnOMPArrayShapingExpr(Expr
*Base
, SourceLocation LParenLoc
,
5280 SourceLocation RParenLoc
,
5281 ArrayRef
<Expr
*> Dims
,
5282 ArrayRef
<SourceRange
> Brackets
) {
5283 if (Base
->hasPlaceholderType()) {
5284 ExprResult Result
= CheckPlaceholderExpr(Base
);
5285 if (Result
.isInvalid())
5287 Result
= DefaultLvalueConversion(Result
.get());
5288 if (Result
.isInvalid())
5290 Base
= Result
.get();
5292 QualType BaseTy
= Base
->getType();
5293 // Delay analysis of the types/expressions if instantiation/specialization is
5295 if (!BaseTy
->isPointerType() && Base
->isTypeDependent())
5296 return OMPArrayShapingExpr::Create(Context
, Context
.DependentTy
, Base
,
5297 LParenLoc
, RParenLoc
, Dims
, Brackets
);
5298 if (!BaseTy
->isPointerType() ||
5299 (!Base
->isTypeDependent() &&
5300 BaseTy
->getPointeeType()->isIncompleteType()))
5301 return ExprError(Diag(Base
->getExprLoc(),
5302 diag::err_omp_non_pointer_type_array_shaping_base
)
5303 << Base
->getSourceRange());
5305 SmallVector
<Expr
*, 4> NewDims
;
5306 bool ErrorFound
= false;
5307 for (Expr
*Dim
: Dims
) {
5308 if (Dim
->hasPlaceholderType()) {
5309 ExprResult Result
= CheckPlaceholderExpr(Dim
);
5310 if (Result
.isInvalid()) {
5314 Result
= DefaultLvalueConversion(Result
.get());
5315 if (Result
.isInvalid()) {
5321 if (!Dim
->isTypeDependent()) {
5323 PerformOpenMPImplicitIntegerConversion(Dim
->getExprLoc(), Dim
);
5324 if (Result
.isInvalid()) {
5326 Diag(Dim
->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer
)
5327 << Dim
->getSourceRange();
5331 Expr::EvalResult EvResult
;
5332 if (!Dim
->isValueDependent() && Dim
->EvaluateAsInt(EvResult
, Context
)) {
5333 // OpenMP 5.0, [2.1.4 Array Shaping]
5334 // Each si is an integral type expression that must evaluate to a
5335 // positive integer.
5336 llvm::APSInt Value
= EvResult
.Val
.getInt();
5337 if (!Value
.isStrictlyPositive()) {
5338 Diag(Dim
->getExprLoc(), diag::err_omp_shaping_dimension_not_positive
)
5339 << toString(Value
, /*Radix=*/10, /*Signed=*/true)
5340 << Dim
->getSourceRange();
5346 NewDims
.push_back(Dim
);
5350 return OMPArrayShapingExpr::Create(Context
, Context
.OMPArrayShapingTy
, Base
,
5351 LParenLoc
, RParenLoc
, NewDims
, Brackets
);
5354 ExprResult
Sema::ActOnOMPIteratorExpr(Scope
*S
, SourceLocation IteratorKwLoc
,
5355 SourceLocation LLoc
, SourceLocation RLoc
,
5356 ArrayRef
<OMPIteratorData
> Data
) {
5357 SmallVector
<OMPIteratorExpr::IteratorDefinition
, 4> ID
;
5358 bool IsCorrect
= true;
5359 for (const OMPIteratorData
&D
: Data
) {
5360 TypeSourceInfo
*TInfo
= nullptr;
5361 SourceLocation StartLoc
;
5363 if (!D
.Type
.getAsOpaquePtr()) {
5364 // OpenMP 5.0, 2.1.6 Iterators
5365 // In an iterator-specifier, if the iterator-type is not specified then
5366 // the type of that iterator is of int type.
5367 DeclTy
= Context
.IntTy
;
5368 StartLoc
= D
.DeclIdentLoc
;
5370 DeclTy
= GetTypeFromParser(D
.Type
, &TInfo
);
5371 StartLoc
= TInfo
->getTypeLoc().getBeginLoc();
5374 bool IsDeclTyDependent
= DeclTy
->isDependentType() ||
5375 DeclTy
->containsUnexpandedParameterPack() ||
5376 DeclTy
->isInstantiationDependentType();
5377 if (!IsDeclTyDependent
) {
5378 if (!DeclTy
->isIntegralType(Context
) && !DeclTy
->isAnyPointerType()) {
5379 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5380 // The iterator-type must be an integral or pointer type.
5381 Diag(StartLoc
, diag::err_omp_iterator_not_integral_or_pointer
)
5386 if (DeclTy
.isConstant(Context
)) {
5387 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5388 // The iterator-type must not be const qualified.
5389 Diag(StartLoc
, diag::err_omp_iterator_not_integral_or_pointer
)
5396 // Iterator declaration.
5397 assert(D
.DeclIdent
&& "Identifier expected.");
5398 // Always try to create iterator declarator to avoid extra error messages
5399 // about unknown declarations use.
5400 auto *VD
= VarDecl::Create(Context
, CurContext
, StartLoc
, D
.DeclIdentLoc
,
5401 D
.DeclIdent
, DeclTy
, TInfo
, SC_None
);
5404 // Check for conflicting previous declaration.
5405 DeclarationNameInfo
NameInfo(VD
->getDeclName(), D
.DeclIdentLoc
);
5406 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
5407 ForVisibleRedeclaration
);
5408 Previous
.suppressDiagnostics();
5409 LookupName(Previous
, S
);
5411 FilterLookupForScope(Previous
, CurContext
, S
, /*ConsiderLinkage=*/false,
5412 /*AllowInlineNamespace=*/false);
5413 if (!Previous
.empty()) {
5414 NamedDecl
*Old
= Previous
.getRepresentativeDecl();
5415 Diag(D
.DeclIdentLoc
, diag::err_redefinition
) << VD
->getDeclName();
5416 Diag(Old
->getLocation(), diag::note_previous_definition
);
5418 PushOnScopeChains(VD
, S
);
5421 CurContext
->addDecl(VD
);
5424 /// Act on the iterator variable declaration.
5425 ActOnOpenMPIteratorVarDecl(VD
);
5427 Expr
*Begin
= D
.Range
.Begin
;
5428 if (!IsDeclTyDependent
&& Begin
&& !Begin
->isTypeDependent()) {
5429 ExprResult BeginRes
=
5430 PerformImplicitConversion(Begin
, DeclTy
, AA_Converting
);
5431 Begin
= BeginRes
.get();
5433 Expr
*End
= D
.Range
.End
;
5434 if (!IsDeclTyDependent
&& End
&& !End
->isTypeDependent()) {
5435 ExprResult EndRes
= PerformImplicitConversion(End
, DeclTy
, AA_Converting
);
5438 Expr
*Step
= D
.Range
.Step
;
5439 if (!IsDeclTyDependent
&& Step
&& !Step
->isTypeDependent()) {
5440 if (!Step
->getType()->isIntegralType(Context
)) {
5441 Diag(Step
->getExprLoc(), diag::err_omp_iterator_step_not_integral
)
5442 << Step
<< Step
->getSourceRange();
5446 std::optional
<llvm::APSInt
> Result
=
5447 Step
->getIntegerConstantExpr(Context
);
5448 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5449 // If the step expression of a range-specification equals zero, the
5450 // behavior is unspecified.
5451 if (Result
&& Result
->isZero()) {
5452 Diag(Step
->getExprLoc(), diag::err_omp_iterator_step_constant_zero
)
5453 << Step
<< Step
->getSourceRange();
5458 if (!Begin
|| !End
|| !IsCorrect
) {
5462 OMPIteratorExpr::IteratorDefinition
&IDElem
= ID
.emplace_back();
5463 IDElem
.IteratorDecl
= VD
;
5464 IDElem
.AssignmentLoc
= D
.AssignLoc
;
5465 IDElem
.Range
.Begin
= Begin
;
5466 IDElem
.Range
.End
= End
;
5467 IDElem
.Range
.Step
= Step
;
5468 IDElem
.ColonLoc
= D
.ColonLoc
;
5469 IDElem
.SecondColonLoc
= D
.SecColonLoc
;
5472 // Invalidate all created iterator declarations if error is found.
5473 for (const OMPIteratorExpr::IteratorDefinition
&D
: ID
) {
5474 if (Decl
*ID
= D
.IteratorDecl
)
5475 ID
->setInvalidDecl();
5479 SmallVector
<OMPIteratorHelperData
, 4> Helpers
;
5480 if (!CurContext
->isDependentContext()) {
5481 // Build number of ityeration for each iteration range.
5482 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5483 // ((Begini-Stepi-1-Endi) / -Stepi);
5484 for (OMPIteratorExpr::IteratorDefinition
&D
: ID
) {
5486 ExprResult Res
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Sub
, D
.Range
.End
,
5488 if(!Res
.isUsable()) {
5495 // (Endi - Begini) + Stepi
5496 Res
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Add
, Res
.get(), St
.get());
5497 if (!Res
.isUsable()) {
5501 // (Endi - Begini) + Stepi - 1
5503 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Sub
, Res
.get(),
5504 ActOnIntegerConstant(D
.AssignmentLoc
, 1).get());
5505 if (!Res
.isUsable()) {
5509 // ((Endi - Begini) + Stepi - 1) / Stepi
5510 Res
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Div
, Res
.get(), St
.get());
5511 if (!Res
.isUsable()) {
5515 St1
= CreateBuiltinUnaryOp(D
.AssignmentLoc
, UO_Minus
, D
.Range
.Step
);
5517 ExprResult Res1
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Sub
,
5518 D
.Range
.Begin
, D
.Range
.End
);
5519 if (!Res1
.isUsable()) {
5523 // (Begini - Endi) - Stepi
5525 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Add
, Res1
.get(), St1
.get());
5526 if (!Res1
.isUsable()) {
5530 // (Begini - Endi) - Stepi - 1
5532 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Sub
, Res1
.get(),
5533 ActOnIntegerConstant(D
.AssignmentLoc
, 1).get());
5534 if (!Res1
.isUsable()) {
5538 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5540 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Div
, Res1
.get(), St1
.get());
5541 if (!Res1
.isUsable()) {
5547 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_GT
, D
.Range
.Step
,
5548 ActOnIntegerConstant(D
.AssignmentLoc
, 0).get());
5549 if (!CmpRes
.isUsable()) {
5553 Res
= ActOnConditionalOp(D
.AssignmentLoc
, D
.AssignmentLoc
, CmpRes
.get(),
5554 Res
.get(), Res1
.get());
5555 if (!Res
.isUsable()) {
5560 Res
= ActOnFinishFullExpr(Res
.get(), /*DiscardedValue=*/false);
5561 if (!Res
.isUsable()) {
5566 // Build counter update.
5569 VarDecl::Create(Context
, CurContext
, D
.IteratorDecl
->getBeginLoc(),
5570 D
.IteratorDecl
->getBeginLoc(), nullptr,
5571 Res
.get()->getType(), nullptr, SC_None
);
5572 CounterVD
->setImplicit();
5574 BuildDeclRefExpr(CounterVD
, CounterVD
->getType(), VK_LValue
,
5575 D
.IteratorDecl
->getBeginLoc());
5576 // Build counter update.
5577 // I = Begini + counter * Stepi;
5578 ExprResult UpdateRes
;
5580 UpdateRes
= CreateBuiltinBinOp(
5581 D
.AssignmentLoc
, BO_Mul
,
5582 DefaultLvalueConversion(RefRes
.get()).get(), St
.get());
5584 UpdateRes
= DefaultLvalueConversion(RefRes
.get());
5586 if (!UpdateRes
.isUsable()) {
5590 UpdateRes
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Add
, D
.Range
.Begin
,
5592 if (!UpdateRes
.isUsable()) {
5597 BuildDeclRefExpr(cast
<VarDecl
>(D
.IteratorDecl
),
5598 cast
<VarDecl
>(D
.IteratorDecl
)->getType(), VK_LValue
,
5599 D
.IteratorDecl
->getBeginLoc());
5600 UpdateRes
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Assign
, VDRes
.get(),
5602 if (!UpdateRes
.isUsable()) {
5607 ActOnFinishFullExpr(UpdateRes
.get(), /*DiscardedValue=*/true);
5608 if (!UpdateRes
.isUsable()) {
5612 ExprResult CounterUpdateRes
=
5613 CreateBuiltinUnaryOp(D
.AssignmentLoc
, UO_PreInc
, RefRes
.get());
5614 if (!CounterUpdateRes
.isUsable()) {
5619 ActOnFinishFullExpr(CounterUpdateRes
.get(), /*DiscardedValue=*/true);
5620 if (!CounterUpdateRes
.isUsable()) {
5624 OMPIteratorHelperData
&HD
= Helpers
.emplace_back();
5625 HD
.CounterVD
= CounterVD
;
5626 HD
.Upper
= Res
.get();
5627 HD
.Update
= UpdateRes
.get();
5628 HD
.CounterUpdate
= CounterUpdateRes
.get();
5631 Helpers
.assign(ID
.size(), {});
5634 // Invalidate all created iterator declarations if error is found.
5635 for (const OMPIteratorExpr::IteratorDefinition
&D
: ID
) {
5636 if (Decl
*ID
= D
.IteratorDecl
)
5637 ID
->setInvalidDecl();
5641 return OMPIteratorExpr::Create(Context
, Context
.OMPIteratorTy
, IteratorKwLoc
,
5642 LLoc
, RLoc
, ID
, Helpers
);
5646 Sema::CreateBuiltinArraySubscriptExpr(Expr
*Base
, SourceLocation LLoc
,
5647 Expr
*Idx
, SourceLocation RLoc
) {
5648 Expr
*LHSExp
= Base
;
5651 ExprValueKind VK
= VK_LValue
;
5652 ExprObjectKind OK
= OK_Ordinary
;
5654 // Per C++ core issue 1213, the result is an xvalue if either operand is
5655 // a non-lvalue array, and an lvalue otherwise.
5656 if (getLangOpts().CPlusPlus11
) {
5657 for (auto *Op
: {LHSExp
, RHSExp
}) {
5658 Op
= Op
->IgnoreImplicit();
5659 if (Op
->getType()->isArrayType() && !Op
->isLValue())
5664 // Perform default conversions.
5665 if (!LHSExp
->getType()->getAs
<VectorType
>()) {
5666 ExprResult Result
= DefaultFunctionArrayLvalueConversion(LHSExp
);
5667 if (Result
.isInvalid())
5669 LHSExp
= Result
.get();
5671 ExprResult Result
= DefaultFunctionArrayLvalueConversion(RHSExp
);
5672 if (Result
.isInvalid())
5674 RHSExp
= Result
.get();
5676 QualType LHSTy
= LHSExp
->getType(), RHSTy
= RHSExp
->getType();
5678 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5679 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5680 // in the subscript position. As a result, we need to derive the array base
5681 // and index from the expression types.
5682 Expr
*BaseExpr
, *IndexExpr
;
5683 QualType ResultType
;
5684 if (LHSTy
->isDependentType() || RHSTy
->isDependentType()) {
5688 getDependentArraySubscriptType(LHSExp
, RHSExp
, getASTContext());
5689 } else if (const PointerType
*PTy
= LHSTy
->getAs
<PointerType
>()) {
5692 ResultType
= PTy
->getPointeeType();
5693 } else if (const ObjCObjectPointerType
*PTy
=
5694 LHSTy
->getAs
<ObjCObjectPointerType
>()) {
5698 // Use custom logic if this should be the pseudo-object subscript
5700 if (!LangOpts
.isSubscriptPointerArithmetic())
5701 return BuildObjCSubscriptExpression(RLoc
, BaseExpr
, IndexExpr
, nullptr,
5704 ResultType
= PTy
->getPointeeType();
5705 } else if (const PointerType
*PTy
= RHSTy
->getAs
<PointerType
>()) {
5706 // Handle the uncommon case of "123[Ptr]".
5709 ResultType
= PTy
->getPointeeType();
5710 } else if (const ObjCObjectPointerType
*PTy
=
5711 RHSTy
->getAs
<ObjCObjectPointerType
>()) {
5712 // Handle the uncommon case of "123[Ptr]".
5715 ResultType
= PTy
->getPointeeType();
5716 if (!LangOpts
.isSubscriptPointerArithmetic()) {
5717 Diag(LLoc
, diag::err_subscript_nonfragile_interface
)
5718 << ResultType
<< BaseExpr
->getSourceRange();
5721 } else if (const VectorType
*VTy
= LHSTy
->getAs
<VectorType
>()) {
5722 BaseExpr
= LHSExp
; // vectors: V[123]
5724 // We apply C++ DR1213 to vector subscripting too.
5725 if (getLangOpts().CPlusPlus11
&& LHSExp
->isPRValue()) {
5726 ExprResult Materialized
= TemporaryMaterializationConversion(LHSExp
);
5727 if (Materialized
.isInvalid())
5729 LHSExp
= Materialized
.get();
5731 VK
= LHSExp
->getValueKind();
5732 if (VK
!= VK_PRValue
)
5733 OK
= OK_VectorComponent
;
5735 ResultType
= VTy
->getElementType();
5736 QualType BaseType
= BaseExpr
->getType();
5737 Qualifiers BaseQuals
= BaseType
.getQualifiers();
5738 Qualifiers MemberQuals
= ResultType
.getQualifiers();
5739 Qualifiers Combined
= BaseQuals
+ MemberQuals
;
5740 if (Combined
!= MemberQuals
)
5741 ResultType
= Context
.getQualifiedType(ResultType
, Combined
);
5742 } else if (LHSTy
->isBuiltinType() &&
5743 LHSTy
->getAs
<BuiltinType
>()->isVLSTBuiltinType()) {
5744 const BuiltinType
*BTy
= LHSTy
->getAs
<BuiltinType
>();
5745 if (BTy
->isSVEBool())
5746 return ExprError(Diag(LLoc
, diag::err_subscript_svbool_t
)
5747 << LHSExp
->getSourceRange() << RHSExp
->getSourceRange());
5751 if (getLangOpts().CPlusPlus11
&& LHSExp
->isPRValue()) {
5752 ExprResult Materialized
= TemporaryMaterializationConversion(LHSExp
);
5753 if (Materialized
.isInvalid())
5755 LHSExp
= Materialized
.get();
5757 VK
= LHSExp
->getValueKind();
5758 if (VK
!= VK_PRValue
)
5759 OK
= OK_VectorComponent
;
5761 ResultType
= BTy
->getSveEltType(Context
);
5763 QualType BaseType
= BaseExpr
->getType();
5764 Qualifiers BaseQuals
= BaseType
.getQualifiers();
5765 Qualifiers MemberQuals
= ResultType
.getQualifiers();
5766 Qualifiers Combined
= BaseQuals
+ MemberQuals
;
5767 if (Combined
!= MemberQuals
)
5768 ResultType
= Context
.getQualifiedType(ResultType
, Combined
);
5769 } else if (LHSTy
->isArrayType()) {
5770 // If we see an array that wasn't promoted by
5771 // DefaultFunctionArrayLvalueConversion, it must be an array that
5772 // wasn't promoted because of the C90 rule that doesn't
5773 // allow promoting non-lvalue arrays. Warn, then
5774 // force the promotion here.
5775 Diag(LHSExp
->getBeginLoc(), diag::ext_subscript_non_lvalue
)
5776 << LHSExp
->getSourceRange();
5777 LHSExp
= ImpCastExprToType(LHSExp
, Context
.getArrayDecayedType(LHSTy
),
5778 CK_ArrayToPointerDecay
).get();
5779 LHSTy
= LHSExp
->getType();
5783 ResultType
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
5784 } else if (RHSTy
->isArrayType()) {
5785 // Same as previous, except for 123[f().a] case
5786 Diag(RHSExp
->getBeginLoc(), diag::ext_subscript_non_lvalue
)
5787 << RHSExp
->getSourceRange();
5788 RHSExp
= ImpCastExprToType(RHSExp
, Context
.getArrayDecayedType(RHSTy
),
5789 CK_ArrayToPointerDecay
).get();
5790 RHSTy
= RHSExp
->getType();
5794 ResultType
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
5796 return ExprError(Diag(LLoc
, diag::err_typecheck_subscript_value
)
5797 << LHSExp
->getSourceRange() << RHSExp
->getSourceRange());
5800 if (!IndexExpr
->getType()->isIntegerType() && !IndexExpr
->isTypeDependent())
5801 return ExprError(Diag(LLoc
, diag::err_typecheck_subscript_not_integer
)
5802 << IndexExpr
->getSourceRange());
5804 if ((IndexExpr
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
5805 IndexExpr
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
5806 && !IndexExpr
->isTypeDependent())
5807 Diag(LLoc
, diag::warn_subscript_is_char
) << IndexExpr
->getSourceRange();
5809 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5810 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5811 // type. Note that Functions are not objects, and that (in C99 parlance)
5812 // incomplete types are not object types.
5813 if (ResultType
->isFunctionType()) {
5814 Diag(BaseExpr
->getBeginLoc(), diag::err_subscript_function_type
)
5815 << ResultType
<< BaseExpr
->getSourceRange();
5819 if (ResultType
->isVoidType() && !getLangOpts().CPlusPlus
) {
5820 // GNU extension: subscripting on pointer to void
5821 Diag(LLoc
, diag::ext_gnu_subscript_void_type
)
5822 << BaseExpr
->getSourceRange();
5824 // C forbids expressions of unqualified void type from being l-values.
5825 // See IsCForbiddenLValueType.
5826 if (!ResultType
.hasQualifiers())
5828 } else if (!ResultType
->isDependentType() &&
5829 RequireCompleteSizedType(
5831 diag::err_subscript_incomplete_or_sizeless_type
, BaseExpr
))
5834 assert(VK
== VK_PRValue
|| LangOpts
.CPlusPlus
||
5835 !ResultType
.isCForbiddenLValueType());
5837 if (LHSExp
->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
5838 FunctionScopes
.size() > 1) {
5840 LHSExp
->IgnoreParenImpCasts()->getType()->getAs
<TypedefType
>()) {
5841 for (auto I
= FunctionScopes
.rbegin(),
5842 E
= std::prev(FunctionScopes
.rend());
5844 auto *CSI
= dyn_cast
<CapturingScopeInfo
>(*I
);
5847 DeclContext
*DC
= nullptr;
5848 if (auto *LSI
= dyn_cast
<LambdaScopeInfo
>(CSI
))
5849 DC
= LSI
->CallOperator
;
5850 else if (auto *CRSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
))
5851 DC
= CRSI
->TheCapturedDecl
;
5852 else if (auto *BSI
= dyn_cast
<BlockScopeInfo
>(CSI
))
5855 if (DC
->containsDecl(TT
->getDecl()))
5857 captureVariablyModifiedType(
5858 Context
, LHSExp
->IgnoreParenImpCasts()->getType(), CSI
);
5864 return new (Context
)
5865 ArraySubscriptExpr(LHSExp
, RHSExp
, ResultType
, VK
, OK
, RLoc
);
5868 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc
, FunctionDecl
*FD
,
5869 ParmVarDecl
*Param
, Expr
*RewrittenInit
,
5870 bool SkipImmediateInvocations
) {
5871 if (Param
->hasUnparsedDefaultArg()) {
5872 assert(!RewrittenInit
&& "Should not have a rewritten init expression yet");
5873 // If we've already cleared out the location for the default argument,
5874 // that means we're parsing it right now.
5875 if (!UnparsedDefaultArgLocs
.count(Param
)) {
5876 Diag(Param
->getBeginLoc(), diag::err_recursive_default_argument
) << FD
;
5877 Diag(CallLoc
, diag::note_recursive_default_argument_used_here
);
5878 Param
->setInvalidDecl();
5882 Diag(CallLoc
, diag::err_use_of_default_argument_to_function_declared_later
)
5883 << FD
<< cast
<CXXRecordDecl
>(FD
->getDeclContext());
5884 Diag(UnparsedDefaultArgLocs
[Param
],
5885 diag::note_default_argument_declared_here
);
5889 if (Param
->hasUninstantiatedDefaultArg()) {
5890 assert(!RewrittenInit
&& "Should not have a rewitten init expression yet");
5891 if (InstantiateDefaultArgument(CallLoc
, FD
, Param
))
5895 Expr
*Init
= RewrittenInit
? RewrittenInit
: Param
->getInit();
5896 assert(Init
&& "default argument but no initializer?");
5898 // If the default expression creates temporaries, we need to
5899 // push them to the current stack of expression temporaries so they'll
5900 // be properly destroyed.
5901 // FIXME: We should really be rebuilding the default argument with new
5902 // bound temporaries; see the comment in PR5810.
5903 // We don't need to do that with block decls, though, because
5904 // blocks in default argument expression can never capture anything.
5905 if (auto *InitWithCleanup
= dyn_cast
<ExprWithCleanups
>(Init
)) {
5906 // Set the "needs cleanups" bit regardless of whether there are
5907 // any explicit objects.
5908 Cleanup
.setExprNeedsCleanups(InitWithCleanup
->cleanupsHaveSideEffects());
5909 // Append all the objects to the cleanup list. Right now, this
5910 // should always be a no-op, because blocks in default argument
5911 // expressions should never be able to capture anything.
5912 assert(!InitWithCleanup
->getNumObjects() &&
5913 "default argument expression has capturing blocks?");
5915 EnterExpressionEvaluationContext
EvalContext(
5916 *this, ExpressionEvaluationContext::PotentiallyEvaluated
, Param
);
5917 ExprEvalContexts
.back().IsCurrentlyCheckingDefaultArgumentOrInitializer
=
5918 SkipImmediateInvocations
;
5919 MarkDeclarationsReferencedInExpr(Init
, /*SkipLocalVariables*/ true);
5923 struct ImmediateCallVisitor
: public RecursiveASTVisitor
<ImmediateCallVisitor
> {
5924 bool HasImmediateCalls
= false;
5926 bool shouldVisitImplicitCode() const { return true; }
5928 bool VisitCallExpr(CallExpr
*E
) {
5929 if (const FunctionDecl
*FD
= E
->getDirectCallee())
5930 HasImmediateCalls
|= FD
->isConsteval();
5931 return RecursiveASTVisitor
<ImmediateCallVisitor
>::VisitStmt(E
);
5934 // SourceLocExpr are not immediate invocations
5935 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
5936 // need to be rebuilt so that they refer to the correct SourceLocation and
5938 bool VisitSourceLocExpr(SourceLocExpr
*E
) {
5939 HasImmediateCalls
= true;
5940 return RecursiveASTVisitor
<ImmediateCallVisitor
>::VisitStmt(E
);
5943 // A nested lambda might have parameters with immediate invocations
5944 // in their default arguments.
5945 // The compound statement is not visited (as it does not constitute a
5947 // FIXME: We should consider visiting and transforming captures
5948 // with init expressions.
5949 bool VisitLambdaExpr(LambdaExpr
*E
) {
5950 return VisitCXXMethodDecl(E
->getCallOperator());
5953 // Blocks don't support default parameters, and, as for lambdas,
5954 // we don't consider their body a subexpression.
5955 bool VisitBlockDecl(BlockDecl
*B
) { return false; }
5957 bool VisitCompoundStmt(CompoundStmt
*B
) { return false; }
5959 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr
*E
) {
5960 return TraverseStmt(E
->getExpr());
5963 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr
*E
) {
5964 return TraverseStmt(E
->getExpr());
5968 struct EnsureImmediateInvocationInDefaultArgs
5969 : TreeTransform
<EnsureImmediateInvocationInDefaultArgs
> {
5970 EnsureImmediateInvocationInDefaultArgs(Sema
&SemaRef
)
5971 : TreeTransform(SemaRef
) {}
5973 // Lambda can only have immediate invocations in the default
5974 // args of their parameters, which is transformed upon calling the closure.
5975 // The body is not a subexpression, so we have nothing to do.
5976 // FIXME: Immediate calls in capture initializers should be transformed.
5977 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) { return E
; }
5978 ExprResult
TransformBlockExpr(BlockExpr
*E
) { return E
; }
5980 // Make sure we don't rebuild the this pointer as it would
5981 // cause it to incorrectly point it to the outermost class
5982 // in the case of nested struct initialization.
5983 ExprResult
TransformCXXThisExpr(CXXThisExpr
*E
) { return E
; }
5986 ExprResult
Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc
,
5987 FunctionDecl
*FD
, ParmVarDecl
*Param
,
5989 assert(Param
->hasDefaultArg() && "can't build nonexistent default arg");
5991 bool NestedDefaultChecking
= isCheckingDefaultArgumentOrInitializer();
5993 std::optional
<ExpressionEvaluationContextRecord::InitializationContext
>
5994 InitializationContext
=
5995 OutermostDeclarationWithDelayedImmediateInvocations();
5996 if (!InitializationContext
.has_value())
5997 InitializationContext
.emplace(CallLoc
, Param
, CurContext
);
5999 if (!Init
&& !Param
->hasUnparsedDefaultArg()) {
6000 // Mark that we are replacing a default argument first.
6001 // If we are instantiating a template we won't have to
6002 // retransform immediate calls.
6003 EnterExpressionEvaluationContext
EvalContext(
6004 *this, ExpressionEvaluationContext::PotentiallyEvaluated
, Param
);
6006 if (Param
->hasUninstantiatedDefaultArg()) {
6007 if (InstantiateDefaultArgument(CallLoc
, FD
, Param
))
6011 // An immediate invocation that is not evaluated where it appears is
6012 // evaluated and checked for whether it is a constant expression at the
6013 // point where the enclosing initializer is used in a function call.
6014 ImmediateCallVisitor V
;
6015 if (!NestedDefaultChecking
)
6016 V
.TraverseDecl(Param
);
6017 if (V
.HasImmediateCalls
) {
6018 ExprEvalContexts
.back().DelayedDefaultInitializationContext
= {
6019 CallLoc
, Param
, CurContext
};
6020 EnsureImmediateInvocationInDefaultArgs
Immediate(*this);
6021 ExprResult Res
= Immediate
.TransformInitializer(Param
->getInit(),
6023 if (Res
.isInvalid())
6025 Res
= ConvertParamDefaultArgument(Param
, Res
.get(),
6026 Res
.get()->getBeginLoc());
6027 if (Res
.isInvalid())
6033 if (CheckCXXDefaultArgExpr(
6034 CallLoc
, FD
, Param
, Init
,
6035 /*SkipImmediateInvocations=*/NestedDefaultChecking
))
6038 return CXXDefaultArgExpr::Create(Context
, InitializationContext
->Loc
, Param
,
6039 Init
, InitializationContext
->Context
);
6042 ExprResult
Sema::BuildCXXDefaultInitExpr(SourceLocation Loc
, FieldDecl
*Field
) {
6043 assert(Field
->hasInClassInitializer());
6045 // If we might have already tried and failed to instantiate, don't try again.
6046 if (Field
->isInvalidDecl())
6049 auto *ParentRD
= cast
<CXXRecordDecl
>(Field
->getParent());
6051 std::optional
<ExpressionEvaluationContextRecord::InitializationContext
>
6052 InitializationContext
=
6053 OutermostDeclarationWithDelayedImmediateInvocations();
6054 if (!InitializationContext
.has_value())
6055 InitializationContext
.emplace(Loc
, Field
, CurContext
);
6057 Expr
*Init
= nullptr;
6059 bool NestedDefaultChecking
= isCheckingDefaultArgumentOrInitializer();
6061 EnterExpressionEvaluationContext
EvalContext(
6062 *this, ExpressionEvaluationContext::PotentiallyEvaluated
, Field
);
6064 if (!Field
->getInClassInitializer()) {
6065 // Maybe we haven't instantiated the in-class initializer. Go check the
6066 // pattern FieldDecl to see if it has one.
6067 if (isTemplateInstantiation(ParentRD
->getTemplateSpecializationKind())) {
6068 CXXRecordDecl
*ClassPattern
= ParentRD
->getTemplateInstantiationPattern();
6069 DeclContext::lookup_result Lookup
=
6070 ClassPattern
->lookup(Field
->getDeclName());
6072 FieldDecl
*Pattern
= nullptr;
6073 for (auto *L
: Lookup
) {
6074 if ((Pattern
= dyn_cast
<FieldDecl
>(L
)))
6077 assert(Pattern
&& "We must have set the Pattern!");
6078 if (!Pattern
->hasInClassInitializer() ||
6079 InstantiateInClassInitializer(Loc
, Field
, Pattern
,
6080 getTemplateInstantiationArgs(Field
))) {
6081 Field
->setInvalidDecl();
6088 // An immediate invocation that is not evaluated where it appears is
6089 // evaluated and checked for whether it is a constant expression at the
6090 // point where the enclosing initializer is used in a [...] a constructor
6091 // definition, or an aggregate initialization.
6092 ImmediateCallVisitor V
;
6093 if (!NestedDefaultChecking
)
6094 V
.TraverseDecl(Field
);
6095 if (V
.HasImmediateCalls
) {
6096 ExprEvalContexts
.back().DelayedDefaultInitializationContext
= {Loc
, Field
,
6098 ExprEvalContexts
.back().IsCurrentlyCheckingDefaultArgumentOrInitializer
=
6099 NestedDefaultChecking
;
6101 EnsureImmediateInvocationInDefaultArgs
Immediate(*this);
6104 Immediate
.TransformInitializer(Field
->getInClassInitializer(),
6105 /*CXXDirectInit=*/false);
6106 if (!Res
.isInvalid())
6107 Res
= ConvertMemberDefaultInitExpression(Field
, Res
.get(), Loc
);
6108 if (Res
.isInvalid()) {
6109 Field
->setInvalidDecl();
6115 if (Field
->getInClassInitializer()) {
6116 Expr
*E
= Init
? Init
: Field
->getInClassInitializer();
6117 if (!NestedDefaultChecking
)
6118 MarkDeclarationsReferencedInExpr(E
, /*SkipLocalVariables=*/false);
6119 // C++11 [class.base.init]p7:
6120 // The initialization of each base and member constitutes a
6122 ExprResult Res
= ActOnFinishFullExpr(E
, /*DiscardedValue=*/false);
6123 if (Res
.isInvalid()) {
6124 Field
->setInvalidDecl();
6129 return CXXDefaultInitExpr::Create(Context
, InitializationContext
->Loc
,
6130 Field
, InitializationContext
->Context
,
6135 // If the brace-or-equal-initializer of a non-static data member
6136 // invokes a defaulted default constructor of its class or of an
6137 // enclosing class in a potentially evaluated subexpression, the
6138 // program is ill-formed.
6140 // This resolution is unworkable: the exception specification of the
6141 // default constructor can be needed in an unevaluated context, in
6142 // particular, in the operand of a noexcept-expression, and we can be
6143 // unable to compute an exception specification for an enclosed class.
6145 // Any attempt to resolve the exception specification of a defaulted default
6146 // constructor before the initializer is lexically complete will ultimately
6147 // come here at which point we can diagnose it.
6148 RecordDecl
*OutermostClass
= ParentRD
->getOuterLexicalRecordContext();
6149 Diag(Loc
, diag::err_default_member_initializer_not_yet_parsed
)
6150 << OutermostClass
<< Field
;
6151 Diag(Field
->getEndLoc(),
6152 diag::note_default_member_initializer_not_yet_parsed
);
6153 // Recover by marking the field invalid, unless we're in a SFINAE context.
6154 if (!isSFINAEContext())
6155 Field
->setInvalidDecl();
6159 Sema::VariadicCallType
6160 Sema::getVariadicCallType(FunctionDecl
*FDecl
, const FunctionProtoType
*Proto
,
6162 if (Proto
&& Proto
->isVariadic()) {
6163 if (isa_and_nonnull
<CXXConstructorDecl
>(FDecl
))
6164 return VariadicConstructor
;
6165 else if (Fn
&& Fn
->getType()->isBlockPointerType())
6166 return VariadicBlock
;
6168 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(FDecl
))
6169 if (Method
->isInstance())
6170 return VariadicMethod
;
6171 } else if (Fn
&& Fn
->getType() == Context
.BoundMemberTy
)
6172 return VariadicMethod
;
6173 return VariadicFunction
;
6175 return VariadicDoesNotApply
;
6179 class FunctionCallCCC final
: public FunctionCallFilterCCC
{
6181 FunctionCallCCC(Sema
&SemaRef
, const IdentifierInfo
*FuncName
,
6182 unsigned NumArgs
, MemberExpr
*ME
)
6183 : FunctionCallFilterCCC(SemaRef
, NumArgs
, false, ME
),
6184 FunctionName(FuncName
) {}
6186 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
6187 if (!candidate
.getCorrectionSpecifier() ||
6188 candidate
.getCorrectionAsIdentifierInfo() != FunctionName
) {
6192 return FunctionCallFilterCCC::ValidateCandidate(candidate
);
6195 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
6196 return std::make_unique
<FunctionCallCCC
>(*this);
6200 const IdentifierInfo
*const FunctionName
;
6204 static TypoCorrection
TryTypoCorrectionForCall(Sema
&S
, Expr
*Fn
,
6205 FunctionDecl
*FDecl
,
6206 ArrayRef
<Expr
*> Args
) {
6207 MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Fn
);
6208 DeclarationName FuncName
= FDecl
->getDeclName();
6209 SourceLocation NameLoc
= ME
? ME
->getMemberLoc() : Fn
->getBeginLoc();
6211 FunctionCallCCC
CCC(S
, FuncName
.getAsIdentifierInfo(), Args
.size(), ME
);
6212 if (TypoCorrection Corrected
= S
.CorrectTypo(
6213 DeclarationNameInfo(FuncName
, NameLoc
), Sema::LookupOrdinaryName
,
6214 S
.getScopeForContext(S
.CurContext
), nullptr, CCC
,
6215 Sema::CTK_ErrorRecovery
)) {
6216 if (NamedDecl
*ND
= Corrected
.getFoundDecl()) {
6217 if (Corrected
.isOverloaded()) {
6218 OverloadCandidateSet
OCS(NameLoc
, OverloadCandidateSet::CSK_Normal
);
6219 OverloadCandidateSet::iterator Best
;
6220 for (NamedDecl
*CD
: Corrected
) {
6221 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(CD
))
6222 S
.AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, AS_none
), Args
,
6225 switch (OCS
.BestViableFunction(S
, NameLoc
, Best
)) {
6227 ND
= Best
->FoundDecl
;
6228 Corrected
.setCorrectionDecl(ND
);
6234 ND
= ND
->getUnderlyingDecl();
6235 if (isa
<ValueDecl
>(ND
) || isa
<FunctionTemplateDecl
>(ND
))
6239 return TypoCorrection();
6242 /// ConvertArgumentsForCall - Converts the arguments specified in
6243 /// Args/NumArgs to the parameter types of the function FDecl with
6244 /// function prototype Proto. Call is the call expression itself, and
6245 /// Fn is the function expression. For a C++ member function, this
6246 /// routine does not attempt to convert the object argument. Returns
6247 /// true if the call is ill-formed.
6249 Sema::ConvertArgumentsForCall(CallExpr
*Call
, Expr
*Fn
,
6250 FunctionDecl
*FDecl
,
6251 const FunctionProtoType
*Proto
,
6252 ArrayRef
<Expr
*> Args
,
6253 SourceLocation RParenLoc
,
6254 bool IsExecConfig
) {
6255 // Bail out early if calling a builtin with custom typechecking.
6257 if (unsigned ID
= FDecl
->getBuiltinID())
6258 if (Context
.BuiltinInfo
.hasCustomTypechecking(ID
))
6261 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6262 // assignment, to the types of the corresponding parameter, ...
6263 unsigned NumParams
= Proto
->getNumParams();
6264 bool Invalid
= false;
6265 unsigned MinArgs
= FDecl
? FDecl
->getMinRequiredArguments() : NumParams
;
6266 unsigned FnKind
= Fn
->getType()->isBlockPointerType()
6268 : (IsExecConfig
? 3 /* kernel function (exec config) */
6269 : 0 /* function */);
6271 // If too few arguments are available (and we don't have default
6272 // arguments for the remaining parameters), don't make the call.
6273 if (Args
.size() < NumParams
) {
6274 if (Args
.size() < MinArgs
) {
6276 if (FDecl
&& (TC
= TryTypoCorrectionForCall(*this, Fn
, FDecl
, Args
))) {
6278 MinArgs
== NumParams
&& !Proto
->isVariadic()
6279 ? diag::err_typecheck_call_too_few_args_suggest
6280 : diag::err_typecheck_call_too_few_args_at_least_suggest
;
6281 diagnoseTypo(TC
, PDiag(diag_id
) << FnKind
<< MinArgs
6282 << static_cast<unsigned>(Args
.size())
6283 << TC
.getCorrectionRange());
6284 } else if (MinArgs
== 1 && FDecl
&& FDecl
->getParamDecl(0)->getDeclName())
6286 MinArgs
== NumParams
&& !Proto
->isVariadic()
6287 ? diag::err_typecheck_call_too_few_args_one
6288 : diag::err_typecheck_call_too_few_args_at_least_one
)
6289 << FnKind
<< FDecl
->getParamDecl(0) << Fn
->getSourceRange();
6291 Diag(RParenLoc
, MinArgs
== NumParams
&& !Proto
->isVariadic()
6292 ? diag::err_typecheck_call_too_few_args
6293 : diag::err_typecheck_call_too_few_args_at_least
)
6294 << FnKind
<< MinArgs
<< static_cast<unsigned>(Args
.size())
6295 << Fn
->getSourceRange();
6297 // Emit the location of the prototype.
6298 if (!TC
&& FDecl
&& !FDecl
->getBuiltinID() && !IsExecConfig
)
6299 Diag(FDecl
->getLocation(), diag::note_callee_decl
) << FDecl
;
6303 // We reserve space for the default arguments when we create
6304 // the call expression, before calling ConvertArgumentsForCall.
6305 assert((Call
->getNumArgs() == NumParams
) &&
6306 "We should have reserved space for the default arguments before!");
6309 // If too many are passed and not variadic, error on the extras and drop
6311 if (Args
.size() > NumParams
) {
6312 if (!Proto
->isVariadic()) {
6314 if (FDecl
&& (TC
= TryTypoCorrectionForCall(*this, Fn
, FDecl
, Args
))) {
6316 MinArgs
== NumParams
&& !Proto
->isVariadic()
6317 ? diag::err_typecheck_call_too_many_args_suggest
6318 : diag::err_typecheck_call_too_many_args_at_most_suggest
;
6319 diagnoseTypo(TC
, PDiag(diag_id
) << FnKind
<< NumParams
6320 << static_cast<unsigned>(Args
.size())
6321 << TC
.getCorrectionRange());
6322 } else if (NumParams
== 1 && FDecl
&&
6323 FDecl
->getParamDecl(0)->getDeclName())
6324 Diag(Args
[NumParams
]->getBeginLoc(),
6325 MinArgs
== NumParams
6326 ? diag::err_typecheck_call_too_many_args_one
6327 : diag::err_typecheck_call_too_many_args_at_most_one
)
6328 << FnKind
<< FDecl
->getParamDecl(0)
6329 << static_cast<unsigned>(Args
.size()) << Fn
->getSourceRange()
6330 << SourceRange(Args
[NumParams
]->getBeginLoc(),
6331 Args
.back()->getEndLoc());
6333 Diag(Args
[NumParams
]->getBeginLoc(),
6334 MinArgs
== NumParams
6335 ? diag::err_typecheck_call_too_many_args
6336 : diag::err_typecheck_call_too_many_args_at_most
)
6337 << FnKind
<< NumParams
<< static_cast<unsigned>(Args
.size())
6338 << Fn
->getSourceRange()
6339 << SourceRange(Args
[NumParams
]->getBeginLoc(),
6340 Args
.back()->getEndLoc());
6342 // Emit the location of the prototype.
6343 if (!TC
&& FDecl
&& !FDecl
->getBuiltinID() && !IsExecConfig
)
6344 Diag(FDecl
->getLocation(), diag::note_callee_decl
) << FDecl
;
6346 // This deletes the extra arguments.
6347 Call
->shrinkNumArgs(NumParams
);
6351 SmallVector
<Expr
*, 8> AllArgs
;
6352 VariadicCallType CallType
= getVariadicCallType(FDecl
, Proto
, Fn
);
6354 Invalid
= GatherArgumentsForCall(Call
->getBeginLoc(), FDecl
, Proto
, 0, Args
,
6358 unsigned TotalNumArgs
= AllArgs
.size();
6359 for (unsigned i
= 0; i
< TotalNumArgs
; ++i
)
6360 Call
->setArg(i
, AllArgs
[i
]);
6362 Call
->computeDependence();
6366 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc
, FunctionDecl
*FDecl
,
6367 const FunctionProtoType
*Proto
,
6368 unsigned FirstParam
, ArrayRef
<Expr
*> Args
,
6369 SmallVectorImpl
<Expr
*> &AllArgs
,
6370 VariadicCallType CallType
, bool AllowExplicit
,
6371 bool IsListInitialization
) {
6372 unsigned NumParams
= Proto
->getNumParams();
6373 bool Invalid
= false;
6375 // Continue to check argument types (even if we have too few/many args).
6376 for (unsigned i
= FirstParam
; i
< NumParams
; i
++) {
6377 QualType ProtoArgType
= Proto
->getParamType(i
);
6380 ParmVarDecl
*Param
= FDecl
? FDecl
->getParamDecl(i
) : nullptr;
6381 if (ArgIx
< Args
.size()) {
6382 Arg
= Args
[ArgIx
++];
6384 if (RequireCompleteType(Arg
->getBeginLoc(), ProtoArgType
,
6385 diag::err_call_incomplete_argument
, Arg
))
6388 // Strip the unbridged-cast placeholder expression off, if applicable.
6389 bool CFAudited
= false;
6390 if (Arg
->getType() == Context
.ARCUnbridgedCastTy
&&
6391 FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>() &&
6392 (!Param
|| !Param
->hasAttr
<CFConsumedAttr
>()))
6393 Arg
= stripARCUnbridgedCast(Arg
);
6394 else if (getLangOpts().ObjCAutoRefCount
&&
6395 FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>() &&
6396 (!Param
|| !Param
->hasAttr
<CFConsumedAttr
>()))
6399 if (Proto
->getExtParameterInfo(i
).isNoEscape() &&
6400 ProtoArgType
->isBlockPointerType())
6401 if (auto *BE
= dyn_cast
<BlockExpr
>(Arg
->IgnoreParenNoopCasts(Context
)))
6402 BE
->getBlockDecl()->setDoesNotEscape();
6404 InitializedEntity Entity
=
6405 Param
? InitializedEntity::InitializeParameter(Context
, Param
,
6407 : InitializedEntity::InitializeParameter(
6408 Context
, ProtoArgType
, Proto
->isParamConsumed(i
));
6410 // Remember that parameter belongs to a CF audited API.
6412 Entity
.setParameterCFAudited();
6414 ExprResult ArgE
= PerformCopyInitialization(
6415 Entity
, SourceLocation(), Arg
, IsListInitialization
, AllowExplicit
);
6416 if (ArgE
.isInvalid())
6419 Arg
= ArgE
.getAs
<Expr
>();
6421 assert(Param
&& "can't use default arguments without a known callee");
6423 ExprResult ArgExpr
= BuildCXXDefaultArgExpr(CallLoc
, FDecl
, Param
);
6424 if (ArgExpr
.isInvalid())
6427 Arg
= ArgExpr
.getAs
<Expr
>();
6430 // Check for array bounds violations for each argument to the call. This
6431 // check only triggers warnings when the argument isn't a more complex Expr
6432 // with its own checking, such as a BinaryOperator.
6433 CheckArrayAccess(Arg
);
6435 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6436 CheckStaticArrayArgument(CallLoc
, Param
, Arg
);
6438 AllArgs
.push_back(Arg
);
6441 // If this is a variadic call, handle args passed through "...".
6442 if (CallType
!= VariadicDoesNotApply
) {
6443 // Assume that extern "C" functions with variadic arguments that
6444 // return __unknown_anytype aren't *really* variadic.
6445 if (Proto
->getReturnType() == Context
.UnknownAnyTy
&& FDecl
&&
6446 FDecl
->isExternC()) {
6447 for (Expr
*A
: Args
.slice(ArgIx
)) {
6448 QualType paramType
; // ignored
6449 ExprResult arg
= checkUnknownAnyArg(CallLoc
, A
, paramType
);
6450 Invalid
|= arg
.isInvalid();
6451 AllArgs
.push_back(arg
.get());
6454 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6456 for (Expr
*A
: Args
.slice(ArgIx
)) {
6457 ExprResult Arg
= DefaultVariadicArgumentPromotion(A
, CallType
, FDecl
);
6458 Invalid
|= Arg
.isInvalid();
6459 AllArgs
.push_back(Arg
.get());
6463 // Check for array bounds violations.
6464 for (Expr
*A
: Args
.slice(ArgIx
))
6465 CheckArrayAccess(A
);
6470 static void DiagnoseCalleeStaticArrayParam(Sema
&S
, ParmVarDecl
*PVD
) {
6471 TypeLoc TL
= PVD
->getTypeSourceInfo()->getTypeLoc();
6472 if (DecayedTypeLoc DTL
= TL
.getAs
<DecayedTypeLoc
>())
6473 TL
= DTL
.getOriginalLoc();
6474 if (ArrayTypeLoc ATL
= TL
.getAs
<ArrayTypeLoc
>())
6475 S
.Diag(PVD
->getLocation(), diag::note_callee_static_array
)
6476 << ATL
.getLocalSourceRange();
6479 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6480 /// array parameter, check that it is non-null, and that if it is formed by
6481 /// array-to-pointer decay, the underlying array is sufficiently large.
6483 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6484 /// array type derivation, then for each call to the function, the value of the
6485 /// corresponding actual argument shall provide access to the first element of
6486 /// an array with at least as many elements as specified by the size expression.
6488 Sema::CheckStaticArrayArgument(SourceLocation CallLoc
,
6490 const Expr
*ArgExpr
) {
6491 // Static array parameters are not supported in C++.
6492 if (!Param
|| getLangOpts().CPlusPlus
)
6495 QualType OrigTy
= Param
->getOriginalType();
6497 const ArrayType
*AT
= Context
.getAsArrayType(OrigTy
);
6498 if (!AT
|| AT
->getSizeModifier() != ArrayType::Static
)
6501 if (ArgExpr
->isNullPointerConstant(Context
,
6502 Expr::NPC_NeverValueDependent
)) {
6503 Diag(CallLoc
, diag::warn_null_arg
) << ArgExpr
->getSourceRange();
6504 DiagnoseCalleeStaticArrayParam(*this, Param
);
6508 const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(AT
);
6512 const ConstantArrayType
*ArgCAT
=
6513 Context
.getAsConstantArrayType(ArgExpr
->IgnoreParenCasts()->getType());
6517 if (getASTContext().hasSameUnqualifiedType(CAT
->getElementType(),
6518 ArgCAT
->getElementType())) {
6519 if (ArgCAT
->getSize().ult(CAT
->getSize())) {
6520 Diag(CallLoc
, diag::warn_static_array_too_small
)
6521 << ArgExpr
->getSourceRange()
6522 << (unsigned)ArgCAT
->getSize().getZExtValue()
6523 << (unsigned)CAT
->getSize().getZExtValue() << 0;
6524 DiagnoseCalleeStaticArrayParam(*this, Param
);
6529 std::optional
<CharUnits
> ArgSize
=
6530 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT
);
6531 std::optional
<CharUnits
> ParmSize
=
6532 getASTContext().getTypeSizeInCharsIfKnown(CAT
);
6533 if (ArgSize
&& ParmSize
&& *ArgSize
< *ParmSize
) {
6534 Diag(CallLoc
, diag::warn_static_array_too_small
)
6535 << ArgExpr
->getSourceRange() << (unsigned)ArgSize
->getQuantity()
6536 << (unsigned)ParmSize
->getQuantity() << 1;
6537 DiagnoseCalleeStaticArrayParam(*this, Param
);
6541 /// Given a function expression of unknown-any type, try to rebuild it
6542 /// to have a function type.
6543 static ExprResult
rebuildUnknownAnyFunction(Sema
&S
, Expr
*fn
);
6545 /// Is the given type a placeholder that we need to lower out
6546 /// immediately during argument processing?
6547 static bool isPlaceholderToRemoveAsArg(QualType type
) {
6548 // Placeholders are never sugared.
6549 const BuiltinType
*placeholder
= dyn_cast
<BuiltinType
>(type
);
6550 if (!placeholder
) return false;
6552 switch (placeholder
->getKind()) {
6553 // Ignore all the non-placeholder types.
6554 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6555 case BuiltinType::Id:
6556 #include "clang/Basic/OpenCLImageTypes.def"
6557 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6558 case BuiltinType::Id:
6559 #include "clang/Basic/OpenCLExtensionTypes.def"
6560 // In practice we'll never use this, since all SVE types are sugared
6561 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6562 #define SVE_TYPE(Name, Id, SingletonId) \
6563 case BuiltinType::Id:
6564 #include "clang/Basic/AArch64SVEACLETypes.def"
6565 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6566 case BuiltinType::Id:
6567 #include "clang/Basic/PPCTypes.def"
6568 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6569 #include "clang/Basic/RISCVVTypes.def"
6570 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6571 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6572 #include "clang/AST/BuiltinTypes.def"
6575 // We cannot lower out overload sets; they might validly be resolved
6576 // by the call machinery.
6577 case BuiltinType::Overload
:
6580 // Unbridged casts in ARC can be handled in some call positions and
6581 // should be left in place.
6582 case BuiltinType::ARCUnbridgedCast
:
6585 // Pseudo-objects should be converted as soon as possible.
6586 case BuiltinType::PseudoObject
:
6589 // The debugger mode could theoretically but currently does not try
6590 // to resolve unknown-typed arguments based on known parameter types.
6591 case BuiltinType::UnknownAny
:
6594 // These are always invalid as call arguments and should be reported.
6595 case BuiltinType::BoundMember
:
6596 case BuiltinType::BuiltinFn
:
6597 case BuiltinType::IncompleteMatrixIdx
:
6598 case BuiltinType::OMPArraySection
:
6599 case BuiltinType::OMPArrayShaping
:
6600 case BuiltinType::OMPIterator
:
6604 llvm_unreachable("bad builtin type kind");
6607 /// Check an argument list for placeholders that we won't try to
6609 static bool checkArgsForPlaceholders(Sema
&S
, MultiExprArg args
) {
6610 // Apply this processing to all the arguments at once instead of
6611 // dying at the first failure.
6612 bool hasInvalid
= false;
6613 for (size_t i
= 0, e
= args
.size(); i
!= e
; i
++) {
6614 if (isPlaceholderToRemoveAsArg(args
[i
]->getType())) {
6615 ExprResult result
= S
.CheckPlaceholderExpr(args
[i
]);
6616 if (result
.isInvalid()) hasInvalid
= true;
6617 else args
[i
] = result
.get();
6623 /// If a builtin function has a pointer argument with no explicit address
6624 /// space, then it should be able to accept a pointer to any address
6625 /// space as input. In order to do this, we need to replace the
6626 /// standard builtin declaration with one that uses the same address space
6629 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6630 /// it does not contain any pointer arguments without
6631 /// an address space qualifer. Otherwise the rewritten
6632 /// FunctionDecl is returned.
6633 /// TODO: Handle pointer return types.
6634 static FunctionDecl
*rewriteBuiltinFunctionDecl(Sema
*Sema
, ASTContext
&Context
,
6635 FunctionDecl
*FDecl
,
6636 MultiExprArg ArgExprs
) {
6638 QualType DeclType
= FDecl
->getType();
6639 const FunctionProtoType
*FT
= dyn_cast
<FunctionProtoType
>(DeclType
);
6641 if (!Context
.BuiltinInfo
.hasPtrArgsOrResult(FDecl
->getBuiltinID()) || !FT
||
6642 ArgExprs
.size() < FT
->getNumParams())
6645 bool NeedsNewDecl
= false;
6647 SmallVector
<QualType
, 8> OverloadParams
;
6649 for (QualType ParamType
: FT
->param_types()) {
6651 // Convert array arguments to pointer to simplify type lookup.
6653 Sema
->DefaultFunctionArrayLvalueConversion(ArgExprs
[i
++]);
6654 if (ArgRes
.isInvalid())
6656 Expr
*Arg
= ArgRes
.get();
6657 QualType ArgType
= Arg
->getType();
6658 if (!ParamType
->isPointerType() || ParamType
.hasAddressSpace() ||
6659 !ArgType
->isPointerType() ||
6660 !ArgType
->getPointeeType().hasAddressSpace() ||
6661 isPtrSizeAddressSpace(ArgType
->getPointeeType().getAddressSpace())) {
6662 OverloadParams
.push_back(ParamType
);
6666 QualType PointeeType
= ParamType
->getPointeeType();
6667 if (PointeeType
.hasAddressSpace())
6670 NeedsNewDecl
= true;
6671 LangAS AS
= ArgType
->getPointeeType().getAddressSpace();
6673 PointeeType
= Context
.getAddrSpaceQualType(PointeeType
, AS
);
6674 OverloadParams
.push_back(Context
.getPointerType(PointeeType
));
6680 FunctionProtoType::ExtProtoInfo EPI
;
6681 EPI
.Variadic
= FT
->isVariadic();
6682 QualType OverloadTy
= Context
.getFunctionType(FT
->getReturnType(),
6683 OverloadParams
, EPI
);
6684 DeclContext
*Parent
= FDecl
->getParent();
6685 FunctionDecl
*OverloadDecl
= FunctionDecl::Create(
6686 Context
, Parent
, FDecl
->getLocation(), FDecl
->getLocation(),
6687 FDecl
->getIdentifier(), OverloadTy
,
6688 /*TInfo=*/nullptr, SC_Extern
, Sema
->getCurFPFeatures().isFPConstrained(),
6690 /*hasPrototype=*/true);
6691 SmallVector
<ParmVarDecl
*, 16> Params
;
6692 FT
= cast
<FunctionProtoType
>(OverloadTy
);
6693 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
6694 QualType ParamType
= FT
->getParamType(i
);
6696 ParmVarDecl::Create(Context
, OverloadDecl
, SourceLocation(),
6697 SourceLocation(), nullptr, ParamType
,
6698 /*TInfo=*/nullptr, SC_None
, nullptr);
6699 Parm
->setScopeInfo(0, i
);
6700 Params
.push_back(Parm
);
6702 OverloadDecl
->setParams(Params
);
6703 Sema
->mergeDeclAttributes(OverloadDecl
, FDecl
);
6704 return OverloadDecl
;
6707 static void checkDirectCallValidity(Sema
&S
, const Expr
*Fn
,
6708 FunctionDecl
*Callee
,
6709 MultiExprArg ArgExprs
) {
6710 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
6711 // similar attributes) really don't like it when functions are called with an
6712 // invalid number of args.
6713 if (S
.TooManyArguments(Callee
->getNumParams(), ArgExprs
.size(),
6714 /*PartialOverloading=*/false) &&
6715 !Callee
->isVariadic())
6717 if (Callee
->getMinRequiredArguments() > ArgExprs
.size())
6720 if (const EnableIfAttr
*Attr
=
6721 S
.CheckEnableIf(Callee
, Fn
->getBeginLoc(), ArgExprs
, true)) {
6722 S
.Diag(Fn
->getBeginLoc(),
6723 isa
<CXXMethodDecl
>(Callee
)
6724 ? diag::err_ovl_no_viable_member_function_in_call
6725 : diag::err_ovl_no_viable_function_in_call
)
6726 << Callee
<< Callee
->getSourceRange();
6727 S
.Diag(Callee
->getLocation(),
6728 diag::note_ovl_candidate_disabled_by_function_cond_attr
)
6729 << Attr
->getCond()->getSourceRange() << Attr
->getMessage();
6734 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
6735 const UnresolvedMemberExpr
*const UME
, Sema
&S
) {
6737 const auto GetFunctionLevelDCIfCXXClass
=
6738 [](Sema
&S
) -> const CXXRecordDecl
* {
6739 const DeclContext
*const DC
= S
.getFunctionLevelDeclContext();
6740 if (!DC
|| !DC
->getParent())
6743 // If the call to some member function was made from within a member
6744 // function body 'M' return return 'M's parent.
6745 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(DC
))
6746 return MD
->getParent()->getCanonicalDecl();
6747 // else the call was made from within a default member initializer of a
6748 // class, so return the class.
6749 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
))
6750 return RD
->getCanonicalDecl();
6753 // If our DeclContext is neither a member function nor a class (in the
6754 // case of a lambda in a default member initializer), we can't have an
6755 // enclosing 'this'.
6757 const CXXRecordDecl
*const CurParentClass
= GetFunctionLevelDCIfCXXClass(S
);
6758 if (!CurParentClass
)
6761 // The naming class for implicit member functions call is the class in which
6762 // name lookup starts.
6763 const CXXRecordDecl
*const NamingClass
=
6764 UME
->getNamingClass()->getCanonicalDecl();
6765 assert(NamingClass
&& "Must have naming class even for implicit access");
6767 // If the unresolved member functions were found in a 'naming class' that is
6768 // related (either the same or derived from) to the class that contains the
6769 // member function that itself contained the implicit member access.
6771 return CurParentClass
== NamingClass
||
6772 CurParentClass
->isDerivedFrom(NamingClass
);
6776 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6777 Sema
&S
, const UnresolvedMemberExpr
*const UME
, SourceLocation CallLoc
) {
6782 LambdaScopeInfo
*const CurLSI
= S
.getCurLambda();
6783 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
6784 // already been captured, or if this is an implicit member function call (if
6785 // it isn't, an attempt to capture 'this' should already have been made).
6786 if (!CurLSI
|| CurLSI
->ImpCaptureStyle
== CurLSI
->ImpCap_None
||
6787 !UME
->isImplicitAccess() || CurLSI
->isCXXThisCaptured())
6790 // Check if the naming class in which the unresolved members were found is
6791 // related (same as or is a base of) to the enclosing class.
6793 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME
, S
))
6797 DeclContext
*EnclosingFunctionCtx
= S
.CurContext
->getParent()->getParent();
6798 // If the enclosing function is not dependent, then this lambda is
6799 // capture ready, so if we can capture this, do so.
6800 if (!EnclosingFunctionCtx
->isDependentContext()) {
6801 // If the current lambda and all enclosing lambdas can capture 'this' -
6802 // then go ahead and capture 'this' (since our unresolved overload set
6803 // contains at least one non-static member function).
6804 if (!S
.CheckCXXThisCapture(CallLoc
, /*Explcit*/ false, /*Diagnose*/ false))
6805 S
.CheckCXXThisCapture(CallLoc
);
6806 } else if (S
.CurContext
->isDependentContext()) {
6807 // ... since this is an implicit member reference, that might potentially
6808 // involve a 'this' capture, mark 'this' for potential capture in
6809 // enclosing lambdas.
6810 if (CurLSI
->ImpCaptureStyle
!= CurLSI
->ImpCap_None
)
6811 CurLSI
->addPotentialThisCapture(CallLoc
);
6815 // Once a call is fully resolved, warn for unqualified calls to specific
6816 // C++ standard functions, like move and forward.
6817 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema
&S
, CallExpr
*Call
) {
6818 // We are only checking unary move and forward so exit early here.
6819 if (Call
->getNumArgs() != 1)
6822 Expr
*E
= Call
->getCallee()->IgnoreParenImpCasts();
6823 if (!E
|| isa
<UnresolvedLookupExpr
>(E
))
6825 DeclRefExpr
*DRE
= dyn_cast_or_null
<DeclRefExpr
>(E
);
6826 if (!DRE
|| !DRE
->getLocation().isValid())
6829 if (DRE
->getQualifier())
6832 const FunctionDecl
*FD
= Call
->getDirectCallee();
6836 // Only warn for some functions deemed more frequent or problematic.
6837 unsigned BuiltinID
= FD
->getBuiltinID();
6838 if (BuiltinID
!= Builtin::BImove
&& BuiltinID
!= Builtin::BIforward
)
6841 S
.Diag(DRE
->getLocation(), diag::warn_unqualified_call_to_std_cast_function
)
6842 << FD
->getQualifiedNameAsString()
6843 << FixItHint::CreateInsertion(DRE
->getLocation(), "std::");
6846 ExprResult
Sema::ActOnCallExpr(Scope
*Scope
, Expr
*Fn
, SourceLocation LParenLoc
,
6847 MultiExprArg ArgExprs
, SourceLocation RParenLoc
,
6850 BuildCallExpr(Scope
, Fn
, LParenLoc
, ArgExprs
, RParenLoc
, ExecConfig
,
6851 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
6852 if (Call
.isInvalid())
6855 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
6857 if (auto *ULE
= dyn_cast
<UnresolvedLookupExpr
>(Fn
)) {
6858 if (ULE
->hasExplicitTemplateArgs() &&
6859 ULE
->decls_begin() == ULE
->decls_end()) {
6860 Diag(Fn
->getExprLoc(), getLangOpts().CPlusPlus20
6861 ? diag::warn_cxx17_compat_adl_only_template_id
6862 : diag::ext_adl_only_template_id
)
6867 if (LangOpts
.OpenMP
)
6868 Call
= ActOnOpenMPCall(Call
, Scope
, LParenLoc
, ArgExprs
, RParenLoc
,
6870 if (LangOpts
.CPlusPlus
) {
6871 CallExpr
*CE
= dyn_cast
<CallExpr
>(Call
.get());
6873 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE
);
6878 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
6879 /// This provides the location of the left/right parens and a list of comma
6881 ExprResult
Sema::BuildCallExpr(Scope
*Scope
, Expr
*Fn
, SourceLocation LParenLoc
,
6882 MultiExprArg ArgExprs
, SourceLocation RParenLoc
,
6883 Expr
*ExecConfig
, bool IsExecConfig
,
6884 bool AllowRecovery
) {
6885 // Since this might be a postfix expression, get rid of ParenListExprs.
6886 ExprResult Result
= MaybeConvertParenListExprToParenExpr(Scope
, Fn
);
6887 if (Result
.isInvalid()) return ExprError();
6890 if (checkArgsForPlaceholders(*this, ArgExprs
))
6893 if (getLangOpts().CPlusPlus
) {
6894 // If this is a pseudo-destructor expression, build the call immediately.
6895 if (isa
<CXXPseudoDestructorExpr
>(Fn
)) {
6896 if (!ArgExprs
.empty()) {
6897 // Pseudo-destructor calls should not have any arguments.
6898 Diag(Fn
->getBeginLoc(), diag::err_pseudo_dtor_call_with_args
)
6899 << FixItHint::CreateRemoval(
6900 SourceRange(ArgExprs
.front()->getBeginLoc(),
6901 ArgExprs
.back()->getEndLoc()));
6904 return CallExpr::Create(Context
, Fn
, /*Args=*/{}, Context
.VoidTy
,
6905 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
6907 if (Fn
->getType() == Context
.PseudoObjectTy
) {
6908 ExprResult result
= CheckPlaceholderExpr(Fn
);
6909 if (result
.isInvalid()) return ExprError();
6913 // Determine whether this is a dependent call inside a C++ template,
6914 // in which case we won't do any semantic analysis now.
6915 if (Fn
->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs
)) {
6917 return CUDAKernelCallExpr::Create(Context
, Fn
,
6918 cast
<CallExpr
>(ExecConfig
), ArgExprs
,
6919 Context
.DependentTy
, VK_PRValue
,
6920 RParenLoc
, CurFPFeatureOverrides());
6923 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
6924 *this, dyn_cast
<UnresolvedMemberExpr
>(Fn
->IgnoreParens()),
6927 return CallExpr::Create(Context
, Fn
, ArgExprs
, Context
.DependentTy
,
6928 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
6932 // Determine whether this is a call to an object (C++ [over.call.object]).
6933 if (Fn
->getType()->isRecordType())
6934 return BuildCallToObjectOfClassType(Scope
, Fn
, LParenLoc
, ArgExprs
,
6937 if (Fn
->getType() == Context
.UnknownAnyTy
) {
6938 ExprResult result
= rebuildUnknownAnyFunction(*this, Fn
);
6939 if (result
.isInvalid()) return ExprError();
6943 if (Fn
->getType() == Context
.BoundMemberTy
) {
6944 return BuildCallToMemberFunction(Scope
, Fn
, LParenLoc
, ArgExprs
,
6945 RParenLoc
, ExecConfig
, IsExecConfig
,
6950 // Check for overloaded calls. This can happen even in C due to extensions.
6951 if (Fn
->getType() == Context
.OverloadTy
) {
6952 OverloadExpr::FindResult find
= OverloadExpr::find(Fn
);
6954 // We aren't supposed to apply this logic if there's an '&' involved.
6955 if (!find
.HasFormOfMemberPointer
) {
6956 if (Expr::hasAnyTypeDependentArguments(ArgExprs
))
6957 return CallExpr::Create(Context
, Fn
, ArgExprs
, Context
.DependentTy
,
6958 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
6959 OverloadExpr
*ovl
= find
.Expression
;
6960 if (UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(ovl
))
6961 return BuildOverloadedCallExpr(
6962 Scope
, Fn
, ULE
, LParenLoc
, ArgExprs
, RParenLoc
, ExecConfig
,
6963 /*AllowTypoCorrection=*/true, find
.IsAddressOfOperand
);
6964 return BuildCallToMemberFunction(Scope
, Fn
, LParenLoc
, ArgExprs
,
6965 RParenLoc
, ExecConfig
, IsExecConfig
,
6970 // If we're directly calling a function, get the appropriate declaration.
6971 if (Fn
->getType() == Context
.UnknownAnyTy
) {
6972 ExprResult result
= rebuildUnknownAnyFunction(*this, Fn
);
6973 if (result
.isInvalid()) return ExprError();
6977 Expr
*NakedFn
= Fn
->IgnoreParens();
6979 bool CallingNDeclIndirectly
= false;
6980 NamedDecl
*NDecl
= nullptr;
6981 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(NakedFn
)) {
6982 if (UnOp
->getOpcode() == UO_AddrOf
) {
6983 CallingNDeclIndirectly
= true;
6984 NakedFn
= UnOp
->getSubExpr()->IgnoreParens();
6988 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(NakedFn
)) {
6989 NDecl
= DRE
->getDecl();
6991 FunctionDecl
*FDecl
= dyn_cast
<FunctionDecl
>(NDecl
);
6992 if (FDecl
&& FDecl
->getBuiltinID()) {
6993 // Rewrite the function decl for this builtin by replacing parameters
6994 // with no explicit address space with the address space of the arguments
6997 rewriteBuiltinFunctionDecl(this, Context
, FDecl
, ArgExprs
))) {
6999 Fn
= DeclRefExpr::Create(
7000 Context
, FDecl
->getQualifierLoc(), SourceLocation(), FDecl
, false,
7001 SourceLocation(), FDecl
->getType(), Fn
->getValueKind(), FDecl
,
7002 nullptr, DRE
->isNonOdrUse());
7005 } else if (auto *ME
= dyn_cast
<MemberExpr
>(NakedFn
))
7006 NDecl
= ME
->getMemberDecl();
7008 if (FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(NDecl
)) {
7009 if (CallingNDeclIndirectly
&& !checkAddressOfFunctionIsAvailable(
7010 FD
, /*Complain=*/true, Fn
->getBeginLoc()))
7013 checkDirectCallValidity(*this, Fn
, FD
, ArgExprs
);
7015 // If this expression is a call to a builtin function in HIP device
7016 // compilation, allow a pointer-type argument to default address space to be
7017 // passed as a pointer-type parameter to a non-default address space.
7018 // If Arg is declared in the default address space and Param is declared
7019 // in a non-default address space, perform an implicit address space cast to
7020 // the parameter type.
7021 if (getLangOpts().HIP
&& getLangOpts().CUDAIsDevice
&& FD
&&
7022 FD
->getBuiltinID()) {
7023 for (unsigned Idx
= 0; Idx
< FD
->param_size(); ++Idx
) {
7024 ParmVarDecl
*Param
= FD
->getParamDecl(Idx
);
7025 if (!ArgExprs
[Idx
] || !Param
|| !Param
->getType()->isPointerType() ||
7026 !ArgExprs
[Idx
]->getType()->isPointerType())
7029 auto ParamAS
= Param
->getType()->getPointeeType().getAddressSpace();
7030 auto ArgTy
= ArgExprs
[Idx
]->getType();
7031 auto ArgPtTy
= ArgTy
->getPointeeType();
7032 auto ArgAS
= ArgPtTy
.getAddressSpace();
7034 // Add address space cast if target address spaces are different
7035 bool NeedImplicitASC
=
7036 ParamAS
!= LangAS::Default
&& // Pointer params in generic AS don't need special handling.
7037 ( ArgAS
== LangAS::Default
|| // We do allow implicit conversion from generic AS
7038 // or from specific AS which has target AS matching that of Param.
7039 getASTContext().getTargetAddressSpace(ArgAS
) == getASTContext().getTargetAddressSpace(ParamAS
));
7040 if (!NeedImplicitASC
)
7043 // First, ensure that the Arg is an RValue.
7044 if (ArgExprs
[Idx
]->isGLValue()) {
7045 ArgExprs
[Idx
] = ImplicitCastExpr::Create(
7046 Context
, ArgExprs
[Idx
]->getType(), CK_NoOp
, ArgExprs
[Idx
],
7047 nullptr, VK_PRValue
, FPOptionsOverride());
7050 // Construct a new arg type with address space of Param
7051 Qualifiers ArgPtQuals
= ArgPtTy
.getQualifiers();
7052 ArgPtQuals
.setAddressSpace(ParamAS
);
7054 Context
.getQualifiedType(ArgPtTy
.getUnqualifiedType(), ArgPtQuals
);
7056 Context
.getQualifiedType(Context
.getPointerType(NewArgPtTy
),
7057 ArgTy
.getQualifiers());
7059 // Finally perform an implicit address space cast
7060 ArgExprs
[Idx
] = ImpCastExprToType(ArgExprs
[Idx
], NewArgTy
,
7061 CK_AddressSpaceConversion
)
7067 if (Context
.isDependenceAllowed() &&
7068 (Fn
->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs
))) {
7069 assert(!getLangOpts().CPlusPlus
);
7070 assert((Fn
->containsErrors() ||
7071 llvm::any_of(ArgExprs
,
7072 [](clang::Expr
*E
) { return E
->containsErrors(); })) &&
7073 "should only occur in error-recovery path.");
7074 QualType ReturnType
=
7075 llvm::isa_and_nonnull
<FunctionDecl
>(NDecl
)
7076 ? cast
<FunctionDecl
>(NDecl
)->getCallResultType()
7077 : Context
.DependentTy
;
7078 return CallExpr::Create(Context
, Fn
, ArgExprs
, ReturnType
,
7079 Expr::getValueKindForType(ReturnType
), RParenLoc
,
7080 CurFPFeatureOverrides());
7082 return BuildResolvedCallExpr(Fn
, NDecl
, LParenLoc
, ArgExprs
, RParenLoc
,
7083 ExecConfig
, IsExecConfig
);
7086 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7087 // with the specified CallArgs
7088 Expr
*Sema::BuildBuiltinCallExpr(SourceLocation Loc
, Builtin::ID Id
,
7089 MultiExprArg CallArgs
) {
7090 StringRef Name
= Context
.BuiltinInfo
.getName(Id
);
7091 LookupResult
R(*this, &Context
.Idents
.get(Name
), Loc
,
7092 Sema::LookupOrdinaryName
);
7093 LookupName(R
, TUScope
, /*AllowBuiltinCreation=*/true);
7095 auto *BuiltInDecl
= R
.getAsSingle
<FunctionDecl
>();
7096 assert(BuiltInDecl
&& "failed to find builtin declaration");
7098 ExprResult DeclRef
=
7099 BuildDeclRefExpr(BuiltInDecl
, BuiltInDecl
->getType(), VK_LValue
, Loc
);
7100 assert(DeclRef
.isUsable() && "Builtin reference cannot fail");
7103 BuildCallExpr(/*Scope=*/nullptr, DeclRef
.get(), Loc
, CallArgs
, Loc
);
7105 assert(!Call
.isInvalid() && "Call to builtin cannot fail!");
7109 /// Parse a __builtin_astype expression.
7111 /// __builtin_astype( value, dst type )
7113 ExprResult
Sema::ActOnAsTypeExpr(Expr
*E
, ParsedType ParsedDestTy
,
7114 SourceLocation BuiltinLoc
,
7115 SourceLocation RParenLoc
) {
7116 QualType DstTy
= GetTypeFromParser(ParsedDestTy
);
7117 return BuildAsTypeExpr(E
, DstTy
, BuiltinLoc
, RParenLoc
);
7120 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7121 ExprResult
Sema::BuildAsTypeExpr(Expr
*E
, QualType DestTy
,
7122 SourceLocation BuiltinLoc
,
7123 SourceLocation RParenLoc
) {
7124 ExprValueKind VK
= VK_PRValue
;
7125 ExprObjectKind OK
= OK_Ordinary
;
7126 QualType SrcTy
= E
->getType();
7127 if (!SrcTy
->isDependentType() &&
7128 Context
.getTypeSize(DestTy
) != Context
.getTypeSize(SrcTy
))
7130 Diag(BuiltinLoc
, diag::err_invalid_astype_of_different_size
)
7131 << DestTy
<< SrcTy
<< E
->getSourceRange());
7132 return new (Context
) AsTypeExpr(E
, DestTy
, VK
, OK
, BuiltinLoc
, RParenLoc
);
7135 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7136 /// provided arguments.
7138 /// __builtin_convertvector( value, dst type )
7140 ExprResult
Sema::ActOnConvertVectorExpr(Expr
*E
, ParsedType ParsedDestTy
,
7141 SourceLocation BuiltinLoc
,
7142 SourceLocation RParenLoc
) {
7143 TypeSourceInfo
*TInfo
;
7144 GetTypeFromParser(ParsedDestTy
, &TInfo
);
7145 return SemaConvertVectorExpr(E
, TInfo
, BuiltinLoc
, RParenLoc
);
7148 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7149 /// i.e. an expression not of \p OverloadTy. The expression should
7150 /// unary-convert to an expression of function-pointer or
7151 /// block-pointer type.
7153 /// \param NDecl the declaration being called, if available
7154 ExprResult
Sema::BuildResolvedCallExpr(Expr
*Fn
, NamedDecl
*NDecl
,
7155 SourceLocation LParenLoc
,
7156 ArrayRef
<Expr
*> Args
,
7157 SourceLocation RParenLoc
, Expr
*Config
,
7158 bool IsExecConfig
, ADLCallKind UsesADL
) {
7159 FunctionDecl
*FDecl
= dyn_cast_or_null
<FunctionDecl
>(NDecl
);
7160 unsigned BuiltinID
= (FDecl
? FDecl
->getBuiltinID() : 0);
7162 // Functions with 'interrupt' attribute cannot be called directly.
7163 if (FDecl
&& FDecl
->hasAttr
<AnyX86InterruptAttr
>()) {
7164 Diag(Fn
->getExprLoc(), diag::err_anyx86_interrupt_called
);
7168 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7169 // so there's some risk when calling out to non-interrupt handler functions
7170 // that the callee might not preserve them. This is easy to diagnose here,
7171 // but can be very challenging to debug.
7172 // Likewise, X86 interrupt handlers may only call routines with attribute
7173 // no_caller_saved_registers since there is no efficient way to
7174 // save and restore the non-GPR state.
7175 if (auto *Caller
= getCurFunctionDecl()) {
7176 if (Caller
->hasAttr
<ARMInterruptAttr
>()) {
7177 bool VFP
= Context
.getTargetInfo().hasFeature("vfp");
7178 if (VFP
&& (!FDecl
|| !FDecl
->hasAttr
<ARMInterruptAttr
>())) {
7179 Diag(Fn
->getExprLoc(), diag::warn_arm_interrupt_calling_convention
);
7181 Diag(FDecl
->getLocation(), diag::note_callee_decl
) << FDecl
;
7184 if (Caller
->hasAttr
<AnyX86InterruptAttr
>() &&
7185 ((!FDecl
|| !FDecl
->hasAttr
<AnyX86NoCallerSavedRegistersAttr
>()))) {
7186 Diag(Fn
->getExprLoc(), diag::warn_anyx86_interrupt_regsave
);
7188 Diag(FDecl
->getLocation(), diag::note_callee_decl
) << FDecl
;
7192 // Promote the function operand.
7193 // We special-case function promotion here because we only allow promoting
7194 // builtin functions to function pointers in the callee of a call.
7198 Fn
->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn
)) {
7199 // Extract the return type from the (builtin) function pointer type.
7200 // FIXME Several builtins still have setType in
7201 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7202 // Builtins.def to ensure they are correct before removing setType calls.
7203 QualType FnPtrTy
= Context
.getPointerType(FDecl
->getType());
7204 Result
= ImpCastExprToType(Fn
, FnPtrTy
, CK_BuiltinFnToFnPtr
).get();
7205 ResultTy
= FDecl
->getCallResultType();
7207 Result
= CallExprUnaryConversions(Fn
);
7208 ResultTy
= Context
.BoolTy
;
7210 if (Result
.isInvalid())
7214 // Check for a valid function type, but only if it is not a builtin which
7215 // requires custom type checking. These will be handled by
7216 // CheckBuiltinFunctionCall below just after creation of the call expression.
7217 const FunctionType
*FuncT
= nullptr;
7218 if (!BuiltinID
|| !Context
.BuiltinInfo
.hasCustomTypechecking(BuiltinID
)) {
7220 if (const PointerType
*PT
= Fn
->getType()->getAs
<PointerType
>()) {
7221 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7222 // have type pointer to function".
7223 FuncT
= PT
->getPointeeType()->getAs
<FunctionType
>();
7225 return ExprError(Diag(LParenLoc
, diag::err_typecheck_call_not_function
)
7226 << Fn
->getType() << Fn
->getSourceRange());
7227 } else if (const BlockPointerType
*BPT
=
7228 Fn
->getType()->getAs
<BlockPointerType
>()) {
7229 FuncT
= BPT
->getPointeeType()->castAs
<FunctionType
>();
7231 // Handle calls to expressions of unknown-any type.
7232 if (Fn
->getType() == Context
.UnknownAnyTy
) {
7233 ExprResult rewrite
= rebuildUnknownAnyFunction(*this, Fn
);
7234 if (rewrite
.isInvalid())
7240 return ExprError(Diag(LParenLoc
, diag::err_typecheck_call_not_function
)
7241 << Fn
->getType() << Fn
->getSourceRange());
7245 // Get the number of parameters in the function prototype, if any.
7246 // We will allocate space for max(Args.size(), NumParams) arguments
7247 // in the call expression.
7248 const auto *Proto
= dyn_cast_or_null
<FunctionProtoType
>(FuncT
);
7249 unsigned NumParams
= Proto
? Proto
->getNumParams() : 0;
7253 assert(UsesADL
== ADLCallKind::NotADL
&&
7254 "CUDAKernelCallExpr should not use ADL");
7255 TheCall
= CUDAKernelCallExpr::Create(Context
, Fn
, cast
<CallExpr
>(Config
),
7256 Args
, ResultTy
, VK_PRValue
, RParenLoc
,
7257 CurFPFeatureOverrides(), NumParams
);
7260 CallExpr::Create(Context
, Fn
, Args
, ResultTy
, VK_PRValue
, RParenLoc
,
7261 CurFPFeatureOverrides(), NumParams
, UsesADL
);
7264 if (!Context
.isDependenceAllowed()) {
7265 // Forget about the nulled arguments since typo correction
7266 // do not handle them well.
7267 TheCall
->shrinkNumArgs(Args
.size());
7268 // C cannot always handle TypoExpr nodes in builtin calls and direct
7269 // function calls as their argument checking don't necessarily handle
7270 // dependent types properly, so make sure any TypoExprs have been
7272 ExprResult Result
= CorrectDelayedTyposInExpr(TheCall
);
7273 if (!Result
.isUsable()) return ExprError();
7274 CallExpr
*TheOldCall
= TheCall
;
7275 TheCall
= dyn_cast
<CallExpr
>(Result
.get());
7276 bool CorrectedTypos
= TheCall
!= TheOldCall
;
7277 if (!TheCall
) return Result
;
7278 Args
= llvm::ArrayRef(TheCall
->getArgs(), TheCall
->getNumArgs());
7280 // A new call expression node was created if some typos were corrected.
7281 // However it may not have been constructed with enough storage. In this
7282 // case, rebuild the node with enough storage. The waste of space is
7283 // immaterial since this only happens when some typos were corrected.
7284 if (CorrectedTypos
&& Args
.size() < NumParams
) {
7286 TheCall
= CUDAKernelCallExpr::Create(
7287 Context
, Fn
, cast
<CallExpr
>(Config
), Args
, ResultTy
, VK_PRValue
,
7288 RParenLoc
, CurFPFeatureOverrides(), NumParams
);
7291 CallExpr::Create(Context
, Fn
, Args
, ResultTy
, VK_PRValue
, RParenLoc
,
7292 CurFPFeatureOverrides(), NumParams
, UsesADL
);
7294 // We can now handle the nulled arguments for the default arguments.
7295 TheCall
->setNumArgsUnsafe(std::max
<unsigned>(Args
.size(), NumParams
));
7298 // Bail out early if calling a builtin with custom type checking.
7299 if (BuiltinID
&& Context
.BuiltinInfo
.hasCustomTypechecking(BuiltinID
))
7300 return CheckBuiltinFunctionCall(FDecl
, BuiltinID
, TheCall
);
7302 if (getLangOpts().CUDA
) {
7304 // CUDA: Kernel calls must be to global functions
7305 if (FDecl
&& !FDecl
->hasAttr
<CUDAGlobalAttr
>())
7306 return ExprError(Diag(LParenLoc
,diag::err_kern_call_not_global_function
)
7307 << FDecl
<< Fn
->getSourceRange());
7309 // CUDA: Kernel function must have 'void' return type
7310 if (!FuncT
->getReturnType()->isVoidType() &&
7311 !FuncT
->getReturnType()->getAs
<AutoType
>() &&
7312 !FuncT
->getReturnType()->isInstantiationDependentType())
7313 return ExprError(Diag(LParenLoc
, diag::err_kern_type_not_void_return
)
7314 << Fn
->getType() << Fn
->getSourceRange());
7316 // CUDA: Calls to global functions must be configured
7317 if (FDecl
&& FDecl
->hasAttr
<CUDAGlobalAttr
>())
7318 return ExprError(Diag(LParenLoc
, diag::err_global_call_not_config
)
7319 << FDecl
<< Fn
->getSourceRange());
7323 // Check for a valid return type
7324 if (CheckCallReturnType(FuncT
->getReturnType(), Fn
->getBeginLoc(), TheCall
,
7328 // We know the result type of the call, set it.
7329 TheCall
->setType(FuncT
->getCallResultType(Context
));
7330 TheCall
->setValueKind(Expr::getValueKindForType(FuncT
->getReturnType()));
7333 if (ConvertArgumentsForCall(TheCall
, Fn
, FDecl
, Proto
, Args
, RParenLoc
,
7337 assert(isa
<FunctionNoProtoType
>(FuncT
) && "Unknown FunctionType!");
7340 // Check if we have too few/too many template arguments, based
7341 // on our knowledge of the function definition.
7342 const FunctionDecl
*Def
= nullptr;
7343 if (FDecl
->hasBody(Def
) && Args
.size() != Def
->param_size()) {
7344 Proto
= Def
->getType()->getAs
<FunctionProtoType
>();
7345 if (!Proto
|| !(Proto
->isVariadic() && Args
.size() >= Def
->param_size()))
7346 Diag(RParenLoc
, diag::warn_call_wrong_number_of_arguments
)
7347 << (Args
.size() > Def
->param_size()) << FDecl
<< Fn
->getSourceRange();
7350 // If the function we're calling isn't a function prototype, but we have
7351 // a function prototype from a prior declaratiom, use that prototype.
7352 if (!FDecl
->hasPrototype())
7353 Proto
= FDecl
->getType()->getAs
<FunctionProtoType
>();
7356 // If we still haven't found a prototype to use but there are arguments to
7357 // the call, diagnose this as calling a function without a prototype.
7358 // However, if we found a function declaration, check to see if
7359 // -Wdeprecated-non-prototype was disabled where the function was declared.
7360 // If so, we will silence the diagnostic here on the assumption that this
7361 // interface is intentional and the user knows what they're doing. We will
7362 // also silence the diagnostic if there is a function declaration but it
7363 // was implicitly defined (the user already gets diagnostics about the
7364 // creation of the implicit function declaration, so the additional warning
7366 if (!Proto
&& !Args
.empty() &&
7367 (!FDecl
|| (!FDecl
->isImplicit() &&
7368 !Diags
.isIgnored(diag::warn_strict_uses_without_prototype
,
7369 FDecl
->getLocation()))))
7370 Diag(LParenLoc
, diag::warn_strict_uses_without_prototype
)
7371 << (FDecl
!= nullptr) << FDecl
;
7373 // Promote the arguments (C99 6.5.2.2p6).
7374 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++) {
7375 Expr
*Arg
= Args
[i
];
7377 if (Proto
&& i
< Proto
->getNumParams()) {
7378 InitializedEntity Entity
= InitializedEntity::InitializeParameter(
7379 Context
, Proto
->getParamType(i
), Proto
->isParamConsumed(i
));
7381 PerformCopyInitialization(Entity
, SourceLocation(), Arg
);
7382 if (ArgE
.isInvalid())
7385 Arg
= ArgE
.getAs
<Expr
>();
7388 ExprResult ArgE
= DefaultArgumentPromotion(Arg
);
7390 if (ArgE
.isInvalid())
7393 Arg
= ArgE
.getAs
<Expr
>();
7396 if (RequireCompleteType(Arg
->getBeginLoc(), Arg
->getType(),
7397 diag::err_call_incomplete_argument
, Arg
))
7400 TheCall
->setArg(i
, Arg
);
7402 TheCall
->computeDependence();
7405 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(FDecl
))
7406 if (!Method
->isStatic())
7407 return ExprError(Diag(LParenLoc
, diag::err_member_call_without_object
)
7408 << Fn
->getSourceRange());
7410 // Check for sentinels
7412 DiagnoseSentinelCalls(NDecl
, LParenLoc
, Args
);
7414 // Warn for unions passing across security boundary (CMSE).
7415 if (FuncT
!= nullptr && FuncT
->getCmseNSCallAttr()) {
7416 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++) {
7417 if (const auto *RT
=
7418 dyn_cast
<RecordType
>(Args
[i
]->getType().getCanonicalType())) {
7419 if (RT
->getDecl()->isOrContainsUnion())
7420 Diag(Args
[i
]->getBeginLoc(), diag::warn_cmse_nonsecure_union
)
7426 // Do special checking on direct calls to functions.
7428 if (CheckFunctionCall(FDecl
, TheCall
, Proto
))
7431 checkFortifiedBuiltinMemoryFunction(FDecl
, TheCall
);
7434 return CheckBuiltinFunctionCall(FDecl
, BuiltinID
, TheCall
);
7436 if (CheckPointerCall(NDecl
, TheCall
, Proto
))
7439 if (CheckOtherCall(TheCall
, Proto
))
7443 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), FDecl
);
7447 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc
, ParsedType Ty
,
7448 SourceLocation RParenLoc
, Expr
*InitExpr
) {
7449 assert(Ty
&& "ActOnCompoundLiteral(): missing type");
7450 assert(InitExpr
&& "ActOnCompoundLiteral(): missing expression");
7452 TypeSourceInfo
*TInfo
;
7453 QualType literalType
= GetTypeFromParser(Ty
, &TInfo
);
7455 TInfo
= Context
.getTrivialTypeSourceInfo(literalType
);
7457 return BuildCompoundLiteralExpr(LParenLoc
, TInfo
, RParenLoc
, InitExpr
);
7461 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc
, TypeSourceInfo
*TInfo
,
7462 SourceLocation RParenLoc
, Expr
*LiteralExpr
) {
7463 QualType literalType
= TInfo
->getType();
7465 if (literalType
->isArrayType()) {
7466 if (RequireCompleteSizedType(
7467 LParenLoc
, Context
.getBaseElementType(literalType
),
7468 diag::err_array_incomplete_or_sizeless_type
,
7469 SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd())))
7471 if (literalType
->isVariableArrayType()) {
7472 if (!tryToFixVariablyModifiedVarType(TInfo
, literalType
, LParenLoc
,
7473 diag::err_variable_object_no_init
)) {
7477 } else if (!literalType
->isDependentType() &&
7478 RequireCompleteType(LParenLoc
, literalType
,
7479 diag::err_typecheck_decl_incomplete_type
,
7480 SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd())))
7483 InitializedEntity Entity
7484 = InitializedEntity::InitializeCompoundLiteralInit(TInfo
);
7485 InitializationKind Kind
7486 = InitializationKind::CreateCStyleCast(LParenLoc
,
7487 SourceRange(LParenLoc
, RParenLoc
),
7489 InitializationSequence
InitSeq(*this, Entity
, Kind
, LiteralExpr
);
7490 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, LiteralExpr
,
7492 if (Result
.isInvalid())
7494 LiteralExpr
= Result
.get();
7496 bool isFileScope
= !CurContext
->isFunctionOrMethod();
7498 // In C, compound literals are l-values for some reason.
7499 // For GCC compatibility, in C++, file-scope array compound literals with
7500 // constant initializers are also l-values, and compound literals are
7501 // otherwise prvalues.
7503 // (GCC also treats C++ list-initialized file-scope array prvalues with
7504 // constant initializers as l-values, but that's non-conforming, so we don't
7505 // follow it there.)
7507 // FIXME: It would be better to handle the lvalue cases as materializing and
7508 // lifetime-extending a temporary object, but our materialized temporaries
7509 // representation only supports lifetime extension from a variable, not "out
7511 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7512 // is bound to the result of applying array-to-pointer decay to the compound
7514 // FIXME: GCC supports compound literals of reference type, which should
7515 // obviously have a value kind derived from the kind of reference involved.
7517 (getLangOpts().CPlusPlus
&& !(isFileScope
&& literalType
->isArrayType()))
7522 if (auto ILE
= dyn_cast
<InitListExpr
>(LiteralExpr
))
7523 for (unsigned i
= 0, j
= ILE
->getNumInits(); i
!= j
; i
++) {
7524 Expr
*Init
= ILE
->getInit(i
);
7525 ILE
->setInit(i
, ConstantExpr::Create(Context
, Init
));
7528 auto *E
= new (Context
) CompoundLiteralExpr(LParenLoc
, TInfo
, literalType
,
7529 VK
, LiteralExpr
, isFileScope
);
7531 if (!LiteralExpr
->isTypeDependent() &&
7532 !LiteralExpr
->isValueDependent() &&
7533 !literalType
->isDependentType()) // C99 6.5.2.5p3
7534 if (CheckForConstantInitializer(LiteralExpr
, literalType
))
7536 } else if (literalType
.getAddressSpace() != LangAS::opencl_private
&&
7537 literalType
.getAddressSpace() != LangAS::Default
) {
7538 // Embedded-C extensions to C99 6.5.2.5:
7539 // "If the compound literal occurs inside the body of a function, the
7540 // type name shall not be qualified by an address-space qualifier."
7541 Diag(LParenLoc
, diag::err_compound_literal_with_address_space
)
7542 << SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd());
7546 if (!isFileScope
&& !getLangOpts().CPlusPlus
) {
7547 // Compound literals that have automatic storage duration are destroyed at
7548 // the end of the scope in C; in C++, they're just temporaries.
7550 // Emit diagnostics if it is or contains a C union type that is non-trivial
7552 if (E
->getType().hasNonTrivialToPrimitiveDestructCUnion())
7553 checkNonTrivialCUnion(E
->getType(), E
->getExprLoc(),
7554 NTCUC_CompoundLiteral
, NTCUK_Destruct
);
7556 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7557 if (literalType
.isDestructedType()) {
7558 Cleanup
.setExprNeedsCleanups(true);
7559 ExprCleanupObjects
.push_back(E
);
7560 getCurFunction()->setHasBranchProtectedScope();
7564 if (E
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7565 E
->getType().hasNonTrivialToPrimitiveCopyCUnion())
7566 checkNonTrivialCUnionInInitializer(E
->getInitializer(),
7567 E
->getInitializer()->getExprLoc());
7569 return MaybeBindToTemporary(E
);
7573 Sema::ActOnInitList(SourceLocation LBraceLoc
, MultiExprArg InitArgList
,
7574 SourceLocation RBraceLoc
) {
7575 // Only produce each kind of designated initialization diagnostic once.
7576 SourceLocation FirstDesignator
;
7577 bool DiagnosedArrayDesignator
= false;
7578 bool DiagnosedNestedDesignator
= false;
7579 bool DiagnosedMixedDesignator
= false;
7581 // Check that any designated initializers are syntactically valid in the
7582 // current language mode.
7583 for (unsigned I
= 0, E
= InitArgList
.size(); I
!= E
; ++I
) {
7584 if (auto *DIE
= dyn_cast
<DesignatedInitExpr
>(InitArgList
[I
])) {
7585 if (FirstDesignator
.isInvalid())
7586 FirstDesignator
= DIE
->getBeginLoc();
7588 if (!getLangOpts().CPlusPlus
)
7591 if (!DiagnosedNestedDesignator
&& DIE
->size() > 1) {
7592 DiagnosedNestedDesignator
= true;
7593 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_nested
)
7594 << DIE
->getDesignatorsSourceRange();
7597 for (auto &Desig
: DIE
->designators()) {
7598 if (!Desig
.isFieldDesignator() && !DiagnosedArrayDesignator
) {
7599 DiagnosedArrayDesignator
= true;
7600 Diag(Desig
.getBeginLoc(), diag::ext_designated_init_array
)
7601 << Desig
.getSourceRange();
7605 if (!DiagnosedMixedDesignator
&&
7606 !isa
<DesignatedInitExpr
>(InitArgList
[0])) {
7607 DiagnosedMixedDesignator
= true;
7608 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_mixed
)
7609 << DIE
->getSourceRange();
7610 Diag(InitArgList
[0]->getBeginLoc(), diag::note_designated_init_mixed
)
7611 << InitArgList
[0]->getSourceRange();
7613 } else if (getLangOpts().CPlusPlus
&& !DiagnosedMixedDesignator
&&
7614 isa
<DesignatedInitExpr
>(InitArgList
[0])) {
7615 DiagnosedMixedDesignator
= true;
7616 auto *DIE
= cast
<DesignatedInitExpr
>(InitArgList
[0]);
7617 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_mixed
)
7618 << DIE
->getSourceRange();
7619 Diag(InitArgList
[I
]->getBeginLoc(), diag::note_designated_init_mixed
)
7620 << InitArgList
[I
]->getSourceRange();
7624 if (FirstDesignator
.isValid()) {
7625 // Only diagnose designated initiaization as a C++20 extension if we didn't
7626 // already diagnose use of (non-C++20) C99 designator syntax.
7627 if (getLangOpts().CPlusPlus
&& !DiagnosedArrayDesignator
&&
7628 !DiagnosedNestedDesignator
&& !DiagnosedMixedDesignator
) {
7629 Diag(FirstDesignator
, getLangOpts().CPlusPlus20
7630 ? diag::warn_cxx17_compat_designated_init
7631 : diag::ext_cxx_designated_init
);
7632 } else if (!getLangOpts().CPlusPlus
&& !getLangOpts().C99
) {
7633 Diag(FirstDesignator
, diag::ext_designated_init
);
7637 return BuildInitList(LBraceLoc
, InitArgList
, RBraceLoc
);
7641 Sema::BuildInitList(SourceLocation LBraceLoc
, MultiExprArg InitArgList
,
7642 SourceLocation RBraceLoc
) {
7643 // Semantic analysis for initializers is done by ActOnDeclarator() and
7644 // CheckInitializer() - it requires knowledge of the object being initialized.
7646 // Immediately handle non-overload placeholders. Overloads can be
7647 // resolved contextually, but everything else here can't.
7648 for (unsigned I
= 0, E
= InitArgList
.size(); I
!= E
; ++I
) {
7649 if (InitArgList
[I
]->getType()->isNonOverloadPlaceholderType()) {
7650 ExprResult result
= CheckPlaceholderExpr(InitArgList
[I
]);
7652 // Ignore failures; dropping the entire initializer list because
7653 // of one failure would be terrible for indexing/etc.
7654 if (result
.isInvalid()) continue;
7656 InitArgList
[I
] = result
.get();
7660 InitListExpr
*E
= new (Context
) InitListExpr(Context
, LBraceLoc
, InitArgList
,
7662 E
->setType(Context
.VoidTy
); // FIXME: just a place holder for now.
7666 /// Do an explicit extend of the given block pointer if we're in ARC.
7667 void Sema::maybeExtendBlockObject(ExprResult
&E
) {
7668 assert(E
.get()->getType()->isBlockPointerType());
7669 assert(E
.get()->isPRValue());
7671 // Only do this in an r-value context.
7672 if (!getLangOpts().ObjCAutoRefCount
) return;
7674 E
= ImplicitCastExpr::Create(
7675 Context
, E
.get()->getType(), CK_ARCExtendBlockObject
, E
.get(),
7676 /*base path*/ nullptr, VK_PRValue
, FPOptionsOverride());
7677 Cleanup
.setExprNeedsCleanups(true);
7680 /// Prepare a conversion of the given expression to an ObjC object
7682 CastKind
Sema::PrepareCastToObjCObjectPointer(ExprResult
&E
) {
7683 QualType type
= E
.get()->getType();
7684 if (type
->isObjCObjectPointerType()) {
7686 } else if (type
->isBlockPointerType()) {
7687 maybeExtendBlockObject(E
);
7688 return CK_BlockPointerToObjCPointerCast
;
7690 assert(type
->isPointerType());
7691 return CK_CPointerToObjCPointerCast
;
7695 /// Prepares for a scalar cast, performing all the necessary stages
7696 /// except the final cast and returning the kind required.
7697 CastKind
Sema::PrepareScalarCast(ExprResult
&Src
, QualType DestTy
) {
7698 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
7699 // Also, callers should have filtered out the invalid cases with
7700 // pointers. Everything else should be possible.
7702 QualType SrcTy
= Src
.get()->getType();
7703 if (Context
.hasSameUnqualifiedType(SrcTy
, DestTy
))
7706 switch (Type::ScalarTypeKind SrcKind
= SrcTy
->getScalarTypeKind()) {
7707 case Type::STK_MemberPointer
:
7708 llvm_unreachable("member pointer type in C");
7710 case Type::STK_CPointer
:
7711 case Type::STK_BlockPointer
:
7712 case Type::STK_ObjCObjectPointer
:
7713 switch (DestTy
->getScalarTypeKind()) {
7714 case Type::STK_CPointer
: {
7715 LangAS SrcAS
= SrcTy
->getPointeeType().getAddressSpace();
7716 LangAS DestAS
= DestTy
->getPointeeType().getAddressSpace();
7717 if (SrcAS
!= DestAS
)
7718 return CK_AddressSpaceConversion
;
7719 if (Context
.hasCvrSimilarType(SrcTy
, DestTy
))
7723 case Type::STK_BlockPointer
:
7724 return (SrcKind
== Type::STK_BlockPointer
7725 ? CK_BitCast
: CK_AnyPointerToBlockPointerCast
);
7726 case Type::STK_ObjCObjectPointer
:
7727 if (SrcKind
== Type::STK_ObjCObjectPointer
)
7729 if (SrcKind
== Type::STK_CPointer
)
7730 return CK_CPointerToObjCPointerCast
;
7731 maybeExtendBlockObject(Src
);
7732 return CK_BlockPointerToObjCPointerCast
;
7733 case Type::STK_Bool
:
7734 return CK_PointerToBoolean
;
7735 case Type::STK_Integral
:
7736 return CK_PointerToIntegral
;
7737 case Type::STK_Floating
:
7738 case Type::STK_FloatingComplex
:
7739 case Type::STK_IntegralComplex
:
7740 case Type::STK_MemberPointer
:
7741 case Type::STK_FixedPoint
:
7742 llvm_unreachable("illegal cast from pointer");
7744 llvm_unreachable("Should have returned before this");
7746 case Type::STK_FixedPoint
:
7747 switch (DestTy
->getScalarTypeKind()) {
7748 case Type::STK_FixedPoint
:
7749 return CK_FixedPointCast
;
7750 case Type::STK_Bool
:
7751 return CK_FixedPointToBoolean
;
7752 case Type::STK_Integral
:
7753 return CK_FixedPointToIntegral
;
7754 case Type::STK_Floating
:
7755 return CK_FixedPointToFloating
;
7756 case Type::STK_IntegralComplex
:
7757 case Type::STK_FloatingComplex
:
7758 Diag(Src
.get()->getExprLoc(),
7759 diag::err_unimplemented_conversion_with_fixed_point_type
)
7761 return CK_IntegralCast
;
7762 case Type::STK_CPointer
:
7763 case Type::STK_ObjCObjectPointer
:
7764 case Type::STK_BlockPointer
:
7765 case Type::STK_MemberPointer
:
7766 llvm_unreachable("illegal cast to pointer type");
7768 llvm_unreachable("Should have returned before this");
7770 case Type::STK_Bool
: // casting from bool is like casting from an integer
7771 case Type::STK_Integral
:
7772 switch (DestTy
->getScalarTypeKind()) {
7773 case Type::STK_CPointer
:
7774 case Type::STK_ObjCObjectPointer
:
7775 case Type::STK_BlockPointer
:
7776 if (Src
.get()->isNullPointerConstant(Context
,
7777 Expr::NPC_ValueDependentIsNull
))
7778 return CK_NullToPointer
;
7779 return CK_IntegralToPointer
;
7780 case Type::STK_Bool
:
7781 return CK_IntegralToBoolean
;
7782 case Type::STK_Integral
:
7783 return CK_IntegralCast
;
7784 case Type::STK_Floating
:
7785 return CK_IntegralToFloating
;
7786 case Type::STK_IntegralComplex
:
7787 Src
= ImpCastExprToType(Src
.get(),
7788 DestTy
->castAs
<ComplexType
>()->getElementType(),
7790 return CK_IntegralRealToComplex
;
7791 case Type::STK_FloatingComplex
:
7792 Src
= ImpCastExprToType(Src
.get(),
7793 DestTy
->castAs
<ComplexType
>()->getElementType(),
7794 CK_IntegralToFloating
);
7795 return CK_FloatingRealToComplex
;
7796 case Type::STK_MemberPointer
:
7797 llvm_unreachable("member pointer type in C");
7798 case Type::STK_FixedPoint
:
7799 return CK_IntegralToFixedPoint
;
7801 llvm_unreachable("Should have returned before this");
7803 case Type::STK_Floating
:
7804 switch (DestTy
->getScalarTypeKind()) {
7805 case Type::STK_Floating
:
7806 return CK_FloatingCast
;
7807 case Type::STK_Bool
:
7808 return CK_FloatingToBoolean
;
7809 case Type::STK_Integral
:
7810 return CK_FloatingToIntegral
;
7811 case Type::STK_FloatingComplex
:
7812 Src
= ImpCastExprToType(Src
.get(),
7813 DestTy
->castAs
<ComplexType
>()->getElementType(),
7815 return CK_FloatingRealToComplex
;
7816 case Type::STK_IntegralComplex
:
7817 Src
= ImpCastExprToType(Src
.get(),
7818 DestTy
->castAs
<ComplexType
>()->getElementType(),
7819 CK_FloatingToIntegral
);
7820 return CK_IntegralRealToComplex
;
7821 case Type::STK_CPointer
:
7822 case Type::STK_ObjCObjectPointer
:
7823 case Type::STK_BlockPointer
:
7824 llvm_unreachable("valid float->pointer cast?");
7825 case Type::STK_MemberPointer
:
7826 llvm_unreachable("member pointer type in C");
7827 case Type::STK_FixedPoint
:
7828 return CK_FloatingToFixedPoint
;
7830 llvm_unreachable("Should have returned before this");
7832 case Type::STK_FloatingComplex
:
7833 switch (DestTy
->getScalarTypeKind()) {
7834 case Type::STK_FloatingComplex
:
7835 return CK_FloatingComplexCast
;
7836 case Type::STK_IntegralComplex
:
7837 return CK_FloatingComplexToIntegralComplex
;
7838 case Type::STK_Floating
: {
7839 QualType ET
= SrcTy
->castAs
<ComplexType
>()->getElementType();
7840 if (Context
.hasSameType(ET
, DestTy
))
7841 return CK_FloatingComplexToReal
;
7842 Src
= ImpCastExprToType(Src
.get(), ET
, CK_FloatingComplexToReal
);
7843 return CK_FloatingCast
;
7845 case Type::STK_Bool
:
7846 return CK_FloatingComplexToBoolean
;
7847 case Type::STK_Integral
:
7848 Src
= ImpCastExprToType(Src
.get(),
7849 SrcTy
->castAs
<ComplexType
>()->getElementType(),
7850 CK_FloatingComplexToReal
);
7851 return CK_FloatingToIntegral
;
7852 case Type::STK_CPointer
:
7853 case Type::STK_ObjCObjectPointer
:
7854 case Type::STK_BlockPointer
:
7855 llvm_unreachable("valid complex float->pointer cast?");
7856 case Type::STK_MemberPointer
:
7857 llvm_unreachable("member pointer type in C");
7858 case Type::STK_FixedPoint
:
7859 Diag(Src
.get()->getExprLoc(),
7860 diag::err_unimplemented_conversion_with_fixed_point_type
)
7862 return CK_IntegralCast
;
7864 llvm_unreachable("Should have returned before this");
7866 case Type::STK_IntegralComplex
:
7867 switch (DestTy
->getScalarTypeKind()) {
7868 case Type::STK_FloatingComplex
:
7869 return CK_IntegralComplexToFloatingComplex
;
7870 case Type::STK_IntegralComplex
:
7871 return CK_IntegralComplexCast
;
7872 case Type::STK_Integral
: {
7873 QualType ET
= SrcTy
->castAs
<ComplexType
>()->getElementType();
7874 if (Context
.hasSameType(ET
, DestTy
))
7875 return CK_IntegralComplexToReal
;
7876 Src
= ImpCastExprToType(Src
.get(), ET
, CK_IntegralComplexToReal
);
7877 return CK_IntegralCast
;
7879 case Type::STK_Bool
:
7880 return CK_IntegralComplexToBoolean
;
7881 case Type::STK_Floating
:
7882 Src
= ImpCastExprToType(Src
.get(),
7883 SrcTy
->castAs
<ComplexType
>()->getElementType(),
7884 CK_IntegralComplexToReal
);
7885 return CK_IntegralToFloating
;
7886 case Type::STK_CPointer
:
7887 case Type::STK_ObjCObjectPointer
:
7888 case Type::STK_BlockPointer
:
7889 llvm_unreachable("valid complex int->pointer cast?");
7890 case Type::STK_MemberPointer
:
7891 llvm_unreachable("member pointer type in C");
7892 case Type::STK_FixedPoint
:
7893 Diag(Src
.get()->getExprLoc(),
7894 diag::err_unimplemented_conversion_with_fixed_point_type
)
7896 return CK_IntegralCast
;
7898 llvm_unreachable("Should have returned before this");
7901 llvm_unreachable("Unhandled scalar cast");
7904 static bool breakDownVectorType(QualType type
, uint64_t &len
,
7905 QualType
&eltType
) {
7906 // Vectors are simple.
7907 if (const VectorType
*vecType
= type
->getAs
<VectorType
>()) {
7908 len
= vecType
->getNumElements();
7909 eltType
= vecType
->getElementType();
7910 assert(eltType
->isScalarType());
7914 // We allow lax conversion to and from non-vector types, but only if
7915 // they're real types (i.e. non-complex, non-pointer scalar types).
7916 if (!type
->isRealType()) return false;
7923 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
7924 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
7927 /// This will also return false if the two given types do not make sense from
7928 /// the perspective of SVE bitcasts.
7929 bool Sema::isValidSveBitcast(QualType srcTy
, QualType destTy
) {
7930 assert(srcTy
->isVectorType() || destTy
->isVectorType());
7932 auto ValidScalableConversion
= [](QualType FirstType
, QualType SecondType
) {
7933 if (!FirstType
->isSizelessBuiltinType())
7936 const auto *VecTy
= SecondType
->getAs
<VectorType
>();
7938 VecTy
->getVectorKind() == VectorType::SveFixedLengthDataVector
;
7941 return ValidScalableConversion(srcTy
, destTy
) ||
7942 ValidScalableConversion(destTy
, srcTy
);
7945 /// Are the two types matrix types and do they have the same dimensions i.e.
7946 /// do they have the same number of rows and the same number of columns?
7947 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy
, QualType destTy
) {
7948 if (!destTy
->isMatrixType() || !srcTy
->isMatrixType())
7951 const ConstantMatrixType
*matSrcType
= srcTy
->getAs
<ConstantMatrixType
>();
7952 const ConstantMatrixType
*matDestType
= destTy
->getAs
<ConstantMatrixType
>();
7954 return matSrcType
->getNumRows() == matDestType
->getNumRows() &&
7955 matSrcType
->getNumColumns() == matDestType
->getNumColumns();
7958 bool Sema::areVectorTypesSameSize(QualType SrcTy
, QualType DestTy
) {
7959 assert(DestTy
->isVectorType() || SrcTy
->isVectorType());
7961 uint64_t SrcLen
, DestLen
;
7962 QualType SrcEltTy
, DestEltTy
;
7963 if (!breakDownVectorType(SrcTy
, SrcLen
, SrcEltTy
))
7965 if (!breakDownVectorType(DestTy
, DestLen
, DestEltTy
))
7968 // ASTContext::getTypeSize will return the size rounded up to a
7969 // power of 2, so instead of using that, we need to use the raw
7970 // element size multiplied by the element count.
7971 uint64_t SrcEltSize
= Context
.getTypeSize(SrcEltTy
);
7972 uint64_t DestEltSize
= Context
.getTypeSize(DestEltTy
);
7974 return (SrcLen
* SrcEltSize
== DestLen
* DestEltSize
);
7977 // This returns true if at least one of the types is an altivec vector.
7978 bool Sema::anyAltivecTypes(QualType SrcTy
, QualType DestTy
) {
7979 assert((DestTy
->isVectorType() || SrcTy
->isVectorType()) &&
7980 "expected at least one type to be a vector here");
7982 bool IsSrcTyAltivec
=
7983 SrcTy
->isVectorType() && (SrcTy
->castAs
<VectorType
>()->getVectorKind() ==
7984 VectorType::AltiVecVector
);
7985 bool IsDestTyAltivec
= DestTy
->isVectorType() &&
7986 (DestTy
->castAs
<VectorType
>()->getVectorKind() ==
7987 VectorType::AltiVecVector
);
7989 return (IsSrcTyAltivec
|| IsDestTyAltivec
);
7992 // This returns true if both vectors have the same element type.
7993 bool Sema::areSameVectorElemTypes(QualType SrcTy
, QualType DestTy
) {
7994 assert((DestTy
->isVectorType() || SrcTy
->isVectorType()) &&
7995 "expected at least one type to be a vector here");
7997 uint64_t SrcLen
, DestLen
;
7998 QualType SrcEltTy
, DestEltTy
;
7999 if (!breakDownVectorType(SrcTy
, SrcLen
, SrcEltTy
))
8001 if (!breakDownVectorType(DestTy
, DestLen
, DestEltTy
))
8004 return (SrcEltTy
== DestEltTy
);
8007 /// Are the two types lax-compatible vector types? That is, given
8008 /// that one of them is a vector, do they have equal storage sizes,
8009 /// where the storage size is the number of elements times the element
8012 /// This will also return false if either of the types is neither a
8013 /// vector nor a real type.
8014 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy
, QualType destTy
) {
8015 assert(destTy
->isVectorType() || srcTy
->isVectorType());
8017 // Disallow lax conversions between scalars and ExtVectors (these
8018 // conversions are allowed for other vector types because common headers
8019 // depend on them). Most scalar OP ExtVector cases are handled by the
8020 // splat path anyway, which does what we want (convert, not bitcast).
8021 // What this rules out for ExtVectors is crazy things like char4*float.
8022 if (srcTy
->isScalarType() && destTy
->isExtVectorType()) return false;
8023 if (destTy
->isScalarType() && srcTy
->isExtVectorType()) return false;
8025 return areVectorTypesSameSize(srcTy
, destTy
);
8028 /// Is this a legal conversion between two types, one of which is
8029 /// known to be a vector type?
8030 bool Sema::isLaxVectorConversion(QualType srcTy
, QualType destTy
) {
8031 assert(destTy
->isVectorType() || srcTy
->isVectorType());
8033 switch (Context
.getLangOpts().getLaxVectorConversions()) {
8034 case LangOptions::LaxVectorConversionKind::None
:
8037 case LangOptions::LaxVectorConversionKind::Integer
:
8038 if (!srcTy
->isIntegralOrEnumerationType()) {
8039 auto *Vec
= srcTy
->getAs
<VectorType
>();
8040 if (!Vec
|| !Vec
->getElementType()->isIntegralOrEnumerationType())
8043 if (!destTy
->isIntegralOrEnumerationType()) {
8044 auto *Vec
= destTy
->getAs
<VectorType
>();
8045 if (!Vec
|| !Vec
->getElementType()->isIntegralOrEnumerationType())
8048 // OK, integer (vector) -> integer (vector) bitcast.
8051 case LangOptions::LaxVectorConversionKind::All
:
8055 return areLaxCompatibleVectorTypes(srcTy
, destTy
);
8058 bool Sema::CheckMatrixCast(SourceRange R
, QualType DestTy
, QualType SrcTy
,
8060 if (SrcTy
->isMatrixType() && DestTy
->isMatrixType()) {
8061 if (!areMatrixTypesOfTheSameDimension(SrcTy
, DestTy
)) {
8062 return Diag(R
.getBegin(), diag::err_invalid_conversion_between_matrixes
)
8063 << DestTy
<< SrcTy
<< R
;
8065 } else if (SrcTy
->isMatrixType()) {
8066 return Diag(R
.getBegin(),
8067 diag::err_invalid_conversion_between_matrix_and_type
)
8068 << SrcTy
<< DestTy
<< R
;
8069 } else if (DestTy
->isMatrixType()) {
8070 return Diag(R
.getBegin(),
8071 diag::err_invalid_conversion_between_matrix_and_type
)
8072 << DestTy
<< SrcTy
<< R
;
8075 Kind
= CK_MatrixCast
;
8079 bool Sema::CheckVectorCast(SourceRange R
, QualType VectorTy
, QualType Ty
,
8081 assert(VectorTy
->isVectorType() && "Not a vector type!");
8083 if (Ty
->isVectorType() || Ty
->isIntegralType(Context
)) {
8084 if (!areLaxCompatibleVectorTypes(Ty
, VectorTy
))
8085 return Diag(R
.getBegin(),
8086 Ty
->isVectorType() ?
8087 diag::err_invalid_conversion_between_vectors
:
8088 diag::err_invalid_conversion_between_vector_and_integer
)
8089 << VectorTy
<< Ty
<< R
;
8091 return Diag(R
.getBegin(),
8092 diag::err_invalid_conversion_between_vector_and_scalar
)
8093 << VectorTy
<< Ty
<< R
;
8099 ExprResult
Sema::prepareVectorSplat(QualType VectorTy
, Expr
*SplattedExpr
) {
8100 QualType DestElemTy
= VectorTy
->castAs
<VectorType
>()->getElementType();
8102 if (DestElemTy
== SplattedExpr
->getType())
8103 return SplattedExpr
;
8105 assert(DestElemTy
->isFloatingType() ||
8106 DestElemTy
->isIntegralOrEnumerationType());
8109 if (VectorTy
->isExtVectorType() && SplattedExpr
->getType()->isBooleanType()) {
8110 // OpenCL requires that we convert `true` boolean expressions to -1, but
8111 // only when splatting vectors.
8112 if (DestElemTy
->isFloatingType()) {
8113 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8114 // in two steps: boolean to signed integral, then to floating.
8115 ExprResult CastExprRes
= ImpCastExprToType(SplattedExpr
, Context
.IntTy
,
8116 CK_BooleanToSignedIntegral
);
8117 SplattedExpr
= CastExprRes
.get();
8118 CK
= CK_IntegralToFloating
;
8120 CK
= CK_BooleanToSignedIntegral
;
8123 ExprResult CastExprRes
= SplattedExpr
;
8124 CK
= PrepareScalarCast(CastExprRes
, DestElemTy
);
8125 if (CastExprRes
.isInvalid())
8127 SplattedExpr
= CastExprRes
.get();
8129 return ImpCastExprToType(SplattedExpr
, DestElemTy
, CK
);
8132 ExprResult
Sema::CheckExtVectorCast(SourceRange R
, QualType DestTy
,
8133 Expr
*CastExpr
, CastKind
&Kind
) {
8134 assert(DestTy
->isExtVectorType() && "Not an extended vector type!");
8136 QualType SrcTy
= CastExpr
->getType();
8138 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8139 // an ExtVectorType.
8140 // In OpenCL, casts between vectors of different types are not allowed.
8141 // (See OpenCL 6.2).
8142 if (SrcTy
->isVectorType()) {
8143 if (!areLaxCompatibleVectorTypes(SrcTy
, DestTy
) ||
8144 (getLangOpts().OpenCL
&&
8145 !Context
.hasSameUnqualifiedType(DestTy
, SrcTy
))) {
8146 Diag(R
.getBegin(),diag::err_invalid_conversion_between_ext_vectors
)
8147 << DestTy
<< SrcTy
<< R
;
8154 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8155 // conversion will take place first from scalar to elt type, and then
8156 // splat from elt type to vector.
8157 if (SrcTy
->isPointerType())
8158 return Diag(R
.getBegin(),
8159 diag::err_invalid_conversion_between_vector_and_scalar
)
8160 << DestTy
<< SrcTy
<< R
;
8162 Kind
= CK_VectorSplat
;
8163 return prepareVectorSplat(DestTy
, CastExpr
);
8167 Sema::ActOnCastExpr(Scope
*S
, SourceLocation LParenLoc
,
8168 Declarator
&D
, ParsedType
&Ty
,
8169 SourceLocation RParenLoc
, Expr
*CastExpr
) {
8170 assert(!D
.isInvalidType() && (CastExpr
!= nullptr) &&
8171 "ActOnCastExpr(): missing type or expr");
8173 TypeSourceInfo
*castTInfo
= GetTypeForDeclaratorCast(D
, CastExpr
->getType());
8174 if (D
.isInvalidType())
8177 if (getLangOpts().CPlusPlus
) {
8178 // Check that there are no default arguments (C++ only).
8179 CheckExtraCXXDefaultArguments(D
);
8181 // Make sure any TypoExprs have been dealt with.
8182 ExprResult Res
= CorrectDelayedTyposInExpr(CastExpr
);
8183 if (!Res
.isUsable())
8185 CastExpr
= Res
.get();
8188 checkUnusedDeclAttributes(D
);
8190 QualType castType
= castTInfo
->getType();
8191 Ty
= CreateParsedType(castType
, castTInfo
);
8193 bool isVectorLiteral
= false;
8195 // Check for an altivec or OpenCL literal,
8196 // i.e. all the elements are integer constants.
8197 ParenExpr
*PE
= dyn_cast
<ParenExpr
>(CastExpr
);
8198 ParenListExpr
*PLE
= dyn_cast
<ParenListExpr
>(CastExpr
);
8199 if ((getLangOpts().AltiVec
|| getLangOpts().ZVector
|| getLangOpts().OpenCL
)
8200 && castType
->isVectorType() && (PE
|| PLE
)) {
8201 if (PLE
&& PLE
->getNumExprs() == 0) {
8202 Diag(PLE
->getExprLoc(), diag::err_altivec_empty_initializer
);
8205 if (PE
|| PLE
->getNumExprs() == 1) {
8206 Expr
*E
= (PE
? PE
->getSubExpr() : PLE
->getExpr(0));
8207 if (!E
->isTypeDependent() && !E
->getType()->isVectorType())
8208 isVectorLiteral
= true;
8211 isVectorLiteral
= true;
8214 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8215 // then handle it as such.
8216 if (isVectorLiteral
)
8217 return BuildVectorLiteral(LParenLoc
, RParenLoc
, CastExpr
, castTInfo
);
8219 // If the Expr being casted is a ParenListExpr, handle it specially.
8220 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8221 // sequence of BinOp comma operators.
8222 if (isa
<ParenListExpr
>(CastExpr
)) {
8223 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, CastExpr
);
8224 if (Result
.isInvalid()) return ExprError();
8225 CastExpr
= Result
.get();
8228 if (getLangOpts().CPlusPlus
&& !castType
->isVoidType())
8229 Diag(LParenLoc
, diag::warn_old_style_cast
) << CastExpr
->getSourceRange();
8231 CheckTollFreeBridgeCast(castType
, CastExpr
);
8233 CheckObjCBridgeRelatedCast(castType
, CastExpr
);
8235 DiscardMisalignedMemberAddress(castType
.getTypePtr(), CastExpr
);
8237 return BuildCStyleCastExpr(LParenLoc
, castTInfo
, RParenLoc
, CastExpr
);
8240 ExprResult
Sema::BuildVectorLiteral(SourceLocation LParenLoc
,
8241 SourceLocation RParenLoc
, Expr
*E
,
8242 TypeSourceInfo
*TInfo
) {
8243 assert((isa
<ParenListExpr
>(E
) || isa
<ParenExpr
>(E
)) &&
8244 "Expected paren or paren list expression");
8249 SourceLocation LiteralLParenLoc
, LiteralRParenLoc
;
8250 if (ParenListExpr
*PE
= dyn_cast
<ParenListExpr
>(E
)) {
8251 LiteralLParenLoc
= PE
->getLParenLoc();
8252 LiteralRParenLoc
= PE
->getRParenLoc();
8253 exprs
= PE
->getExprs();
8254 numExprs
= PE
->getNumExprs();
8255 } else { // isa<ParenExpr> by assertion at function entrance
8256 LiteralLParenLoc
= cast
<ParenExpr
>(E
)->getLParen();
8257 LiteralRParenLoc
= cast
<ParenExpr
>(E
)->getRParen();
8258 subExpr
= cast
<ParenExpr
>(E
)->getSubExpr();
8263 QualType Ty
= TInfo
->getType();
8264 assert(Ty
->isVectorType() && "Expected vector type");
8266 SmallVector
<Expr
*, 8> initExprs
;
8267 const VectorType
*VTy
= Ty
->castAs
<VectorType
>();
8268 unsigned numElems
= VTy
->getNumElements();
8270 // '(...)' form of vector initialization in AltiVec: the number of
8271 // initializers must be one or must match the size of the vector.
8272 // If a single value is specified in the initializer then it will be
8273 // replicated to all the components of the vector
8274 if (CheckAltivecInitFromScalar(E
->getSourceRange(), Ty
,
8275 VTy
->getElementType()))
8277 if (ShouldSplatAltivecScalarInCast(VTy
)) {
8278 // The number of initializers must be one or must match the size of the
8279 // vector. If a single value is specified in the initializer then it will
8280 // be replicated to all the components of the vector
8281 if (numExprs
== 1) {
8282 QualType ElemTy
= VTy
->getElementType();
8283 ExprResult Literal
= DefaultLvalueConversion(exprs
[0]);
8284 if (Literal
.isInvalid())
8286 Literal
= ImpCastExprToType(Literal
.get(), ElemTy
,
8287 PrepareScalarCast(Literal
, ElemTy
));
8288 return BuildCStyleCastExpr(LParenLoc
, TInfo
, RParenLoc
, Literal
.get());
8290 else if (numExprs
< numElems
) {
8291 Diag(E
->getExprLoc(),
8292 diag::err_incorrect_number_of_vector_initializers
);
8296 initExprs
.append(exprs
, exprs
+ numExprs
);
8299 // For OpenCL, when the number of initializers is a single value,
8300 // it will be replicated to all components of the vector.
8301 if (getLangOpts().OpenCL
&&
8302 VTy
->getVectorKind() == VectorType::GenericVector
&&
8304 QualType ElemTy
= VTy
->getElementType();
8305 ExprResult Literal
= DefaultLvalueConversion(exprs
[0]);
8306 if (Literal
.isInvalid())
8308 Literal
= ImpCastExprToType(Literal
.get(), ElemTy
,
8309 PrepareScalarCast(Literal
, ElemTy
));
8310 return BuildCStyleCastExpr(LParenLoc
, TInfo
, RParenLoc
, Literal
.get());
8313 initExprs
.append(exprs
, exprs
+ numExprs
);
8315 // FIXME: This means that pretty-printing the final AST will produce curly
8316 // braces instead of the original commas.
8317 InitListExpr
*initE
= new (Context
) InitListExpr(Context
, LiteralLParenLoc
,
8318 initExprs
, LiteralRParenLoc
);
8320 return BuildCompoundLiteralExpr(LParenLoc
, TInfo
, RParenLoc
, initE
);
8323 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8324 /// the ParenListExpr into a sequence of comma binary operators.
8326 Sema::MaybeConvertParenListExprToParenExpr(Scope
*S
, Expr
*OrigExpr
) {
8327 ParenListExpr
*E
= dyn_cast
<ParenListExpr
>(OrigExpr
);
8331 ExprResult
Result(E
->getExpr(0));
8333 for (unsigned i
= 1, e
= E
->getNumExprs(); i
!= e
&& !Result
.isInvalid(); ++i
)
8334 Result
= ActOnBinOp(S
, E
->getExprLoc(), tok::comma
, Result
.get(),
8337 if (Result
.isInvalid()) return ExprError();
8339 return ActOnParenExpr(E
->getLParenLoc(), E
->getRParenLoc(), Result
.get());
8342 ExprResult
Sema::ActOnParenListExpr(SourceLocation L
,
8345 return ParenListExpr::Create(Context
, L
, Val
, R
);
8348 /// Emit a specialized diagnostic when one expression is a null pointer
8349 /// constant and the other is not a pointer. Returns true if a diagnostic is
8351 bool Sema::DiagnoseConditionalForNull(Expr
*LHSExpr
, Expr
*RHSExpr
,
8352 SourceLocation QuestionLoc
) {
8353 Expr
*NullExpr
= LHSExpr
;
8354 Expr
*NonPointerExpr
= RHSExpr
;
8355 Expr::NullPointerConstantKind NullKind
=
8356 NullExpr
->isNullPointerConstant(Context
,
8357 Expr::NPC_ValueDependentIsNotNull
);
8359 if (NullKind
== Expr::NPCK_NotNull
) {
8361 NonPointerExpr
= LHSExpr
;
8363 NullExpr
->isNullPointerConstant(Context
,
8364 Expr::NPC_ValueDependentIsNotNull
);
8367 if (NullKind
== Expr::NPCK_NotNull
)
8370 if (NullKind
== Expr::NPCK_ZeroExpression
)
8373 if (NullKind
== Expr::NPCK_ZeroLiteral
) {
8374 // In this case, check to make sure that we got here from a "NULL"
8375 // string in the source code.
8376 NullExpr
= NullExpr
->IgnoreParenImpCasts();
8377 SourceLocation loc
= NullExpr
->getExprLoc();
8378 if (!findMacroSpelling(loc
, "NULL"))
8382 int DiagType
= (NullKind
== Expr::NPCK_CXX11_nullptr
);
8383 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands_null
)
8384 << NonPointerExpr
->getType() << DiagType
8385 << NonPointerExpr
->getSourceRange();
8389 /// Return false if the condition expression is valid, true otherwise.
8390 static bool checkCondition(Sema
&S
, Expr
*Cond
, SourceLocation QuestionLoc
) {
8391 QualType CondTy
= Cond
->getType();
8393 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8394 if (S
.getLangOpts().OpenCL
&& CondTy
->isFloatingType()) {
8395 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_nonfloat
)
8396 << CondTy
<< Cond
->getSourceRange();
8401 if (CondTy
->isScalarType()) return false;
8403 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_scalar
)
8404 << CondTy
<< Cond
->getSourceRange();
8408 /// Return false if the NullExpr can be promoted to PointerTy,
8410 static bool checkConditionalNullPointer(Sema
&S
, ExprResult
&NullExpr
,
8411 QualType PointerTy
) {
8412 if ((!PointerTy
->isAnyPointerType() && !PointerTy
->isBlockPointerType()) ||
8413 !NullExpr
.get()->isNullPointerConstant(S
.Context
,
8414 Expr::NPC_ValueDependentIsNull
))
8417 NullExpr
= S
.ImpCastExprToType(NullExpr
.get(), PointerTy
, CK_NullToPointer
);
8421 /// Checks compatibility between two pointers and return the resulting
8423 static QualType
checkConditionalPointerCompatibility(Sema
&S
, ExprResult
&LHS
,
8425 SourceLocation Loc
) {
8426 QualType LHSTy
= LHS
.get()->getType();
8427 QualType RHSTy
= RHS
.get()->getType();
8429 if (S
.Context
.hasSameType(LHSTy
, RHSTy
)) {
8430 // Two identical pointers types are always compatible.
8431 return S
.Context
.getCommonSugaredType(LHSTy
, RHSTy
);
8434 QualType lhptee
, rhptee
;
8436 // Get the pointee types.
8437 bool IsBlockPointer
= false;
8438 if (const BlockPointerType
*LHSBTy
= LHSTy
->getAs
<BlockPointerType
>()) {
8439 lhptee
= LHSBTy
->getPointeeType();
8440 rhptee
= RHSTy
->castAs
<BlockPointerType
>()->getPointeeType();
8441 IsBlockPointer
= true;
8443 lhptee
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
8444 rhptee
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
8447 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8448 // differently qualified versions of compatible types, the result type is
8449 // a pointer to an appropriately qualified version of the composite
8452 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8453 // clause doesn't make sense for our extensions. E.g. address space 2 should
8454 // be incompatible with address space 3: they may live on different devices or
8456 Qualifiers lhQual
= lhptee
.getQualifiers();
8457 Qualifiers rhQual
= rhptee
.getQualifiers();
8459 LangAS ResultAddrSpace
= LangAS::Default
;
8460 LangAS LAddrSpace
= lhQual
.getAddressSpace();
8461 LangAS RAddrSpace
= rhQual
.getAddressSpace();
8463 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8464 // spaces is disallowed.
8465 if (lhQual
.isAddressSpaceSupersetOf(rhQual
))
8466 ResultAddrSpace
= LAddrSpace
;
8467 else if (rhQual
.isAddressSpaceSupersetOf(lhQual
))
8468 ResultAddrSpace
= RAddrSpace
;
8470 S
.Diag(Loc
, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
8471 << LHSTy
<< RHSTy
<< 2 << LHS
.get()->getSourceRange()
8472 << RHS
.get()->getSourceRange();
8476 unsigned MergedCVRQual
= lhQual
.getCVRQualifiers() | rhQual
.getCVRQualifiers();
8477 auto LHSCastKind
= CK_BitCast
, RHSCastKind
= CK_BitCast
;
8478 lhQual
.removeCVRQualifiers();
8479 rhQual
.removeCVRQualifiers();
8481 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8482 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8483 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8484 // qual types are compatible iff
8485 // * corresponded types are compatible
8486 // * CVR qualifiers are equal
8487 // * address spaces are equal
8488 // Thus for conditional operator we merge CVR and address space unqualified
8489 // pointees and if there is a composite type we return a pointer to it with
8490 // merged qualifiers.
8492 LAddrSpace
== ResultAddrSpace
? CK_BitCast
: CK_AddressSpaceConversion
;
8494 RAddrSpace
== ResultAddrSpace
? CK_BitCast
: CK_AddressSpaceConversion
;
8495 lhQual
.removeAddressSpace();
8496 rhQual
.removeAddressSpace();
8498 lhptee
= S
.Context
.getQualifiedType(lhptee
.getUnqualifiedType(), lhQual
);
8499 rhptee
= S
.Context
.getQualifiedType(rhptee
.getUnqualifiedType(), rhQual
);
8501 QualType CompositeTy
= S
.Context
.mergeTypes(
8502 lhptee
, rhptee
, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8503 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8505 if (CompositeTy
.isNull()) {
8506 // In this situation, we assume void* type. No especially good
8507 // reason, but this is what gcc does, and we do have to pick
8508 // to get a consistent AST.
8509 QualType incompatTy
;
8510 incompatTy
= S
.Context
.getPointerType(
8511 S
.Context
.getAddrSpaceQualType(S
.Context
.VoidTy
, ResultAddrSpace
));
8512 LHS
= S
.ImpCastExprToType(LHS
.get(), incompatTy
, LHSCastKind
);
8513 RHS
= S
.ImpCastExprToType(RHS
.get(), incompatTy
, RHSCastKind
);
8515 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8516 // for casts between types with incompatible address space qualifiers.
8517 // For the following code the compiler produces casts between global and
8518 // local address spaces of the corresponded innermost pointees:
8519 // local int *global *a;
8520 // global int *global *b;
8521 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8522 S
.Diag(Loc
, diag::ext_typecheck_cond_incompatible_pointers
)
8523 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8524 << RHS
.get()->getSourceRange();
8529 // The pointer types are compatible.
8530 // In case of OpenCL ResultTy should have the address space qualifier
8531 // which is a superset of address spaces of both the 2nd and the 3rd
8532 // operands of the conditional operator.
8533 QualType ResultTy
= [&, ResultAddrSpace
]() {
8534 if (S
.getLangOpts().OpenCL
) {
8535 Qualifiers CompositeQuals
= CompositeTy
.getQualifiers();
8536 CompositeQuals
.setAddressSpace(ResultAddrSpace
);
8538 .getQualifiedType(CompositeTy
.getUnqualifiedType(), CompositeQuals
)
8539 .withCVRQualifiers(MergedCVRQual
);
8541 return CompositeTy
.withCVRQualifiers(MergedCVRQual
);
8544 ResultTy
= S
.Context
.getBlockPointerType(ResultTy
);
8546 ResultTy
= S
.Context
.getPointerType(ResultTy
);
8548 LHS
= S
.ImpCastExprToType(LHS
.get(), ResultTy
, LHSCastKind
);
8549 RHS
= S
.ImpCastExprToType(RHS
.get(), ResultTy
, RHSCastKind
);
8553 /// Return the resulting type when the operands are both block pointers.
8554 static QualType
checkConditionalBlockPointerCompatibility(Sema
&S
,
8557 SourceLocation Loc
) {
8558 QualType LHSTy
= LHS
.get()->getType();
8559 QualType RHSTy
= RHS
.get()->getType();
8561 if (!LHSTy
->isBlockPointerType() || !RHSTy
->isBlockPointerType()) {
8562 if (LHSTy
->isVoidPointerType() || RHSTy
->isVoidPointerType()) {
8563 QualType destType
= S
.Context
.getPointerType(S
.Context
.VoidTy
);
8564 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_BitCast
);
8565 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_BitCast
);
8568 S
.Diag(Loc
, diag::err_typecheck_cond_incompatible_operands
)
8569 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8570 << RHS
.get()->getSourceRange();
8574 // We have 2 block pointer types.
8575 return checkConditionalPointerCompatibility(S
, LHS
, RHS
, Loc
);
8578 /// Return the resulting type when the operands are both pointers.
8580 checkConditionalObjectPointersCompatibility(Sema
&S
, ExprResult
&LHS
,
8582 SourceLocation Loc
) {
8583 // get the pointer types
8584 QualType LHSTy
= LHS
.get()->getType();
8585 QualType RHSTy
= RHS
.get()->getType();
8587 // get the "pointed to" types
8588 QualType lhptee
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
8589 QualType rhptee
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
8591 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8592 if (lhptee
->isVoidType() && rhptee
->isIncompleteOrObjectType()) {
8593 // Figure out necessary qualifiers (C99 6.5.15p6)
8594 QualType destPointee
8595 = S
.Context
.getQualifiedType(lhptee
, rhptee
.getQualifiers());
8596 QualType destType
= S
.Context
.getPointerType(destPointee
);
8597 // Add qualifiers if necessary.
8598 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_NoOp
);
8599 // Promote to void*.
8600 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_BitCast
);
8603 if (rhptee
->isVoidType() && lhptee
->isIncompleteOrObjectType()) {
8604 QualType destPointee
8605 = S
.Context
.getQualifiedType(rhptee
, lhptee
.getQualifiers());
8606 QualType destType
= S
.Context
.getPointerType(destPointee
);
8607 // Add qualifiers if necessary.
8608 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_NoOp
);
8609 // Promote to void*.
8610 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_BitCast
);
8614 return checkConditionalPointerCompatibility(S
, LHS
, RHS
, Loc
);
8617 /// Return false if the first expression is not an integer and the second
8618 /// expression is not a pointer, true otherwise.
8619 static bool checkPointerIntegerMismatch(Sema
&S
, ExprResult
&Int
,
8620 Expr
* PointerExpr
, SourceLocation Loc
,
8621 bool IsIntFirstExpr
) {
8622 if (!PointerExpr
->getType()->isPointerType() ||
8623 !Int
.get()->getType()->isIntegerType())
8626 Expr
*Expr1
= IsIntFirstExpr
? Int
.get() : PointerExpr
;
8627 Expr
*Expr2
= IsIntFirstExpr
? PointerExpr
: Int
.get();
8629 S
.Diag(Loc
, diag::ext_typecheck_cond_pointer_integer_mismatch
)
8630 << Expr1
->getType() << Expr2
->getType()
8631 << Expr1
->getSourceRange() << Expr2
->getSourceRange();
8632 Int
= S
.ImpCastExprToType(Int
.get(), PointerExpr
->getType(),
8633 CK_IntegralToPointer
);
8637 /// Simple conversion between integer and floating point types.
8639 /// Used when handling the OpenCL conditional operator where the
8640 /// condition is a vector while the other operands are scalar.
8642 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8643 /// types are either integer or floating type. Between the two
8644 /// operands, the type with the higher rank is defined as the "result
8645 /// type". The other operand needs to be promoted to the same type. No
8646 /// other type promotion is allowed. We cannot use
8647 /// UsualArithmeticConversions() for this purpose, since it always
8648 /// promotes promotable types.
8649 static QualType
OpenCLArithmeticConversions(Sema
&S
, ExprResult
&LHS
,
8651 SourceLocation QuestionLoc
) {
8652 LHS
= S
.DefaultFunctionArrayLvalueConversion(LHS
.get());
8653 if (LHS
.isInvalid())
8655 RHS
= S
.DefaultFunctionArrayLvalueConversion(RHS
.get());
8656 if (RHS
.isInvalid())
8659 // For conversion purposes, we ignore any qualifiers.
8660 // For example, "const float" and "float" are equivalent.
8662 S
.Context
.getCanonicalType(LHS
.get()->getType()).getUnqualifiedType();
8664 S
.Context
.getCanonicalType(RHS
.get()->getType()).getUnqualifiedType();
8666 if (!LHSType
->isIntegerType() && !LHSType
->isRealFloatingType()) {
8667 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_int_float
)
8668 << LHSType
<< LHS
.get()->getSourceRange();
8672 if (!RHSType
->isIntegerType() && !RHSType
->isRealFloatingType()) {
8673 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_int_float
)
8674 << RHSType
<< RHS
.get()->getSourceRange();
8678 // If both types are identical, no conversion is needed.
8679 if (LHSType
== RHSType
)
8682 // Now handle "real" floating types (i.e. float, double, long double).
8683 if (LHSType
->isRealFloatingType() || RHSType
->isRealFloatingType())
8684 return handleFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
8685 /*IsCompAssign = */ false);
8687 // Finally, we have two differing integer types.
8688 return handleIntegerConversion
<doIntegralCast
, doIntegralCast
>
8689 (S
, LHS
, RHS
, LHSType
, RHSType
, /*IsCompAssign = */ false);
8692 /// Convert scalar operands to a vector that matches the
8693 /// condition in length.
8695 /// Used when handling the OpenCL conditional operator where the
8696 /// condition is a vector while the other operands are scalar.
8698 /// We first compute the "result type" for the scalar operands
8699 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
8700 /// into a vector of that type where the length matches the condition
8701 /// vector type. s6.11.6 requires that the element types of the result
8702 /// and the condition must have the same number of bits.
8704 OpenCLConvertScalarsToVectors(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
8705 QualType CondTy
, SourceLocation QuestionLoc
) {
8706 QualType ResTy
= OpenCLArithmeticConversions(S
, LHS
, RHS
, QuestionLoc
);
8707 if (ResTy
.isNull()) return QualType();
8709 const VectorType
*CV
= CondTy
->getAs
<VectorType
>();
8712 // Determine the vector result type
8713 unsigned NumElements
= CV
->getNumElements();
8714 QualType VectorTy
= S
.Context
.getExtVectorType(ResTy
, NumElements
);
8716 // Ensure that all types have the same number of bits
8717 if (S
.Context
.getTypeSize(CV
->getElementType())
8718 != S
.Context
.getTypeSize(ResTy
)) {
8719 // Since VectorTy is created internally, it does not pretty print
8720 // with an OpenCL name. Instead, we just print a description.
8721 std::string EleTyName
= ResTy
.getUnqualifiedType().getAsString();
8722 SmallString
<64> Str
;
8723 llvm::raw_svector_ostream
OS(Str
);
8724 OS
<< "(vector of " << NumElements
<< " '" << EleTyName
<< "' values)";
8725 S
.Diag(QuestionLoc
, diag::err_conditional_vector_element_size
)
8726 << CondTy
<< OS
.str();
8730 // Convert operands to the vector result type
8731 LHS
= S
.ImpCastExprToType(LHS
.get(), VectorTy
, CK_VectorSplat
);
8732 RHS
= S
.ImpCastExprToType(RHS
.get(), VectorTy
, CK_VectorSplat
);
8737 /// Return false if this is a valid OpenCL condition vector
8738 static bool checkOpenCLConditionVector(Sema
&S
, Expr
*Cond
,
8739 SourceLocation QuestionLoc
) {
8740 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
8742 const VectorType
*CondTy
= Cond
->getType()->getAs
<VectorType
>();
8744 QualType EleTy
= CondTy
->getElementType();
8745 if (EleTy
->isIntegerType()) return false;
8747 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_nonfloat
)
8748 << Cond
->getType() << Cond
->getSourceRange();
8752 /// Return false if the vector condition type and the vector
8753 /// result type are compatible.
8755 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
8756 /// number of elements, and their element types have the same number
8758 static bool checkVectorResult(Sema
&S
, QualType CondTy
, QualType VecResTy
,
8759 SourceLocation QuestionLoc
) {
8760 const VectorType
*CV
= CondTy
->getAs
<VectorType
>();
8761 const VectorType
*RV
= VecResTy
->getAs
<VectorType
>();
8764 if (CV
->getNumElements() != RV
->getNumElements()) {
8765 S
.Diag(QuestionLoc
, diag::err_conditional_vector_size
)
8766 << CondTy
<< VecResTy
;
8770 QualType CVE
= CV
->getElementType();
8771 QualType RVE
= RV
->getElementType();
8773 if (S
.Context
.getTypeSize(CVE
) != S
.Context
.getTypeSize(RVE
)) {
8774 S
.Diag(QuestionLoc
, diag::err_conditional_vector_element_size
)
8775 << CondTy
<< VecResTy
;
8782 /// Return the resulting type for the conditional operator in
8783 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
8784 /// s6.3.i) when the condition is a vector type.
8786 OpenCLCheckVectorConditional(Sema
&S
, ExprResult
&Cond
,
8787 ExprResult
&LHS
, ExprResult
&RHS
,
8788 SourceLocation QuestionLoc
) {
8789 Cond
= S
.DefaultFunctionArrayLvalueConversion(Cond
.get());
8790 if (Cond
.isInvalid())
8792 QualType CondTy
= Cond
.get()->getType();
8794 if (checkOpenCLConditionVector(S
, Cond
.get(), QuestionLoc
))
8797 // If either operand is a vector then find the vector type of the
8798 // result as specified in OpenCL v1.1 s6.3.i.
8799 if (LHS
.get()->getType()->isVectorType() ||
8800 RHS
.get()->getType()->isVectorType()) {
8801 bool IsBoolVecLang
=
8802 !S
.getLangOpts().OpenCL
&& !S
.getLangOpts().OpenCLCPlusPlus
;
8804 S
.CheckVectorOperands(LHS
, RHS
, QuestionLoc
,
8805 /*isCompAssign*/ false,
8806 /*AllowBothBool*/ true,
8807 /*AllowBoolConversions*/ false,
8808 /*AllowBooleanOperation*/ IsBoolVecLang
,
8809 /*ReportInvalid*/ true);
8810 if (VecResTy
.isNull())
8812 // The result type must match the condition type as specified in
8813 // OpenCL v1.1 s6.11.6.
8814 if (checkVectorResult(S
, CondTy
, VecResTy
, QuestionLoc
))
8819 // Both operands are scalar.
8820 return OpenCLConvertScalarsToVectors(S
, LHS
, RHS
, CondTy
, QuestionLoc
);
8823 /// Return true if the Expr is block type
8824 static bool checkBlockType(Sema
&S
, const Expr
*E
) {
8825 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
8826 QualType Ty
= CE
->getCallee()->getType();
8827 if (Ty
->isBlockPointerType()) {
8828 S
.Diag(E
->getExprLoc(), diag::err_opencl_ternary_with_block
);
8835 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
8836 /// In that case, LHS = cond.
8838 QualType
Sema::CheckConditionalOperands(ExprResult
&Cond
, ExprResult
&LHS
,
8839 ExprResult
&RHS
, ExprValueKind
&VK
,
8841 SourceLocation QuestionLoc
) {
8843 ExprResult LHSResult
= CheckPlaceholderExpr(LHS
.get());
8844 if (!LHSResult
.isUsable()) return QualType();
8847 ExprResult RHSResult
= CheckPlaceholderExpr(RHS
.get());
8848 if (!RHSResult
.isUsable()) return QualType();
8851 // C++ is sufficiently different to merit its own checker.
8852 if (getLangOpts().CPlusPlus
)
8853 return CXXCheckConditionalOperands(Cond
, LHS
, RHS
, VK
, OK
, QuestionLoc
);
8858 if (Context
.isDependenceAllowed() &&
8859 (Cond
.get()->isTypeDependent() || LHS
.get()->isTypeDependent() ||
8860 RHS
.get()->isTypeDependent())) {
8861 assert(!getLangOpts().CPlusPlus
);
8862 assert((Cond
.get()->containsErrors() || LHS
.get()->containsErrors() ||
8863 RHS
.get()->containsErrors()) &&
8864 "should only occur in error-recovery path.");
8865 return Context
.DependentTy
;
8868 // The OpenCL operator with a vector condition is sufficiently
8869 // different to merit its own checker.
8870 if ((getLangOpts().OpenCL
&& Cond
.get()->getType()->isVectorType()) ||
8871 Cond
.get()->getType()->isExtVectorType())
8872 return OpenCLCheckVectorConditional(*this, Cond
, LHS
, RHS
, QuestionLoc
);
8874 // First, check the condition.
8875 Cond
= UsualUnaryConversions(Cond
.get());
8876 if (Cond
.isInvalid())
8878 if (checkCondition(*this, Cond
.get(), QuestionLoc
))
8881 // Now check the two expressions.
8882 if (LHS
.get()->getType()->isVectorType() ||
8883 RHS
.get()->getType()->isVectorType())
8884 return CheckVectorOperands(LHS
, RHS
, QuestionLoc
, /*isCompAssign*/ false,
8885 /*AllowBothBool*/ true,
8886 /*AllowBoolConversions*/ false,
8887 /*AllowBooleanOperation*/ false,
8888 /*ReportInvalid*/ true);
8891 UsualArithmeticConversions(LHS
, RHS
, QuestionLoc
, ACK_Conditional
);
8892 if (LHS
.isInvalid() || RHS
.isInvalid())
8895 QualType LHSTy
= LHS
.get()->getType();
8896 QualType RHSTy
= RHS
.get()->getType();
8898 // Diagnose attempts to convert between __ibm128, __float128 and long double
8899 // where such conversions currently can't be handled.
8900 if (unsupportedTypeConversion(*this, LHSTy
, RHSTy
)) {
8902 diag::err_typecheck_cond_incompatible_operands
) << LHSTy
<< RHSTy
8903 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
8907 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
8908 // selection operator (?:).
8909 if (getLangOpts().OpenCL
&&
8910 ((int)checkBlockType(*this, LHS
.get()) | (int)checkBlockType(*this, RHS
.get()))) {
8914 // If both operands have arithmetic type, do the usual arithmetic conversions
8915 // to find a common type: C99 6.5.15p3,5.
8916 if (LHSTy
->isArithmeticType() && RHSTy
->isArithmeticType()) {
8917 // Disallow invalid arithmetic conversions, such as those between bit-
8918 // precise integers types of different sizes, or between a bit-precise
8919 // integer and another type.
8920 if (ResTy
.isNull() && (LHSTy
->isBitIntType() || RHSTy
->isBitIntType())) {
8921 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
8922 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8923 << RHS
.get()->getSourceRange();
8927 LHS
= ImpCastExprToType(LHS
.get(), ResTy
, PrepareScalarCast(LHS
, ResTy
));
8928 RHS
= ImpCastExprToType(RHS
.get(), ResTy
, PrepareScalarCast(RHS
, ResTy
));
8933 // And if they're both bfloat (which isn't arithmetic), that's fine too.
8934 if (LHSTy
->isBFloat16Type() && RHSTy
->isBFloat16Type()) {
8935 return Context
.getCommonSugaredType(LHSTy
, RHSTy
);
8938 // If both operands are the same structure or union type, the result is that
8940 if (const RecordType
*LHSRT
= LHSTy
->getAs
<RecordType
>()) { // C99 6.5.15p3
8941 if (const RecordType
*RHSRT
= RHSTy
->getAs
<RecordType
>())
8942 if (LHSRT
->getDecl() == RHSRT
->getDecl())
8943 // "If both the operands have structure or union type, the result has
8944 // that type." This implies that CV qualifiers are dropped.
8945 return Context
.getCommonSugaredType(LHSTy
.getUnqualifiedType(),
8946 RHSTy
.getUnqualifiedType());
8947 // FIXME: Type of conditional expression must be complete in C mode.
8950 // C99 6.5.15p5: "If both operands have void type, the result has void type."
8951 // The following || allows only one side to be void (a GCC-ism).
8952 if (LHSTy
->isVoidType() || RHSTy
->isVoidType()) {
8954 if (LHSTy
->isVoidType() && RHSTy
->isVoidType()) {
8955 ResTy
= Context
.getCommonSugaredType(LHSTy
, RHSTy
);
8956 } else if (RHSTy
->isVoidType()) {
8958 Diag(RHS
.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void
)
8959 << RHS
.get()->getSourceRange();
8962 Diag(LHS
.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void
)
8963 << LHS
.get()->getSourceRange();
8965 LHS
= ImpCastExprToType(LHS
.get(), ResTy
, CK_ToVoid
);
8966 RHS
= ImpCastExprToType(RHS
.get(), ResTy
, CK_ToVoid
);
8971 // ... if both the second and third operands have nullptr_t type, the
8972 // result also has that type.
8973 if (LHSTy
->isNullPtrType() && Context
.hasSameType(LHSTy
, RHSTy
))
8976 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
8977 // the type of the other operand."
8978 if (!checkConditionalNullPointer(*this, RHS
, LHSTy
)) return LHSTy
;
8979 if (!checkConditionalNullPointer(*this, LHS
, RHSTy
)) return RHSTy
;
8981 // All objective-c pointer type analysis is done here.
8982 QualType compositeType
= FindCompositeObjCPointerType(LHS
, RHS
,
8984 if (LHS
.isInvalid() || RHS
.isInvalid())
8986 if (!compositeType
.isNull())
8987 return compositeType
;
8990 // Handle block pointer types.
8991 if (LHSTy
->isBlockPointerType() || RHSTy
->isBlockPointerType())
8992 return checkConditionalBlockPointerCompatibility(*this, LHS
, RHS
,
8995 // Check constraints for C object pointers types (C99 6.5.15p3,6).
8996 if (LHSTy
->isPointerType() && RHSTy
->isPointerType())
8997 return checkConditionalObjectPointersCompatibility(*this, LHS
, RHS
,
9000 // GCC compatibility: soften pointer/integer mismatch. Note that
9001 // null pointers have been filtered out by this point.
9002 if (checkPointerIntegerMismatch(*this, LHS
, RHS
.get(), QuestionLoc
,
9003 /*IsIntFirstExpr=*/true))
9005 if (checkPointerIntegerMismatch(*this, RHS
, LHS
.get(), QuestionLoc
,
9006 /*IsIntFirstExpr=*/false))
9009 // Allow ?: operations in which both operands have the same
9010 // built-in sizeless type.
9011 if (LHSTy
->isSizelessBuiltinType() && Context
.hasSameType(LHSTy
, RHSTy
))
9012 return Context
.getCommonSugaredType(LHSTy
, RHSTy
);
9014 // Emit a better diagnostic if one of the expressions is a null pointer
9015 // constant and the other is not a pointer type. In this case, the user most
9016 // likely forgot to take the address of the other expression.
9017 if (DiagnoseConditionalForNull(LHS
.get(), RHS
.get(), QuestionLoc
))
9020 // Otherwise, the operands are not compatible.
9021 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
9022 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
9023 << RHS
.get()->getSourceRange();
9027 /// FindCompositeObjCPointerType - Helper method to find composite type of
9028 /// two objective-c pointer types of the two input expressions.
9029 QualType
Sema::FindCompositeObjCPointerType(ExprResult
&LHS
, ExprResult
&RHS
,
9030 SourceLocation QuestionLoc
) {
9031 QualType LHSTy
= LHS
.get()->getType();
9032 QualType RHSTy
= RHS
.get()->getType();
9034 // Handle things like Class and struct objc_class*. Here we case the result
9035 // to the pseudo-builtin, because that will be implicitly cast back to the
9036 // redefinition type if an attempt is made to access its fields.
9037 if (LHSTy
->isObjCClassType() &&
9038 (Context
.hasSameType(RHSTy
, Context
.getObjCClassRedefinitionType()))) {
9039 RHS
= ImpCastExprToType(RHS
.get(), LHSTy
, CK_CPointerToObjCPointerCast
);
9042 if (RHSTy
->isObjCClassType() &&
9043 (Context
.hasSameType(LHSTy
, Context
.getObjCClassRedefinitionType()))) {
9044 LHS
= ImpCastExprToType(LHS
.get(), RHSTy
, CK_CPointerToObjCPointerCast
);
9047 // And the same for struct objc_object* / id
9048 if (LHSTy
->isObjCIdType() &&
9049 (Context
.hasSameType(RHSTy
, Context
.getObjCIdRedefinitionType()))) {
9050 RHS
= ImpCastExprToType(RHS
.get(), LHSTy
, CK_CPointerToObjCPointerCast
);
9053 if (RHSTy
->isObjCIdType() &&
9054 (Context
.hasSameType(LHSTy
, Context
.getObjCIdRedefinitionType()))) {
9055 LHS
= ImpCastExprToType(LHS
.get(), RHSTy
, CK_CPointerToObjCPointerCast
);
9058 // And the same for struct objc_selector* / SEL
9059 if (Context
.isObjCSelType(LHSTy
) &&
9060 (Context
.hasSameType(RHSTy
, Context
.getObjCSelRedefinitionType()))) {
9061 RHS
= ImpCastExprToType(RHS
.get(), LHSTy
, CK_BitCast
);
9064 if (Context
.isObjCSelType(RHSTy
) &&
9065 (Context
.hasSameType(LHSTy
, Context
.getObjCSelRedefinitionType()))) {
9066 LHS
= ImpCastExprToType(LHS
.get(), RHSTy
, CK_BitCast
);
9069 // Check constraints for Objective-C object pointers types.
9070 if (LHSTy
->isObjCObjectPointerType() && RHSTy
->isObjCObjectPointerType()) {
9072 if (Context
.getCanonicalType(LHSTy
) == Context
.getCanonicalType(RHSTy
)) {
9073 // Two identical object pointer types are always compatible.
9076 const ObjCObjectPointerType
*LHSOPT
= LHSTy
->castAs
<ObjCObjectPointerType
>();
9077 const ObjCObjectPointerType
*RHSOPT
= RHSTy
->castAs
<ObjCObjectPointerType
>();
9078 QualType compositeType
= LHSTy
;
9080 // If both operands are interfaces and either operand can be
9081 // assigned to the other, use that type as the composite
9082 // type. This allows
9083 // xxx ? (A*) a : (B*) b
9084 // where B is a subclass of A.
9086 // Additionally, as for assignment, if either type is 'id'
9087 // allow silent coercion. Finally, if the types are
9088 // incompatible then make sure to use 'id' as the composite
9089 // type so the result is acceptable for sending messages to.
9091 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9092 // It could return the composite type.
9093 if (!(compositeType
=
9094 Context
.areCommonBaseCompatible(LHSOPT
, RHSOPT
)).isNull()) {
9095 // Nothing more to do.
9096 } else if (Context
.canAssignObjCInterfaces(LHSOPT
, RHSOPT
)) {
9097 compositeType
= RHSOPT
->isObjCBuiltinType() ? RHSTy
: LHSTy
;
9098 } else if (Context
.canAssignObjCInterfaces(RHSOPT
, LHSOPT
)) {
9099 compositeType
= LHSOPT
->isObjCBuiltinType() ? LHSTy
: RHSTy
;
9100 } else if ((LHSOPT
->isObjCQualifiedIdType() ||
9101 RHSOPT
->isObjCQualifiedIdType()) &&
9102 Context
.ObjCQualifiedIdTypesAreCompatible(LHSOPT
, RHSOPT
,
9104 // Need to handle "id<xx>" explicitly.
9105 // GCC allows qualified id and any Objective-C type to devolve to
9106 // id. Currently localizing to here until clear this should be
9107 // part of ObjCQualifiedIdTypesAreCompatible.
9108 compositeType
= Context
.getObjCIdType();
9109 } else if (LHSTy
->isObjCIdType() || RHSTy
->isObjCIdType()) {
9110 compositeType
= Context
.getObjCIdType();
9112 Diag(QuestionLoc
, diag::ext_typecheck_cond_incompatible_operands
)
9114 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9115 QualType incompatTy
= Context
.getObjCIdType();
9116 LHS
= ImpCastExprToType(LHS
.get(), incompatTy
, CK_BitCast
);
9117 RHS
= ImpCastExprToType(RHS
.get(), incompatTy
, CK_BitCast
);
9120 // The object pointer types are compatible.
9121 LHS
= ImpCastExprToType(LHS
.get(), compositeType
, CK_BitCast
);
9122 RHS
= ImpCastExprToType(RHS
.get(), compositeType
, CK_BitCast
);
9123 return compositeType
;
9125 // Check Objective-C object pointer types and 'void *'
9126 if (LHSTy
->isVoidPointerType() && RHSTy
->isObjCObjectPointerType()) {
9127 if (getLangOpts().ObjCAutoRefCount
) {
9128 // ARC forbids the implicit conversion of object pointers to 'void *',
9129 // so these types are not compatible.
9130 Diag(QuestionLoc
, diag::err_cond_voidptr_arc
) << LHSTy
<< RHSTy
9131 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9135 QualType lhptee
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
9136 QualType rhptee
= RHSTy
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
9137 QualType destPointee
9138 = Context
.getQualifiedType(lhptee
, rhptee
.getQualifiers());
9139 QualType destType
= Context
.getPointerType(destPointee
);
9140 // Add qualifiers if necessary.
9141 LHS
= ImpCastExprToType(LHS
.get(), destType
, CK_NoOp
);
9142 // Promote to void*.
9143 RHS
= ImpCastExprToType(RHS
.get(), destType
, CK_BitCast
);
9146 if (LHSTy
->isObjCObjectPointerType() && RHSTy
->isVoidPointerType()) {
9147 if (getLangOpts().ObjCAutoRefCount
) {
9148 // ARC forbids the implicit conversion of object pointers to 'void *',
9149 // so these types are not compatible.
9150 Diag(QuestionLoc
, diag::err_cond_voidptr_arc
) << LHSTy
<< RHSTy
9151 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9155 QualType lhptee
= LHSTy
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
9156 QualType rhptee
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
9157 QualType destPointee
9158 = Context
.getQualifiedType(rhptee
, lhptee
.getQualifiers());
9159 QualType destType
= Context
.getPointerType(destPointee
);
9160 // Add qualifiers if necessary.
9161 RHS
= ImpCastExprToType(RHS
.get(), destType
, CK_NoOp
);
9162 // Promote to void*.
9163 LHS
= ImpCastExprToType(LHS
.get(), destType
, CK_BitCast
);
9169 /// SuggestParentheses - Emit a note with a fixit hint that wraps
9170 /// ParenRange in parentheses.
9171 static void SuggestParentheses(Sema
&Self
, SourceLocation Loc
,
9172 const PartialDiagnostic
&Note
,
9173 SourceRange ParenRange
) {
9174 SourceLocation EndLoc
= Self
.getLocForEndOfToken(ParenRange
.getEnd());
9175 if (ParenRange
.getBegin().isFileID() && ParenRange
.getEnd().isFileID() &&
9177 Self
.Diag(Loc
, Note
)
9178 << FixItHint::CreateInsertion(ParenRange
.getBegin(), "(")
9179 << FixItHint::CreateInsertion(EndLoc
, ")");
9181 // We can't display the parentheses, so just show the bare note.
9182 Self
.Diag(Loc
, Note
) << ParenRange
;
9186 static bool IsArithmeticOp(BinaryOperatorKind Opc
) {
9187 return BinaryOperator::isAdditiveOp(Opc
) ||
9188 BinaryOperator::isMultiplicativeOp(Opc
) ||
9189 BinaryOperator::isShiftOp(Opc
) || Opc
== BO_And
|| Opc
== BO_Or
;
9190 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9191 // not any of the logical operators. Bitwise-xor is commonly used as a
9192 // logical-xor because there is no logical-xor operator. The logical
9193 // operators, including uses of xor, have a high false positive rate for
9194 // precedence warnings.
9197 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9198 /// expression, either using a built-in or overloaded operator,
9199 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9201 static bool IsArithmeticBinaryExpr(Expr
*E
, BinaryOperatorKind
*Opcode
,
9203 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9204 E
= E
->IgnoreImpCasts();
9205 E
= E
->IgnoreConversionOperatorSingleStep();
9206 E
= E
->IgnoreImpCasts();
9207 if (auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(E
)) {
9208 E
= MTE
->getSubExpr();
9209 E
= E
->IgnoreImpCasts();
9212 // Built-in binary operator.
9213 if (BinaryOperator
*OP
= dyn_cast
<BinaryOperator
>(E
)) {
9214 if (IsArithmeticOp(OP
->getOpcode())) {
9215 *Opcode
= OP
->getOpcode();
9216 *RHSExprs
= OP
->getRHS();
9221 // Overloaded operator.
9222 if (CXXOperatorCallExpr
*Call
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
9223 if (Call
->getNumArgs() != 2)
9226 // Make sure this is really a binary operator that is safe to pass into
9227 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9228 OverloadedOperatorKind OO
= Call
->getOperator();
9229 if (OO
< OO_Plus
|| OO
> OO_Arrow
||
9230 OO
== OO_PlusPlus
|| OO
== OO_MinusMinus
)
9233 BinaryOperatorKind OpKind
= BinaryOperator::getOverloadedOpcode(OO
);
9234 if (IsArithmeticOp(OpKind
)) {
9236 *RHSExprs
= Call
->getArg(1);
9244 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9245 /// or is a logical expression such as (x==y) which has int type, but is
9246 /// commonly interpreted as boolean.
9247 static bool ExprLooksBoolean(Expr
*E
) {
9248 E
= E
->IgnoreParenImpCasts();
9250 if (E
->getType()->isBooleanType())
9252 if (BinaryOperator
*OP
= dyn_cast
<BinaryOperator
>(E
))
9253 return OP
->isComparisonOp() || OP
->isLogicalOp();
9254 if (UnaryOperator
*OP
= dyn_cast
<UnaryOperator
>(E
))
9255 return OP
->getOpcode() == UO_LNot
;
9256 if (E
->getType()->isPointerType())
9258 // FIXME: What about overloaded operator calls returning "unspecified boolean
9259 // type"s (commonly pointer-to-members)?
9264 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9265 /// and binary operator are mixed in a way that suggests the programmer assumed
9266 /// the conditional operator has higher precedence, for example:
9267 /// "int x = a + someBinaryCondition ? 1 : 2".
9268 static void DiagnoseConditionalPrecedence(Sema
&Self
,
9269 SourceLocation OpLoc
,
9273 BinaryOperatorKind CondOpcode
;
9276 if (!IsArithmeticBinaryExpr(Condition
, &CondOpcode
, &CondRHS
))
9278 if (!ExprLooksBoolean(CondRHS
))
9281 // The condition is an arithmetic binary expression, with a right-
9282 // hand side that looks boolean, so warn.
9284 unsigned DiagID
= BinaryOperator::isBitwiseOp(CondOpcode
)
9285 ? diag::warn_precedence_bitwise_conditional
9286 : diag::warn_precedence_conditional
;
9288 Self
.Diag(OpLoc
, DiagID
)
9289 << Condition
->getSourceRange()
9290 << BinaryOperator::getOpcodeStr(CondOpcode
);
9294 Self
.PDiag(diag::note_precedence_silence
)
9295 << BinaryOperator::getOpcodeStr(CondOpcode
),
9296 SourceRange(Condition
->getBeginLoc(), Condition
->getEndLoc()));
9298 SuggestParentheses(Self
, OpLoc
,
9299 Self
.PDiag(diag::note_precedence_conditional_first
),
9300 SourceRange(CondRHS
->getBeginLoc(), RHSExpr
->getEndLoc()));
9303 /// Compute the nullability of a conditional expression.
9304 static QualType
computeConditionalNullability(QualType ResTy
, bool IsBin
,
9305 QualType LHSTy
, QualType RHSTy
,
9307 if (!ResTy
->isAnyPointerType())
9310 auto GetNullability
= [](QualType Ty
) {
9311 std::optional
<NullabilityKind
> Kind
= Ty
->getNullability();
9313 // For our purposes, treat _Nullable_result as _Nullable.
9314 if (*Kind
== NullabilityKind::NullableResult
)
9315 return NullabilityKind::Nullable
;
9318 return NullabilityKind::Unspecified
;
9321 auto LHSKind
= GetNullability(LHSTy
), RHSKind
= GetNullability(RHSTy
);
9322 NullabilityKind MergedKind
;
9324 // Compute nullability of a binary conditional expression.
9326 if (LHSKind
== NullabilityKind::NonNull
)
9327 MergedKind
= NullabilityKind::NonNull
;
9329 MergedKind
= RHSKind
;
9330 // Compute nullability of a normal conditional expression.
9332 if (LHSKind
== NullabilityKind::Nullable
||
9333 RHSKind
== NullabilityKind::Nullable
)
9334 MergedKind
= NullabilityKind::Nullable
;
9335 else if (LHSKind
== NullabilityKind::NonNull
)
9336 MergedKind
= RHSKind
;
9337 else if (RHSKind
== NullabilityKind::NonNull
)
9338 MergedKind
= LHSKind
;
9340 MergedKind
= NullabilityKind::Unspecified
;
9343 // Return if ResTy already has the correct nullability.
9344 if (GetNullability(ResTy
) == MergedKind
)
9347 // Strip all nullability from ResTy.
9348 while (ResTy
->getNullability())
9349 ResTy
= ResTy
.getSingleStepDesugaredType(Ctx
);
9351 // Create a new AttributedType with the new nullability kind.
9352 auto NewAttr
= AttributedType::getNullabilityAttrKind(MergedKind
);
9353 return Ctx
.getAttributedType(NewAttr
, ResTy
, ResTy
);
9356 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9357 /// in the case of a the GNU conditional expr extension.
9358 ExprResult
Sema::ActOnConditionalOp(SourceLocation QuestionLoc
,
9359 SourceLocation ColonLoc
,
9360 Expr
*CondExpr
, Expr
*LHSExpr
,
9362 if (!Context
.isDependenceAllowed()) {
9363 // C cannot handle TypoExpr nodes in the condition because it
9364 // doesn't handle dependent types properly, so make sure any TypoExprs have
9365 // been dealt with before checking the operands.
9366 ExprResult CondResult
= CorrectDelayedTyposInExpr(CondExpr
);
9367 ExprResult LHSResult
= CorrectDelayedTyposInExpr(LHSExpr
);
9368 ExprResult RHSResult
= CorrectDelayedTyposInExpr(RHSExpr
);
9370 if (!CondResult
.isUsable())
9374 if (!LHSResult
.isUsable())
9378 if (!RHSResult
.isUsable())
9381 CondExpr
= CondResult
.get();
9382 LHSExpr
= LHSResult
.get();
9383 RHSExpr
= RHSResult
.get();
9386 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9387 // was the condition.
9388 OpaqueValueExpr
*opaqueValue
= nullptr;
9389 Expr
*commonExpr
= nullptr;
9391 commonExpr
= CondExpr
;
9392 // Lower out placeholder types first. This is important so that we don't
9393 // try to capture a placeholder. This happens in few cases in C++; such
9394 // as Objective-C++'s dictionary subscripting syntax.
9395 if (commonExpr
->hasPlaceholderType()) {
9396 ExprResult result
= CheckPlaceholderExpr(commonExpr
);
9397 if (!result
.isUsable()) return ExprError();
9398 commonExpr
= result
.get();
9400 // We usually want to apply unary conversions *before* saving, except
9401 // in the special case of a C++ l-value conditional.
9402 if (!(getLangOpts().CPlusPlus
9403 && !commonExpr
->isTypeDependent()
9404 && commonExpr
->getValueKind() == RHSExpr
->getValueKind()
9405 && commonExpr
->isGLValue()
9406 && commonExpr
->isOrdinaryOrBitFieldObject()
9407 && RHSExpr
->isOrdinaryOrBitFieldObject()
9408 && Context
.hasSameType(commonExpr
->getType(), RHSExpr
->getType()))) {
9409 ExprResult commonRes
= UsualUnaryConversions(commonExpr
);
9410 if (commonRes
.isInvalid())
9412 commonExpr
= commonRes
.get();
9415 // If the common expression is a class or array prvalue, materialize it
9416 // so that we can safely refer to it multiple times.
9417 if (commonExpr
->isPRValue() && (commonExpr
->getType()->isRecordType() ||
9418 commonExpr
->getType()->isArrayType())) {
9419 ExprResult MatExpr
= TemporaryMaterializationConversion(commonExpr
);
9420 if (MatExpr
.isInvalid())
9422 commonExpr
= MatExpr
.get();
9425 opaqueValue
= new (Context
) OpaqueValueExpr(commonExpr
->getExprLoc(),
9426 commonExpr
->getType(),
9427 commonExpr
->getValueKind(),
9428 commonExpr
->getObjectKind(),
9430 LHSExpr
= CondExpr
= opaqueValue
;
9433 QualType LHSTy
= LHSExpr
->getType(), RHSTy
= RHSExpr
->getType();
9434 ExprValueKind VK
= VK_PRValue
;
9435 ExprObjectKind OK
= OK_Ordinary
;
9436 ExprResult Cond
= CondExpr
, LHS
= LHSExpr
, RHS
= RHSExpr
;
9437 QualType result
= CheckConditionalOperands(Cond
, LHS
, RHS
,
9438 VK
, OK
, QuestionLoc
);
9439 if (result
.isNull() || Cond
.isInvalid() || LHS
.isInvalid() ||
9443 DiagnoseConditionalPrecedence(*this, QuestionLoc
, Cond
.get(), LHS
.get(),
9446 CheckBoolLikeConversion(Cond
.get(), QuestionLoc
);
9448 result
= computeConditionalNullability(result
, commonExpr
, LHSTy
, RHSTy
,
9452 return new (Context
)
9453 ConditionalOperator(Cond
.get(), QuestionLoc
, LHS
.get(), ColonLoc
,
9454 RHS
.get(), result
, VK
, OK
);
9456 return new (Context
) BinaryConditionalOperator(
9457 commonExpr
, opaqueValue
, Cond
.get(), LHS
.get(), RHS
.get(), QuestionLoc
,
9458 ColonLoc
, result
, VK
, OK
);
9461 // Check if we have a conversion between incompatible cmse function pointer
9462 // types, that is, a conversion between a function pointer with the
9463 // cmse_nonsecure_call attribute and one without.
9464 static bool IsInvalidCmseNSCallConversion(Sema
&S
, QualType FromType
,
9466 if (const auto *ToFn
=
9467 dyn_cast
<FunctionType
>(S
.Context
.getCanonicalType(ToType
))) {
9468 if (const auto *FromFn
=
9469 dyn_cast
<FunctionType
>(S
.Context
.getCanonicalType(FromType
))) {
9470 FunctionType::ExtInfo ToEInfo
= ToFn
->getExtInfo();
9471 FunctionType::ExtInfo FromEInfo
= FromFn
->getExtInfo();
9473 return ToEInfo
.getCmseNSCall() != FromEInfo
.getCmseNSCall();
9479 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9480 // being closely modeled after the C99 spec:-). The odd characteristic of this
9481 // routine is it effectively iqnores the qualifiers on the top level pointee.
9482 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9483 // FIXME: add a couple examples in this comment.
9484 static Sema::AssignConvertType
9485 checkPointerTypesForAssignment(Sema
&S
, QualType LHSType
, QualType RHSType
,
9486 SourceLocation Loc
) {
9487 assert(LHSType
.isCanonical() && "LHS not canonicalized!");
9488 assert(RHSType
.isCanonical() && "RHS not canonicalized!");
9490 // get the "pointed to" type (ignoring qualifiers at the top level)
9491 const Type
*lhptee
, *rhptee
;
9492 Qualifiers lhq
, rhq
;
9493 std::tie(lhptee
, lhq
) =
9494 cast
<PointerType
>(LHSType
)->getPointeeType().split().asPair();
9495 std::tie(rhptee
, rhq
) =
9496 cast
<PointerType
>(RHSType
)->getPointeeType().split().asPair();
9498 Sema::AssignConvertType ConvTy
= Sema::Compatible
;
9500 // C99 6.5.16.1p1: This following citation is common to constraints
9501 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9502 // qualifiers of the type *pointed to* by the right;
9504 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9505 if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime() &&
9506 lhq
.compatiblyIncludesObjCLifetime(rhq
)) {
9507 // Ignore lifetime for further calculation.
9508 lhq
.removeObjCLifetime();
9509 rhq
.removeObjCLifetime();
9512 if (!lhq
.compatiblyIncludes(rhq
)) {
9513 // Treat address-space mismatches as fatal.
9514 if (!lhq
.isAddressSpaceSupersetOf(rhq
))
9515 return Sema::IncompatiblePointerDiscardsQualifiers
;
9517 // It's okay to add or remove GC or lifetime qualifiers when converting to
9519 else if (lhq
.withoutObjCGCAttr().withoutObjCLifetime()
9520 .compatiblyIncludes(
9521 rhq
.withoutObjCGCAttr().withoutObjCLifetime())
9522 && (lhptee
->isVoidType() || rhptee
->isVoidType()))
9525 // Treat lifetime mismatches as fatal.
9526 else if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime())
9527 ConvTy
= Sema::IncompatiblePointerDiscardsQualifiers
;
9529 // For GCC/MS compatibility, other qualifier mismatches are treated
9530 // as still compatible in C.
9531 else ConvTy
= Sema::CompatiblePointerDiscardsQualifiers
;
9534 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9535 // incomplete type and the other is a pointer to a qualified or unqualified
9536 // version of void...
9537 if (lhptee
->isVoidType()) {
9538 if (rhptee
->isIncompleteOrObjectType())
9541 // As an extension, we allow cast to/from void* to function pointer.
9542 assert(rhptee
->isFunctionType());
9543 return Sema::FunctionVoidPointer
;
9546 if (rhptee
->isVoidType()) {
9547 if (lhptee
->isIncompleteOrObjectType())
9550 // As an extension, we allow cast to/from void* to function pointer.
9551 assert(lhptee
->isFunctionType());
9552 return Sema::FunctionVoidPointer
;
9555 if (!S
.Diags
.isIgnored(
9556 diag::warn_typecheck_convert_incompatible_function_pointer_strict
,
9558 RHSType
->isFunctionPointerType() && LHSType
->isFunctionPointerType() &&
9559 !S
.IsFunctionConversion(RHSType
, LHSType
, RHSType
))
9560 return Sema::IncompatibleFunctionPointerStrict
;
9562 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9563 // unqualified versions of compatible types, ...
9564 QualType ltrans
= QualType(lhptee
, 0), rtrans
= QualType(rhptee
, 0);
9565 if (!S
.Context
.typesAreCompatible(ltrans
, rtrans
)) {
9566 // Check if the pointee types are compatible ignoring the sign.
9567 // We explicitly check for char so that we catch "char" vs
9568 // "unsigned char" on systems where "char" is unsigned.
9569 if (lhptee
->isCharType())
9570 ltrans
= S
.Context
.UnsignedCharTy
;
9571 else if (lhptee
->hasSignedIntegerRepresentation())
9572 ltrans
= S
.Context
.getCorrespondingUnsignedType(ltrans
);
9574 if (rhptee
->isCharType())
9575 rtrans
= S
.Context
.UnsignedCharTy
;
9576 else if (rhptee
->hasSignedIntegerRepresentation())
9577 rtrans
= S
.Context
.getCorrespondingUnsignedType(rtrans
);
9579 if (ltrans
== rtrans
) {
9580 // Types are compatible ignoring the sign. Qualifier incompatibility
9581 // takes priority over sign incompatibility because the sign
9582 // warning can be disabled.
9583 if (ConvTy
!= Sema::Compatible
)
9586 return Sema::IncompatiblePointerSign
;
9589 // If we are a multi-level pointer, it's possible that our issue is simply
9590 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9591 // the eventual target type is the same and the pointers have the same
9592 // level of indirection, this must be the issue.
9593 if (isa
<PointerType
>(lhptee
) && isa
<PointerType
>(rhptee
)) {
9595 std::tie(lhptee
, lhq
) =
9596 cast
<PointerType
>(lhptee
)->getPointeeType().split().asPair();
9597 std::tie(rhptee
, rhq
) =
9598 cast
<PointerType
>(rhptee
)->getPointeeType().split().asPair();
9600 // Inconsistent address spaces at this point is invalid, even if the
9601 // address spaces would be compatible.
9602 // FIXME: This doesn't catch address space mismatches for pointers of
9603 // different nesting levels, like:
9604 // __local int *** a;
9606 // It's not clear how to actually determine when such pointers are
9607 // invalidly incompatible.
9608 if (lhq
.getAddressSpace() != rhq
.getAddressSpace())
9609 return Sema::IncompatibleNestedPointerAddressSpaceMismatch
;
9611 } while (isa
<PointerType
>(lhptee
) && isa
<PointerType
>(rhptee
));
9613 if (lhptee
== rhptee
)
9614 return Sema::IncompatibleNestedPointerQualifiers
;
9617 // General pointer incompatibility takes priority over qualifiers.
9618 if (RHSType
->isFunctionPointerType() && LHSType
->isFunctionPointerType())
9619 return Sema::IncompatibleFunctionPointer
;
9620 return Sema::IncompatiblePointer
;
9622 if (!S
.getLangOpts().CPlusPlus
&&
9623 S
.IsFunctionConversion(ltrans
, rtrans
, ltrans
))
9624 return Sema::IncompatibleFunctionPointer
;
9625 if (IsInvalidCmseNSCallConversion(S
, ltrans
, rtrans
))
9626 return Sema::IncompatibleFunctionPointer
;
9630 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9631 /// block pointer types are compatible or whether a block and normal pointer
9632 /// are compatible. It is more restrict than comparing two function pointer
9634 static Sema::AssignConvertType
9635 checkBlockPointerTypesForAssignment(Sema
&S
, QualType LHSType
,
9637 assert(LHSType
.isCanonical() && "LHS not canonicalized!");
9638 assert(RHSType
.isCanonical() && "RHS not canonicalized!");
9640 QualType lhptee
, rhptee
;
9642 // get the "pointed to" type (ignoring qualifiers at the top level)
9643 lhptee
= cast
<BlockPointerType
>(LHSType
)->getPointeeType();
9644 rhptee
= cast
<BlockPointerType
>(RHSType
)->getPointeeType();
9646 // In C++, the types have to match exactly.
9647 if (S
.getLangOpts().CPlusPlus
)
9648 return Sema::IncompatibleBlockPointer
;
9650 Sema::AssignConvertType ConvTy
= Sema::Compatible
;
9652 // For blocks we enforce that qualifiers are identical.
9653 Qualifiers LQuals
= lhptee
.getLocalQualifiers();
9654 Qualifiers RQuals
= rhptee
.getLocalQualifiers();
9655 if (S
.getLangOpts().OpenCL
) {
9656 LQuals
.removeAddressSpace();
9657 RQuals
.removeAddressSpace();
9659 if (LQuals
!= RQuals
)
9660 ConvTy
= Sema::CompatiblePointerDiscardsQualifiers
;
9662 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
9664 // The current behavior is similar to C++ lambdas. A block might be
9665 // assigned to a variable iff its return type and parameters are compatible
9666 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
9667 // an assignment. Presumably it should behave in way that a function pointer
9668 // assignment does in C, so for each parameter and return type:
9669 // * CVR and address space of LHS should be a superset of CVR and address
9671 // * unqualified types should be compatible.
9672 if (S
.getLangOpts().OpenCL
) {
9673 if (!S
.Context
.typesAreBlockPointerCompatible(
9674 S
.Context
.getQualifiedType(LHSType
.getUnqualifiedType(), LQuals
),
9675 S
.Context
.getQualifiedType(RHSType
.getUnqualifiedType(), RQuals
)))
9676 return Sema::IncompatibleBlockPointer
;
9677 } else if (!S
.Context
.typesAreBlockPointerCompatible(LHSType
, RHSType
))
9678 return Sema::IncompatibleBlockPointer
;
9683 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
9684 /// for assignment compatibility.
9685 static Sema::AssignConvertType
9686 checkObjCPointerTypesForAssignment(Sema
&S
, QualType LHSType
,
9688 assert(LHSType
.isCanonical() && "LHS was not canonicalized!");
9689 assert(RHSType
.isCanonical() && "RHS was not canonicalized!");
9691 if (LHSType
->isObjCBuiltinType()) {
9692 // Class is not compatible with ObjC object pointers.
9693 if (LHSType
->isObjCClassType() && !RHSType
->isObjCBuiltinType() &&
9694 !RHSType
->isObjCQualifiedClassType())
9695 return Sema::IncompatiblePointer
;
9696 return Sema::Compatible
;
9698 if (RHSType
->isObjCBuiltinType()) {
9699 if (RHSType
->isObjCClassType() && !LHSType
->isObjCBuiltinType() &&
9700 !LHSType
->isObjCQualifiedClassType())
9701 return Sema::IncompatiblePointer
;
9702 return Sema::Compatible
;
9704 QualType lhptee
= LHSType
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
9705 QualType rhptee
= RHSType
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
9707 if (!lhptee
.isAtLeastAsQualifiedAs(rhptee
) &&
9708 // make an exception for id<P>
9709 !LHSType
->isObjCQualifiedIdType())
9710 return Sema::CompatiblePointerDiscardsQualifiers
;
9712 if (S
.Context
.typesAreCompatible(LHSType
, RHSType
))
9713 return Sema::Compatible
;
9714 if (LHSType
->isObjCQualifiedIdType() || RHSType
->isObjCQualifiedIdType())
9715 return Sema::IncompatibleObjCQualifiedId
;
9716 return Sema::IncompatiblePointer
;
9719 Sema::AssignConvertType
9720 Sema::CheckAssignmentConstraints(SourceLocation Loc
,
9721 QualType LHSType
, QualType RHSType
) {
9722 // Fake up an opaque expression. We don't actually care about what
9723 // cast operations are required, so if CheckAssignmentConstraints
9724 // adds casts to this they'll be wasted, but fortunately that doesn't
9725 // usually happen on valid code.
9726 OpaqueValueExpr
RHSExpr(Loc
, RHSType
, VK_PRValue
);
9727 ExprResult RHSPtr
= &RHSExpr
;
9730 return CheckAssignmentConstraints(LHSType
, RHSPtr
, K
, /*ConvertRHS=*/false);
9733 /// This helper function returns true if QT is a vector type that has element
9734 /// type ElementType.
9735 static bool isVector(QualType QT
, QualType ElementType
) {
9736 if (const VectorType
*VT
= QT
->getAs
<VectorType
>())
9737 return VT
->getElementType().getCanonicalType() == ElementType
;
9741 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
9742 /// has code to accommodate several GCC extensions when type checking
9743 /// pointers. Here are some objectionable examples that GCC considers warnings:
9747 /// struct foo *pfoo;
9749 /// pint = pshort; // warning: assignment from incompatible pointer type
9750 /// a = pint; // warning: assignment makes integer from pointer without a cast
9751 /// pint = a; // warning: assignment makes pointer from integer without a cast
9752 /// pint = pfoo; // warning: assignment from incompatible pointer type
9754 /// As a result, the code for dealing with pointers is more complex than the
9755 /// C99 spec dictates.
9757 /// Sets 'Kind' for any result kind except Incompatible.
9758 Sema::AssignConvertType
9759 Sema::CheckAssignmentConstraints(QualType LHSType
, ExprResult
&RHS
,
9760 CastKind
&Kind
, bool ConvertRHS
) {
9761 QualType RHSType
= RHS
.get()->getType();
9762 QualType OrigLHSType
= LHSType
;
9764 // Get canonical types. We're not formatting these types, just comparing
9766 LHSType
= Context
.getCanonicalType(LHSType
).getUnqualifiedType();
9767 RHSType
= Context
.getCanonicalType(RHSType
).getUnqualifiedType();
9769 // Common case: no conversion required.
9770 if (LHSType
== RHSType
) {
9775 // If the LHS has an __auto_type, there are no additional type constraints
9776 // to be worried about.
9777 if (const auto *AT
= dyn_cast
<AutoType
>(LHSType
)) {
9778 if (AT
->isGNUAutoType()) {
9784 // If we have an atomic type, try a non-atomic assignment, then just add an
9785 // atomic qualification step.
9786 if (const AtomicType
*AtomicTy
= dyn_cast
<AtomicType
>(LHSType
)) {
9787 Sema::AssignConvertType result
=
9788 CheckAssignmentConstraints(AtomicTy
->getValueType(), RHS
, Kind
);
9789 if (result
!= Compatible
)
9791 if (Kind
!= CK_NoOp
&& ConvertRHS
)
9792 RHS
= ImpCastExprToType(RHS
.get(), AtomicTy
->getValueType(), Kind
);
9793 Kind
= CK_NonAtomicToAtomic
;
9797 // If the left-hand side is a reference type, then we are in a
9798 // (rare!) case where we've allowed the use of references in C,
9799 // e.g., as a parameter type in a built-in function. In this case,
9800 // just make sure that the type referenced is compatible with the
9801 // right-hand side type. The caller is responsible for adjusting
9802 // LHSType so that the resulting expression does not have reference
9804 if (const ReferenceType
*LHSTypeRef
= LHSType
->getAs
<ReferenceType
>()) {
9805 if (Context
.typesAreCompatible(LHSTypeRef
->getPointeeType(), RHSType
)) {
9806 Kind
= CK_LValueBitCast
;
9809 return Incompatible
;
9812 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
9813 // to the same ExtVector type.
9814 if (LHSType
->isExtVectorType()) {
9815 if (RHSType
->isExtVectorType())
9816 return Incompatible
;
9817 if (RHSType
->isArithmeticType()) {
9818 // CK_VectorSplat does T -> vector T, so first cast to the element type.
9820 RHS
= prepareVectorSplat(LHSType
, RHS
.get());
9821 Kind
= CK_VectorSplat
;
9826 // Conversions to or from vector type.
9827 if (LHSType
->isVectorType() || RHSType
->isVectorType()) {
9828 if (LHSType
->isVectorType() && RHSType
->isVectorType()) {
9829 // Allow assignments of an AltiVec vector type to an equivalent GCC
9830 // vector type and vice versa
9831 if (Context
.areCompatibleVectorTypes(LHSType
, RHSType
)) {
9836 // If we are allowing lax vector conversions, and LHS and RHS are both
9837 // vectors, the total size only needs to be the same. This is a bitcast;
9838 // no bits are changed but the result type is different.
9839 if (isLaxVectorConversion(RHSType
, LHSType
)) {
9840 // The default for lax vector conversions with Altivec vectors will
9841 // change, so if we are converting between vector types where
9842 // at least one is an Altivec vector, emit a warning.
9843 if (anyAltivecTypes(RHSType
, LHSType
) &&
9844 !areSameVectorElemTypes(RHSType
, LHSType
))
9845 Diag(RHS
.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all
)
9846 << RHSType
<< LHSType
;
9848 return IncompatibleVectors
;
9852 // When the RHS comes from another lax conversion (e.g. binops between
9853 // scalars and vectors) the result is canonicalized as a vector. When the
9854 // LHS is also a vector, the lax is allowed by the condition above. Handle
9855 // the case where LHS is a scalar.
9856 if (LHSType
->isScalarType()) {
9857 const VectorType
*VecType
= RHSType
->getAs
<VectorType
>();
9858 if (VecType
&& VecType
->getNumElements() == 1 &&
9859 isLaxVectorConversion(RHSType
, LHSType
)) {
9860 if (VecType
->getVectorKind() == VectorType::AltiVecVector
)
9861 Diag(RHS
.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all
)
9862 << RHSType
<< LHSType
;
9863 ExprResult
*VecExpr
= &RHS
;
9864 *VecExpr
= ImpCastExprToType(VecExpr
->get(), LHSType
, CK_BitCast
);
9870 // Allow assignments between fixed-length and sizeless SVE vectors.
9871 if ((LHSType
->isSizelessBuiltinType() && RHSType
->isVectorType()) ||
9872 (LHSType
->isVectorType() && RHSType
->isSizelessBuiltinType()))
9873 if (Context
.areCompatibleSveTypes(LHSType
, RHSType
) ||
9874 Context
.areLaxCompatibleSveTypes(LHSType
, RHSType
)) {
9879 return Incompatible
;
9882 // Diagnose attempts to convert between __ibm128, __float128 and long double
9883 // where such conversions currently can't be handled.
9884 if (unsupportedTypeConversion(*this, LHSType
, RHSType
))
9885 return Incompatible
;
9887 // Disallow assigning a _Complex to a real type in C++ mode since it simply
9888 // discards the imaginary part.
9889 if (getLangOpts().CPlusPlus
&& RHSType
->getAs
<ComplexType
>() &&
9890 !LHSType
->getAs
<ComplexType
>())
9891 return Incompatible
;
9893 // Arithmetic conversions.
9894 if (LHSType
->isArithmeticType() && RHSType
->isArithmeticType() &&
9895 !(getLangOpts().CPlusPlus
&& LHSType
->isEnumeralType())) {
9897 Kind
= PrepareScalarCast(RHS
, LHSType
);
9901 // Conversions to normal pointers.
9902 if (const PointerType
*LHSPointer
= dyn_cast
<PointerType
>(LHSType
)) {
9904 if (isa
<PointerType
>(RHSType
)) {
9905 LangAS AddrSpaceL
= LHSPointer
->getPointeeType().getAddressSpace();
9906 LangAS AddrSpaceR
= RHSType
->getPointeeType().getAddressSpace();
9907 if (AddrSpaceL
!= AddrSpaceR
)
9908 Kind
= CK_AddressSpaceConversion
;
9909 else if (Context
.hasCvrSimilarType(RHSType
, LHSType
))
9913 return checkPointerTypesForAssignment(*this, LHSType
, RHSType
,
9914 RHS
.get()->getBeginLoc());
9918 if (RHSType
->isIntegerType()) {
9919 Kind
= CK_IntegralToPointer
; // FIXME: null?
9920 return IntToPointer
;
9923 // C pointers are not compatible with ObjC object pointers,
9924 // with two exceptions:
9925 if (isa
<ObjCObjectPointerType
>(RHSType
)) {
9926 // - conversions to void*
9927 if (LHSPointer
->getPointeeType()->isVoidType()) {
9932 // - conversions from 'Class' to the redefinition type
9933 if (RHSType
->isObjCClassType() &&
9934 Context
.hasSameType(LHSType
,
9935 Context
.getObjCClassRedefinitionType())) {
9941 return IncompatiblePointer
;
9945 if (RHSType
->getAs
<BlockPointerType
>()) {
9946 if (LHSPointer
->getPointeeType()->isVoidType()) {
9947 LangAS AddrSpaceL
= LHSPointer
->getPointeeType().getAddressSpace();
9948 LangAS AddrSpaceR
= RHSType
->getAs
<BlockPointerType
>()
9952 AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
: CK_BitCast
;
9957 return Incompatible
;
9960 // Conversions to block pointers.
9961 if (isa
<BlockPointerType
>(LHSType
)) {
9963 if (RHSType
->isBlockPointerType()) {
9964 LangAS AddrSpaceL
= LHSType
->getAs
<BlockPointerType
>()
9967 LangAS AddrSpaceR
= RHSType
->getAs
<BlockPointerType
>()
9970 Kind
= AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
: CK_BitCast
;
9971 return checkBlockPointerTypesForAssignment(*this, LHSType
, RHSType
);
9974 // int or null -> T^
9975 if (RHSType
->isIntegerType()) {
9976 Kind
= CK_IntegralToPointer
; // FIXME: null
9977 return IntToBlockPointer
;
9981 if (getLangOpts().ObjC
&& RHSType
->isObjCIdType()) {
9982 Kind
= CK_AnyPointerToBlockPointerCast
;
9987 if (const PointerType
*RHSPT
= RHSType
->getAs
<PointerType
>())
9988 if (RHSPT
->getPointeeType()->isVoidType()) {
9989 Kind
= CK_AnyPointerToBlockPointerCast
;
9993 return Incompatible
;
9996 // Conversions to Objective-C pointers.
9997 if (isa
<ObjCObjectPointerType
>(LHSType
)) {
9999 if (RHSType
->isObjCObjectPointerType()) {
10001 Sema::AssignConvertType result
=
10002 checkObjCPointerTypesForAssignment(*this, LHSType
, RHSType
);
10003 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10004 result
== Compatible
&&
10005 !CheckObjCARCUnavailableWeakConversion(OrigLHSType
, RHSType
))
10006 result
= IncompatibleObjCWeakRef
;
10010 // int or null -> A*
10011 if (RHSType
->isIntegerType()) {
10012 Kind
= CK_IntegralToPointer
; // FIXME: null
10013 return IntToPointer
;
10016 // In general, C pointers are not compatible with ObjC object pointers,
10017 // with two exceptions:
10018 if (isa
<PointerType
>(RHSType
)) {
10019 Kind
= CK_CPointerToObjCPointerCast
;
10021 // - conversions from 'void*'
10022 if (RHSType
->isVoidPointerType()) {
10026 // - conversions to 'Class' from its redefinition type
10027 if (LHSType
->isObjCClassType() &&
10028 Context
.hasSameType(RHSType
,
10029 Context
.getObjCClassRedefinitionType())) {
10033 return IncompatiblePointer
;
10036 // Only under strict condition T^ is compatible with an Objective-C pointer.
10037 if (RHSType
->isBlockPointerType() &&
10038 LHSType
->isBlockCompatibleObjCPointerType(Context
)) {
10040 maybeExtendBlockObject(RHS
);
10041 Kind
= CK_BlockPointerToObjCPointerCast
;
10045 return Incompatible
;
10048 // Conversions from pointers that are not covered by the above.
10049 if (isa
<PointerType
>(RHSType
)) {
10051 if (LHSType
== Context
.BoolTy
) {
10052 Kind
= CK_PointerToBoolean
;
10057 if (LHSType
->isIntegerType()) {
10058 Kind
= CK_PointerToIntegral
;
10059 return PointerToInt
;
10062 return Incompatible
;
10065 // Conversions from Objective-C pointers that are not covered by the above.
10066 if (isa
<ObjCObjectPointerType
>(RHSType
)) {
10068 if (LHSType
== Context
.BoolTy
) {
10069 Kind
= CK_PointerToBoolean
;
10074 if (LHSType
->isIntegerType()) {
10075 Kind
= CK_PointerToIntegral
;
10076 return PointerToInt
;
10079 return Incompatible
;
10082 // struct A -> struct B
10083 if (isa
<TagType
>(LHSType
) && isa
<TagType
>(RHSType
)) {
10084 if (Context
.typesAreCompatible(LHSType
, RHSType
)) {
10090 if (LHSType
->isSamplerT() && RHSType
->isIntegerType()) {
10091 Kind
= CK_IntToOCLSampler
;
10095 return Incompatible
;
10098 /// Constructs a transparent union from an expression that is
10099 /// used to initialize the transparent union.
10100 static void ConstructTransparentUnion(Sema
&S
, ASTContext
&C
,
10101 ExprResult
&EResult
, QualType UnionType
,
10102 FieldDecl
*Field
) {
10103 // Build an initializer list that designates the appropriate member
10104 // of the transparent union.
10105 Expr
*E
= EResult
.get();
10106 InitListExpr
*Initializer
= new (C
) InitListExpr(C
, SourceLocation(),
10107 E
, SourceLocation());
10108 Initializer
->setType(UnionType
);
10109 Initializer
->setInitializedFieldInUnion(Field
);
10111 // Build a compound literal constructing a value of the transparent
10112 // union type from this initializer list.
10113 TypeSourceInfo
*unionTInfo
= C
.getTrivialTypeSourceInfo(UnionType
);
10114 EResult
= new (C
) CompoundLiteralExpr(SourceLocation(), unionTInfo
, UnionType
,
10115 VK_PRValue
, Initializer
, false);
10118 Sema::AssignConvertType
10119 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType
,
10121 QualType RHSType
= RHS
.get()->getType();
10123 // If the ArgType is a Union type, we want to handle a potential
10124 // transparent_union GCC extension.
10125 const RecordType
*UT
= ArgType
->getAsUnionType();
10126 if (!UT
|| !UT
->getDecl()->hasAttr
<TransparentUnionAttr
>())
10127 return Incompatible
;
10129 // The field to initialize within the transparent union.
10130 RecordDecl
*UD
= UT
->getDecl();
10131 FieldDecl
*InitField
= nullptr;
10132 // It's compatible if the expression matches any of the fields.
10133 for (auto *it
: UD
->fields()) {
10134 if (it
->getType()->isPointerType()) {
10135 // If the transparent union contains a pointer type, we allow:
10137 // 2) null pointer constant
10138 if (RHSType
->isPointerType())
10139 if (RHSType
->castAs
<PointerType
>()->getPointeeType()->isVoidType()) {
10140 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(), CK_BitCast
);
10145 if (RHS
.get()->isNullPointerConstant(Context
,
10146 Expr::NPC_ValueDependentIsNull
)) {
10147 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(),
10155 if (CheckAssignmentConstraints(it
->getType(), RHS
, Kind
)
10157 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(), Kind
);
10164 return Incompatible
;
10166 ConstructTransparentUnion(*this, Context
, RHS
, ArgType
, InitField
);
10170 Sema::AssignConvertType
10171 Sema::CheckSingleAssignmentConstraints(QualType LHSType
, ExprResult
&CallerRHS
,
10173 bool DiagnoseCFAudited
,
10175 // We need to be able to tell the caller whether we diagnosed a problem, if
10176 // they ask us to issue diagnostics.
10177 assert((ConvertRHS
|| !Diagnose
) && "can't indicate whether we diagnosed");
10179 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10180 // we can't avoid *all* modifications at the moment, so we need some somewhere
10181 // to put the updated value.
10182 ExprResult LocalRHS
= CallerRHS
;
10183 ExprResult
&RHS
= ConvertRHS
? CallerRHS
: LocalRHS
;
10185 if (const auto *LHSPtrType
= LHSType
->getAs
<PointerType
>()) {
10186 if (const auto *RHSPtrType
= RHS
.get()->getType()->getAs
<PointerType
>()) {
10187 if (RHSPtrType
->getPointeeType()->hasAttr(attr::NoDeref
) &&
10188 !LHSPtrType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
10189 Diag(RHS
.get()->getExprLoc(),
10190 diag::warn_noderef_to_dereferenceable_pointer
)
10191 << RHS
.get()->getSourceRange();
10196 if (getLangOpts().CPlusPlus
) {
10197 if (!LHSType
->isRecordType() && !LHSType
->isAtomicType()) {
10198 // C++ 5.17p3: If the left operand is not of class type, the
10199 // expression is implicitly converted (C++ 4) to the
10200 // cv-unqualified type of the left operand.
10201 QualType RHSType
= RHS
.get()->getType();
10203 RHS
= PerformImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
10206 ImplicitConversionSequence ICS
=
10207 TryImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
10208 /*SuppressUserConversions=*/false,
10209 AllowedExplicit::None
,
10210 /*InOverloadResolution=*/false,
10212 /*AllowObjCWritebackConversion=*/false);
10213 if (ICS
.isFailure())
10214 return Incompatible
;
10215 RHS
= PerformImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
10216 ICS
, AA_Assigning
);
10218 if (RHS
.isInvalid())
10219 return Incompatible
;
10220 Sema::AssignConvertType result
= Compatible
;
10221 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10222 !CheckObjCARCUnavailableWeakConversion(LHSType
, RHSType
))
10223 result
= IncompatibleObjCWeakRef
;
10227 // FIXME: Currently, we fall through and treat C++ classes like C
10229 // FIXME: We also fall through for atomics; not sure what should
10230 // happen there, though.
10231 } else if (RHS
.get()->getType() == Context
.OverloadTy
) {
10232 // As a set of extensions to C, we support overloading on functions. These
10233 // functions need to be resolved here.
10234 DeclAccessPair DAP
;
10235 if (FunctionDecl
*FD
= ResolveAddressOfOverloadedFunction(
10236 RHS
.get(), LHSType
, /*Complain=*/false, DAP
))
10237 RHS
= FixOverloadedFunctionReference(RHS
.get(), DAP
, FD
);
10239 return Incompatible
;
10242 // This check seems unnatural, however it is necessary to ensure the proper
10243 // conversion of functions/arrays. If the conversion were done for all
10244 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10245 // expressions that suppress this implicit conversion (&, sizeof). This needs
10246 // to happen before we check for null pointer conversions because C does not
10247 // undergo the same implicit conversions as C++ does above (by the calls to
10248 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10249 // lvalue to rvalue cast before checking for null pointer constraints. This
10250 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10252 // Suppress this for references: C++ 8.5.3p5.
10253 if (!LHSType
->isReferenceType()) {
10254 // FIXME: We potentially allocate here even if ConvertRHS is false.
10255 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get(), Diagnose
);
10256 if (RHS
.isInvalid())
10257 return Incompatible
;
10260 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10261 // a null pointer constant.
10262 if ((LHSType
->isPointerType() || LHSType
->isObjCObjectPointerType() ||
10263 LHSType
->isBlockPointerType()) &&
10264 RHS
.get()->isNullPointerConstant(Context
,
10265 Expr::NPC_ValueDependentIsNull
)) {
10266 if (Diagnose
|| ConvertRHS
) {
10269 CheckPointerConversion(RHS
.get(), LHSType
, Kind
, Path
,
10270 /*IgnoreBaseAccess=*/false, Diagnose
);
10272 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, Kind
, VK_PRValue
, &Path
);
10277 // OpenCL queue_t type assignment.
10278 if (LHSType
->isQueueT() && RHS
.get()->isNullPointerConstant(
10279 Context
, Expr::NPC_ValueDependentIsNull
)) {
10280 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
10285 Sema::AssignConvertType result
=
10286 CheckAssignmentConstraints(LHSType
, RHS
, Kind
, ConvertRHS
);
10288 // C99 6.5.16.1p2: The value of the right operand is converted to the
10289 // type of the assignment expression.
10290 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10291 // so that we can use references in built-in functions even in C.
10292 // The getNonReferenceType() call makes sure that the resulting expression
10293 // does not have reference type.
10294 if (result
!= Incompatible
&& RHS
.get()->getType() != LHSType
) {
10295 QualType Ty
= LHSType
.getNonLValueExprType(Context
);
10296 Expr
*E
= RHS
.get();
10298 // Check for various Objective-C errors. If we are not reporting
10299 // diagnostics and just checking for errors, e.g., during overload
10300 // resolution, return Incompatible to indicate the failure.
10301 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10302 CheckObjCConversion(SourceRange(), Ty
, E
, CCK_ImplicitConversion
,
10303 Diagnose
, DiagnoseCFAudited
) != ACR_okay
) {
10305 return Incompatible
;
10307 if (getLangOpts().ObjC
&&
10308 (CheckObjCBridgeRelatedConversions(E
->getBeginLoc(), LHSType
,
10309 E
->getType(), E
, Diagnose
) ||
10310 CheckConversionToObjCLiteral(LHSType
, E
, Diagnose
))) {
10312 return Incompatible
;
10313 // Replace the expression with a corrected version and continue so we
10314 // can find further errors.
10320 RHS
= ImpCastExprToType(E
, Ty
, Kind
);
10327 /// The original operand to an operator, prior to the application of the usual
10328 /// arithmetic conversions and converting the arguments of a builtin operator
10330 struct OriginalOperand
{
10331 explicit OriginalOperand(Expr
*Op
) : Orig(Op
), Conversion(nullptr) {
10332 if (auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(Op
))
10333 Op
= MTE
->getSubExpr();
10334 if (auto *BTE
= dyn_cast
<CXXBindTemporaryExpr
>(Op
))
10335 Op
= BTE
->getSubExpr();
10336 if (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(Op
)) {
10337 Orig
= ICE
->getSubExprAsWritten();
10338 Conversion
= ICE
->getConversionFunction();
10342 QualType
getType() const { return Orig
->getType(); }
10345 NamedDecl
*Conversion
;
10349 QualType
Sema::InvalidOperands(SourceLocation Loc
, ExprResult
&LHS
,
10351 OriginalOperand
OrigLHS(LHS
.get()), OrigRHS(RHS
.get());
10353 Diag(Loc
, diag::err_typecheck_invalid_operands
)
10354 << OrigLHS
.getType() << OrigRHS
.getType()
10355 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
10357 // If a user-defined conversion was applied to either of the operands prior
10358 // to applying the built-in operator rules, tell the user about it.
10359 if (OrigLHS
.Conversion
) {
10360 Diag(OrigLHS
.Conversion
->getLocation(),
10361 diag::note_typecheck_invalid_operands_converted
)
10362 << 0 << LHS
.get()->getType();
10364 if (OrigRHS
.Conversion
) {
10365 Diag(OrigRHS
.Conversion
->getLocation(),
10366 diag::note_typecheck_invalid_operands_converted
)
10367 << 1 << RHS
.get()->getType();
10373 // Diagnose cases where a scalar was implicitly converted to a vector and
10374 // diagnose the underlying types. Otherwise, diagnose the error
10375 // as invalid vector logical operands for non-C++ cases.
10376 QualType
Sema::InvalidLogicalVectorOperands(SourceLocation Loc
, ExprResult
&LHS
,
10378 QualType LHSType
= LHS
.get()->IgnoreImpCasts()->getType();
10379 QualType RHSType
= RHS
.get()->IgnoreImpCasts()->getType();
10381 bool LHSNatVec
= LHSType
->isVectorType();
10382 bool RHSNatVec
= RHSType
->isVectorType();
10384 if (!(LHSNatVec
&& RHSNatVec
)) {
10385 Expr
*Vector
= LHSNatVec
? LHS
.get() : RHS
.get();
10386 Expr
*NonVector
= !LHSNatVec
? LHS
.get() : RHS
.get();
10387 Diag(Loc
, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict
)
10388 << 0 << Vector
->getType() << NonVector
->IgnoreImpCasts()->getType()
10389 << Vector
->getSourceRange();
10393 Diag(Loc
, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict
)
10394 << 1 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10395 << RHS
.get()->getSourceRange();
10400 /// Try to convert a value of non-vector type to a vector type by converting
10401 /// the type to the element type of the vector and then performing a splat.
10402 /// If the language is OpenCL, we only use conversions that promote scalar
10403 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10404 /// for float->int.
10406 /// OpenCL V2.0 6.2.6.p2:
10407 /// An error shall occur if any scalar operand type has greater rank
10408 /// than the type of the vector element.
10410 /// \param scalar - if non-null, actually perform the conversions
10411 /// \return true if the operation fails (but without diagnosing the failure)
10412 static bool tryVectorConvertAndSplat(Sema
&S
, ExprResult
*scalar
,
10414 QualType vectorEltTy
,
10416 unsigned &DiagID
) {
10417 // The conversion to apply to the scalar before splatting it,
10419 CastKind scalarCast
= CK_NoOp
;
10421 if (vectorEltTy
->isIntegralType(S
.Context
)) {
10422 if (S
.getLangOpts().OpenCL
&& (scalarTy
->isRealFloatingType() ||
10423 (scalarTy
->isIntegerType() &&
10424 S
.Context
.getIntegerTypeOrder(vectorEltTy
, scalarTy
) < 0))) {
10425 DiagID
= diag::err_opencl_scalar_type_rank_greater_than_vector_type
;
10428 if (!scalarTy
->isIntegralType(S
.Context
))
10430 scalarCast
= CK_IntegralCast
;
10431 } else if (vectorEltTy
->isRealFloatingType()) {
10432 if (scalarTy
->isRealFloatingType()) {
10433 if (S
.getLangOpts().OpenCL
&&
10434 S
.Context
.getFloatingTypeOrder(vectorEltTy
, scalarTy
) < 0) {
10435 DiagID
= diag::err_opencl_scalar_type_rank_greater_than_vector_type
;
10438 scalarCast
= CK_FloatingCast
;
10440 else if (scalarTy
->isIntegralType(S
.Context
))
10441 scalarCast
= CK_IntegralToFloating
;
10448 // Adjust scalar if desired.
10450 if (scalarCast
!= CK_NoOp
)
10451 *scalar
= S
.ImpCastExprToType(scalar
->get(), vectorEltTy
, scalarCast
);
10452 *scalar
= S
.ImpCastExprToType(scalar
->get(), vectorTy
, CK_VectorSplat
);
10457 /// Convert vector E to a vector with the same number of elements but different
10459 static ExprResult
convertVector(Expr
*E
, QualType ElementType
, Sema
&S
) {
10460 const auto *VecTy
= E
->getType()->getAs
<VectorType
>();
10461 assert(VecTy
&& "Expression E must be a vector");
10462 QualType NewVecTy
=
10463 VecTy
->isExtVectorType()
10464 ? S
.Context
.getExtVectorType(ElementType
, VecTy
->getNumElements())
10465 : S
.Context
.getVectorType(ElementType
, VecTy
->getNumElements(),
10466 VecTy
->getVectorKind());
10468 // Look through the implicit cast. Return the subexpression if its type is
10470 if (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
10471 if (ICE
->getSubExpr()->getType() == NewVecTy
)
10472 return ICE
->getSubExpr();
10474 auto Cast
= ElementType
->isIntegerType() ? CK_IntegralCast
: CK_FloatingCast
;
10475 return S
.ImpCastExprToType(E
, NewVecTy
, Cast
);
10478 /// Test if a (constant) integer Int can be casted to another integer type
10479 /// IntTy without losing precision.
10480 static bool canConvertIntToOtherIntTy(Sema
&S
, ExprResult
*Int
,
10481 QualType OtherIntTy
) {
10482 QualType IntTy
= Int
->get()->getType().getUnqualifiedType();
10484 // Reject cases where the value of the Int is unknown as that would
10485 // possibly cause truncation, but accept cases where the scalar can be
10486 // demoted without loss of precision.
10487 Expr::EvalResult EVResult
;
10488 bool CstInt
= Int
->get()->EvaluateAsInt(EVResult
, S
.Context
);
10489 int Order
= S
.Context
.getIntegerTypeOrder(OtherIntTy
, IntTy
);
10490 bool IntSigned
= IntTy
->hasSignedIntegerRepresentation();
10491 bool OtherIntSigned
= OtherIntTy
->hasSignedIntegerRepresentation();
10494 // If the scalar is constant and is of a higher order and has more active
10495 // bits that the vector element type, reject it.
10496 llvm::APSInt Result
= EVResult
.Val
.getInt();
10497 unsigned NumBits
= IntSigned
10498 ? (Result
.isNegative() ? Result
.getMinSignedBits()
10499 : Result
.getActiveBits())
10500 : Result
.getActiveBits();
10501 if (Order
< 0 && S
.Context
.getIntWidth(OtherIntTy
) < NumBits
)
10504 // If the signedness of the scalar type and the vector element type
10505 // differs and the number of bits is greater than that of the vector
10506 // element reject it.
10507 return (IntSigned
!= OtherIntSigned
&&
10508 NumBits
> S
.Context
.getIntWidth(OtherIntTy
));
10511 // Reject cases where the value of the scalar is not constant and it's
10512 // order is greater than that of the vector element type.
10513 return (Order
< 0);
10516 /// Test if a (constant) integer Int can be casted to floating point type
10517 /// FloatTy without losing precision.
10518 static bool canConvertIntTyToFloatTy(Sema
&S
, ExprResult
*Int
,
10519 QualType FloatTy
) {
10520 QualType IntTy
= Int
->get()->getType().getUnqualifiedType();
10522 // Determine if the integer constant can be expressed as a floating point
10523 // number of the appropriate type.
10524 Expr::EvalResult EVResult
;
10525 bool CstInt
= Int
->get()->EvaluateAsInt(EVResult
, S
.Context
);
10529 // Reject constants that would be truncated if they were converted to
10530 // the floating point type. Test by simple to/from conversion.
10531 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10532 // could be avoided if there was a convertFromAPInt method
10533 // which could signal back if implicit truncation occurred.
10534 llvm::APSInt Result
= EVResult
.Val
.getInt();
10535 llvm::APFloat
Float(S
.Context
.getFloatTypeSemantics(FloatTy
));
10536 Float
.convertFromAPInt(Result
, IntTy
->hasSignedIntegerRepresentation(),
10537 llvm::APFloat::rmTowardZero
);
10538 llvm::APSInt
ConvertBack(S
.Context
.getIntWidth(IntTy
),
10539 !IntTy
->hasSignedIntegerRepresentation());
10540 bool Ignored
= false;
10541 Float
.convertToInteger(ConvertBack
, llvm::APFloat::rmNearestTiesToEven
,
10543 if (Result
!= ConvertBack
)
10546 // Reject types that cannot be fully encoded into the mantissa of
10548 Bits
= S
.Context
.getTypeSize(IntTy
);
10549 unsigned FloatPrec
= llvm::APFloat::semanticsPrecision(
10550 S
.Context
.getFloatTypeSemantics(FloatTy
));
10551 if (Bits
> FloatPrec
)
10558 /// Attempt to convert and splat Scalar into a vector whose types matches
10559 /// Vector following GCC conversion rules. The rule is that implicit
10560 /// conversion can occur when Scalar can be casted to match Vector's element
10561 /// type without causing truncation of Scalar.
10562 static bool tryGCCVectorConvertAndSplat(Sema
&S
, ExprResult
*Scalar
,
10563 ExprResult
*Vector
) {
10564 QualType ScalarTy
= Scalar
->get()->getType().getUnqualifiedType();
10565 QualType VectorTy
= Vector
->get()->getType().getUnqualifiedType();
10566 QualType VectorEltTy
;
10568 if (const auto *VT
= VectorTy
->getAs
<VectorType
>()) {
10569 assert(!isa
<ExtVectorType
>(VT
) &&
10570 "ExtVectorTypes should not be handled here!");
10571 VectorEltTy
= VT
->getElementType();
10572 } else if (VectorTy
->isVLSTBuiltinType()) {
10574 VectorTy
->castAs
<BuiltinType
>()->getSveEltType(S
.getASTContext());
10576 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10579 // Reject cases where the vector element type or the scalar element type are
10580 // not integral or floating point types.
10581 if (!VectorEltTy
->isArithmeticType() || !ScalarTy
->isArithmeticType())
10584 // The conversion to apply to the scalar before splatting it,
10586 CastKind ScalarCast
= CK_NoOp
;
10588 // Accept cases where the vector elements are integers and the scalar is
10590 // FIXME: Notionally if the scalar was a floating point value with a precise
10591 // integral representation, we could cast it to an appropriate integer
10592 // type and then perform the rest of the checks here. GCC will perform
10593 // this conversion in some cases as determined by the input language.
10594 // We should accept it on a language independent basis.
10595 if (VectorEltTy
->isIntegralType(S
.Context
) &&
10596 ScalarTy
->isIntegralType(S
.Context
) &&
10597 S
.Context
.getIntegerTypeOrder(VectorEltTy
, ScalarTy
)) {
10599 if (canConvertIntToOtherIntTy(S
, Scalar
, VectorEltTy
))
10602 ScalarCast
= CK_IntegralCast
;
10603 } else if (VectorEltTy
->isIntegralType(S
.Context
) &&
10604 ScalarTy
->isRealFloatingType()) {
10605 if (S
.Context
.getTypeSize(VectorEltTy
) == S
.Context
.getTypeSize(ScalarTy
))
10606 ScalarCast
= CK_FloatingToIntegral
;
10609 } else if (VectorEltTy
->isRealFloatingType()) {
10610 if (ScalarTy
->isRealFloatingType()) {
10612 // Reject cases where the scalar type is not a constant and has a higher
10613 // Order than the vector element type.
10614 llvm::APFloat
Result(0.0);
10616 // Determine whether this is a constant scalar. In the event that the
10617 // value is dependent (and thus cannot be evaluated by the constant
10618 // evaluator), skip the evaluation. This will then diagnose once the
10619 // expression is instantiated.
10620 bool CstScalar
= Scalar
->get()->isValueDependent() ||
10621 Scalar
->get()->EvaluateAsFloat(Result
, S
.Context
);
10622 int Order
= S
.Context
.getFloatingTypeOrder(VectorEltTy
, ScalarTy
);
10623 if (!CstScalar
&& Order
< 0)
10626 // If the scalar cannot be safely casted to the vector element type,
10629 bool Truncated
= false;
10630 Result
.convert(S
.Context
.getFloatTypeSemantics(VectorEltTy
),
10631 llvm::APFloat::rmNearestTiesToEven
, &Truncated
);
10636 ScalarCast
= CK_FloatingCast
;
10637 } else if (ScalarTy
->isIntegralType(S
.Context
)) {
10638 if (canConvertIntTyToFloatTy(S
, Scalar
, VectorEltTy
))
10641 ScalarCast
= CK_IntegralToFloating
;
10644 } else if (ScalarTy
->isEnumeralType())
10647 // Adjust scalar if desired.
10649 if (ScalarCast
!= CK_NoOp
)
10650 *Scalar
= S
.ImpCastExprToType(Scalar
->get(), VectorEltTy
, ScalarCast
);
10651 *Scalar
= S
.ImpCastExprToType(Scalar
->get(), VectorTy
, CK_VectorSplat
);
10656 QualType
Sema::CheckVectorOperands(ExprResult
&LHS
, ExprResult
&RHS
,
10657 SourceLocation Loc
, bool IsCompAssign
,
10658 bool AllowBothBool
,
10659 bool AllowBoolConversions
,
10660 bool AllowBoolOperation
,
10661 bool ReportInvalid
) {
10662 if (!IsCompAssign
) {
10663 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
10664 if (LHS
.isInvalid())
10667 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
10668 if (RHS
.isInvalid())
10671 // For conversion purposes, we ignore any qualifiers.
10672 // For example, "const float" and "float" are equivalent.
10673 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
10674 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
10676 const VectorType
*LHSVecType
= LHSType
->getAs
<VectorType
>();
10677 const VectorType
*RHSVecType
= RHSType
->getAs
<VectorType
>();
10678 assert(LHSVecType
|| RHSVecType
);
10680 if ((LHSVecType
&& LHSVecType
->getElementType()->isBFloat16Type()) ||
10681 (RHSVecType
&& RHSVecType
->getElementType()->isBFloat16Type()))
10682 return ReportInvalid
? InvalidOperands(Loc
, LHS
, RHS
) : QualType();
10684 // AltiVec-style "vector bool op vector bool" combinations are allowed
10685 // for some operators but not others.
10686 if (!AllowBothBool
&&
10687 LHSVecType
&& LHSVecType
->getVectorKind() == VectorType::AltiVecBool
&&
10688 RHSVecType
&& RHSVecType
->getVectorKind() == VectorType::AltiVecBool
)
10689 return ReportInvalid
? InvalidOperands(Loc
, LHS
, RHS
) : QualType();
10691 // This operation may not be performed on boolean vectors.
10692 if (!AllowBoolOperation
&&
10693 (LHSType
->isExtVectorBoolType() || RHSType
->isExtVectorBoolType()))
10694 return ReportInvalid
? InvalidOperands(Loc
, LHS
, RHS
) : QualType();
10696 // If the vector types are identical, return.
10697 if (Context
.hasSameType(LHSType
, RHSType
))
10698 return Context
.getCommonSugaredType(LHSType
, RHSType
);
10700 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
10701 if (LHSVecType
&& RHSVecType
&&
10702 Context
.areCompatibleVectorTypes(LHSType
, RHSType
)) {
10703 if (isa
<ExtVectorType
>(LHSVecType
)) {
10704 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
10709 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
10713 // AllowBoolConversions says that bool and non-bool AltiVec vectors
10714 // can be mixed, with the result being the non-bool type. The non-bool
10715 // operand must have integer element type.
10716 if (AllowBoolConversions
&& LHSVecType
&& RHSVecType
&&
10717 LHSVecType
->getNumElements() == RHSVecType
->getNumElements() &&
10718 (Context
.getTypeSize(LHSVecType
->getElementType()) ==
10719 Context
.getTypeSize(RHSVecType
->getElementType()))) {
10720 if (LHSVecType
->getVectorKind() == VectorType::AltiVecVector
&&
10721 LHSVecType
->getElementType()->isIntegerType() &&
10722 RHSVecType
->getVectorKind() == VectorType::AltiVecBool
) {
10723 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
10726 if (!IsCompAssign
&&
10727 LHSVecType
->getVectorKind() == VectorType::AltiVecBool
&&
10728 RHSVecType
->getVectorKind() == VectorType::AltiVecVector
&&
10729 RHSVecType
->getElementType()->isIntegerType()) {
10730 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
10735 // Expressions containing fixed-length and sizeless SVE vectors are invalid
10736 // since the ambiguity can affect the ABI.
10737 auto IsSveConversion
= [](QualType FirstType
, QualType SecondType
) {
10738 const VectorType
*VecType
= SecondType
->getAs
<VectorType
>();
10739 return FirstType
->isSizelessBuiltinType() && VecType
&&
10740 (VecType
->getVectorKind() == VectorType::SveFixedLengthDataVector
||
10741 VecType
->getVectorKind() ==
10742 VectorType::SveFixedLengthPredicateVector
);
10745 if (IsSveConversion(LHSType
, RHSType
) || IsSveConversion(RHSType
, LHSType
)) {
10746 Diag(Loc
, diag::err_typecheck_sve_ambiguous
) << LHSType
<< RHSType
;
10750 // Expressions containing GNU and SVE (fixed or sizeless) vectors are invalid
10751 // since the ambiguity can affect the ABI.
10752 auto IsSveGnuConversion
= [](QualType FirstType
, QualType SecondType
) {
10753 const VectorType
*FirstVecType
= FirstType
->getAs
<VectorType
>();
10754 const VectorType
*SecondVecType
= SecondType
->getAs
<VectorType
>();
10756 if (FirstVecType
&& SecondVecType
)
10757 return FirstVecType
->getVectorKind() == VectorType::GenericVector
&&
10758 (SecondVecType
->getVectorKind() ==
10759 VectorType::SveFixedLengthDataVector
||
10760 SecondVecType
->getVectorKind() ==
10761 VectorType::SveFixedLengthPredicateVector
);
10763 return FirstType
->isSizelessBuiltinType() && SecondVecType
&&
10764 SecondVecType
->getVectorKind() == VectorType::GenericVector
;
10767 if (IsSveGnuConversion(LHSType
, RHSType
) ||
10768 IsSveGnuConversion(RHSType
, LHSType
)) {
10769 Diag(Loc
, diag::err_typecheck_sve_gnu_ambiguous
) << LHSType
<< RHSType
;
10773 // If there's a vector type and a scalar, try to convert the scalar to
10774 // the vector element type and splat.
10775 unsigned DiagID
= diag::err_typecheck_vector_not_convertable
;
10777 if (isa
<ExtVectorType
>(LHSVecType
)) {
10778 if (!tryVectorConvertAndSplat(*this, &RHS
, RHSType
,
10779 LHSVecType
->getElementType(), LHSType
,
10783 if (!tryGCCVectorConvertAndSplat(*this, &RHS
, &LHS
))
10788 if (isa
<ExtVectorType
>(RHSVecType
)) {
10789 if (!tryVectorConvertAndSplat(*this, (IsCompAssign
? nullptr : &LHS
),
10790 LHSType
, RHSVecType
->getElementType(),
10794 if (LHS
.get()->isLValue() ||
10795 !tryGCCVectorConvertAndSplat(*this, &LHS
, &RHS
))
10800 // FIXME: The code below also handles conversion between vectors and
10801 // non-scalars, we should break this down into fine grained specific checks
10802 // and emit proper diagnostics.
10803 QualType VecType
= LHSVecType
? LHSType
: RHSType
;
10804 const VectorType
*VT
= LHSVecType
? LHSVecType
: RHSVecType
;
10805 QualType OtherType
= LHSVecType
? RHSType
: LHSType
;
10806 ExprResult
*OtherExpr
= LHSVecType
? &RHS
: &LHS
;
10807 if (isLaxVectorConversion(OtherType
, VecType
)) {
10808 if (anyAltivecTypes(RHSType
, LHSType
) &&
10809 !areSameVectorElemTypes(RHSType
, LHSType
))
10810 Diag(Loc
, diag::warn_deprecated_lax_vec_conv_all
) << RHSType
<< LHSType
;
10811 // If we're allowing lax vector conversions, only the total (data) size
10812 // needs to be the same. For non compound assignment, if one of the types is
10813 // scalar, the result is always the vector type.
10814 if (!IsCompAssign
) {
10815 *OtherExpr
= ImpCastExprToType(OtherExpr
->get(), VecType
, CK_BitCast
);
10817 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
10818 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
10819 // type. Note that this is already done by non-compound assignments in
10820 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
10821 // <1 x T> -> T. The result is also a vector type.
10822 } else if (OtherType
->isExtVectorType() || OtherType
->isVectorType() ||
10823 (OtherType
->isScalarType() && VT
->getNumElements() == 1)) {
10824 ExprResult
*RHSExpr
= &RHS
;
10825 *RHSExpr
= ImpCastExprToType(RHSExpr
->get(), LHSType
, CK_BitCast
);
10830 // Okay, the expression is invalid.
10832 // If there's a non-vector, non-real operand, diagnose that.
10833 if ((!RHSVecType
&& !RHSType
->isRealType()) ||
10834 (!LHSVecType
&& !LHSType
->isRealType())) {
10835 Diag(Loc
, diag::err_typecheck_vector_not_convertable_non_scalar
)
10836 << LHSType
<< RHSType
10837 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
10841 // OpenCL V1.1 6.2.6.p1:
10842 // If the operands are of more than one vector type, then an error shall
10843 // occur. Implicit conversions between vector types are not permitted, per
10845 if (getLangOpts().OpenCL
&&
10846 RHSVecType
&& isa
<ExtVectorType
>(RHSVecType
) &&
10847 LHSVecType
&& isa
<ExtVectorType
>(LHSVecType
)) {
10848 Diag(Loc
, diag::err_opencl_implicit_vector_conversion
) << LHSType
10854 // If there is a vector type that is not a ExtVector and a scalar, we reach
10855 // this point if scalar could not be converted to the vector's element type
10856 // without truncation.
10857 if ((RHSVecType
&& !isa
<ExtVectorType
>(RHSVecType
)) ||
10858 (LHSVecType
&& !isa
<ExtVectorType
>(LHSVecType
))) {
10859 QualType Scalar
= LHSVecType
? RHSType
: LHSType
;
10860 QualType Vector
= LHSVecType
? LHSType
: RHSType
;
10861 unsigned ScalarOrVector
= LHSVecType
&& RHSVecType
? 1 : 0;
10863 diag::err_typecheck_vector_not_convertable_implict_truncation
)
10864 << ScalarOrVector
<< Scalar
<< Vector
;
10869 // Otherwise, use the generic diagnostic.
10871 << LHSType
<< RHSType
10872 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
10876 QualType
Sema::CheckSizelessVectorOperands(ExprResult
&LHS
, ExprResult
&RHS
,
10877 SourceLocation Loc
,
10879 ArithConvKind OperationKind
) {
10880 if (!IsCompAssign
) {
10881 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
10882 if (LHS
.isInvalid())
10885 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
10886 if (RHS
.isInvalid())
10889 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
10890 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
10892 const BuiltinType
*LHSBuiltinTy
= LHSType
->getAs
<BuiltinType
>();
10893 const BuiltinType
*RHSBuiltinTy
= RHSType
->getAs
<BuiltinType
>();
10895 unsigned DiagID
= diag::err_typecheck_invalid_operands
;
10896 if ((OperationKind
== ACK_Arithmetic
) &&
10897 ((LHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool()) ||
10898 (RHSBuiltinTy
&& RHSBuiltinTy
->isSVEBool()))) {
10899 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10900 << RHS
.get()->getSourceRange();
10904 if (Context
.hasSameType(LHSType
, RHSType
))
10907 if (LHSType
->isVLSTBuiltinType() && !RHSType
->isVLSTBuiltinType()) {
10908 if (!tryGCCVectorConvertAndSplat(*this, &RHS
, &LHS
))
10911 if (RHSType
->isVLSTBuiltinType() && !LHSType
->isVLSTBuiltinType()) {
10912 if (LHS
.get()->isLValue() ||
10913 !tryGCCVectorConvertAndSplat(*this, &LHS
, &RHS
))
10917 if ((!LHSType
->isVLSTBuiltinType() && !LHSType
->isRealType()) ||
10918 (!RHSType
->isVLSTBuiltinType() && !RHSType
->isRealType())) {
10919 Diag(Loc
, diag::err_typecheck_vector_not_convertable_non_scalar
)
10920 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10921 << RHS
.get()->getSourceRange();
10925 if (LHSType
->isVLSTBuiltinType() && RHSType
->isVLSTBuiltinType() &&
10926 Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
!=
10927 Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
) {
10928 Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
10929 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10930 << RHS
.get()->getSourceRange();
10934 if (LHSType
->isVLSTBuiltinType() || RHSType
->isVLSTBuiltinType()) {
10935 QualType Scalar
= LHSType
->isVLSTBuiltinType() ? RHSType
: LHSType
;
10936 QualType Vector
= LHSType
->isVLSTBuiltinType() ? LHSType
: RHSType
;
10937 bool ScalarOrVector
=
10938 LHSType
->isVLSTBuiltinType() && RHSType
->isVLSTBuiltinType();
10940 Diag(Loc
, diag::err_typecheck_vector_not_convertable_implict_truncation
)
10941 << ScalarOrVector
<< Scalar
<< Vector
;
10946 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10947 << RHS
.get()->getSourceRange();
10951 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
10952 // expression. These are mainly cases where the null pointer is used as an
10953 // integer instead of a pointer.
10954 static void checkArithmeticNull(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
10955 SourceLocation Loc
, bool IsCompare
) {
10956 // The canonical way to check for a GNU null is with isNullPointerConstant,
10957 // but we use a bit of a hack here for speed; this is a relatively
10958 // hot path, and isNullPointerConstant is slow.
10959 bool LHSNull
= isa
<GNUNullExpr
>(LHS
.get()->IgnoreParenImpCasts());
10960 bool RHSNull
= isa
<GNUNullExpr
>(RHS
.get()->IgnoreParenImpCasts());
10962 QualType NonNullType
= LHSNull
? RHS
.get()->getType() : LHS
.get()->getType();
10964 // Avoid analyzing cases where the result will either be invalid (and
10965 // diagnosed as such) or entirely valid and not something to warn about.
10966 if ((!LHSNull
&& !RHSNull
) || NonNullType
->isBlockPointerType() ||
10967 NonNullType
->isMemberPointerType() || NonNullType
->isFunctionType())
10970 // Comparison operations would not make sense with a null pointer no matter
10971 // what the other expression is.
10973 S
.Diag(Loc
, diag::warn_null_in_arithmetic_operation
)
10974 << (LHSNull
? LHS
.get()->getSourceRange() : SourceRange())
10975 << (RHSNull
? RHS
.get()->getSourceRange() : SourceRange());
10979 // The rest of the operations only make sense with a null pointer
10980 // if the other expression is a pointer.
10981 if (LHSNull
== RHSNull
|| NonNullType
->isAnyPointerType() ||
10982 NonNullType
->canDecayToPointerType())
10985 S
.Diag(Loc
, diag::warn_null_in_comparison_operation
)
10986 << LHSNull
/* LHS is NULL */ << NonNullType
10987 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
10990 static void DiagnoseDivisionSizeofPointerOrArray(Sema
&S
, Expr
*LHS
, Expr
*RHS
,
10991 SourceLocation Loc
) {
10992 const auto *LUE
= dyn_cast
<UnaryExprOrTypeTraitExpr
>(LHS
);
10993 const auto *RUE
= dyn_cast
<UnaryExprOrTypeTraitExpr
>(RHS
);
10996 if (LUE
->getKind() != UETT_SizeOf
|| LUE
->isArgumentType() ||
10997 RUE
->getKind() != UETT_SizeOf
)
11000 const Expr
*LHSArg
= LUE
->getArgumentExpr()->IgnoreParens();
11001 QualType LHSTy
= LHSArg
->getType();
11004 if (RUE
->isArgumentType())
11005 RHSTy
= RUE
->getArgumentType().getNonReferenceType();
11007 RHSTy
= RUE
->getArgumentExpr()->IgnoreParens()->getType();
11009 if (LHSTy
->isPointerType() && !RHSTy
->isPointerType()) {
11010 if (!S
.Context
.hasSameUnqualifiedType(LHSTy
->getPointeeType(), RHSTy
))
11013 S
.Diag(Loc
, diag::warn_division_sizeof_ptr
) << LHS
<< LHS
->getSourceRange();
11014 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(LHSArg
)) {
11015 if (const ValueDecl
*LHSArgDecl
= DRE
->getDecl())
11016 S
.Diag(LHSArgDecl
->getLocation(), diag::note_pointer_declared_here
)
11019 } else if (const auto *ArrayTy
= S
.Context
.getAsArrayType(LHSTy
)) {
11020 QualType ArrayElemTy
= ArrayTy
->getElementType();
11021 if (ArrayElemTy
!= S
.Context
.getBaseElementType(ArrayTy
) ||
11022 ArrayElemTy
->isDependentType() || RHSTy
->isDependentType() ||
11023 RHSTy
->isReferenceType() || ArrayElemTy
->isCharType() ||
11024 S
.Context
.getTypeSize(ArrayElemTy
) == S
.Context
.getTypeSize(RHSTy
))
11026 S
.Diag(Loc
, diag::warn_division_sizeof_array
)
11027 << LHSArg
->getSourceRange() << ArrayElemTy
<< RHSTy
;
11028 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(LHSArg
)) {
11029 if (const ValueDecl
*LHSArgDecl
= DRE
->getDecl())
11030 S
.Diag(LHSArgDecl
->getLocation(), diag::note_array_declared_here
)
11034 S
.Diag(Loc
, diag::note_precedence_silence
) << RHS
;
11038 static void DiagnoseBadDivideOrRemainderValues(Sema
& S
, ExprResult
&LHS
,
11040 SourceLocation Loc
, bool IsDiv
) {
11041 // Check for division/remainder by zero.
11042 Expr::EvalResult RHSValue
;
11043 if (!RHS
.get()->isValueDependent() &&
11044 RHS
.get()->EvaluateAsInt(RHSValue
, S
.Context
) &&
11045 RHSValue
.Val
.getInt() == 0)
11046 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
11047 S
.PDiag(diag::warn_remainder_division_by_zero
)
11048 << IsDiv
<< RHS
.get()->getSourceRange());
11051 QualType
Sema::CheckMultiplyDivideOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11052 SourceLocation Loc
,
11053 bool IsCompAssign
, bool IsDiv
) {
11054 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11056 QualType LHSTy
= LHS
.get()->getType();
11057 QualType RHSTy
= RHS
.get()->getType();
11058 if (LHSTy
->isVectorType() || RHSTy
->isVectorType())
11059 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
11060 /*AllowBothBool*/ getLangOpts().AltiVec
,
11061 /*AllowBoolConversions*/ false,
11062 /*AllowBooleanOperation*/ false,
11063 /*ReportInvalid*/ true);
11064 if (LHSTy
->isVLSTBuiltinType() || RHSTy
->isVLSTBuiltinType())
11065 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
11068 (LHSTy
->isConstantMatrixType() || RHSTy
->isConstantMatrixType()))
11069 return CheckMatrixMultiplyOperands(LHS
, RHS
, Loc
, IsCompAssign
);
11070 // For division, only matrix-by-scalar is supported. Other combinations with
11071 // matrix types are invalid.
11072 if (IsDiv
&& LHSTy
->isConstantMatrixType() && RHSTy
->isArithmeticType())
11073 return CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, IsCompAssign
);
11075 QualType compType
= UsualArithmeticConversions(
11076 LHS
, RHS
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_Arithmetic
);
11077 if (LHS
.isInvalid() || RHS
.isInvalid())
11081 if (compType
.isNull() || !compType
->isArithmeticType())
11082 return InvalidOperands(Loc
, LHS
, RHS
);
11084 DiagnoseBadDivideOrRemainderValues(*this, LHS
, RHS
, Loc
, IsDiv
);
11085 DiagnoseDivisionSizeofPointerOrArray(*this, LHS
.get(), RHS
.get(), Loc
);
11090 QualType
Sema::CheckRemainderOperands(
11091 ExprResult
&LHS
, ExprResult
&RHS
, SourceLocation Loc
, bool IsCompAssign
) {
11092 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11094 if (LHS
.get()->getType()->isVectorType() ||
11095 RHS
.get()->getType()->isVectorType()) {
11096 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
11097 RHS
.get()->getType()->hasIntegerRepresentation())
11098 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
11099 /*AllowBothBool*/ getLangOpts().AltiVec
,
11100 /*AllowBoolConversions*/ false,
11101 /*AllowBooleanOperation*/ false,
11102 /*ReportInvalid*/ true);
11103 return InvalidOperands(Loc
, LHS
, RHS
);
11106 if (LHS
.get()->getType()->isVLSTBuiltinType() ||
11107 RHS
.get()->getType()->isVLSTBuiltinType()) {
11108 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
11109 RHS
.get()->getType()->hasIntegerRepresentation())
11110 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
11113 return InvalidOperands(Loc
, LHS
, RHS
);
11116 QualType compType
= UsualArithmeticConversions(
11117 LHS
, RHS
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_Arithmetic
);
11118 if (LHS
.isInvalid() || RHS
.isInvalid())
11121 if (compType
.isNull() || !compType
->isIntegerType())
11122 return InvalidOperands(Loc
, LHS
, RHS
);
11123 DiagnoseBadDivideOrRemainderValues(*this, LHS
, RHS
, Loc
, false /* IsDiv */);
11127 /// Diagnose invalid arithmetic on two void pointers.
11128 static void diagnoseArithmeticOnTwoVoidPointers(Sema
&S
, SourceLocation Loc
,
11129 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11130 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
11131 ? diag::err_typecheck_pointer_arith_void_type
11132 : diag::ext_gnu_void_ptr
)
11133 << 1 /* two pointers */ << LHSExpr
->getSourceRange()
11134 << RHSExpr
->getSourceRange();
11137 /// Diagnose invalid arithmetic on a void pointer.
11138 static void diagnoseArithmeticOnVoidPointer(Sema
&S
, SourceLocation Loc
,
11140 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
11141 ? diag::err_typecheck_pointer_arith_void_type
11142 : diag::ext_gnu_void_ptr
)
11143 << 0 /* one pointer */ << Pointer
->getSourceRange();
11146 /// Diagnose invalid arithmetic on a null pointer.
11148 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11149 /// idiom, which we recognize as a GNU extension.
11151 static void diagnoseArithmeticOnNullPointer(Sema
&S
, SourceLocation Loc
,
11152 Expr
*Pointer
, bool IsGNUIdiom
) {
11154 S
.Diag(Loc
, diag::warn_gnu_null_ptr_arith
)
11155 << Pointer
->getSourceRange();
11157 S
.Diag(Loc
, diag::warn_pointer_arith_null_ptr
)
11158 << S
.getLangOpts().CPlusPlus
<< Pointer
->getSourceRange();
11161 /// Diagnose invalid subraction on a null pointer.
11163 static void diagnoseSubtractionOnNullPointer(Sema
&S
, SourceLocation Loc
,
11164 Expr
*Pointer
, bool BothNull
) {
11165 // Null - null is valid in C++ [expr.add]p7
11166 if (BothNull
&& S
.getLangOpts().CPlusPlus
)
11169 // Is this s a macro from a system header?
11170 if (S
.Diags
.getSuppressSystemWarnings() && S
.SourceMgr
.isInSystemMacro(Loc
))
11173 S
.DiagRuntimeBehavior(Loc
, Pointer
,
11174 S
.PDiag(diag::warn_pointer_sub_null_ptr
)
11175 << S
.getLangOpts().CPlusPlus
11176 << Pointer
->getSourceRange());
11179 /// Diagnose invalid arithmetic on two function pointers.
11180 static void diagnoseArithmeticOnTwoFunctionPointers(Sema
&S
, SourceLocation Loc
,
11181 Expr
*LHS
, Expr
*RHS
) {
11182 assert(LHS
->getType()->isAnyPointerType());
11183 assert(RHS
->getType()->isAnyPointerType());
11184 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
11185 ? diag::err_typecheck_pointer_arith_function_type
11186 : diag::ext_gnu_ptr_func_arith
)
11187 << 1 /* two pointers */ << LHS
->getType()->getPointeeType()
11188 // We only show the second type if it differs from the first.
11189 << (unsigned)!S
.Context
.hasSameUnqualifiedType(LHS
->getType(),
11191 << RHS
->getType()->getPointeeType()
11192 << LHS
->getSourceRange() << RHS
->getSourceRange();
11195 /// Diagnose invalid arithmetic on a function pointer.
11196 static void diagnoseArithmeticOnFunctionPointer(Sema
&S
, SourceLocation Loc
,
11198 assert(Pointer
->getType()->isAnyPointerType());
11199 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
11200 ? diag::err_typecheck_pointer_arith_function_type
11201 : diag::ext_gnu_ptr_func_arith
)
11202 << 0 /* one pointer */ << Pointer
->getType()->getPointeeType()
11203 << 0 /* one pointer, so only one type */
11204 << Pointer
->getSourceRange();
11207 /// Emit error if Operand is incomplete pointer type
11209 /// \returns True if pointer has incomplete type
11210 static bool checkArithmeticIncompletePointerType(Sema
&S
, SourceLocation Loc
,
11212 QualType ResType
= Operand
->getType();
11213 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
11214 ResType
= ResAtomicType
->getValueType();
11216 assert(ResType
->isAnyPointerType() && !ResType
->isDependentType());
11217 QualType PointeeTy
= ResType
->getPointeeType();
11218 return S
.RequireCompleteSizedType(
11220 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type
,
11221 Operand
->getSourceRange());
11224 /// Check the validity of an arithmetic pointer operand.
11226 /// If the operand has pointer type, this code will check for pointer types
11227 /// which are invalid in arithmetic operations. These will be diagnosed
11228 /// appropriately, including whether or not the use is supported as an
11231 /// \returns True when the operand is valid to use (even if as an extension).
11232 static bool checkArithmeticOpPointerOperand(Sema
&S
, SourceLocation Loc
,
11234 QualType ResType
= Operand
->getType();
11235 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
11236 ResType
= ResAtomicType
->getValueType();
11238 if (!ResType
->isAnyPointerType()) return true;
11240 QualType PointeeTy
= ResType
->getPointeeType();
11241 if (PointeeTy
->isVoidType()) {
11242 diagnoseArithmeticOnVoidPointer(S
, Loc
, Operand
);
11243 return !S
.getLangOpts().CPlusPlus
;
11245 if (PointeeTy
->isFunctionType()) {
11246 diagnoseArithmeticOnFunctionPointer(S
, Loc
, Operand
);
11247 return !S
.getLangOpts().CPlusPlus
;
11250 if (checkArithmeticIncompletePointerType(S
, Loc
, Operand
)) return false;
11255 /// Check the validity of a binary arithmetic operation w.r.t. pointer
11258 /// This routine will diagnose any invalid arithmetic on pointer operands much
11259 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
11260 /// for emitting a single diagnostic even for operations where both LHS and RHS
11261 /// are (potentially problematic) pointers.
11263 /// \returns True when the operand is valid to use (even if as an extension).
11264 static bool checkArithmeticBinOpPointerOperands(Sema
&S
, SourceLocation Loc
,
11265 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11266 bool isLHSPointer
= LHSExpr
->getType()->isAnyPointerType();
11267 bool isRHSPointer
= RHSExpr
->getType()->isAnyPointerType();
11268 if (!isLHSPointer
&& !isRHSPointer
) return true;
11270 QualType LHSPointeeTy
, RHSPointeeTy
;
11271 if (isLHSPointer
) LHSPointeeTy
= LHSExpr
->getType()->getPointeeType();
11272 if (isRHSPointer
) RHSPointeeTy
= RHSExpr
->getType()->getPointeeType();
11274 // if both are pointers check if operation is valid wrt address spaces
11275 if (isLHSPointer
&& isRHSPointer
) {
11276 if (!LHSPointeeTy
.isAddressSpaceOverlapping(RHSPointeeTy
)) {
11278 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
11279 << LHSExpr
->getType() << RHSExpr
->getType() << 1 /*arithmetic op*/
11280 << LHSExpr
->getSourceRange() << RHSExpr
->getSourceRange();
11285 // Check for arithmetic on pointers to incomplete types.
11286 bool isLHSVoidPtr
= isLHSPointer
&& LHSPointeeTy
->isVoidType();
11287 bool isRHSVoidPtr
= isRHSPointer
&& RHSPointeeTy
->isVoidType();
11288 if (isLHSVoidPtr
|| isRHSVoidPtr
) {
11289 if (!isRHSVoidPtr
) diagnoseArithmeticOnVoidPointer(S
, Loc
, LHSExpr
);
11290 else if (!isLHSVoidPtr
) diagnoseArithmeticOnVoidPointer(S
, Loc
, RHSExpr
);
11291 else diagnoseArithmeticOnTwoVoidPointers(S
, Loc
, LHSExpr
, RHSExpr
);
11293 return !S
.getLangOpts().CPlusPlus
;
11296 bool isLHSFuncPtr
= isLHSPointer
&& LHSPointeeTy
->isFunctionType();
11297 bool isRHSFuncPtr
= isRHSPointer
&& RHSPointeeTy
->isFunctionType();
11298 if (isLHSFuncPtr
|| isRHSFuncPtr
) {
11299 if (!isRHSFuncPtr
) diagnoseArithmeticOnFunctionPointer(S
, Loc
, LHSExpr
);
11300 else if (!isLHSFuncPtr
) diagnoseArithmeticOnFunctionPointer(S
, Loc
,
11302 else diagnoseArithmeticOnTwoFunctionPointers(S
, Loc
, LHSExpr
, RHSExpr
);
11304 return !S
.getLangOpts().CPlusPlus
;
11307 if (isLHSPointer
&& checkArithmeticIncompletePointerType(S
, Loc
, LHSExpr
))
11309 if (isRHSPointer
&& checkArithmeticIncompletePointerType(S
, Loc
, RHSExpr
))
11315 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11317 static void diagnoseStringPlusInt(Sema
&Self
, SourceLocation OpLoc
,
11318 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11319 StringLiteral
* StrExpr
= dyn_cast
<StringLiteral
>(LHSExpr
->IgnoreImpCasts());
11320 Expr
* IndexExpr
= RHSExpr
;
11322 StrExpr
= dyn_cast
<StringLiteral
>(RHSExpr
->IgnoreImpCasts());
11323 IndexExpr
= LHSExpr
;
11326 bool IsStringPlusInt
= StrExpr
&&
11327 IndexExpr
->getType()->isIntegralOrUnscopedEnumerationType();
11328 if (!IsStringPlusInt
|| IndexExpr
->isValueDependent())
11331 SourceRange
DiagRange(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
11332 Self
.Diag(OpLoc
, diag::warn_string_plus_int
)
11333 << DiagRange
<< IndexExpr
->IgnoreImpCasts()->getType();
11335 // Only print a fixit for "str" + int, not for int + "str".
11336 if (IndexExpr
== RHSExpr
) {
11337 SourceLocation EndLoc
= Self
.getLocForEndOfToken(RHSExpr
->getEndLoc());
11338 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
)
11339 << FixItHint::CreateInsertion(LHSExpr
->getBeginLoc(), "&")
11340 << FixItHint::CreateReplacement(SourceRange(OpLoc
), "[")
11341 << FixItHint::CreateInsertion(EndLoc
, "]");
11343 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
);
11346 /// Emit a warning when adding a char literal to a string.
11347 static void diagnoseStringPlusChar(Sema
&Self
, SourceLocation OpLoc
,
11348 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11349 const Expr
*StringRefExpr
= LHSExpr
;
11350 const CharacterLiteral
*CharExpr
=
11351 dyn_cast
<CharacterLiteral
>(RHSExpr
->IgnoreImpCasts());
11354 CharExpr
= dyn_cast
<CharacterLiteral
>(LHSExpr
->IgnoreImpCasts());
11355 StringRefExpr
= RHSExpr
;
11358 if (!CharExpr
|| !StringRefExpr
)
11361 const QualType StringType
= StringRefExpr
->getType();
11363 // Return if not a PointerType.
11364 if (!StringType
->isAnyPointerType())
11367 // Return if not a CharacterType.
11368 if (!StringType
->getPointeeType()->isAnyCharacterType())
11371 ASTContext
&Ctx
= Self
.getASTContext();
11372 SourceRange
DiagRange(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
11374 const QualType CharType
= CharExpr
->getType();
11375 if (!CharType
->isAnyCharacterType() &&
11376 CharType
->isIntegerType() &&
11377 llvm::isUIntN(Ctx
.getCharWidth(), CharExpr
->getValue())) {
11378 Self
.Diag(OpLoc
, diag::warn_string_plus_char
)
11379 << DiagRange
<< Ctx
.CharTy
;
11381 Self
.Diag(OpLoc
, diag::warn_string_plus_char
)
11382 << DiagRange
<< CharExpr
->getType();
11385 // Only print a fixit for str + char, not for char + str.
11386 if (isa
<CharacterLiteral
>(RHSExpr
->IgnoreImpCasts())) {
11387 SourceLocation EndLoc
= Self
.getLocForEndOfToken(RHSExpr
->getEndLoc());
11388 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
)
11389 << FixItHint::CreateInsertion(LHSExpr
->getBeginLoc(), "&")
11390 << FixItHint::CreateReplacement(SourceRange(OpLoc
), "[")
11391 << FixItHint::CreateInsertion(EndLoc
, "]");
11393 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
);
11397 /// Emit error when two pointers are incompatible.
11398 static void diagnosePointerIncompatibility(Sema
&S
, SourceLocation Loc
,
11399 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11400 assert(LHSExpr
->getType()->isAnyPointerType());
11401 assert(RHSExpr
->getType()->isAnyPointerType());
11402 S
.Diag(Loc
, diag::err_typecheck_sub_ptr_compatible
)
11403 << LHSExpr
->getType() << RHSExpr
->getType() << LHSExpr
->getSourceRange()
11404 << RHSExpr
->getSourceRange();
11408 QualType
Sema::CheckAdditionOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11409 SourceLocation Loc
, BinaryOperatorKind Opc
,
11410 QualType
* CompLHSTy
) {
11411 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11413 if (LHS
.get()->getType()->isVectorType() ||
11414 RHS
.get()->getType()->isVectorType()) {
11415 QualType compType
=
11416 CheckVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
,
11417 /*AllowBothBool*/ getLangOpts().AltiVec
,
11418 /*AllowBoolConversions*/ getLangOpts().ZVector
,
11419 /*AllowBooleanOperation*/ false,
11420 /*ReportInvalid*/ true);
11421 if (CompLHSTy
) *CompLHSTy
= compType
;
11425 if (LHS
.get()->getType()->isVLSTBuiltinType() ||
11426 RHS
.get()->getType()->isVLSTBuiltinType()) {
11427 QualType compType
=
11428 CheckSizelessVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
, ACK_Arithmetic
);
11430 *CompLHSTy
= compType
;
11434 if (LHS
.get()->getType()->isConstantMatrixType() ||
11435 RHS
.get()->getType()->isConstantMatrixType()) {
11436 QualType compType
=
11437 CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, CompLHSTy
);
11439 *CompLHSTy
= compType
;
11443 QualType compType
= UsualArithmeticConversions(
11444 LHS
, RHS
, Loc
, CompLHSTy
? ACK_CompAssign
: ACK_Arithmetic
);
11445 if (LHS
.isInvalid() || RHS
.isInvalid())
11448 // Diagnose "string literal" '+' int and string '+' "char literal".
11449 if (Opc
== BO_Add
) {
11450 diagnoseStringPlusInt(*this, Loc
, LHS
.get(), RHS
.get());
11451 diagnoseStringPlusChar(*this, Loc
, LHS
.get(), RHS
.get());
11454 // handle the common case first (both operands are arithmetic).
11455 if (!compType
.isNull() && compType
->isArithmeticType()) {
11456 if (CompLHSTy
) *CompLHSTy
= compType
;
11460 // Type-checking. Ultimately the pointer's going to be in PExp;
11461 // note that we bias towards the LHS being the pointer.
11462 Expr
*PExp
= LHS
.get(), *IExp
= RHS
.get();
11464 bool isObjCPointer
;
11465 if (PExp
->getType()->isPointerType()) {
11466 isObjCPointer
= false;
11467 } else if (PExp
->getType()->isObjCObjectPointerType()) {
11468 isObjCPointer
= true;
11470 std::swap(PExp
, IExp
);
11471 if (PExp
->getType()->isPointerType()) {
11472 isObjCPointer
= false;
11473 } else if (PExp
->getType()->isObjCObjectPointerType()) {
11474 isObjCPointer
= true;
11476 return InvalidOperands(Loc
, LHS
, RHS
);
11479 assert(PExp
->getType()->isAnyPointerType());
11481 if (!IExp
->getType()->isIntegerType())
11482 return InvalidOperands(Loc
, LHS
, RHS
);
11484 // Adding to a null pointer results in undefined behavior.
11485 if (PExp
->IgnoreParenCasts()->isNullPointerConstant(
11486 Context
, Expr::NPC_ValueDependentIsNotNull
)) {
11487 // In C++ adding zero to a null pointer is defined.
11488 Expr::EvalResult KnownVal
;
11489 if (!getLangOpts().CPlusPlus
||
11490 (!IExp
->isValueDependent() &&
11491 (!IExp
->EvaluateAsInt(KnownVal
, Context
) ||
11492 KnownVal
.Val
.getInt() != 0))) {
11493 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11494 bool IsGNUIdiom
= BinaryOperator::isNullPointerArithmeticExtension(
11495 Context
, BO_Add
, PExp
, IExp
);
11496 diagnoseArithmeticOnNullPointer(*this, Loc
, PExp
, IsGNUIdiom
);
11500 if (!checkArithmeticOpPointerOperand(*this, Loc
, PExp
))
11503 if (isObjCPointer
&& checkArithmeticOnObjCPointer(*this, Loc
, PExp
))
11506 // Check array bounds for pointer arithemtic
11507 CheckArrayAccess(PExp
, IExp
);
11510 QualType LHSTy
= Context
.isPromotableBitField(LHS
.get());
11511 if (LHSTy
.isNull()) {
11512 LHSTy
= LHS
.get()->getType();
11513 if (Context
.isPromotableIntegerType(LHSTy
))
11514 LHSTy
= Context
.getPromotedIntegerType(LHSTy
);
11516 *CompLHSTy
= LHSTy
;
11519 return PExp
->getType();
11523 QualType
Sema::CheckSubtractionOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11524 SourceLocation Loc
,
11525 QualType
* CompLHSTy
) {
11526 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11528 if (LHS
.get()->getType()->isVectorType() ||
11529 RHS
.get()->getType()->isVectorType()) {
11530 QualType compType
=
11531 CheckVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
,
11532 /*AllowBothBool*/ getLangOpts().AltiVec
,
11533 /*AllowBoolConversions*/ getLangOpts().ZVector
,
11534 /*AllowBooleanOperation*/ false,
11535 /*ReportInvalid*/ true);
11536 if (CompLHSTy
) *CompLHSTy
= compType
;
11540 if (LHS
.get()->getType()->isVLSTBuiltinType() ||
11541 RHS
.get()->getType()->isVLSTBuiltinType()) {
11542 QualType compType
=
11543 CheckSizelessVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
, ACK_Arithmetic
);
11545 *CompLHSTy
= compType
;
11549 if (LHS
.get()->getType()->isConstantMatrixType() ||
11550 RHS
.get()->getType()->isConstantMatrixType()) {
11551 QualType compType
=
11552 CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, CompLHSTy
);
11554 *CompLHSTy
= compType
;
11558 QualType compType
= UsualArithmeticConversions(
11559 LHS
, RHS
, Loc
, CompLHSTy
? ACK_CompAssign
: ACK_Arithmetic
);
11560 if (LHS
.isInvalid() || RHS
.isInvalid())
11563 // Enforce type constraints: C99 6.5.6p3.
11565 // Handle the common case first (both operands are arithmetic).
11566 if (!compType
.isNull() && compType
->isArithmeticType()) {
11567 if (CompLHSTy
) *CompLHSTy
= compType
;
11571 // Either ptr - int or ptr - ptr.
11572 if (LHS
.get()->getType()->isAnyPointerType()) {
11573 QualType lpointee
= LHS
.get()->getType()->getPointeeType();
11575 // Diagnose bad cases where we step over interface counts.
11576 if (LHS
.get()->getType()->isObjCObjectPointerType() &&
11577 checkArithmeticOnObjCPointer(*this, Loc
, LHS
.get()))
11580 // The result type of a pointer-int computation is the pointer type.
11581 if (RHS
.get()->getType()->isIntegerType()) {
11582 // Subtracting from a null pointer should produce a warning.
11583 // The last argument to the diagnose call says this doesn't match the
11584 // GNU int-to-pointer idiom.
11585 if (LHS
.get()->IgnoreParenCasts()->isNullPointerConstant(Context
,
11586 Expr::NPC_ValueDependentIsNotNull
)) {
11587 // In C++ adding zero to a null pointer is defined.
11588 Expr::EvalResult KnownVal
;
11589 if (!getLangOpts().CPlusPlus
||
11590 (!RHS
.get()->isValueDependent() &&
11591 (!RHS
.get()->EvaluateAsInt(KnownVal
, Context
) ||
11592 KnownVal
.Val
.getInt() != 0))) {
11593 diagnoseArithmeticOnNullPointer(*this, Loc
, LHS
.get(), false);
11597 if (!checkArithmeticOpPointerOperand(*this, Loc
, LHS
.get()))
11600 // Check array bounds for pointer arithemtic
11601 CheckArrayAccess(LHS
.get(), RHS
.get(), /*ArraySubscriptExpr*/nullptr,
11602 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
11604 if (CompLHSTy
) *CompLHSTy
= LHS
.get()->getType();
11605 return LHS
.get()->getType();
11608 // Handle pointer-pointer subtractions.
11609 if (const PointerType
*RHSPTy
11610 = RHS
.get()->getType()->getAs
<PointerType
>()) {
11611 QualType rpointee
= RHSPTy
->getPointeeType();
11613 if (getLangOpts().CPlusPlus
) {
11614 // Pointee types must be the same: C++ [expr.add]
11615 if (!Context
.hasSameUnqualifiedType(lpointee
, rpointee
)) {
11616 diagnosePointerIncompatibility(*this, Loc
, LHS
.get(), RHS
.get());
11619 // Pointee types must be compatible C99 6.5.6p3
11620 if (!Context
.typesAreCompatible(
11621 Context
.getCanonicalType(lpointee
).getUnqualifiedType(),
11622 Context
.getCanonicalType(rpointee
).getUnqualifiedType())) {
11623 diagnosePointerIncompatibility(*this, Loc
, LHS
.get(), RHS
.get());
11628 if (!checkArithmeticBinOpPointerOperands(*this, Loc
,
11629 LHS
.get(), RHS
.get()))
11632 bool LHSIsNullPtr
= LHS
.get()->IgnoreParenCasts()->isNullPointerConstant(
11633 Context
, Expr::NPC_ValueDependentIsNotNull
);
11634 bool RHSIsNullPtr
= RHS
.get()->IgnoreParenCasts()->isNullPointerConstant(
11635 Context
, Expr::NPC_ValueDependentIsNotNull
);
11637 // Subtracting nullptr or from nullptr is suspect
11639 diagnoseSubtractionOnNullPointer(*this, Loc
, LHS
.get(), RHSIsNullPtr
);
11641 diagnoseSubtractionOnNullPointer(*this, Loc
, RHS
.get(), LHSIsNullPtr
);
11643 // The pointee type may have zero size. As an extension, a structure or
11644 // union may have zero size or an array may have zero length. In this
11645 // case subtraction does not make sense.
11646 if (!rpointee
->isVoidType() && !rpointee
->isFunctionType()) {
11647 CharUnits ElementSize
= Context
.getTypeSizeInChars(rpointee
);
11648 if (ElementSize
.isZero()) {
11649 Diag(Loc
,diag::warn_sub_ptr_zero_size_types
)
11650 << rpointee
.getUnqualifiedType()
11651 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11655 if (CompLHSTy
) *CompLHSTy
= LHS
.get()->getType();
11656 return Context
.getPointerDiffType();
11660 return InvalidOperands(Loc
, LHS
, RHS
);
11663 static bool isScopedEnumerationType(QualType T
) {
11664 if (const EnumType
*ET
= T
->getAs
<EnumType
>())
11665 return ET
->getDecl()->isScoped();
11669 static void DiagnoseBadShiftValues(Sema
& S
, ExprResult
&LHS
, ExprResult
&RHS
,
11670 SourceLocation Loc
, BinaryOperatorKind Opc
,
11671 QualType LHSType
) {
11672 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
11673 // so skip remaining warnings as we don't want to modify values within Sema.
11674 if (S
.getLangOpts().OpenCL
)
11677 // Check right/shifter operand
11678 Expr::EvalResult RHSResult
;
11679 if (RHS
.get()->isValueDependent() ||
11680 !RHS
.get()->EvaluateAsInt(RHSResult
, S
.Context
))
11682 llvm::APSInt Right
= RHSResult
.Val
.getInt();
11684 if (Right
.isNegative()) {
11685 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
11686 S
.PDiag(diag::warn_shift_negative
)
11687 << RHS
.get()->getSourceRange());
11691 QualType LHSExprType
= LHS
.get()->getType();
11692 uint64_t LeftSize
= S
.Context
.getTypeSize(LHSExprType
);
11693 if (LHSExprType
->isBitIntType())
11694 LeftSize
= S
.Context
.getIntWidth(LHSExprType
);
11695 else if (LHSExprType
->isFixedPointType()) {
11696 auto FXSema
= S
.Context
.getFixedPointSemantics(LHSExprType
);
11697 LeftSize
= FXSema
.getWidth() - (unsigned)FXSema
.hasUnsignedPadding();
11699 llvm::APInt
LeftBits(Right
.getBitWidth(), LeftSize
);
11700 if (Right
.uge(LeftBits
)) {
11701 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
11702 S
.PDiag(diag::warn_shift_gt_typewidth
)
11703 << RHS
.get()->getSourceRange());
11707 // FIXME: We probably need to handle fixed point types specially here.
11708 if (Opc
!= BO_Shl
|| LHSExprType
->isFixedPointType())
11711 // When left shifting an ICE which is signed, we can check for overflow which
11712 // according to C++ standards prior to C++2a has undefined behavior
11713 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
11714 // more than the maximum value representable in the result type, so never
11715 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
11716 // expression is still probably a bug.)
11717 Expr::EvalResult LHSResult
;
11718 if (LHS
.get()->isValueDependent() ||
11719 LHSType
->hasUnsignedIntegerRepresentation() ||
11720 !LHS
.get()->EvaluateAsInt(LHSResult
, S
.Context
))
11722 llvm::APSInt Left
= LHSResult
.Val
.getInt();
11724 // Don't warn if signed overflow is defined, then all the rest of the
11725 // diagnostics will not be triggered because the behavior is defined.
11726 // Also don't warn in C++20 mode (and newer), as signed left shifts
11727 // always wrap and never overflow.
11728 if (S
.getLangOpts().isSignedOverflowDefined() || S
.getLangOpts().CPlusPlus20
)
11731 // If LHS does not have a non-negative value then, the
11732 // behavior is undefined before C++2a. Warn about it.
11733 if (Left
.isNegative()) {
11734 S
.DiagRuntimeBehavior(Loc
, LHS
.get(),
11735 S
.PDiag(diag::warn_shift_lhs_negative
)
11736 << LHS
.get()->getSourceRange());
11740 llvm::APInt ResultBits
=
11741 static_cast<llvm::APInt
&>(Right
) + Left
.getMinSignedBits();
11742 if (LeftBits
.uge(ResultBits
))
11744 llvm::APSInt Result
= Left
.extend(ResultBits
.getLimitedValue());
11745 Result
= Result
.shl(Right
);
11747 // Print the bit representation of the signed integer as an unsigned
11748 // hexadecimal number.
11749 SmallString
<40> HexResult
;
11750 Result
.toString(HexResult
, 16, /*Signed =*/false, /*Literal =*/true);
11752 // If we are only missing a sign bit, this is less likely to result in actual
11753 // bugs -- if the result is cast back to an unsigned type, it will have the
11754 // expected value. Thus we place this behind a different warning that can be
11755 // turned off separately if needed.
11756 if (LeftBits
== ResultBits
- 1) {
11757 S
.Diag(Loc
, diag::warn_shift_result_sets_sign_bit
)
11758 << HexResult
<< LHSType
11759 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11763 S
.Diag(Loc
, diag::warn_shift_result_gt_typewidth
)
11764 << HexResult
.str() << Result
.getMinSignedBits() << LHSType
11765 << Left
.getBitWidth() << LHS
.get()->getSourceRange()
11766 << RHS
.get()->getSourceRange();
11769 /// Return the resulting type when a vector is shifted
11770 /// by a scalar or vector shift amount.
11771 static QualType
checkVectorShift(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
11772 SourceLocation Loc
, bool IsCompAssign
) {
11773 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
11774 if ((S
.LangOpts
.OpenCL
|| S
.LangOpts
.ZVector
) &&
11775 !LHS
.get()->getType()->isVectorType()) {
11776 S
.Diag(Loc
, diag::err_shift_rhs_only_vector
)
11777 << RHS
.get()->getType() << LHS
.get()->getType()
11778 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11782 if (!IsCompAssign
) {
11783 LHS
= S
.UsualUnaryConversions(LHS
.get());
11784 if (LHS
.isInvalid()) return QualType();
11787 RHS
= S
.UsualUnaryConversions(RHS
.get());
11788 if (RHS
.isInvalid()) return QualType();
11790 QualType LHSType
= LHS
.get()->getType();
11791 // Note that LHS might be a scalar because the routine calls not only in
11793 const VectorType
*LHSVecTy
= LHSType
->getAs
<VectorType
>();
11794 QualType LHSEleType
= LHSVecTy
? LHSVecTy
->getElementType() : LHSType
;
11796 // Note that RHS might not be a vector.
11797 QualType RHSType
= RHS
.get()->getType();
11798 const VectorType
*RHSVecTy
= RHSType
->getAs
<VectorType
>();
11799 QualType RHSEleType
= RHSVecTy
? RHSVecTy
->getElementType() : RHSType
;
11801 // Do not allow shifts for boolean vectors.
11802 if ((LHSVecTy
&& LHSVecTy
->isExtVectorBoolType()) ||
11803 (RHSVecTy
&& RHSVecTy
->isExtVectorBoolType())) {
11804 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
11805 << LHS
.get()->getType() << RHS
.get()->getType()
11806 << LHS
.get()->getSourceRange();
11810 // The operands need to be integers.
11811 if (!LHSEleType
->isIntegerType()) {
11812 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
11813 << LHS
.get()->getType() << LHS
.get()->getSourceRange();
11817 if (!RHSEleType
->isIntegerType()) {
11818 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
11819 << RHS
.get()->getType() << RHS
.get()->getSourceRange();
11827 if (LHSEleType
!= RHSEleType
) {
11828 LHS
= S
.ImpCastExprToType(LHS
.get(),RHSEleType
, CK_IntegralCast
);
11829 LHSEleType
= RHSEleType
;
11832 S
.Context
.getExtVectorType(LHSEleType
, RHSVecTy
->getNumElements());
11833 LHS
= S
.ImpCastExprToType(LHS
.get(), VecTy
, CK_VectorSplat
);
11835 } else if (RHSVecTy
) {
11836 // OpenCL v1.1 s6.3.j says that for vector types, the operators
11837 // are applied component-wise. So if RHS is a vector, then ensure
11838 // that the number of elements is the same as LHS...
11839 if (RHSVecTy
->getNumElements() != LHSVecTy
->getNumElements()) {
11840 S
.Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
11841 << LHS
.get()->getType() << RHS
.get()->getType()
11842 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11845 if (!S
.LangOpts
.OpenCL
&& !S
.LangOpts
.ZVector
) {
11846 const BuiltinType
*LHSBT
= LHSEleType
->getAs
<clang::BuiltinType
>();
11847 const BuiltinType
*RHSBT
= RHSEleType
->getAs
<clang::BuiltinType
>();
11848 if (LHSBT
!= RHSBT
&&
11849 S
.Context
.getTypeSize(LHSBT
) != S
.Context
.getTypeSize(RHSBT
)) {
11850 S
.Diag(Loc
, diag::warn_typecheck_vector_element_sizes_not_equal
)
11851 << LHS
.get()->getType() << RHS
.get()->getType()
11852 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11856 // ...else expand RHS to match the number of elements in LHS.
11858 S
.Context
.getExtVectorType(RHSEleType
, LHSVecTy
->getNumElements());
11859 RHS
= S
.ImpCastExprToType(RHS
.get(), VecTy
, CK_VectorSplat
);
11865 static QualType
checkSizelessVectorShift(Sema
&S
, ExprResult
&LHS
,
11866 ExprResult
&RHS
, SourceLocation Loc
,
11867 bool IsCompAssign
) {
11868 if (!IsCompAssign
) {
11869 LHS
= S
.UsualUnaryConversions(LHS
.get());
11870 if (LHS
.isInvalid())
11874 RHS
= S
.UsualUnaryConversions(RHS
.get());
11875 if (RHS
.isInvalid())
11878 QualType LHSType
= LHS
.get()->getType();
11879 const BuiltinType
*LHSBuiltinTy
= LHSType
->getAs
<BuiltinType
>();
11880 QualType LHSEleType
= LHSType
->isVLSTBuiltinType()
11881 ? LHSBuiltinTy
->getSveEltType(S
.getASTContext())
11884 // Note that RHS might not be a vector
11885 QualType RHSType
= RHS
.get()->getType();
11886 const BuiltinType
*RHSBuiltinTy
= RHSType
->getAs
<BuiltinType
>();
11887 QualType RHSEleType
= RHSType
->isVLSTBuiltinType()
11888 ? RHSBuiltinTy
->getSveEltType(S
.getASTContext())
11891 if ((LHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool()) ||
11892 (RHSBuiltinTy
&& RHSBuiltinTy
->isSVEBool())) {
11893 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
11894 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange();
11898 if (!LHSEleType
->isIntegerType()) {
11899 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
11900 << LHS
.get()->getType() << LHS
.get()->getSourceRange();
11904 if (!RHSEleType
->isIntegerType()) {
11905 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
11906 << RHS
.get()->getType() << RHS
.get()->getSourceRange();
11910 if (LHSType
->isVLSTBuiltinType() && RHSType
->isVLSTBuiltinType() &&
11911 (S
.Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
!=
11912 S
.Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
)) {
11913 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
11914 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
11915 << RHS
.get()->getSourceRange();
11919 if (!LHSType
->isVLSTBuiltinType()) {
11920 assert(RHSType
->isVLSTBuiltinType());
11923 if (LHSEleType
!= RHSEleType
) {
11924 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSEleType
, clang::CK_IntegralCast
);
11925 LHSEleType
= RHSEleType
;
11927 const llvm::ElementCount VecSize
=
11928 S
.Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
;
11930 S
.Context
.getScalableVectorType(LHSEleType
, VecSize
.getKnownMinValue());
11931 LHS
= S
.ImpCastExprToType(LHS
.get(), VecTy
, clang::CK_VectorSplat
);
11933 } else if (RHSBuiltinTy
&& RHSBuiltinTy
->isVLSTBuiltinType()) {
11934 if (S
.Context
.getTypeSize(RHSBuiltinTy
) !=
11935 S
.Context
.getTypeSize(LHSBuiltinTy
)) {
11936 S
.Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
11937 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
11938 << RHS
.get()->getSourceRange();
11942 const llvm::ElementCount VecSize
=
11943 S
.Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
;
11944 if (LHSEleType
!= RHSEleType
) {
11945 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSEleType
, clang::CK_IntegralCast
);
11946 RHSEleType
= LHSEleType
;
11949 S
.Context
.getScalableVectorType(RHSEleType
, VecSize
.getKnownMinValue());
11950 RHS
= S
.ImpCastExprToType(RHS
.get(), VecTy
, CK_VectorSplat
);
11957 QualType
Sema::CheckShiftOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11958 SourceLocation Loc
, BinaryOperatorKind Opc
,
11959 bool IsCompAssign
) {
11960 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11962 // Vector shifts promote their scalar inputs to vector type.
11963 if (LHS
.get()->getType()->isVectorType() ||
11964 RHS
.get()->getType()->isVectorType()) {
11965 if (LangOpts
.ZVector
) {
11966 // The shift operators for the z vector extensions work basically
11967 // like general shifts, except that neither the LHS nor the RHS is
11968 // allowed to be a "vector bool".
11969 if (auto LHSVecType
= LHS
.get()->getType()->getAs
<VectorType
>())
11970 if (LHSVecType
->getVectorKind() == VectorType::AltiVecBool
)
11971 return InvalidOperands(Loc
, LHS
, RHS
);
11972 if (auto RHSVecType
= RHS
.get()->getType()->getAs
<VectorType
>())
11973 if (RHSVecType
->getVectorKind() == VectorType::AltiVecBool
)
11974 return InvalidOperands(Loc
, LHS
, RHS
);
11976 return checkVectorShift(*this, LHS
, RHS
, Loc
, IsCompAssign
);
11979 if (LHS
.get()->getType()->isVLSTBuiltinType() ||
11980 RHS
.get()->getType()->isVLSTBuiltinType())
11981 return checkSizelessVectorShift(*this, LHS
, RHS
, Loc
, IsCompAssign
);
11983 // Shifts don't perform usual arithmetic conversions, they just do integer
11984 // promotions on each operand. C99 6.5.7p3
11986 // For the LHS, do usual unary conversions, but then reset them away
11987 // if this is a compound assignment.
11988 ExprResult OldLHS
= LHS
;
11989 LHS
= UsualUnaryConversions(LHS
.get());
11990 if (LHS
.isInvalid())
11992 QualType LHSType
= LHS
.get()->getType();
11993 if (IsCompAssign
) LHS
= OldLHS
;
11995 // The RHS is simpler.
11996 RHS
= UsualUnaryConversions(RHS
.get());
11997 if (RHS
.isInvalid())
11999 QualType RHSType
= RHS
.get()->getType();
12001 // C99 6.5.7p2: Each of the operands shall have integer type.
12002 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12003 if ((!LHSType
->isFixedPointOrIntegerType() &&
12004 !LHSType
->hasIntegerRepresentation()) ||
12005 !RHSType
->hasIntegerRepresentation())
12006 return InvalidOperands(Loc
, LHS
, RHS
);
12008 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12009 // hasIntegerRepresentation() above instead of this.
12010 if (isScopedEnumerationType(LHSType
) ||
12011 isScopedEnumerationType(RHSType
)) {
12012 return InvalidOperands(Loc
, LHS
, RHS
);
12014 DiagnoseBadShiftValues(*this, LHS
, RHS
, Loc
, Opc
, LHSType
);
12016 // "The type of the result is that of the promoted left operand."
12020 /// Diagnose bad pointer comparisons.
12021 static void diagnoseDistinctPointerComparison(Sema
&S
, SourceLocation Loc
,
12022 ExprResult
&LHS
, ExprResult
&RHS
,
12024 S
.Diag(Loc
, IsError
? diag::err_typecheck_comparison_of_distinct_pointers
12025 : diag::ext_typecheck_comparison_of_distinct_pointers
)
12026 << LHS
.get()->getType() << RHS
.get()->getType()
12027 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12030 /// Returns false if the pointers are converted to a composite type,
12031 /// true otherwise.
12032 static bool convertPointersToCompositeType(Sema
&S
, SourceLocation Loc
,
12033 ExprResult
&LHS
, ExprResult
&RHS
) {
12034 // C++ [expr.rel]p2:
12035 // [...] Pointer conversions (4.10) and qualification
12036 // conversions (4.4) are performed on pointer operands (or on
12037 // a pointer operand and a null pointer constant) to bring
12038 // them to their composite pointer type. [...]
12040 // C++ [expr.eq]p1 uses the same notion for (in)equality
12041 // comparisons of pointers.
12043 QualType LHSType
= LHS
.get()->getType();
12044 QualType RHSType
= RHS
.get()->getType();
12045 assert(LHSType
->isPointerType() || RHSType
->isPointerType() ||
12046 LHSType
->isMemberPointerType() || RHSType
->isMemberPointerType());
12048 QualType T
= S
.FindCompositePointerType(Loc
, LHS
, RHS
);
12050 if ((LHSType
->isAnyPointerType() || LHSType
->isMemberPointerType()) &&
12051 (RHSType
->isAnyPointerType() || RHSType
->isMemberPointerType()))
12052 diagnoseDistinctPointerComparison(S
, Loc
, LHS
, RHS
, /*isError*/true);
12054 S
.InvalidOperands(Loc
, LHS
, RHS
);
12061 static void diagnoseFunctionPointerToVoidComparison(Sema
&S
, SourceLocation Loc
,
12065 S
.Diag(Loc
, IsError
? diag::err_typecheck_comparison_of_fptr_to_void
12066 : diag::ext_typecheck_comparison_of_fptr_to_void
)
12067 << LHS
.get()->getType() << RHS
.get()->getType()
12068 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12071 static bool isObjCObjectLiteral(ExprResult
&E
) {
12072 switch (E
.get()->IgnoreParenImpCasts()->getStmtClass()) {
12073 case Stmt::ObjCArrayLiteralClass
:
12074 case Stmt::ObjCDictionaryLiteralClass
:
12075 case Stmt::ObjCStringLiteralClass
:
12076 case Stmt::ObjCBoxedExprClass
:
12079 // Note that ObjCBoolLiteral is NOT an object literal!
12084 static bool hasIsEqualMethod(Sema
&S
, const Expr
*LHS
, const Expr
*RHS
) {
12085 const ObjCObjectPointerType
*Type
=
12086 LHS
->getType()->getAs
<ObjCObjectPointerType
>();
12088 // If this is not actually an Objective-C object, bail out.
12092 // Get the LHS object's interface type.
12093 QualType InterfaceType
= Type
->getPointeeType();
12095 // If the RHS isn't an Objective-C object, bail out.
12096 if (!RHS
->getType()->isObjCObjectPointerType())
12099 // Try to find the -isEqual: method.
12100 Selector IsEqualSel
= S
.NSAPIObj
->getIsEqualSelector();
12101 ObjCMethodDecl
*Method
= S
.LookupMethodInObjectType(IsEqualSel
,
12103 /*IsInstance=*/true);
12105 if (Type
->isObjCIdType()) {
12106 // For 'id', just check the global pool.
12107 Method
= S
.LookupInstanceMethodInGlobalPool(IsEqualSel
, SourceRange(),
12108 /*receiverId=*/true);
12110 // Check protocols.
12111 Method
= S
.LookupMethodInQualifiedType(IsEqualSel
, Type
,
12112 /*IsInstance=*/true);
12119 QualType T
= Method
->parameters()[0]->getType();
12120 if (!T
->isObjCObjectPointerType())
12123 QualType R
= Method
->getReturnType();
12124 if (!R
->isScalarType())
12130 Sema::ObjCLiteralKind
Sema::CheckLiteralKind(Expr
*FromE
) {
12131 FromE
= FromE
->IgnoreParenImpCasts();
12132 switch (FromE
->getStmtClass()) {
12135 case Stmt::ObjCStringLiteralClass
:
12136 // "string literal"
12138 case Stmt::ObjCArrayLiteralClass
:
12141 case Stmt::ObjCDictionaryLiteralClass
:
12142 // "dictionary literal"
12143 return LK_Dictionary
;
12144 case Stmt::BlockExprClass
:
12146 case Stmt::ObjCBoxedExprClass
: {
12147 Expr
*Inner
= cast
<ObjCBoxedExpr
>(FromE
)->getSubExpr()->IgnoreParens();
12148 switch (Inner
->getStmtClass()) {
12149 case Stmt::IntegerLiteralClass
:
12150 case Stmt::FloatingLiteralClass
:
12151 case Stmt::CharacterLiteralClass
:
12152 case Stmt::ObjCBoolLiteralExprClass
:
12153 case Stmt::CXXBoolLiteralExprClass
:
12154 // "numeric literal"
12156 case Stmt::ImplicitCastExprClass
: {
12157 CastKind CK
= cast
<CastExpr
>(Inner
)->getCastKind();
12158 // Boolean literals can be represented by implicit casts.
12159 if (CK
== CK_IntegralToBoolean
|| CK
== CK_IntegralCast
)
12172 static void diagnoseObjCLiteralComparison(Sema
&S
, SourceLocation Loc
,
12173 ExprResult
&LHS
, ExprResult
&RHS
,
12174 BinaryOperator::Opcode Opc
){
12177 if (isObjCObjectLiteral(LHS
)) {
12178 Literal
= LHS
.get();
12181 Literal
= RHS
.get();
12185 // Don't warn on comparisons against nil.
12186 Other
= Other
->IgnoreParenCasts();
12187 if (Other
->isNullPointerConstant(S
.getASTContext(),
12188 Expr::NPC_ValueDependentIsNotNull
))
12191 // This should be kept in sync with warn_objc_literal_comparison.
12192 // LK_String should always be after the other literals, since it has its own
12194 Sema::ObjCLiteralKind LiteralKind
= S
.CheckLiteralKind(Literal
);
12195 assert(LiteralKind
!= Sema::LK_Block
);
12196 if (LiteralKind
== Sema::LK_None
) {
12197 llvm_unreachable("Unknown Objective-C object literal kind");
12200 if (LiteralKind
== Sema::LK_String
)
12201 S
.Diag(Loc
, diag::warn_objc_string_literal_comparison
)
12202 << Literal
->getSourceRange();
12204 S
.Diag(Loc
, diag::warn_objc_literal_comparison
)
12205 << LiteralKind
<< Literal
->getSourceRange();
12207 if (BinaryOperator::isEqualityOp(Opc
) &&
12208 hasIsEqualMethod(S
, LHS
.get(), RHS
.get())) {
12209 SourceLocation Start
= LHS
.get()->getBeginLoc();
12210 SourceLocation End
= S
.getLocForEndOfToken(RHS
.get()->getEndLoc());
12211 CharSourceRange OpRange
=
12212 CharSourceRange::getCharRange(Loc
, S
.getLocForEndOfToken(Loc
));
12214 S
.Diag(Loc
, diag::note_objc_literal_comparison_isequal
)
12215 << FixItHint::CreateInsertion(Start
, Opc
== BO_EQ
? "[" : "![")
12216 << FixItHint::CreateReplacement(OpRange
, " isEqual:")
12217 << FixItHint::CreateInsertion(End
, "]");
12221 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12222 static void diagnoseLogicalNotOnLHSofCheck(Sema
&S
, ExprResult
&LHS
,
12223 ExprResult
&RHS
, SourceLocation Loc
,
12224 BinaryOperatorKind Opc
) {
12225 // Check that left hand side is !something.
12226 UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(LHS
.get()->IgnoreImpCasts());
12227 if (!UO
|| UO
->getOpcode() != UO_LNot
) return;
12229 // Only check if the right hand side is non-bool arithmetic type.
12230 if (RHS
.get()->isKnownToHaveBooleanValue()) return;
12232 // Make sure that the something in !something is not bool.
12233 Expr
*SubExpr
= UO
->getSubExpr()->IgnoreImpCasts();
12234 if (SubExpr
->isKnownToHaveBooleanValue()) return;
12237 bool IsBitwiseOp
= Opc
== BO_And
|| Opc
== BO_Or
|| Opc
== BO_Xor
;
12238 S
.Diag(UO
->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check
)
12239 << Loc
<< IsBitwiseOp
;
12241 // First note suggest !(x < y)
12242 SourceLocation FirstOpen
= SubExpr
->getBeginLoc();
12243 SourceLocation FirstClose
= RHS
.get()->getEndLoc();
12244 FirstClose
= S
.getLocForEndOfToken(FirstClose
);
12245 if (FirstClose
.isInvalid())
12246 FirstOpen
= SourceLocation();
12247 S
.Diag(UO
->getOperatorLoc(), diag::note_logical_not_fix
)
12249 << FixItHint::CreateInsertion(FirstOpen
, "(")
12250 << FixItHint::CreateInsertion(FirstClose
, ")");
12252 // Second note suggests (!x) < y
12253 SourceLocation SecondOpen
= LHS
.get()->getBeginLoc();
12254 SourceLocation SecondClose
= LHS
.get()->getEndLoc();
12255 SecondClose
= S
.getLocForEndOfToken(SecondClose
);
12256 if (SecondClose
.isInvalid())
12257 SecondOpen
= SourceLocation();
12258 S
.Diag(UO
->getOperatorLoc(), diag::note_logical_not_silence_with_parens
)
12259 << FixItHint::CreateInsertion(SecondOpen
, "(")
12260 << FixItHint::CreateInsertion(SecondClose
, ")");
12263 // Returns true if E refers to a non-weak array.
12264 static bool checkForArray(const Expr
*E
) {
12265 const ValueDecl
*D
= nullptr;
12266 if (const DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(E
)) {
12268 } else if (const MemberExpr
*Mem
= dyn_cast
<MemberExpr
>(E
)) {
12269 if (Mem
->isImplicitAccess())
12270 D
= Mem
->getMemberDecl();
12274 return D
->getType()->isArrayType() && !D
->isWeak();
12277 /// Diagnose some forms of syntactically-obvious tautological comparison.
12278 static void diagnoseTautologicalComparison(Sema
&S
, SourceLocation Loc
,
12279 Expr
*LHS
, Expr
*RHS
,
12280 BinaryOperatorKind Opc
) {
12281 Expr
*LHSStripped
= LHS
->IgnoreParenImpCasts();
12282 Expr
*RHSStripped
= RHS
->IgnoreParenImpCasts();
12284 QualType LHSType
= LHS
->getType();
12285 QualType RHSType
= RHS
->getType();
12286 if (LHSType
->hasFloatingRepresentation() ||
12287 (LHSType
->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc
)) ||
12288 S
.inTemplateInstantiation())
12291 // Comparisons between two array types are ill-formed for operator<=>, so
12292 // we shouldn't emit any additional warnings about it.
12293 if (Opc
== BO_Cmp
&& LHSType
->isArrayType() && RHSType
->isArrayType())
12296 // For non-floating point types, check for self-comparisons of the form
12297 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12298 // often indicate logic errors in the program.
12300 // NOTE: Don't warn about comparison expressions resulting from macro
12301 // expansion. Also don't warn about comparisons which are only self
12302 // comparisons within a template instantiation. The warnings should catch
12303 // obvious cases in the definition of the template anyways. The idea is to
12304 // warn when the typed comparison operator will always evaluate to the same
12307 // Used for indexing into %select in warn_comparison_always
12312 AlwaysEqual
, // std::strong_ordering::equal from operator<=>
12315 // C++2a [depr.array.comp]:
12316 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12317 // operands of array type are deprecated.
12318 if (S
.getLangOpts().CPlusPlus20
&& LHSStripped
->getType()->isArrayType() &&
12319 RHSStripped
->getType()->isArrayType()) {
12320 S
.Diag(Loc
, diag::warn_depr_array_comparison
)
12321 << LHS
->getSourceRange() << RHS
->getSourceRange()
12322 << LHSStripped
->getType() << RHSStripped
->getType();
12323 // Carry on to produce the tautological comparison warning, if this
12324 // expression is potentially-evaluated, we can resolve the array to a
12325 // non-weak declaration, and so on.
12328 if (!LHS
->getBeginLoc().isMacroID() && !RHS
->getBeginLoc().isMacroID()) {
12329 if (Expr::isSameComparisonOperand(LHS
, RHS
)) {
12335 Result
= AlwaysTrue
;
12340 Result
= AlwaysFalse
;
12343 Result
= AlwaysEqual
;
12346 Result
= AlwaysConstant
;
12349 S
.DiagRuntimeBehavior(Loc
, nullptr,
12350 S
.PDiag(diag::warn_comparison_always
)
12351 << 0 /*self-comparison*/
12353 } else if (checkForArray(LHSStripped
) && checkForArray(RHSStripped
)) {
12354 // What is it always going to evaluate to?
12357 case BO_EQ
: // e.g. array1 == array2
12358 Result
= AlwaysFalse
;
12360 case BO_NE
: // e.g. array1 != array2
12361 Result
= AlwaysTrue
;
12363 default: // e.g. array1 <= array2
12364 // The best we can say is 'a constant'
12365 Result
= AlwaysConstant
;
12368 S
.DiagRuntimeBehavior(Loc
, nullptr,
12369 S
.PDiag(diag::warn_comparison_always
)
12370 << 1 /*array comparison*/
12375 if (isa
<CastExpr
>(LHSStripped
))
12376 LHSStripped
= LHSStripped
->IgnoreParenCasts();
12377 if (isa
<CastExpr
>(RHSStripped
))
12378 RHSStripped
= RHSStripped
->IgnoreParenCasts();
12380 // Warn about comparisons against a string constant (unless the other
12381 // operand is null); the user probably wants string comparison function.
12382 Expr
*LiteralString
= nullptr;
12383 Expr
*LiteralStringStripped
= nullptr;
12384 if ((isa
<StringLiteral
>(LHSStripped
) || isa
<ObjCEncodeExpr
>(LHSStripped
)) &&
12385 !RHSStripped
->isNullPointerConstant(S
.Context
,
12386 Expr::NPC_ValueDependentIsNull
)) {
12387 LiteralString
= LHS
;
12388 LiteralStringStripped
= LHSStripped
;
12389 } else if ((isa
<StringLiteral
>(RHSStripped
) ||
12390 isa
<ObjCEncodeExpr
>(RHSStripped
)) &&
12391 !LHSStripped
->isNullPointerConstant(S
.Context
,
12392 Expr::NPC_ValueDependentIsNull
)) {
12393 LiteralString
= RHS
;
12394 LiteralStringStripped
= RHSStripped
;
12397 if (LiteralString
) {
12398 S
.DiagRuntimeBehavior(Loc
, nullptr,
12399 S
.PDiag(diag::warn_stringcompare
)
12400 << isa
<ObjCEncodeExpr
>(LiteralStringStripped
)
12401 << LiteralString
->getSourceRange());
12405 static ImplicitConversionKind
castKindToImplicitConversionKind(CastKind CK
) {
12409 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK
)
12412 llvm_unreachable("unhandled cast kind");
12414 case CK_UserDefinedConversion
:
12415 return ICK_Identity
;
12416 case CK_LValueToRValue
:
12417 return ICK_Lvalue_To_Rvalue
;
12418 case CK_ArrayToPointerDecay
:
12419 return ICK_Array_To_Pointer
;
12420 case CK_FunctionToPointerDecay
:
12421 return ICK_Function_To_Pointer
;
12422 case CK_IntegralCast
:
12423 return ICK_Integral_Conversion
;
12424 case CK_FloatingCast
:
12425 return ICK_Floating_Conversion
;
12426 case CK_IntegralToFloating
:
12427 case CK_FloatingToIntegral
:
12428 return ICK_Floating_Integral
;
12429 case CK_IntegralComplexCast
:
12430 case CK_FloatingComplexCast
:
12431 case CK_FloatingComplexToIntegralComplex
:
12432 case CK_IntegralComplexToFloatingComplex
:
12433 return ICK_Complex_Conversion
;
12434 case CK_FloatingComplexToReal
:
12435 case CK_FloatingRealToComplex
:
12436 case CK_IntegralComplexToReal
:
12437 case CK_IntegralRealToComplex
:
12438 return ICK_Complex_Real
;
12442 static bool checkThreeWayNarrowingConversion(Sema
&S
, QualType ToType
, Expr
*E
,
12444 SourceLocation Loc
) {
12445 // Check for a narrowing implicit conversion.
12446 StandardConversionSequence SCS
;
12447 SCS
.setAsIdentityConversion();
12448 SCS
.setToType(0, FromType
);
12449 SCS
.setToType(1, ToType
);
12450 if (const auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
12451 SCS
.Second
= castKindToImplicitConversionKind(ICE
->getCastKind());
12453 APValue PreNarrowingValue
;
12454 QualType PreNarrowingType
;
12455 switch (SCS
.getNarrowingKind(S
.Context
, E
, PreNarrowingValue
,
12457 /*IgnoreFloatToIntegralConversion*/ true)) {
12458 case NK_Dependent_Narrowing
:
12459 // Implicit conversion to a narrower type, but the expression is
12460 // value-dependent so we can't tell whether it's actually narrowing.
12461 case NK_Not_Narrowing
:
12464 case NK_Constant_Narrowing
:
12465 // Implicit conversion to a narrower type, and the value is not a constant
12467 S
.Diag(E
->getBeginLoc(), diag::err_spaceship_argument_narrowing
)
12469 << PreNarrowingValue
.getAsString(S
.Context
, PreNarrowingType
) << ToType
;
12472 case NK_Variable_Narrowing
:
12473 // Implicit conversion to a narrower type, and the value is not a constant
12475 case NK_Type_Narrowing
:
12476 S
.Diag(E
->getBeginLoc(), diag::err_spaceship_argument_narrowing
)
12477 << /*Constant*/ 0 << FromType
<< ToType
;
12478 // TODO: It's not a constant expression, but what if the user intended it
12479 // to be? Can we produce notes to help them figure out why it isn't?
12482 llvm_unreachable("unhandled case in switch");
12485 static QualType
checkArithmeticOrEnumeralThreeWayCompare(Sema
&S
,
12488 SourceLocation Loc
) {
12489 QualType LHSType
= LHS
.get()->getType();
12490 QualType RHSType
= RHS
.get()->getType();
12491 // Dig out the original argument type and expression before implicit casts
12492 // were applied. These are the types/expressions we need to check the
12493 // [expr.spaceship] requirements against.
12494 ExprResult LHSStripped
= LHS
.get()->IgnoreParenImpCasts();
12495 ExprResult RHSStripped
= RHS
.get()->IgnoreParenImpCasts();
12496 QualType LHSStrippedType
= LHSStripped
.get()->getType();
12497 QualType RHSStrippedType
= RHSStripped
.get()->getType();
12499 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12500 // other is not, the program is ill-formed.
12501 if (LHSStrippedType
->isBooleanType() != RHSStrippedType
->isBooleanType()) {
12502 S
.InvalidOperands(Loc
, LHSStripped
, RHSStripped
);
12506 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12507 int NumEnumArgs
= (int)LHSStrippedType
->isEnumeralType() +
12508 RHSStrippedType
->isEnumeralType();
12509 if (NumEnumArgs
== 1) {
12510 bool LHSIsEnum
= LHSStrippedType
->isEnumeralType();
12511 QualType OtherTy
= LHSIsEnum
? RHSStrippedType
: LHSStrippedType
;
12512 if (OtherTy
->hasFloatingRepresentation()) {
12513 S
.InvalidOperands(Loc
, LHSStripped
, RHSStripped
);
12517 if (NumEnumArgs
== 2) {
12518 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12519 // type E, the operator yields the result of converting the operands
12520 // to the underlying type of E and applying <=> to the converted operands.
12521 if (!S
.Context
.hasSameUnqualifiedType(LHSStrippedType
, RHSStrippedType
)) {
12522 S
.InvalidOperands(Loc
, LHS
, RHS
);
12526 LHSStrippedType
->castAs
<EnumType
>()->getDecl()->getIntegerType();
12527 assert(IntType
->isArithmeticType());
12529 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12530 // promote the boolean type, and all other promotable integer types, to
12532 if (S
.Context
.isPromotableIntegerType(IntType
))
12533 IntType
= S
.Context
.getPromotedIntegerType(IntType
);
12535 LHS
= S
.ImpCastExprToType(LHS
.get(), IntType
, CK_IntegralCast
);
12536 RHS
= S
.ImpCastExprToType(RHS
.get(), IntType
, CK_IntegralCast
);
12537 LHSType
= RHSType
= IntType
;
12540 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12541 // usual arithmetic conversions are applied to the operands.
12543 S
.UsualArithmeticConversions(LHS
, RHS
, Loc
, Sema::ACK_Comparison
);
12544 if (LHS
.isInvalid() || RHS
.isInvalid())
12547 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12549 std::optional
<ComparisonCategoryType
> CCT
=
12550 getComparisonCategoryForBuiltinCmp(Type
);
12552 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12554 bool HasNarrowing
= checkThreeWayNarrowingConversion(
12555 S
, Type
, LHS
.get(), LHSType
, LHS
.get()->getBeginLoc());
12556 HasNarrowing
|= checkThreeWayNarrowingConversion(S
, Type
, RHS
.get(), RHSType
,
12557 RHS
.get()->getBeginLoc());
12561 assert(!Type
.isNull() && "composite type for <=> has not been set");
12563 return S
.CheckComparisonCategoryType(
12564 *CCT
, Loc
, Sema::ComparisonCategoryUsage::OperatorInExpression
);
12567 static QualType
checkArithmeticOrEnumeralCompare(Sema
&S
, ExprResult
&LHS
,
12569 SourceLocation Loc
,
12570 BinaryOperatorKind Opc
) {
12572 return checkArithmeticOrEnumeralThreeWayCompare(S
, LHS
, RHS
, Loc
);
12574 // C99 6.5.8p3 / C99 6.5.9p4
12576 S
.UsualArithmeticConversions(LHS
, RHS
, Loc
, Sema::ACK_Comparison
);
12577 if (LHS
.isInvalid() || RHS
.isInvalid())
12580 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12581 assert(Type
->isArithmeticType() || Type
->isEnumeralType());
12583 if (Type
->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc
))
12584 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12586 // Check for comparisons of floating point operands using != and ==.
12587 if (Type
->hasFloatingRepresentation())
12588 S
.CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
12590 // The result of comparisons is 'bool' in C++, 'int' in C.
12591 return S
.Context
.getLogicalOperationType();
12594 void Sema::CheckPtrComparisonWithNullChar(ExprResult
&E
, ExprResult
&NullE
) {
12595 if (!NullE
.get()->getType()->isAnyPointerType())
12597 int NullValue
= PP
.isMacroDefined("NULL") ? 0 : 1;
12598 if (!E
.get()->getType()->isAnyPointerType() &&
12599 E
.get()->isNullPointerConstant(Context
,
12600 Expr::NPC_ValueDependentIsNotNull
) ==
12601 Expr::NPCK_ZeroExpression
) {
12602 if (const auto *CL
= dyn_cast
<CharacterLiteral
>(E
.get())) {
12603 if (CL
->getValue() == 0)
12604 Diag(E
.get()->getExprLoc(), diag::warn_pointer_compare
)
12606 << FixItHint::CreateReplacement(E
.get()->getExprLoc(),
12607 NullValue
? "NULL" : "(void *)0");
12608 } else if (const auto *CE
= dyn_cast
<CStyleCastExpr
>(E
.get())) {
12609 TypeSourceInfo
*TI
= CE
->getTypeInfoAsWritten();
12610 QualType T
= Context
.getCanonicalType(TI
->getType()).getUnqualifiedType();
12611 if (T
== Context
.CharTy
)
12612 Diag(E
.get()->getExprLoc(), diag::warn_pointer_compare
)
12614 << FixItHint::CreateReplacement(E
.get()->getExprLoc(),
12615 NullValue
? "NULL" : "(void *)0");
12620 // C99 6.5.8, C++ [expr.rel]
12621 QualType
Sema::CheckCompareOperands(ExprResult
&LHS
, ExprResult
&RHS
,
12622 SourceLocation Loc
,
12623 BinaryOperatorKind Opc
) {
12624 bool IsRelational
= BinaryOperator::isRelationalOp(Opc
);
12625 bool IsThreeWay
= Opc
== BO_Cmp
;
12626 bool IsOrdered
= IsRelational
|| IsThreeWay
;
12627 auto IsAnyPointerType
= [](ExprResult E
) {
12628 QualType Ty
= E
.get()->getType();
12629 return Ty
->isPointerType() || Ty
->isMemberPointerType();
12632 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
12633 // type, array-to-pointer, ..., conversions are performed on both operands to
12634 // bring them to their composite type.
12635 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
12636 // any type-related checks.
12637 if (!IsThreeWay
|| IsAnyPointerType(LHS
) || IsAnyPointerType(RHS
)) {
12638 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
12639 if (LHS
.isInvalid())
12641 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
12642 if (RHS
.isInvalid())
12645 LHS
= DefaultLvalueConversion(LHS
.get());
12646 if (LHS
.isInvalid())
12648 RHS
= DefaultLvalueConversion(RHS
.get());
12649 if (RHS
.isInvalid())
12653 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/true);
12654 if (!getLangOpts().CPlusPlus
&& BinaryOperator::isEqualityOp(Opc
)) {
12655 CheckPtrComparisonWithNullChar(LHS
, RHS
);
12656 CheckPtrComparisonWithNullChar(RHS
, LHS
);
12659 // Handle vector comparisons separately.
12660 if (LHS
.get()->getType()->isVectorType() ||
12661 RHS
.get()->getType()->isVectorType())
12662 return CheckVectorCompareOperands(LHS
, RHS
, Loc
, Opc
);
12664 if (LHS
.get()->getType()->isVLSTBuiltinType() ||
12665 RHS
.get()->getType()->isVLSTBuiltinType())
12666 return CheckSizelessVectorCompareOperands(LHS
, RHS
, Loc
, Opc
);
12668 diagnoseLogicalNotOnLHSofCheck(*this, LHS
, RHS
, Loc
, Opc
);
12669 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
12671 QualType LHSType
= LHS
.get()->getType();
12672 QualType RHSType
= RHS
.get()->getType();
12673 if ((LHSType
->isArithmeticType() || LHSType
->isEnumeralType()) &&
12674 (RHSType
->isArithmeticType() || RHSType
->isEnumeralType()))
12675 return checkArithmeticOrEnumeralCompare(*this, LHS
, RHS
, Loc
, Opc
);
12677 const Expr::NullPointerConstantKind LHSNullKind
=
12678 LHS
.get()->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
);
12679 const Expr::NullPointerConstantKind RHSNullKind
=
12680 RHS
.get()->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
);
12681 bool LHSIsNull
= LHSNullKind
!= Expr::NPCK_NotNull
;
12682 bool RHSIsNull
= RHSNullKind
!= Expr::NPCK_NotNull
;
12684 auto computeResultTy
= [&]() {
12686 return Context
.getLogicalOperationType();
12687 assert(getLangOpts().CPlusPlus
);
12688 assert(Context
.hasSameType(LHS
.get()->getType(), RHS
.get()->getType()));
12690 QualType CompositeTy
= LHS
.get()->getType();
12691 assert(!CompositeTy
->isReferenceType());
12693 std::optional
<ComparisonCategoryType
> CCT
=
12694 getComparisonCategoryForBuiltinCmp(CompositeTy
);
12696 return InvalidOperands(Loc
, LHS
, RHS
);
12698 if (CompositeTy
->isPointerType() && LHSIsNull
!= RHSIsNull
) {
12699 // P0946R0: Comparisons between a null pointer constant and an object
12700 // pointer result in std::strong_equality, which is ill-formed under
12702 Diag(Loc
, diag::err_typecheck_three_way_comparison_of_pointer_and_zero
)
12703 << (LHSIsNull
? LHS
.get()->getSourceRange()
12704 : RHS
.get()->getSourceRange());
12708 return CheckComparisonCategoryType(
12709 *CCT
, Loc
, ComparisonCategoryUsage::OperatorInExpression
);
12712 if (!IsOrdered
&& LHSIsNull
!= RHSIsNull
) {
12713 bool IsEquality
= Opc
== BO_EQ
;
12715 DiagnoseAlwaysNonNullPointer(LHS
.get(), RHSNullKind
, IsEquality
,
12716 RHS
.get()->getSourceRange());
12718 DiagnoseAlwaysNonNullPointer(RHS
.get(), LHSNullKind
, IsEquality
,
12719 LHS
.get()->getSourceRange());
12722 if (IsOrdered
&& LHSType
->isFunctionPointerType() &&
12723 RHSType
->isFunctionPointerType()) {
12724 // Valid unless a relational comparison of function pointers
12725 bool IsError
= Opc
== BO_Cmp
;
12727 IsError
? diag::err_typecheck_ordered_comparison_of_function_pointers
12728 : getLangOpts().CPlusPlus
12729 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
12730 : diag::ext_typecheck_ordered_comparison_of_function_pointers
;
12731 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12732 << RHS
.get()->getSourceRange();
12737 if ((LHSType
->isIntegerType() && !LHSIsNull
) ||
12738 (RHSType
->isIntegerType() && !RHSIsNull
)) {
12739 // Skip normal pointer conversion checks in this case; we have better
12740 // diagnostics for this below.
12741 } else if (getLangOpts().CPlusPlus
) {
12742 // Equality comparison of a function pointer to a void pointer is invalid,
12743 // but we allow it as an extension.
12744 // FIXME: If we really want to allow this, should it be part of composite
12745 // pointer type computation so it works in conditionals too?
12747 ((LHSType
->isFunctionPointerType() && RHSType
->isVoidPointerType()) ||
12748 (RHSType
->isFunctionPointerType() && LHSType
->isVoidPointerType()))) {
12749 // This is a gcc extension compatibility comparison.
12750 // In a SFINAE context, we treat this as a hard error to maintain
12751 // conformance with the C++ standard.
12752 diagnoseFunctionPointerToVoidComparison(
12753 *this, Loc
, LHS
, RHS
, /*isError*/ (bool)isSFINAEContext());
12755 if (isSFINAEContext())
12758 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
12759 return computeResultTy();
12762 // C++ [expr.eq]p2:
12763 // If at least one operand is a pointer [...] bring them to their
12764 // composite pointer type.
12765 // C++ [expr.spaceship]p6
12766 // If at least one of the operands is of pointer type, [...] bring them
12767 // to their composite pointer type.
12768 // C++ [expr.rel]p2:
12769 // If both operands are pointers, [...] bring them to their composite
12771 // For <=>, the only valid non-pointer types are arrays and functions, and
12772 // we already decayed those, so this is really the same as the relational
12773 // comparison rule.
12774 if ((int)LHSType
->isPointerType() + (int)RHSType
->isPointerType() >=
12775 (IsOrdered
? 2 : 1) &&
12776 (!LangOpts
.ObjCAutoRefCount
|| !(LHSType
->isObjCObjectPointerType() ||
12777 RHSType
->isObjCObjectPointerType()))) {
12778 if (convertPointersToCompositeType(*this, Loc
, LHS
, RHS
))
12780 return computeResultTy();
12782 } else if (LHSType
->isPointerType() &&
12783 RHSType
->isPointerType()) { // C99 6.5.8p2
12784 // All of the following pointer-related warnings are GCC extensions, except
12785 // when handling null pointer constants.
12786 QualType LCanPointeeTy
=
12787 LHSType
->castAs
<PointerType
>()->getPointeeType().getCanonicalType();
12788 QualType RCanPointeeTy
=
12789 RHSType
->castAs
<PointerType
>()->getPointeeType().getCanonicalType();
12791 // C99 6.5.9p2 and C99 6.5.8p2
12792 if (Context
.typesAreCompatible(LCanPointeeTy
.getUnqualifiedType(),
12793 RCanPointeeTy
.getUnqualifiedType())) {
12794 if (IsRelational
) {
12795 // Pointers both need to point to complete or incomplete types
12796 if ((LCanPointeeTy
->isIncompleteType() !=
12797 RCanPointeeTy
->isIncompleteType()) &&
12798 !getLangOpts().C11
) {
12799 Diag(Loc
, diag::ext_typecheck_compare_complete_incomplete_pointers
)
12800 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange()
12801 << LHSType
<< RHSType
<< LCanPointeeTy
->isIncompleteType()
12802 << RCanPointeeTy
->isIncompleteType();
12805 } else if (!IsRelational
&&
12806 (LCanPointeeTy
->isVoidType() || RCanPointeeTy
->isVoidType())) {
12807 // Valid unless comparison between non-null pointer and function pointer
12808 if ((LCanPointeeTy
->isFunctionType() || RCanPointeeTy
->isFunctionType())
12809 && !LHSIsNull
&& !RHSIsNull
)
12810 diagnoseFunctionPointerToVoidComparison(*this, Loc
, LHS
, RHS
,
12814 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
, /*isError*/false);
12816 if (LCanPointeeTy
!= RCanPointeeTy
) {
12817 // Treat NULL constant as a special case in OpenCL.
12818 if (getLangOpts().OpenCL
&& !LHSIsNull
&& !RHSIsNull
) {
12819 if (!LCanPointeeTy
.isAddressSpaceOverlapping(RCanPointeeTy
)) {
12821 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
12822 << LHSType
<< RHSType
<< 0 /* comparison */
12823 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12826 LangAS AddrSpaceL
= LCanPointeeTy
.getAddressSpace();
12827 LangAS AddrSpaceR
= RCanPointeeTy
.getAddressSpace();
12828 CastKind Kind
= AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
12830 if (LHSIsNull
&& !RHSIsNull
)
12831 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, Kind
);
12833 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, Kind
);
12835 return computeResultTy();
12839 // C++ [expr.eq]p4:
12840 // Two operands of type std::nullptr_t or one operand of type
12841 // std::nullptr_t and the other a null pointer constant compare
12844 // If both operands have type nullptr_t or one operand has type nullptr_t
12845 // and the other is a null pointer constant, they compare equal.
12846 if (!IsOrdered
&& LHSIsNull
&& RHSIsNull
) {
12847 if (LHSType
->isNullPtrType()) {
12848 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12849 return computeResultTy();
12851 if (RHSType
->isNullPtrType()) {
12852 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12853 return computeResultTy();
12857 if (!getLangOpts().CPlusPlus
&& !IsOrdered
&& (LHSIsNull
|| RHSIsNull
)) {
12859 // Otherwise, at least one operand is a pointer. If one is a pointer and
12860 // the other is a null pointer constant, the null pointer constant is
12861 // converted to the type of the pointer.
12862 if (LHSIsNull
&& RHSType
->isPointerType()) {
12863 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12864 return computeResultTy();
12866 if (RHSIsNull
&& LHSType
->isPointerType()) {
12867 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12868 return computeResultTy();
12872 // Comparison of Objective-C pointers and block pointers against nullptr_t.
12873 // These aren't covered by the composite pointer type rules.
12874 if (!IsOrdered
&& RHSType
->isNullPtrType() &&
12875 (LHSType
->isObjCObjectPointerType() || LHSType
->isBlockPointerType())) {
12876 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12877 return computeResultTy();
12879 if (!IsOrdered
&& LHSType
->isNullPtrType() &&
12880 (RHSType
->isObjCObjectPointerType() || RHSType
->isBlockPointerType())) {
12881 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12882 return computeResultTy();
12885 if (getLangOpts().CPlusPlus
) {
12886 if (IsRelational
&&
12887 ((LHSType
->isNullPtrType() && RHSType
->isPointerType()) ||
12888 (RHSType
->isNullPtrType() && LHSType
->isPointerType()))) {
12889 // HACK: Relational comparison of nullptr_t against a pointer type is
12890 // invalid per DR583, but we allow it within std::less<> and friends,
12891 // since otherwise common uses of it break.
12892 // FIXME: Consider removing this hack once LWG fixes std::less<> and
12893 // friends to have std::nullptr_t overload candidates.
12894 DeclContext
*DC
= CurContext
;
12895 if (isa
<FunctionDecl
>(DC
))
12896 DC
= DC
->getParent();
12897 if (auto *CTSD
= dyn_cast
<ClassTemplateSpecializationDecl
>(DC
)) {
12898 if (CTSD
->isInStdNamespace() &&
12899 llvm::StringSwitch
<bool>(CTSD
->getName())
12900 .Cases("less", "less_equal", "greater", "greater_equal", true)
12902 if (RHSType
->isNullPtrType())
12903 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
12905 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
12906 return computeResultTy();
12911 // C++ [expr.eq]p2:
12912 // If at least one operand is a pointer to member, [...] bring them to
12913 // their composite pointer type.
12915 (LHSType
->isMemberPointerType() || RHSType
->isMemberPointerType())) {
12916 if (convertPointersToCompositeType(*this, Loc
, LHS
, RHS
))
12919 return computeResultTy();
12923 // Handle block pointer types.
12924 if (!IsOrdered
&& LHSType
->isBlockPointerType() &&
12925 RHSType
->isBlockPointerType()) {
12926 QualType lpointee
= LHSType
->castAs
<BlockPointerType
>()->getPointeeType();
12927 QualType rpointee
= RHSType
->castAs
<BlockPointerType
>()->getPointeeType();
12929 if (!LHSIsNull
&& !RHSIsNull
&&
12930 !Context
.typesAreCompatible(lpointee
, rpointee
)) {
12931 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_blocks
)
12932 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12933 << RHS
.get()->getSourceRange();
12935 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
12936 return computeResultTy();
12939 // Allow block pointers to be compared with null pointer constants.
12941 && ((LHSType
->isBlockPointerType() && RHSType
->isPointerType())
12942 || (LHSType
->isPointerType() && RHSType
->isBlockPointerType()))) {
12943 if (!LHSIsNull
&& !RHSIsNull
) {
12944 if (!((RHSType
->isPointerType() && RHSType
->castAs
<PointerType
>()
12945 ->getPointeeType()->isVoidType())
12946 || (LHSType
->isPointerType() && LHSType
->castAs
<PointerType
>()
12947 ->getPointeeType()->isVoidType())))
12948 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_blocks
)
12949 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12950 << RHS
.get()->getSourceRange();
12952 if (LHSIsNull
&& !RHSIsNull
)
12953 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
12954 RHSType
->isPointerType() ? CK_BitCast
12955 : CK_AnyPointerToBlockPointerCast
);
12957 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
12958 LHSType
->isPointerType() ? CK_BitCast
12959 : CK_AnyPointerToBlockPointerCast
);
12960 return computeResultTy();
12963 if (LHSType
->isObjCObjectPointerType() ||
12964 RHSType
->isObjCObjectPointerType()) {
12965 const PointerType
*LPT
= LHSType
->getAs
<PointerType
>();
12966 const PointerType
*RPT
= RHSType
->getAs
<PointerType
>();
12968 bool LPtrToVoid
= LPT
? LPT
->getPointeeType()->isVoidType() : false;
12969 bool RPtrToVoid
= RPT
? RPT
->getPointeeType()->isVoidType() : false;
12971 if (!LPtrToVoid
&& !RPtrToVoid
&&
12972 !Context
.typesAreCompatible(LHSType
, RHSType
)) {
12973 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
,
12976 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
12977 // the RHS, but we have test coverage for this behavior.
12978 // FIXME: Consider using convertPointersToCompositeType in C++.
12979 if (LHSIsNull
&& !RHSIsNull
) {
12980 Expr
*E
= LHS
.get();
12981 if (getLangOpts().ObjCAutoRefCount
)
12982 CheckObjCConversion(SourceRange(), RHSType
, E
,
12983 CCK_ImplicitConversion
);
12984 LHS
= ImpCastExprToType(E
, RHSType
,
12985 RPT
? CK_BitCast
:CK_CPointerToObjCPointerCast
);
12988 Expr
*E
= RHS
.get();
12989 if (getLangOpts().ObjCAutoRefCount
)
12990 CheckObjCConversion(SourceRange(), LHSType
, E
, CCK_ImplicitConversion
,
12992 /*DiagnoseCFAudited=*/false, Opc
);
12993 RHS
= ImpCastExprToType(E
, LHSType
,
12994 LPT
? CK_BitCast
:CK_CPointerToObjCPointerCast
);
12996 return computeResultTy();
12998 if (LHSType
->isObjCObjectPointerType() &&
12999 RHSType
->isObjCObjectPointerType()) {
13000 if (!Context
.areComparableObjCPointerTypes(LHSType
, RHSType
))
13001 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
,
13003 if (isObjCObjectLiteral(LHS
) || isObjCObjectLiteral(RHS
))
13004 diagnoseObjCLiteralComparison(*this, Loc
, LHS
, RHS
, Opc
);
13006 if (LHSIsNull
&& !RHSIsNull
)
13007 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
13009 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
13010 return computeResultTy();
13013 if (!IsOrdered
&& LHSType
->isBlockPointerType() &&
13014 RHSType
->isBlockCompatibleObjCPointerType(Context
)) {
13015 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
13016 CK_BlockPointerToObjCPointerCast
);
13017 return computeResultTy();
13018 } else if (!IsOrdered
&&
13019 LHSType
->isBlockCompatibleObjCPointerType(Context
) &&
13020 RHSType
->isBlockPointerType()) {
13021 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
13022 CK_BlockPointerToObjCPointerCast
);
13023 return computeResultTy();
13026 if ((LHSType
->isAnyPointerType() && RHSType
->isIntegerType()) ||
13027 (LHSType
->isIntegerType() && RHSType
->isAnyPointerType())) {
13028 unsigned DiagID
= 0;
13029 bool isError
= false;
13030 if (LangOpts
.DebuggerSupport
) {
13031 // Under a debugger, allow the comparison of pointers to integers,
13032 // since users tend to want to compare addresses.
13033 } else if ((LHSIsNull
&& LHSType
->isIntegerType()) ||
13034 (RHSIsNull
&& RHSType
->isIntegerType())) {
13036 isError
= getLangOpts().CPlusPlus
;
13038 isError
? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13039 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero
;
13041 } else if (getLangOpts().CPlusPlus
) {
13042 DiagID
= diag::err_typecheck_comparison_of_pointer_integer
;
13044 } else if (IsOrdered
)
13045 DiagID
= diag::ext_typecheck_ordered_comparison_of_pointer_integer
;
13047 DiagID
= diag::ext_typecheck_comparison_of_pointer_integer
;
13051 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
13052 << RHS
.get()->getSourceRange();
13057 if (LHSType
->isIntegerType())
13058 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
13059 LHSIsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
13061 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
13062 RHSIsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
13063 return computeResultTy();
13066 // Handle block pointers.
13067 if (!IsOrdered
&& RHSIsNull
13068 && LHSType
->isBlockPointerType() && RHSType
->isIntegerType()) {
13069 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
13070 return computeResultTy();
13072 if (!IsOrdered
&& LHSIsNull
13073 && LHSType
->isIntegerType() && RHSType
->isBlockPointerType()) {
13074 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
13075 return computeResultTy();
13078 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13079 if (LHSType
->isClkEventT() && RHSType
->isClkEventT()) {
13080 return computeResultTy();
13083 if (LHSType
->isQueueT() && RHSType
->isQueueT()) {
13084 return computeResultTy();
13087 if (LHSIsNull
&& RHSType
->isQueueT()) {
13088 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
13089 return computeResultTy();
13092 if (LHSType
->isQueueT() && RHSIsNull
) {
13093 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
13094 return computeResultTy();
13098 return InvalidOperands(Loc
, LHS
, RHS
);
13101 // Return a signed ext_vector_type that is of identical size and number of
13102 // elements. For floating point vectors, return an integer type of identical
13103 // size and number of elements. In the non ext_vector_type case, search from
13104 // the largest type to the smallest type to avoid cases where long long == long,
13105 // where long gets picked over long long.
13106 QualType
Sema::GetSignedVectorType(QualType V
) {
13107 const VectorType
*VTy
= V
->castAs
<VectorType
>();
13108 unsigned TypeSize
= Context
.getTypeSize(VTy
->getElementType());
13110 if (isa
<ExtVectorType
>(VTy
)) {
13111 if (VTy
->isExtVectorBoolType())
13112 return Context
.getExtVectorType(Context
.BoolTy
, VTy
->getNumElements());
13113 if (TypeSize
== Context
.getTypeSize(Context
.CharTy
))
13114 return Context
.getExtVectorType(Context
.CharTy
, VTy
->getNumElements());
13115 if (TypeSize
== Context
.getTypeSize(Context
.ShortTy
))
13116 return Context
.getExtVectorType(Context
.ShortTy
, VTy
->getNumElements());
13117 if (TypeSize
== Context
.getTypeSize(Context
.IntTy
))
13118 return Context
.getExtVectorType(Context
.IntTy
, VTy
->getNumElements());
13119 if (TypeSize
== Context
.getTypeSize(Context
.Int128Ty
))
13120 return Context
.getExtVectorType(Context
.Int128Ty
, VTy
->getNumElements());
13121 if (TypeSize
== Context
.getTypeSize(Context
.LongTy
))
13122 return Context
.getExtVectorType(Context
.LongTy
, VTy
->getNumElements());
13123 assert(TypeSize
== Context
.getTypeSize(Context
.LongLongTy
) &&
13124 "Unhandled vector element size in vector compare");
13125 return Context
.getExtVectorType(Context
.LongLongTy
, VTy
->getNumElements());
13128 if (TypeSize
== Context
.getTypeSize(Context
.Int128Ty
))
13129 return Context
.getVectorType(Context
.Int128Ty
, VTy
->getNumElements(),
13130 VectorType::GenericVector
);
13131 if (TypeSize
== Context
.getTypeSize(Context
.LongLongTy
))
13132 return Context
.getVectorType(Context
.LongLongTy
, VTy
->getNumElements(),
13133 VectorType::GenericVector
);
13134 if (TypeSize
== Context
.getTypeSize(Context
.LongTy
))
13135 return Context
.getVectorType(Context
.LongTy
, VTy
->getNumElements(),
13136 VectorType::GenericVector
);
13137 if (TypeSize
== Context
.getTypeSize(Context
.IntTy
))
13138 return Context
.getVectorType(Context
.IntTy
, VTy
->getNumElements(),
13139 VectorType::GenericVector
);
13140 if (TypeSize
== Context
.getTypeSize(Context
.ShortTy
))
13141 return Context
.getVectorType(Context
.ShortTy
, VTy
->getNumElements(),
13142 VectorType::GenericVector
);
13143 assert(TypeSize
== Context
.getTypeSize(Context
.CharTy
) &&
13144 "Unhandled vector element size in vector compare");
13145 return Context
.getVectorType(Context
.CharTy
, VTy
->getNumElements(),
13146 VectorType::GenericVector
);
13149 QualType
Sema::GetSignedSizelessVectorType(QualType V
) {
13150 const BuiltinType
*VTy
= V
->castAs
<BuiltinType
>();
13151 assert(VTy
->isSizelessBuiltinType() && "expected sizeless type");
13153 const QualType ETy
= V
->getSveEltType(Context
);
13154 const auto TypeSize
= Context
.getTypeSize(ETy
);
13156 const QualType IntTy
= Context
.getIntTypeForBitwidth(TypeSize
, true);
13157 const llvm::ElementCount VecSize
= Context
.getBuiltinVectorTypeInfo(VTy
).EC
;
13158 return Context
.getScalableVectorType(IntTy
, VecSize
.getKnownMinValue());
13161 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
13162 /// operates on extended vector types. Instead of producing an IntTy result,
13163 /// like a scalar comparison, a vector comparison produces a vector of integer
13165 QualType
Sema::CheckVectorCompareOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13166 SourceLocation Loc
,
13167 BinaryOperatorKind Opc
) {
13168 if (Opc
== BO_Cmp
) {
13169 Diag(Loc
, diag::err_three_way_vector_comparison
);
13173 // Check to make sure we're operating on vectors of the same type and width,
13174 // Allowing one side to be a scalar of element type.
13176 CheckVectorOperands(LHS
, RHS
, Loc
, /*isCompAssign*/ false,
13177 /*AllowBothBool*/ true,
13178 /*AllowBoolConversions*/ getLangOpts().ZVector
,
13179 /*AllowBooleanOperation*/ true,
13180 /*ReportInvalid*/ true);
13181 if (vType
.isNull())
13184 QualType LHSType
= LHS
.get()->getType();
13186 // Determine the return type of a vector compare. By default clang will return
13187 // a scalar for all vector compares except vector bool and vector pixel.
13188 // With the gcc compiler we will always return a vector type and with the xl
13189 // compiler we will always return a scalar type. This switch allows choosing
13190 // which behavior is prefered.
13191 if (getLangOpts().AltiVec
) {
13192 switch (getLangOpts().getAltivecSrcCompat()) {
13193 case LangOptions::AltivecSrcCompatKind::Mixed
:
13194 // If AltiVec, the comparison results in a numeric type, i.e.
13195 // bool for C++, int for C
13196 if (vType
->castAs
<VectorType
>()->getVectorKind() ==
13197 VectorType::AltiVecVector
)
13198 return Context
.getLogicalOperationType();
13200 Diag(Loc
, diag::warn_deprecated_altivec_src_compat
);
13202 case LangOptions::AltivecSrcCompatKind::GCC
:
13203 // For GCC we always return the vector type.
13205 case LangOptions::AltivecSrcCompatKind::XL
:
13206 return Context
.getLogicalOperationType();
13211 // For non-floating point types, check for self-comparisons of the form
13212 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13213 // often indicate logic errors in the program.
13214 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
13216 // Check for comparisons of floating point operands using != and ==.
13217 if (LHSType
->hasFloatingRepresentation()) {
13218 assert(RHS
.get()->getType()->hasFloatingRepresentation());
13219 CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
13222 // Return a signed type for the vector.
13223 return GetSignedVectorType(vType
);
13226 QualType
Sema::CheckSizelessVectorCompareOperands(ExprResult
&LHS
,
13228 SourceLocation Loc
,
13229 BinaryOperatorKind Opc
) {
13230 if (Opc
== BO_Cmp
) {
13231 Diag(Loc
, diag::err_three_way_vector_comparison
);
13235 // Check to make sure we're operating on vectors of the same type and width,
13236 // Allowing one side to be a scalar of element type.
13237 QualType vType
= CheckSizelessVectorOperands(
13238 LHS
, RHS
, Loc
, /*isCompAssign*/ false, ACK_Comparison
);
13240 if (vType
.isNull())
13243 QualType LHSType
= LHS
.get()->getType();
13245 // For non-floating point types, check for self-comparisons of the form
13246 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13247 // often indicate logic errors in the program.
13248 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
13250 // Check for comparisons of floating point operands using != and ==.
13251 if (LHSType
->hasFloatingRepresentation()) {
13252 assert(RHS
.get()->getType()->hasFloatingRepresentation());
13253 CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
13256 const BuiltinType
*LHSBuiltinTy
= LHSType
->getAs
<BuiltinType
>();
13257 const BuiltinType
*RHSBuiltinTy
= RHS
.get()->getType()->getAs
<BuiltinType
>();
13259 if (LHSBuiltinTy
&& RHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool() &&
13260 RHSBuiltinTy
->isSVEBool())
13263 // Return a signed type for the vector.
13264 return GetSignedSizelessVectorType(vType
);
13267 static void diagnoseXorMisusedAsPow(Sema
&S
, const ExprResult
&XorLHS
,
13268 const ExprResult
&XorRHS
,
13269 const SourceLocation Loc
) {
13270 // Do not diagnose macros.
13271 if (Loc
.isMacroID())
13274 // Do not diagnose if both LHS and RHS are macros.
13275 if (XorLHS
.get()->getExprLoc().isMacroID() &&
13276 XorRHS
.get()->getExprLoc().isMacroID())
13279 bool Negative
= false;
13280 bool ExplicitPlus
= false;
13281 const auto *LHSInt
= dyn_cast
<IntegerLiteral
>(XorLHS
.get());
13282 const auto *RHSInt
= dyn_cast
<IntegerLiteral
>(XorRHS
.get());
13287 // Check negative literals.
13288 if (const auto *UO
= dyn_cast
<UnaryOperator
>(XorRHS
.get())) {
13289 UnaryOperatorKind Opc
= UO
->getOpcode();
13290 if (Opc
!= UO_Minus
&& Opc
!= UO_Plus
)
13292 RHSInt
= dyn_cast
<IntegerLiteral
>(UO
->getSubExpr());
13295 Negative
= (Opc
== UO_Minus
);
13296 ExplicitPlus
= !Negative
;
13302 const llvm::APInt
&LeftSideValue
= LHSInt
->getValue();
13303 llvm::APInt RightSideValue
= RHSInt
->getValue();
13304 if (LeftSideValue
!= 2 && LeftSideValue
!= 10)
13307 if (LeftSideValue
.getBitWidth() != RightSideValue
.getBitWidth())
13310 CharSourceRange ExprRange
= CharSourceRange::getCharRange(
13311 LHSInt
->getBeginLoc(), S
.getLocForEndOfToken(RHSInt
->getLocation()));
13312 llvm::StringRef ExprStr
=
13313 Lexer::getSourceText(ExprRange
, S
.getSourceManager(), S
.getLangOpts());
13315 CharSourceRange XorRange
=
13316 CharSourceRange::getCharRange(Loc
, S
.getLocForEndOfToken(Loc
));
13317 llvm::StringRef XorStr
=
13318 Lexer::getSourceText(XorRange
, S
.getSourceManager(), S
.getLangOpts());
13319 // Do not diagnose if xor keyword/macro is used.
13320 if (XorStr
== "xor")
13323 std::string LHSStr
= std::string(Lexer::getSourceText(
13324 CharSourceRange::getTokenRange(LHSInt
->getSourceRange()),
13325 S
.getSourceManager(), S
.getLangOpts()));
13326 std::string RHSStr
= std::string(Lexer::getSourceText(
13327 CharSourceRange::getTokenRange(RHSInt
->getSourceRange()),
13328 S
.getSourceManager(), S
.getLangOpts()));
13331 RightSideValue
= -RightSideValue
;
13332 RHSStr
= "-" + RHSStr
;
13333 } else if (ExplicitPlus
) {
13334 RHSStr
= "+" + RHSStr
;
13337 StringRef LHSStrRef
= LHSStr
;
13338 StringRef RHSStrRef
= RHSStr
;
13339 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13341 if (LHSStrRef
.startswith("0b") || LHSStrRef
.startswith("0B") ||
13342 RHSStrRef
.startswith("0b") || RHSStrRef
.startswith("0B") ||
13343 LHSStrRef
.startswith("0x") || LHSStrRef
.startswith("0X") ||
13344 RHSStrRef
.startswith("0x") || RHSStrRef
.startswith("0X") ||
13345 (LHSStrRef
.size() > 1 && LHSStrRef
.startswith("0")) ||
13346 (RHSStrRef
.size() > 1 && RHSStrRef
.startswith("0")) ||
13347 LHSStrRef
.contains('\'') || RHSStrRef
.contains('\''))
13351 S
.getLangOpts().CPlusPlus
|| S
.getPreprocessor().isMacroDefined("xor");
13352 const llvm::APInt XorValue
= LeftSideValue
^ RightSideValue
;
13353 int64_t RightSideIntValue
= RightSideValue
.getSExtValue();
13354 if (LeftSideValue
== 2 && RightSideIntValue
>= 0) {
13355 std::string SuggestedExpr
= "1 << " + RHSStr
;
13356 bool Overflow
= false;
13357 llvm::APInt One
= (LeftSideValue
- 1);
13358 llvm::APInt PowValue
= One
.sshl_ov(RightSideValue
, Overflow
);
13360 if (RightSideIntValue
< 64)
13361 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base
)
13362 << ExprStr
<< toString(XorValue
, 10, true) << ("1LL << " + RHSStr
)
13363 << FixItHint::CreateReplacement(ExprRange
, "1LL << " + RHSStr
);
13364 else if (RightSideIntValue
== 64)
13365 S
.Diag(Loc
, diag::warn_xor_used_as_pow
)
13366 << ExprStr
<< toString(XorValue
, 10, true);
13370 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base_extra
)
13371 << ExprStr
<< toString(XorValue
, 10, true) << SuggestedExpr
13372 << toString(PowValue
, 10, true)
13373 << FixItHint::CreateReplacement(
13374 ExprRange
, (RightSideIntValue
== 0) ? "1" : SuggestedExpr
);
13377 S
.Diag(Loc
, diag::note_xor_used_as_pow_silence
)
13378 << ("0x2 ^ " + RHSStr
) << SuggestXor
;
13379 } else if (LeftSideValue
== 10) {
13380 std::string SuggestedValue
= "1e" + std::to_string(RightSideIntValue
);
13381 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base
)
13382 << ExprStr
<< toString(XorValue
, 10, true) << SuggestedValue
13383 << FixItHint::CreateReplacement(ExprRange
, SuggestedValue
);
13384 S
.Diag(Loc
, diag::note_xor_used_as_pow_silence
)
13385 << ("0xA ^ " + RHSStr
) << SuggestXor
;
13389 QualType
Sema::CheckVectorLogicalOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13390 SourceLocation Loc
) {
13391 // Ensure that either both operands are of the same vector type, or
13392 // one operand is of a vector type and the other is of its element type.
13393 QualType vType
= CheckVectorOperands(LHS
, RHS
, Loc
, false,
13394 /*AllowBothBool*/ true,
13395 /*AllowBoolConversions*/ false,
13396 /*AllowBooleanOperation*/ false,
13397 /*ReportInvalid*/ false);
13398 if (vType
.isNull())
13399 return InvalidOperands(Loc
, LHS
, RHS
);
13400 if (getLangOpts().OpenCL
&&
13401 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13402 vType
->hasFloatingRepresentation())
13403 return InvalidOperands(Loc
, LHS
, RHS
);
13404 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13405 // usage of the logical operators && and || with vectors in C. This
13406 // check could be notionally dropped.
13407 if (!getLangOpts().CPlusPlus
&&
13408 !(isa
<ExtVectorType
>(vType
->getAs
<VectorType
>())))
13409 return InvalidLogicalVectorOperands(Loc
, LHS
, RHS
);
13411 return GetSignedVectorType(LHS
.get()->getType());
13414 QualType
Sema::CheckMatrixElementwiseOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13415 SourceLocation Loc
,
13416 bool IsCompAssign
) {
13417 if (!IsCompAssign
) {
13418 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
13419 if (LHS
.isInvalid())
13422 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
13423 if (RHS
.isInvalid())
13426 // For conversion purposes, we ignore any qualifiers.
13427 // For example, "const float" and "float" are equivalent.
13428 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
13429 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
13431 const MatrixType
*LHSMatType
= LHSType
->getAs
<MatrixType
>();
13432 const MatrixType
*RHSMatType
= RHSType
->getAs
<MatrixType
>();
13433 assert((LHSMatType
|| RHSMatType
) && "At least one operand must be a matrix");
13435 if (Context
.hasSameType(LHSType
, RHSType
))
13436 return Context
.getCommonSugaredType(LHSType
, RHSType
);
13438 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13439 // case we have to return InvalidOperands.
13440 ExprResult OriginalLHS
= LHS
;
13441 ExprResult OriginalRHS
= RHS
;
13442 if (LHSMatType
&& !RHSMatType
) {
13443 RHS
= tryConvertExprToType(RHS
.get(), LHSMatType
->getElementType());
13444 if (!RHS
.isInvalid())
13447 return InvalidOperands(Loc
, OriginalLHS
, OriginalRHS
);
13450 if (!LHSMatType
&& RHSMatType
) {
13451 LHS
= tryConvertExprToType(LHS
.get(), RHSMatType
->getElementType());
13452 if (!LHS
.isInvalid())
13454 return InvalidOperands(Loc
, OriginalLHS
, OriginalRHS
);
13457 return InvalidOperands(Loc
, LHS
, RHS
);
13460 QualType
Sema::CheckMatrixMultiplyOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13461 SourceLocation Loc
,
13462 bool IsCompAssign
) {
13463 if (!IsCompAssign
) {
13464 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
13465 if (LHS
.isInvalid())
13468 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
13469 if (RHS
.isInvalid())
13472 auto *LHSMatType
= LHS
.get()->getType()->getAs
<ConstantMatrixType
>();
13473 auto *RHSMatType
= RHS
.get()->getType()->getAs
<ConstantMatrixType
>();
13474 assert((LHSMatType
|| RHSMatType
) && "At least one operand must be a matrix");
13476 if (LHSMatType
&& RHSMatType
) {
13477 if (LHSMatType
->getNumColumns() != RHSMatType
->getNumRows())
13478 return InvalidOperands(Loc
, LHS
, RHS
);
13480 if (Context
.hasSameType(LHSMatType
, RHSMatType
))
13481 return Context
.getCommonSugaredType(
13482 LHS
.get()->getType().getUnqualifiedType(),
13483 RHS
.get()->getType().getUnqualifiedType());
13485 QualType LHSELTy
= LHSMatType
->getElementType(),
13486 RHSELTy
= RHSMatType
->getElementType();
13487 if (!Context
.hasSameType(LHSELTy
, RHSELTy
))
13488 return InvalidOperands(Loc
, LHS
, RHS
);
13490 return Context
.getConstantMatrixType(
13491 Context
.getCommonSugaredType(LHSELTy
, RHSELTy
),
13492 LHSMatType
->getNumRows(), RHSMatType
->getNumColumns());
13494 return CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, IsCompAssign
);
13497 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc
) {
13511 inline QualType
Sema::CheckBitwiseOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13512 SourceLocation Loc
,
13513 BinaryOperatorKind Opc
) {
13514 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
13516 bool IsCompAssign
=
13517 Opc
== BO_AndAssign
|| Opc
== BO_OrAssign
|| Opc
== BO_XorAssign
;
13519 bool LegalBoolVecOperator
= isLegalBoolVectorBinaryOp(Opc
);
13521 if (LHS
.get()->getType()->isVectorType() ||
13522 RHS
.get()->getType()->isVectorType()) {
13523 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13524 RHS
.get()->getType()->hasIntegerRepresentation())
13525 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
13526 /*AllowBothBool*/ true,
13527 /*AllowBoolConversions*/ getLangOpts().ZVector
,
13528 /*AllowBooleanOperation*/ LegalBoolVecOperator
,
13529 /*ReportInvalid*/ true);
13530 return InvalidOperands(Loc
, LHS
, RHS
);
13533 if (LHS
.get()->getType()->isVLSTBuiltinType() ||
13534 RHS
.get()->getType()->isVLSTBuiltinType()) {
13535 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13536 RHS
.get()->getType()->hasIntegerRepresentation())
13537 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
13539 return InvalidOperands(Loc
, LHS
, RHS
);
13542 if (LHS
.get()->getType()->isVLSTBuiltinType() ||
13543 RHS
.get()->getType()->isVLSTBuiltinType()) {
13544 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13545 RHS
.get()->getType()->hasIntegerRepresentation())
13546 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
13548 return InvalidOperands(Loc
, LHS
, RHS
);
13552 diagnoseLogicalNotOnLHSofCheck(*this, LHS
, RHS
, Loc
, Opc
);
13554 if (LHS
.get()->getType()->hasFloatingRepresentation() ||
13555 RHS
.get()->getType()->hasFloatingRepresentation())
13556 return InvalidOperands(Loc
, LHS
, RHS
);
13558 ExprResult LHSResult
= LHS
, RHSResult
= RHS
;
13559 QualType compType
= UsualArithmeticConversions(
13560 LHSResult
, RHSResult
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_BitwiseOp
);
13561 if (LHSResult
.isInvalid() || RHSResult
.isInvalid())
13563 LHS
= LHSResult
.get();
13564 RHS
= RHSResult
.get();
13567 diagnoseXorMisusedAsPow(*this, LHS
, RHS
, Loc
);
13569 if (!compType
.isNull() && compType
->isIntegralOrUnscopedEnumerationType())
13571 return InvalidOperands(Loc
, LHS
, RHS
);
13575 inline QualType
Sema::CheckLogicalOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13576 SourceLocation Loc
,
13577 BinaryOperatorKind Opc
) {
13578 // Check vector operands differently.
13579 if (LHS
.get()->getType()->isVectorType() ||
13580 RHS
.get()->getType()->isVectorType())
13581 return CheckVectorLogicalOperands(LHS
, RHS
, Loc
);
13583 bool EnumConstantInBoolContext
= false;
13584 for (const ExprResult
&HS
: {LHS
, RHS
}) {
13585 if (const auto *DREHS
= dyn_cast
<DeclRefExpr
>(HS
.get())) {
13586 const auto *ECDHS
= dyn_cast
<EnumConstantDecl
>(DREHS
->getDecl());
13587 if (ECDHS
&& ECDHS
->getInitVal() != 0 && ECDHS
->getInitVal() != 1)
13588 EnumConstantInBoolContext
= true;
13592 if (EnumConstantInBoolContext
)
13593 Diag(Loc
, diag::warn_enum_constant_in_bool_context
);
13595 // Diagnose cases where the user write a logical and/or but probably meant a
13596 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
13598 if (!EnumConstantInBoolContext
&& LHS
.get()->getType()->isIntegerType() &&
13599 !LHS
.get()->getType()->isBooleanType() &&
13600 RHS
.get()->getType()->isIntegerType() && !RHS
.get()->isValueDependent() &&
13601 // Don't warn in macros or template instantiations.
13602 !Loc
.isMacroID() && !inTemplateInstantiation()) {
13603 // If the RHS can be constant folded, and if it constant folds to something
13604 // that isn't 0 or 1 (which indicate a potential logical operation that
13605 // happened to fold to true/false) then warn.
13606 // Parens on the RHS are ignored.
13607 Expr::EvalResult EVResult
;
13608 if (RHS
.get()->EvaluateAsInt(EVResult
, Context
)) {
13609 llvm::APSInt Result
= EVResult
.Val
.getInt();
13610 if ((getLangOpts().Bool
&& !RHS
.get()->getType()->isBooleanType() &&
13611 !RHS
.get()->getExprLoc().isMacroID()) ||
13612 (Result
!= 0 && Result
!= 1)) {
13613 Diag(Loc
, diag::warn_logical_instead_of_bitwise
)
13614 << RHS
.get()->getSourceRange() << (Opc
== BO_LAnd
? "&&" : "||");
13615 // Suggest replacing the logical operator with the bitwise version
13616 Diag(Loc
, diag::note_logical_instead_of_bitwise_change_operator
)
13617 << (Opc
== BO_LAnd
? "&" : "|")
13618 << FixItHint::CreateReplacement(
13619 SourceRange(Loc
, getLocForEndOfToken(Loc
)),
13620 Opc
== BO_LAnd
? "&" : "|");
13621 if (Opc
== BO_LAnd
)
13622 // Suggest replacing "Foo() && kNonZero" with "Foo()"
13623 Diag(Loc
, diag::note_logical_instead_of_bitwise_remove_constant
)
13624 << FixItHint::CreateRemoval(
13625 SourceRange(getLocForEndOfToken(LHS
.get()->getEndLoc()),
13626 RHS
.get()->getEndLoc()));
13631 if (!Context
.getLangOpts().CPlusPlus
) {
13632 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
13633 // not operate on the built-in scalar and vector float types.
13634 if (Context
.getLangOpts().OpenCL
&&
13635 Context
.getLangOpts().OpenCLVersion
< 120) {
13636 if (LHS
.get()->getType()->isFloatingType() ||
13637 RHS
.get()->getType()->isFloatingType())
13638 return InvalidOperands(Loc
, LHS
, RHS
);
13641 LHS
= UsualUnaryConversions(LHS
.get());
13642 if (LHS
.isInvalid())
13645 RHS
= UsualUnaryConversions(RHS
.get());
13646 if (RHS
.isInvalid())
13649 if (!LHS
.get()->getType()->isScalarType() ||
13650 !RHS
.get()->getType()->isScalarType())
13651 return InvalidOperands(Loc
, LHS
, RHS
);
13653 return Context
.IntTy
;
13656 // The following is safe because we only use this method for
13657 // non-overloadable operands.
13659 // C++ [expr.log.and]p1
13660 // C++ [expr.log.or]p1
13661 // The operands are both contextually converted to type bool.
13662 ExprResult LHSRes
= PerformContextuallyConvertToBool(LHS
.get());
13663 if (LHSRes
.isInvalid())
13664 return InvalidOperands(Loc
, LHS
, RHS
);
13667 ExprResult RHSRes
= PerformContextuallyConvertToBool(RHS
.get());
13668 if (RHSRes
.isInvalid())
13669 return InvalidOperands(Loc
, LHS
, RHS
);
13672 // C++ [expr.log.and]p2
13673 // C++ [expr.log.or]p2
13674 // The result is a bool.
13675 return Context
.BoolTy
;
13678 static bool IsReadonlyMessage(Expr
*E
, Sema
&S
) {
13679 const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
);
13680 if (!ME
) return false;
13681 if (!isa
<FieldDecl
>(ME
->getMemberDecl())) return false;
13682 ObjCMessageExpr
*Base
= dyn_cast
<ObjCMessageExpr
>(
13683 ME
->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
13684 if (!Base
) return false;
13685 return Base
->getMethodDecl() != nullptr;
13688 /// Is the given expression (which must be 'const') a reference to a
13689 /// variable which was originally non-const, but which has become
13690 /// 'const' due to being captured within a block?
13691 enum NonConstCaptureKind
{ NCCK_None
, NCCK_Block
, NCCK_Lambda
};
13692 static NonConstCaptureKind
isReferenceToNonConstCapture(Sema
&S
, Expr
*E
) {
13693 assert(E
->isLValue() && E
->getType().isConstQualified());
13694 E
= E
->IgnoreParens();
13696 // Must be a reference to a declaration from an enclosing scope.
13697 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
);
13698 if (!DRE
) return NCCK_None
;
13699 if (!DRE
->refersToEnclosingVariableOrCapture()) return NCCK_None
;
13701 // The declaration must be a variable which is not declared 'const'.
13702 VarDecl
*var
= dyn_cast
<VarDecl
>(DRE
->getDecl());
13703 if (!var
) return NCCK_None
;
13704 if (var
->getType().isConstQualified()) return NCCK_None
;
13705 assert(var
->hasLocalStorage() && "capture added 'const' to non-local?");
13707 // Decide whether the first capture was for a block or a lambda.
13708 DeclContext
*DC
= S
.CurContext
, *Prev
= nullptr;
13709 // Decide whether the first capture was for a block or a lambda.
13711 // For init-capture, it is possible that the variable belongs to the
13712 // template pattern of the current context.
13713 if (auto *FD
= dyn_cast
<FunctionDecl
>(DC
))
13714 if (var
->isInitCapture() &&
13715 FD
->getTemplateInstantiationPattern() == var
->getDeclContext())
13717 if (DC
== var
->getDeclContext())
13720 DC
= DC
->getParent();
13722 // Unless we have an init-capture, we've gone one step too far.
13723 if (!var
->isInitCapture())
13725 return (isa
<BlockDecl
>(DC
) ? NCCK_Block
: NCCK_Lambda
);
13728 static bool IsTypeModifiable(QualType Ty
, bool IsDereference
) {
13729 Ty
= Ty
.getNonReferenceType();
13730 if (IsDereference
&& Ty
->isPointerType())
13731 Ty
= Ty
->getPointeeType();
13732 return !Ty
.isConstQualified();
13735 // Update err_typecheck_assign_const and note_typecheck_assign_const
13736 // when this enum is changed.
13743 ConstUnknown
, // Keep as last element
13746 /// Emit the "read-only variable not assignable" error and print notes to give
13747 /// more information about why the variable is not assignable, such as pointing
13748 /// to the declaration of a const variable, showing that a method is const, or
13749 /// that the function is returning a const reference.
13750 static void DiagnoseConstAssignment(Sema
&S
, const Expr
*E
,
13751 SourceLocation Loc
) {
13752 SourceRange ExprRange
= E
->getSourceRange();
13754 // Only emit one error on the first const found. All other consts will emit
13755 // a note to the error.
13756 bool DiagnosticEmitted
= false;
13758 // Track if the current expression is the result of a dereference, and if the
13759 // next checked expression is the result of a dereference.
13760 bool IsDereference
= false;
13761 bool NextIsDereference
= false;
13763 // Loop to process MemberExpr chains.
13765 IsDereference
= NextIsDereference
;
13767 E
= E
->IgnoreImplicit()->IgnoreParenImpCasts();
13768 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
)) {
13769 NextIsDereference
= ME
->isArrow();
13770 const ValueDecl
*VD
= ME
->getMemberDecl();
13771 if (const FieldDecl
*Field
= dyn_cast
<FieldDecl
>(VD
)) {
13772 // Mutable fields can be modified even if the class is const.
13773 if (Field
->isMutable()) {
13774 assert(DiagnosticEmitted
&& "Expected diagnostic not emitted.");
13778 if (!IsTypeModifiable(Field
->getType(), IsDereference
)) {
13779 if (!DiagnosticEmitted
) {
13780 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
13781 << ExprRange
<< ConstMember
<< false /*static*/ << Field
13782 << Field
->getType();
13783 DiagnosticEmitted
= true;
13785 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
13786 << ConstMember
<< false /*static*/ << Field
<< Field
->getType()
13787 << Field
->getSourceRange();
13791 } else if (const VarDecl
*VDecl
= dyn_cast
<VarDecl
>(VD
)) {
13792 if (VDecl
->getType().isConstQualified()) {
13793 if (!DiagnosticEmitted
) {
13794 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
13795 << ExprRange
<< ConstMember
<< true /*static*/ << VDecl
13796 << VDecl
->getType();
13797 DiagnosticEmitted
= true;
13799 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
13800 << ConstMember
<< true /*static*/ << VDecl
<< VDecl
->getType()
13801 << VDecl
->getSourceRange();
13803 // Static fields do not inherit constness from parents.
13806 break; // End MemberExpr
13807 } else if (const ArraySubscriptExpr
*ASE
=
13808 dyn_cast
<ArraySubscriptExpr
>(E
)) {
13809 E
= ASE
->getBase()->IgnoreParenImpCasts();
13811 } else if (const ExtVectorElementExpr
*EVE
=
13812 dyn_cast
<ExtVectorElementExpr
>(E
)) {
13813 E
= EVE
->getBase()->IgnoreParenImpCasts();
13819 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
13821 const FunctionDecl
*FD
= CE
->getDirectCallee();
13822 if (FD
&& !IsTypeModifiable(FD
->getReturnType(), IsDereference
)) {
13823 if (!DiagnosticEmitted
) {
13824 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
13825 << ConstFunction
<< FD
;
13826 DiagnosticEmitted
= true;
13828 S
.Diag(FD
->getReturnTypeSourceRange().getBegin(),
13829 diag::note_typecheck_assign_const
)
13830 << ConstFunction
<< FD
<< FD
->getReturnType()
13831 << FD
->getReturnTypeSourceRange();
13833 } else if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
13834 // Point to variable declaration.
13835 if (const ValueDecl
*VD
= DRE
->getDecl()) {
13836 if (!IsTypeModifiable(VD
->getType(), IsDereference
)) {
13837 if (!DiagnosticEmitted
) {
13838 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
13839 << ExprRange
<< ConstVariable
<< VD
<< VD
->getType();
13840 DiagnosticEmitted
= true;
13842 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
13843 << ConstVariable
<< VD
<< VD
->getType() << VD
->getSourceRange();
13846 } else if (isa
<CXXThisExpr
>(E
)) {
13847 if (const DeclContext
*DC
= S
.getFunctionLevelDeclContext()) {
13848 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(DC
)) {
13849 if (MD
->isConst()) {
13850 if (!DiagnosticEmitted
) {
13851 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
13852 << ConstMethod
<< MD
;
13853 DiagnosticEmitted
= true;
13855 S
.Diag(MD
->getLocation(), diag::note_typecheck_assign_const
)
13856 << ConstMethod
<< MD
<< MD
->getSourceRange();
13862 if (DiagnosticEmitted
)
13865 // Can't determine a more specific message, so display the generic error.
13866 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
<< ConstUnknown
;
13869 enum OriginalExprKind
{
13875 static void DiagnoseRecursiveConstFields(Sema
&S
, const ValueDecl
*VD
,
13876 const RecordType
*Ty
,
13877 SourceLocation Loc
, SourceRange Range
,
13878 OriginalExprKind OEK
,
13879 bool &DiagnosticEmitted
) {
13880 std::vector
<const RecordType
*> RecordTypeList
;
13881 RecordTypeList
.push_back(Ty
);
13882 unsigned NextToCheckIndex
= 0;
13883 // We walk the record hierarchy breadth-first to ensure that we print
13884 // diagnostics in field nesting order.
13885 while (RecordTypeList
.size() > NextToCheckIndex
) {
13886 bool IsNested
= NextToCheckIndex
> 0;
13887 for (const FieldDecl
*Field
:
13888 RecordTypeList
[NextToCheckIndex
]->getDecl()->fields()) {
13889 // First, check every field for constness.
13890 QualType FieldTy
= Field
->getType();
13891 if (FieldTy
.isConstQualified()) {
13892 if (!DiagnosticEmitted
) {
13893 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
13894 << Range
<< NestedConstMember
<< OEK
<< VD
13895 << IsNested
<< Field
;
13896 DiagnosticEmitted
= true;
13898 S
.Diag(Field
->getLocation(), diag::note_typecheck_assign_const
)
13899 << NestedConstMember
<< IsNested
<< Field
13900 << FieldTy
<< Field
->getSourceRange();
13903 // Then we append it to the list to check next in order.
13904 FieldTy
= FieldTy
.getCanonicalType();
13905 if (const auto *FieldRecTy
= FieldTy
->getAs
<RecordType
>()) {
13906 if (!llvm::is_contained(RecordTypeList
, FieldRecTy
))
13907 RecordTypeList
.push_back(FieldRecTy
);
13910 ++NextToCheckIndex
;
13914 /// Emit an error for the case where a record we are trying to assign to has a
13915 /// const-qualified field somewhere in its hierarchy.
13916 static void DiagnoseRecursiveConstFields(Sema
&S
, const Expr
*E
,
13917 SourceLocation Loc
) {
13918 QualType Ty
= E
->getType();
13919 assert(Ty
->isRecordType() && "lvalue was not record?");
13920 SourceRange Range
= E
->getSourceRange();
13921 const RecordType
*RTy
= Ty
.getCanonicalType()->getAs
<RecordType
>();
13922 bool DiagEmitted
= false;
13924 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
))
13925 DiagnoseRecursiveConstFields(S
, ME
->getMemberDecl(), RTy
, Loc
,
13926 Range
, OEK_Member
, DiagEmitted
);
13927 else if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
))
13928 DiagnoseRecursiveConstFields(S
, DRE
->getDecl(), RTy
, Loc
,
13929 Range
, OEK_Variable
, DiagEmitted
);
13931 DiagnoseRecursiveConstFields(S
, nullptr, RTy
, Loc
,
13932 Range
, OEK_LValue
, DiagEmitted
);
13934 DiagnoseConstAssignment(S
, E
, Loc
);
13937 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
13938 /// emit an error and return true. If so, return false.
13939 static bool CheckForModifiableLvalue(Expr
*E
, SourceLocation Loc
, Sema
&S
) {
13940 assert(!E
->hasPlaceholderType(BuiltinType::PseudoObject
));
13942 S
.CheckShadowingDeclModification(E
, Loc
);
13944 SourceLocation OrigLoc
= Loc
;
13945 Expr::isModifiableLvalueResult IsLV
= E
->isModifiableLvalue(S
.Context
,
13947 if (IsLV
== Expr::MLV_ClassTemporary
&& IsReadonlyMessage(E
, S
))
13948 IsLV
= Expr::MLV_InvalidMessageExpression
;
13949 if (IsLV
== Expr::MLV_Valid
)
13952 unsigned DiagID
= 0;
13953 bool NeedType
= false;
13954 switch (IsLV
) { // C99 6.5.16p2
13955 case Expr::MLV_ConstQualified
:
13956 // Use a specialized diagnostic when we're assigning to an object
13957 // from an enclosing function or block.
13958 if (NonConstCaptureKind NCCK
= isReferenceToNonConstCapture(S
, E
)) {
13959 if (NCCK
== NCCK_Block
)
13960 DiagID
= diag::err_block_decl_ref_not_modifiable_lvalue
;
13962 DiagID
= diag::err_lambda_decl_ref_not_modifiable_lvalue
;
13966 // In ARC, use some specialized diagnostics for occasions where we
13967 // infer 'const'. These are always pseudo-strong variables.
13968 if (S
.getLangOpts().ObjCAutoRefCount
) {
13969 DeclRefExpr
*declRef
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenCasts());
13970 if (declRef
&& isa
<VarDecl
>(declRef
->getDecl())) {
13971 VarDecl
*var
= cast
<VarDecl
>(declRef
->getDecl());
13973 // Use the normal diagnostic if it's pseudo-__strong but the
13974 // user actually wrote 'const'.
13975 if (var
->isARCPseudoStrong() &&
13976 (!var
->getTypeSourceInfo() ||
13977 !var
->getTypeSourceInfo()->getType().isConstQualified())) {
13978 // There are three pseudo-strong cases:
13980 ObjCMethodDecl
*method
= S
.getCurMethodDecl();
13981 if (method
&& var
== method
->getSelfDecl()) {
13982 DiagID
= method
->isClassMethod()
13983 ? diag::err_typecheck_arc_assign_self_class_method
13984 : diag::err_typecheck_arc_assign_self
;
13986 // - Objective-C externally_retained attribute.
13987 } else if (var
->hasAttr
<ObjCExternallyRetainedAttr
>() ||
13988 isa
<ParmVarDecl
>(var
)) {
13989 DiagID
= diag::err_typecheck_arc_assign_externally_retained
;
13991 // - fast enumeration variables
13993 DiagID
= diag::err_typecheck_arr_assign_enumeration
;
13996 SourceRange Assign
;
13997 if (Loc
!= OrigLoc
)
13998 Assign
= SourceRange(OrigLoc
, OrigLoc
);
13999 S
.Diag(Loc
, DiagID
) << E
->getSourceRange() << Assign
;
14000 // We need to preserve the AST regardless, so migration tool
14007 // If none of the special cases above are triggered, then this is a
14008 // simple const assignment.
14010 DiagnoseConstAssignment(S
, E
, Loc
);
14015 case Expr::MLV_ConstAddrSpace
:
14016 DiagnoseConstAssignment(S
, E
, Loc
);
14018 case Expr::MLV_ConstQualifiedField
:
14019 DiagnoseRecursiveConstFields(S
, E
, Loc
);
14021 case Expr::MLV_ArrayType
:
14022 case Expr::MLV_ArrayTemporary
:
14023 DiagID
= diag::err_typecheck_array_not_modifiable_lvalue
;
14026 case Expr::MLV_NotObjectType
:
14027 DiagID
= diag::err_typecheck_non_object_not_modifiable_lvalue
;
14030 case Expr::MLV_LValueCast
:
14031 DiagID
= diag::err_typecheck_lvalue_casts_not_supported
;
14033 case Expr::MLV_Valid
:
14034 llvm_unreachable("did not take early return for MLV_Valid");
14035 case Expr::MLV_InvalidExpression
:
14036 case Expr::MLV_MemberFunction
:
14037 case Expr::MLV_ClassTemporary
:
14038 DiagID
= diag::err_typecheck_expression_not_modifiable_lvalue
;
14040 case Expr::MLV_IncompleteType
:
14041 case Expr::MLV_IncompleteVoidType
:
14042 return S
.RequireCompleteType(Loc
, E
->getType(),
14043 diag::err_typecheck_incomplete_type_not_modifiable_lvalue
, E
);
14044 case Expr::MLV_DuplicateVectorComponents
:
14045 DiagID
= diag::err_typecheck_duplicate_vector_components_not_mlvalue
;
14047 case Expr::MLV_NoSetterProperty
:
14048 llvm_unreachable("readonly properties should be processed differently");
14049 case Expr::MLV_InvalidMessageExpression
:
14050 DiagID
= diag::err_readonly_message_assignment
;
14052 case Expr::MLV_SubObjCPropertySetting
:
14053 DiagID
= diag::err_no_subobject_property_setting
;
14057 SourceRange Assign
;
14058 if (Loc
!= OrigLoc
)
14059 Assign
= SourceRange(OrigLoc
, OrigLoc
);
14061 S
.Diag(Loc
, DiagID
) << E
->getType() << E
->getSourceRange() << Assign
;
14063 S
.Diag(Loc
, DiagID
) << E
->getSourceRange() << Assign
;
14067 static void CheckIdentityFieldAssignment(Expr
*LHSExpr
, Expr
*RHSExpr
,
14068 SourceLocation Loc
,
14070 if (Sema
.inTemplateInstantiation())
14072 if (Sema
.isUnevaluatedContext())
14074 if (Loc
.isInvalid() || Loc
.isMacroID())
14076 if (LHSExpr
->getExprLoc().isMacroID() || RHSExpr
->getExprLoc().isMacroID())
14080 MemberExpr
*ML
= dyn_cast
<MemberExpr
>(LHSExpr
);
14081 MemberExpr
*MR
= dyn_cast
<MemberExpr
>(RHSExpr
);
14083 if (!(isa
<CXXThisExpr
>(ML
->getBase()) && isa
<CXXThisExpr
>(MR
->getBase())))
14085 const ValueDecl
*LHSDecl
=
14086 cast
<ValueDecl
>(ML
->getMemberDecl()->getCanonicalDecl());
14087 const ValueDecl
*RHSDecl
=
14088 cast
<ValueDecl
>(MR
->getMemberDecl()->getCanonicalDecl());
14089 if (LHSDecl
!= RHSDecl
)
14091 if (LHSDecl
->getType().isVolatileQualified())
14093 if (const ReferenceType
*RefTy
= LHSDecl
->getType()->getAs
<ReferenceType
>())
14094 if (RefTy
->getPointeeType().isVolatileQualified())
14097 Sema
.Diag(Loc
, diag::warn_identity_field_assign
) << 0;
14100 // Objective-C instance variables
14101 ObjCIvarRefExpr
*OL
= dyn_cast
<ObjCIvarRefExpr
>(LHSExpr
);
14102 ObjCIvarRefExpr
*OR
= dyn_cast
<ObjCIvarRefExpr
>(RHSExpr
);
14103 if (OL
&& OR
&& OL
->getDecl() == OR
->getDecl()) {
14104 DeclRefExpr
*RL
= dyn_cast
<DeclRefExpr
>(OL
->getBase()->IgnoreImpCasts());
14105 DeclRefExpr
*RR
= dyn_cast
<DeclRefExpr
>(OR
->getBase()->IgnoreImpCasts());
14106 if (RL
&& RR
&& RL
->getDecl() == RR
->getDecl())
14107 Sema
.Diag(Loc
, diag::warn_identity_field_assign
) << 1;
14112 QualType
Sema::CheckAssignmentOperands(Expr
*LHSExpr
, ExprResult
&RHS
,
14113 SourceLocation Loc
,
14114 QualType CompoundType
,
14115 BinaryOperatorKind Opc
) {
14116 assert(!LHSExpr
->hasPlaceholderType(BuiltinType::PseudoObject
));
14118 // Verify that LHS is a modifiable lvalue, and emit error if not.
14119 if (CheckForModifiableLvalue(LHSExpr
, Loc
, *this))
14122 QualType LHSType
= LHSExpr
->getType();
14123 QualType RHSType
= CompoundType
.isNull() ? RHS
.get()->getType() :
14125 // OpenCL v1.2 s6.1.1.1 p2:
14126 // The half data type can only be used to declare a pointer to a buffer that
14127 // contains half values
14128 if (getLangOpts().OpenCL
&&
14129 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14130 LHSType
->isHalfType()) {
14131 Diag(Loc
, diag::err_opencl_half_load_store
) << 1
14132 << LHSType
.getUnqualifiedType();
14136 AssignConvertType ConvTy
;
14137 if (CompoundType
.isNull()) {
14138 Expr
*RHSCheck
= RHS
.get();
14140 CheckIdentityFieldAssignment(LHSExpr
, RHSCheck
, Loc
, *this);
14142 QualType
LHSTy(LHSType
);
14143 ConvTy
= CheckSingleAssignmentConstraints(LHSTy
, RHS
);
14144 if (RHS
.isInvalid())
14146 // Special case of NSObject attributes on c-style pointer types.
14147 if (ConvTy
== IncompatiblePointer
&&
14148 ((Context
.isObjCNSObjectType(LHSType
) &&
14149 RHSType
->isObjCObjectPointerType()) ||
14150 (Context
.isObjCNSObjectType(RHSType
) &&
14151 LHSType
->isObjCObjectPointerType())))
14152 ConvTy
= Compatible
;
14154 if (ConvTy
== Compatible
&&
14155 LHSType
->isObjCObjectType())
14156 Diag(Loc
, diag::err_objc_object_assignment
)
14159 // If the RHS is a unary plus or minus, check to see if they = and + are
14160 // right next to each other. If so, the user may have typo'd "x =+ 4"
14161 // instead of "x += 4".
14162 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(RHSCheck
))
14163 RHSCheck
= ICE
->getSubExpr();
14164 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(RHSCheck
)) {
14165 if ((UO
->getOpcode() == UO_Plus
|| UO
->getOpcode() == UO_Minus
) &&
14166 Loc
.isFileID() && UO
->getOperatorLoc().isFileID() &&
14167 // Only if the two operators are exactly adjacent.
14168 Loc
.getLocWithOffset(1) == UO
->getOperatorLoc() &&
14169 // And there is a space or other character before the subexpr of the
14170 // unary +/-. We don't want to warn on "x=-1".
14171 Loc
.getLocWithOffset(2) != UO
->getSubExpr()->getBeginLoc() &&
14172 UO
->getSubExpr()->getBeginLoc().isFileID()) {
14173 Diag(Loc
, diag::warn_not_compound_assign
)
14174 << (UO
->getOpcode() == UO_Plus
? "+" : "-")
14175 << SourceRange(UO
->getOperatorLoc(), UO
->getOperatorLoc());
14179 if (ConvTy
== Compatible
) {
14180 if (LHSType
.getObjCLifetime() == Qualifiers::OCL_Strong
) {
14181 // Warn about retain cycles where a block captures the LHS, but
14182 // not if the LHS is a simple variable into which the block is
14183 // being stored...unless that variable can be captured by reference!
14184 const Expr
*InnerLHS
= LHSExpr
->IgnoreParenCasts();
14185 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(InnerLHS
);
14186 if (!DRE
|| DRE
->getDecl()->hasAttr
<BlocksAttr
>())
14187 checkRetainCycles(LHSExpr
, RHS
.get());
14190 if (LHSType
.getObjCLifetime() == Qualifiers::OCL_Strong
||
14191 LHSType
.isNonWeakInMRRWithObjCWeak(Context
)) {
14192 // It is safe to assign a weak reference into a strong variable.
14193 // Although this code can still have problems:
14194 // id x = self.weakProp;
14195 // id y = self.weakProp;
14196 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14197 // paths through the function. This should be revisited if
14198 // -Wrepeated-use-of-weak is made flow-sensitive.
14199 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14200 // variable, which will be valid for the current autorelease scope.
14201 if (!Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
,
14202 RHS
.get()->getBeginLoc()))
14203 getCurFunction()->markSafeWeakUse(RHS
.get());
14205 } else if (getLangOpts().ObjCAutoRefCount
|| getLangOpts().ObjCWeak
) {
14206 checkUnsafeExprAssigns(Loc
, LHSExpr
, RHS
.get());
14210 // Compound assignment "x += y"
14211 ConvTy
= CheckAssignmentConstraints(Loc
, LHSType
, RHSType
);
14214 if (DiagnoseAssignmentResult(ConvTy
, Loc
, LHSType
, RHSType
,
14215 RHS
.get(), AA_Assigning
))
14218 CheckForNullPointerDereference(*this, LHSExpr
);
14220 if (getLangOpts().CPlusPlus20
&& LHSType
.isVolatileQualified()) {
14221 if (CompoundType
.isNull()) {
14222 // C++2a [expr.ass]p5:
14223 // A simple-assignment whose left operand is of a volatile-qualified
14224 // type is deprecated unless the assignment is either a discarded-value
14225 // expression or an unevaluated operand
14226 ExprEvalContexts
.back().VolatileAssignmentLHSs
.push_back(LHSExpr
);
14230 // C11 6.5.16p3: The type of an assignment expression is the type of the
14231 // left operand would have after lvalue conversion.
14232 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14233 // qualified type, the value has the unqualified version of the type of the
14234 // lvalue; additionally, if the lvalue has atomic type, the value has the
14235 // non-atomic version of the type of the lvalue.
14236 // C++ 5.17p1: the type of the assignment expression is that of its left
14238 return getLangOpts().CPlusPlus
? LHSType
: LHSType
.getAtomicUnqualifiedType();
14241 // Scenarios to ignore if expression E is:
14242 // 1. an explicit cast expression into void
14243 // 2. a function call expression that returns void
14244 static bool IgnoreCommaOperand(const Expr
*E
, const ASTContext
&Context
) {
14245 E
= E
->IgnoreParens();
14247 if (const CastExpr
*CE
= dyn_cast
<CastExpr
>(E
)) {
14248 if (CE
->getCastKind() == CK_ToVoid
) {
14252 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14253 if (CE
->getCastKind() == CK_Dependent
&& E
->getType()->isVoidType() &&
14254 CE
->getSubExpr()->getType()->isDependentType()) {
14259 if (const auto *CE
= dyn_cast
<CallExpr
>(E
))
14260 return CE
->getCallReturnType(Context
)->isVoidType();
14264 // Look for instances where it is likely the comma operator is confused with
14265 // another operator. There is an explicit list of acceptable expressions for
14266 // the left hand side of the comma operator, otherwise emit a warning.
14267 void Sema::DiagnoseCommaOperator(const Expr
*LHS
, SourceLocation Loc
) {
14268 // No warnings in macros
14269 if (Loc
.isMacroID())
14272 // Don't warn in template instantiations.
14273 if (inTemplateInstantiation())
14276 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14277 // instead, skip more than needed, then call back into here with the
14278 // CommaVisitor in SemaStmt.cpp.
14279 // The listed locations are the initialization and increment portions
14280 // of a for loop. The additional checks are on the condition of
14281 // if statements, do/while loops, and for loops.
14282 // Differences in scope flags for C89 mode requires the extra logic.
14283 const unsigned ForIncrementFlags
=
14284 getLangOpts().C99
|| getLangOpts().CPlusPlus
14285 ? Scope::ControlScope
| Scope::ContinueScope
| Scope::BreakScope
14286 : Scope::ContinueScope
| Scope::BreakScope
;
14287 const unsigned ForInitFlags
= Scope::ControlScope
| Scope::DeclScope
;
14288 const unsigned ScopeFlags
= getCurScope()->getFlags();
14289 if ((ScopeFlags
& ForIncrementFlags
) == ForIncrementFlags
||
14290 (ScopeFlags
& ForInitFlags
) == ForInitFlags
)
14293 // If there are multiple comma operators used together, get the RHS of the
14294 // of the comma operator as the LHS.
14295 while (const BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(LHS
)) {
14296 if (BO
->getOpcode() != BO_Comma
)
14298 LHS
= BO
->getRHS();
14301 // Only allow some expressions on LHS to not warn.
14302 if (IgnoreCommaOperand(LHS
, Context
))
14305 Diag(Loc
, diag::warn_comma_operator
);
14306 Diag(LHS
->getBeginLoc(), diag::note_cast_to_void
)
14307 << LHS
->getSourceRange()
14308 << FixItHint::CreateInsertion(LHS
->getBeginLoc(),
14309 LangOpts
.CPlusPlus
? "static_cast<void>("
14311 << FixItHint::CreateInsertion(PP
.getLocForEndOfToken(LHS
->getEndLoc()),
14316 static QualType
CheckCommaOperands(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
14317 SourceLocation Loc
) {
14318 LHS
= S
.CheckPlaceholderExpr(LHS
.get());
14319 RHS
= S
.CheckPlaceholderExpr(RHS
.get());
14320 if (LHS
.isInvalid() || RHS
.isInvalid())
14323 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14324 // operands, but not unary promotions.
14325 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14327 // So we treat the LHS as a ignored value, and in C++ we allow the
14328 // containing site to determine what should be done with the RHS.
14329 LHS
= S
.IgnoredValueConversions(LHS
.get());
14330 if (LHS
.isInvalid())
14333 S
.DiagnoseUnusedExprResult(LHS
.get(), diag::warn_unused_comma_left_operand
);
14335 if (!S
.getLangOpts().CPlusPlus
) {
14336 RHS
= S
.DefaultFunctionArrayLvalueConversion(RHS
.get());
14337 if (RHS
.isInvalid())
14339 if (!RHS
.get()->getType()->isVoidType())
14340 S
.RequireCompleteType(Loc
, RHS
.get()->getType(),
14341 diag::err_incomplete_type
);
14344 if (!S
.getDiagnostics().isIgnored(diag::warn_comma_operator
, Loc
))
14345 S
.DiagnoseCommaOperator(LHS
.get(), Loc
);
14347 return RHS
.get()->getType();
14350 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14351 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14352 static QualType
CheckIncrementDecrementOperand(Sema
&S
, Expr
*Op
,
14354 ExprObjectKind
&OK
,
14355 SourceLocation OpLoc
,
14356 bool IsInc
, bool IsPrefix
) {
14357 if (Op
->isTypeDependent())
14358 return S
.Context
.DependentTy
;
14360 QualType ResType
= Op
->getType();
14361 // Atomic types can be used for increment / decrement where the non-atomic
14362 // versions can, so ignore the _Atomic() specifier for the purpose of
14364 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
14365 ResType
= ResAtomicType
->getValueType();
14367 assert(!ResType
.isNull() && "no type for increment/decrement expression");
14369 if (S
.getLangOpts().CPlusPlus
&& ResType
->isBooleanType()) {
14370 // Decrement of bool is not allowed.
14372 S
.Diag(OpLoc
, diag::err_decrement_bool
) << Op
->getSourceRange();
14375 // Increment of bool sets it to true, but is deprecated.
14376 S
.Diag(OpLoc
, S
.getLangOpts().CPlusPlus17
? diag::ext_increment_bool
14377 : diag::warn_increment_bool
)
14378 << Op
->getSourceRange();
14379 } else if (S
.getLangOpts().CPlusPlus
&& ResType
->isEnumeralType()) {
14380 // Error on enum increments and decrements in C++ mode
14381 S
.Diag(OpLoc
, diag::err_increment_decrement_enum
) << IsInc
<< ResType
;
14383 } else if (ResType
->isRealType()) {
14385 } else if (ResType
->isPointerType()) {
14386 // C99 6.5.2.4p2, 6.5.6p2
14387 if (!checkArithmeticOpPointerOperand(S
, OpLoc
, Op
))
14389 } else if (ResType
->isObjCObjectPointerType()) {
14390 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14391 // Otherwise, we just need a complete type.
14392 if (checkArithmeticIncompletePointerType(S
, OpLoc
, Op
) ||
14393 checkArithmeticOnObjCPointer(S
, OpLoc
, Op
))
14395 } else if (ResType
->isAnyComplexType()) {
14396 // C99 does not support ++/-- on complex types, we allow as an extension.
14397 S
.Diag(OpLoc
, diag::ext_integer_increment_complex
)
14398 << ResType
<< Op
->getSourceRange();
14399 } else if (ResType
->isPlaceholderType()) {
14400 ExprResult PR
= S
.CheckPlaceholderExpr(Op
);
14401 if (PR
.isInvalid()) return QualType();
14402 return CheckIncrementDecrementOperand(S
, PR
.get(), VK
, OK
, OpLoc
,
14404 } else if (S
.getLangOpts().AltiVec
&& ResType
->isVectorType()) {
14405 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14406 } else if (S
.getLangOpts().ZVector
&& ResType
->isVectorType() &&
14407 (ResType
->castAs
<VectorType
>()->getVectorKind() !=
14408 VectorType::AltiVecBool
)) {
14409 // The z vector extensions allow ++ and -- for non-bool vectors.
14410 } else if(S
.getLangOpts().OpenCL
&& ResType
->isVectorType() &&
14411 ResType
->castAs
<VectorType
>()->getElementType()->isIntegerType()) {
14412 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14414 S
.Diag(OpLoc
, diag::err_typecheck_illegal_increment_decrement
)
14415 << ResType
<< int(IsInc
) << Op
->getSourceRange();
14418 // At this point, we know we have a real, complex or pointer type.
14419 // Now make sure the operand is a modifiable lvalue.
14420 if (CheckForModifiableLvalue(Op
, OpLoc
, S
))
14422 if (S
.getLangOpts().CPlusPlus20
&& ResType
.isVolatileQualified()) {
14423 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14424 // An operand with volatile-qualified type is deprecated
14425 S
.Diag(OpLoc
, diag::warn_deprecated_increment_decrement_volatile
)
14426 << IsInc
<< ResType
;
14428 // In C++, a prefix increment is the same type as the operand. Otherwise
14429 // (in C or with postfix), the increment is the unqualified type of the
14431 if (IsPrefix
&& S
.getLangOpts().CPlusPlus
) {
14433 OK
= Op
->getObjectKind();
14437 return ResType
.getUnqualifiedType();
14442 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14443 /// This routine allows us to typecheck complex/recursive expressions
14444 /// where the declaration is needed for type checking. We only need to
14445 /// handle cases when the expression references a function designator
14446 /// or is an lvalue. Here are some examples:
14448 /// - &*****f => f for f a function designator.
14450 /// - &s.zz[1].yy -> s, if zz is an array
14451 /// - *(x + 1) -> x, if x is an array
14452 /// - &"123"[2] -> 0
14453 /// - & __real__ x -> x
14455 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14457 static ValueDecl
*getPrimaryDecl(Expr
*E
) {
14458 switch (E
->getStmtClass()) {
14459 case Stmt::DeclRefExprClass
:
14460 return cast
<DeclRefExpr
>(E
)->getDecl();
14461 case Stmt::MemberExprClass
:
14462 // If this is an arrow operator, the address is an offset from
14463 // the base's value, so the object the base refers to is
14465 if (cast
<MemberExpr
>(E
)->isArrow())
14467 // Otherwise, the expression refers to a part of the base
14468 return getPrimaryDecl(cast
<MemberExpr
>(E
)->getBase());
14469 case Stmt::ArraySubscriptExprClass
: {
14470 // FIXME: This code shouldn't be necessary! We should catch the implicit
14471 // promotion of register arrays earlier.
14472 Expr
* Base
= cast
<ArraySubscriptExpr
>(E
)->getBase();
14473 if (ImplicitCastExpr
* ICE
= dyn_cast
<ImplicitCastExpr
>(Base
)) {
14474 if (ICE
->getSubExpr()->getType()->isArrayType())
14475 return getPrimaryDecl(ICE
->getSubExpr());
14479 case Stmt::UnaryOperatorClass
: {
14480 UnaryOperator
*UO
= cast
<UnaryOperator
>(E
);
14482 switch(UO
->getOpcode()) {
14486 return getPrimaryDecl(UO
->getSubExpr());
14491 case Stmt::ParenExprClass
:
14492 return getPrimaryDecl(cast
<ParenExpr
>(E
)->getSubExpr());
14493 case Stmt::ImplicitCastExprClass
:
14494 // If the result of an implicit cast is an l-value, we care about
14495 // the sub-expression; otherwise, the result here doesn't matter.
14496 return getPrimaryDecl(cast
<ImplicitCastExpr
>(E
)->getSubExpr());
14497 case Stmt::CXXUuidofExprClass
:
14498 return cast
<CXXUuidofExpr
>(E
)->getGuidDecl();
14507 AO_Vector_Element
= 1,
14508 AO_Property_Expansion
= 2,
14509 AO_Register_Variable
= 3,
14510 AO_Matrix_Element
= 4,
14514 /// Diagnose invalid operand for address of operations.
14516 /// \param Type The type of operand which cannot have its address taken.
14517 static void diagnoseAddressOfInvalidType(Sema
&S
, SourceLocation Loc
,
14518 Expr
*E
, unsigned Type
) {
14519 S
.Diag(Loc
, diag::err_typecheck_address_of
) << Type
<< E
->getSourceRange();
14522 /// CheckAddressOfOperand - The operand of & must be either a function
14523 /// designator or an lvalue designating an object. If it is an lvalue, the
14524 /// object cannot be declared with storage class register or be a bit field.
14525 /// Note: The usual conversions are *not* applied to the operand of the &
14526 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
14527 /// In C++, the operand might be an overloaded function name, in which case
14528 /// we allow the '&' but retain the overloaded-function type.
14529 QualType
Sema::CheckAddressOfOperand(ExprResult
&OrigOp
, SourceLocation OpLoc
) {
14530 if (const BuiltinType
*PTy
= OrigOp
.get()->getType()->getAsPlaceholderType()){
14531 if (PTy
->getKind() == BuiltinType::Overload
) {
14532 Expr
*E
= OrigOp
.get()->IgnoreParens();
14533 if (!isa
<OverloadExpr
>(E
)) {
14534 assert(cast
<UnaryOperator
>(E
)->getOpcode() == UO_AddrOf
);
14535 Diag(OpLoc
, diag::err_typecheck_invalid_lvalue_addrof_addrof_function
)
14536 << OrigOp
.get()->getSourceRange();
14540 OverloadExpr
*Ovl
= cast
<OverloadExpr
>(E
);
14541 if (isa
<UnresolvedMemberExpr
>(Ovl
))
14542 if (!ResolveSingleFunctionTemplateSpecialization(Ovl
)) {
14543 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
14544 << OrigOp
.get()->getSourceRange();
14548 return Context
.OverloadTy
;
14551 if (PTy
->getKind() == BuiltinType::UnknownAny
)
14552 return Context
.UnknownAnyTy
;
14554 if (PTy
->getKind() == BuiltinType::BoundMember
) {
14555 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
14556 << OrigOp
.get()->getSourceRange();
14560 OrigOp
= CheckPlaceholderExpr(OrigOp
.get());
14561 if (OrigOp
.isInvalid()) return QualType();
14564 if (OrigOp
.get()->isTypeDependent())
14565 return Context
.DependentTy
;
14567 assert(!OrigOp
.get()->hasPlaceholderType());
14569 // Make sure to ignore parentheses in subsequent checks
14570 Expr
*op
= OrigOp
.get()->IgnoreParens();
14572 // In OpenCL captures for blocks called as lambda functions
14573 // are located in the private address space. Blocks used in
14574 // enqueue_kernel can be located in a different address space
14575 // depending on a vendor implementation. Thus preventing
14576 // taking an address of the capture to avoid invalid AS casts.
14577 if (LangOpts
.OpenCL
) {
14578 auto* VarRef
= dyn_cast
<DeclRefExpr
>(op
);
14579 if (VarRef
&& VarRef
->refersToEnclosingVariableOrCapture()) {
14580 Diag(op
->getExprLoc(), diag::err_opencl_taking_address_capture
);
14585 if (getLangOpts().C99
) {
14586 // Implement C99-only parts of addressof rules.
14587 if (UnaryOperator
* uOp
= dyn_cast
<UnaryOperator
>(op
)) {
14588 if (uOp
->getOpcode() == UO_Deref
)
14589 // Per C99 6.5.3.2, the address of a deref always returns a valid result
14590 // (assuming the deref expression is valid).
14591 return uOp
->getSubExpr()->getType();
14593 // Technically, there should be a check for array subscript
14594 // expressions here, but the result of one is always an lvalue anyway.
14596 ValueDecl
*dcl
= getPrimaryDecl(op
);
14598 if (auto *FD
= dyn_cast_or_null
<FunctionDecl
>(dcl
))
14599 if (!checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
14600 op
->getBeginLoc()))
14603 Expr::LValueClassification lval
= op
->ClassifyLValue(Context
);
14604 unsigned AddressOfError
= AO_No_Error
;
14606 if (lval
== Expr::LV_ClassTemporary
|| lval
== Expr::LV_ArrayTemporary
) {
14607 bool sfinae
= (bool)isSFINAEContext();
14608 Diag(OpLoc
, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
14609 : diag::ext_typecheck_addrof_temporary
)
14610 << op
->getType() << op
->getSourceRange();
14613 // Materialize the temporary as an lvalue so that we can take its address.
14615 CreateMaterializeTemporaryExpr(op
->getType(), OrigOp
.get(), true);
14616 } else if (isa
<ObjCSelectorExpr
>(op
)) {
14617 return Context
.getPointerType(op
->getType());
14618 } else if (lval
== Expr::LV_MemberFunction
) {
14619 // If it's an instance method, make a member pointer.
14620 // The expression must have exactly the form &A::foo.
14622 // If the underlying expression isn't a decl ref, give up.
14623 if (!isa
<DeclRefExpr
>(op
)) {
14624 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
14625 << OrigOp
.get()->getSourceRange();
14628 DeclRefExpr
*DRE
= cast
<DeclRefExpr
>(op
);
14629 CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(DRE
->getDecl());
14631 // The id-expression was parenthesized.
14632 if (OrigOp
.get() != DRE
) {
14633 Diag(OpLoc
, diag::err_parens_pointer_member_function
)
14634 << OrigOp
.get()->getSourceRange();
14636 // The method was named without a qualifier.
14637 } else if (!DRE
->getQualifier()) {
14638 if (MD
->getParent()->getName().empty())
14639 Diag(OpLoc
, diag::err_unqualified_pointer_member_function
)
14640 << op
->getSourceRange();
14642 SmallString
<32> Str
;
14643 StringRef Qual
= (MD
->getParent()->getName() + "::").toStringRef(Str
);
14644 Diag(OpLoc
, diag::err_unqualified_pointer_member_function
)
14645 << op
->getSourceRange()
14646 << FixItHint::CreateInsertion(op
->getSourceRange().getBegin(), Qual
);
14650 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
14651 if (isa
<CXXDestructorDecl
>(MD
))
14652 Diag(OpLoc
, diag::err_typecheck_addrof_dtor
) << op
->getSourceRange();
14654 QualType MPTy
= Context
.getMemberPointerType(
14655 op
->getType(), Context
.getTypeDeclType(MD
->getParent()).getTypePtr());
14656 // Under the MS ABI, lock down the inheritance model now.
14657 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
14658 (void)isCompleteType(OpLoc
, MPTy
);
14660 } else if (lval
!= Expr::LV_Valid
&& lval
!= Expr::LV_IncompleteVoidType
) {
14662 // The operand must be either an l-value or a function designator
14663 if (!op
->getType()->isFunctionType()) {
14664 // Use a special diagnostic for loads from property references.
14665 if (isa
<PseudoObjectExpr
>(op
)) {
14666 AddressOfError
= AO_Property_Expansion
;
14668 Diag(OpLoc
, diag::err_typecheck_invalid_lvalue_addrof
)
14669 << op
->getType() << op
->getSourceRange();
14673 } else if (op
->getObjectKind() == OK_BitField
) { // C99 6.5.3.2p1
14674 // The operand cannot be a bit-field
14675 AddressOfError
= AO_Bit_Field
;
14676 } else if (op
->getObjectKind() == OK_VectorComponent
) {
14677 // The operand cannot be an element of a vector
14678 AddressOfError
= AO_Vector_Element
;
14679 } else if (op
->getObjectKind() == OK_MatrixComponent
) {
14680 // The operand cannot be an element of a matrix.
14681 AddressOfError
= AO_Matrix_Element
;
14682 } else if (dcl
) { // C99 6.5.3.2p1
14683 // We have an lvalue with a decl. Make sure the decl is not declared
14684 // with the register storage-class specifier.
14685 if (const VarDecl
*vd
= dyn_cast
<VarDecl
>(dcl
)) {
14686 // in C++ it is not error to take address of a register
14687 // variable (c++03 7.1.1P3)
14688 if (vd
->getStorageClass() == SC_Register
&&
14689 !getLangOpts().CPlusPlus
) {
14690 AddressOfError
= AO_Register_Variable
;
14692 } else if (isa
<MSPropertyDecl
>(dcl
)) {
14693 AddressOfError
= AO_Property_Expansion
;
14694 } else if (isa
<FunctionTemplateDecl
>(dcl
)) {
14695 return Context
.OverloadTy
;
14696 } else if (isa
<FieldDecl
>(dcl
) || isa
<IndirectFieldDecl
>(dcl
)) {
14697 // Okay: we can take the address of a field.
14698 // Could be a pointer to member, though, if there is an explicit
14699 // scope qualifier for the class.
14700 if (isa
<DeclRefExpr
>(op
) && cast
<DeclRefExpr
>(op
)->getQualifier()) {
14701 DeclContext
*Ctx
= dcl
->getDeclContext();
14702 if (Ctx
&& Ctx
->isRecord()) {
14703 if (dcl
->getType()->isReferenceType()) {
14705 diag::err_cannot_form_pointer_to_member_of_reference_type
)
14706 << dcl
->getDeclName() << dcl
->getType();
14710 while (cast
<RecordDecl
>(Ctx
)->isAnonymousStructOrUnion())
14711 Ctx
= Ctx
->getParent();
14713 QualType MPTy
= Context
.getMemberPointerType(
14715 Context
.getTypeDeclType(cast
<RecordDecl
>(Ctx
)).getTypePtr());
14716 // Under the MS ABI, lock down the inheritance model now.
14717 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
14718 (void)isCompleteType(OpLoc
, MPTy
);
14722 } else if (!isa
<FunctionDecl
, NonTypeTemplateParmDecl
, BindingDecl
,
14723 MSGuidDecl
, UnnamedGlobalConstantDecl
>(dcl
))
14724 llvm_unreachable("Unknown/unexpected decl type");
14727 if (AddressOfError
!= AO_No_Error
) {
14728 diagnoseAddressOfInvalidType(*this, OpLoc
, op
, AddressOfError
);
14732 if (lval
== Expr::LV_IncompleteVoidType
) {
14733 // Taking the address of a void variable is technically illegal, but we
14734 // allow it in cases which are otherwise valid.
14735 // Example: "extern void x; void* y = &x;".
14736 Diag(OpLoc
, diag::ext_typecheck_addrof_void
) << op
->getSourceRange();
14739 // If the operand has type "type", the result has type "pointer to type".
14740 if (op
->getType()->isObjCObjectType())
14741 return Context
.getObjCObjectPointerType(op
->getType());
14743 CheckAddressOfPackedMember(op
);
14745 return Context
.getPointerType(op
->getType());
14748 static void RecordModifiableNonNullParam(Sema
&S
, const Expr
*Exp
) {
14749 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Exp
);
14752 const Decl
*D
= DRE
->getDecl();
14755 const ParmVarDecl
*Param
= dyn_cast
<ParmVarDecl
>(D
);
14758 if (const FunctionDecl
* FD
= dyn_cast
<FunctionDecl
>(Param
->getDeclContext()))
14759 if (!FD
->hasAttr
<NonNullAttr
>() && !Param
->hasAttr
<NonNullAttr
>())
14761 if (FunctionScopeInfo
*FD
= S
.getCurFunction())
14762 FD
->ModifiedNonNullParams
.insert(Param
);
14765 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
14766 static QualType
CheckIndirectionOperand(Sema
&S
, Expr
*Op
, ExprValueKind
&VK
,
14767 SourceLocation OpLoc
,
14768 bool IsAfterAmp
= false) {
14769 if (Op
->isTypeDependent())
14770 return S
.Context
.DependentTy
;
14772 ExprResult ConvResult
= S
.UsualUnaryConversions(Op
);
14773 if (ConvResult
.isInvalid())
14775 Op
= ConvResult
.get();
14776 QualType OpTy
= Op
->getType();
14779 if (isa
<CXXReinterpretCastExpr
>(Op
)) {
14780 QualType OpOrigType
= Op
->IgnoreParenCasts()->getType();
14781 S
.CheckCompatibleReinterpretCast(OpOrigType
, OpTy
, /*IsDereference*/true,
14782 Op
->getSourceRange());
14785 if (const PointerType
*PT
= OpTy
->getAs
<PointerType
>())
14787 Result
= PT
->getPointeeType();
14789 else if (const ObjCObjectPointerType
*OPT
=
14790 OpTy
->getAs
<ObjCObjectPointerType
>())
14791 Result
= OPT
->getPointeeType();
14793 ExprResult PR
= S
.CheckPlaceholderExpr(Op
);
14794 if (PR
.isInvalid()) return QualType();
14795 if (PR
.get() != Op
)
14796 return CheckIndirectionOperand(S
, PR
.get(), VK
, OpLoc
);
14799 if (Result
.isNull()) {
14800 S
.Diag(OpLoc
, diag::err_typecheck_indirection_requires_pointer
)
14801 << OpTy
<< Op
->getSourceRange();
14805 if (Result
->isVoidType()) {
14806 // C++ [expr.unary.op]p1:
14807 // [...] the expression to which [the unary * operator] is applied shall
14808 // be a pointer to an object type, or a pointer to a function type
14809 LangOptions LO
= S
.getLangOpts();
14811 S
.Diag(OpLoc
, diag::ext_typecheck_indirection_through_void_pointer_cpp
)
14812 << OpTy
<< Op
->getSourceRange();
14813 else if (!(LO
.C99
&& IsAfterAmp
) && !S
.isUnevaluatedContext())
14814 S
.Diag(OpLoc
, diag::ext_typecheck_indirection_through_void_pointer
)
14815 << OpTy
<< Op
->getSourceRange();
14818 // Dereferences are usually l-values...
14821 // ...except that certain expressions are never l-values in C.
14822 if (!S
.getLangOpts().CPlusPlus
&& Result
.isCForbiddenLValueType())
14828 BinaryOperatorKind
Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind
) {
14829 BinaryOperatorKind Opc
;
14831 default: llvm_unreachable("Unknown binop!");
14832 case tok::periodstar
: Opc
= BO_PtrMemD
; break;
14833 case tok::arrowstar
: Opc
= BO_PtrMemI
; break;
14834 case tok::star
: Opc
= BO_Mul
; break;
14835 case tok::slash
: Opc
= BO_Div
; break;
14836 case tok::percent
: Opc
= BO_Rem
; break;
14837 case tok::plus
: Opc
= BO_Add
; break;
14838 case tok::minus
: Opc
= BO_Sub
; break;
14839 case tok::lessless
: Opc
= BO_Shl
; break;
14840 case tok::greatergreater
: Opc
= BO_Shr
; break;
14841 case tok::lessequal
: Opc
= BO_LE
; break;
14842 case tok::less
: Opc
= BO_LT
; break;
14843 case tok::greaterequal
: Opc
= BO_GE
; break;
14844 case tok::greater
: Opc
= BO_GT
; break;
14845 case tok::exclaimequal
: Opc
= BO_NE
; break;
14846 case tok::equalequal
: Opc
= BO_EQ
; break;
14847 case tok::spaceship
: Opc
= BO_Cmp
; break;
14848 case tok::amp
: Opc
= BO_And
; break;
14849 case tok::caret
: Opc
= BO_Xor
; break;
14850 case tok::pipe
: Opc
= BO_Or
; break;
14851 case tok::ampamp
: Opc
= BO_LAnd
; break;
14852 case tok::pipepipe
: Opc
= BO_LOr
; break;
14853 case tok::equal
: Opc
= BO_Assign
; break;
14854 case tok::starequal
: Opc
= BO_MulAssign
; break;
14855 case tok::slashequal
: Opc
= BO_DivAssign
; break;
14856 case tok::percentequal
: Opc
= BO_RemAssign
; break;
14857 case tok::plusequal
: Opc
= BO_AddAssign
; break;
14858 case tok::minusequal
: Opc
= BO_SubAssign
; break;
14859 case tok::lesslessequal
: Opc
= BO_ShlAssign
; break;
14860 case tok::greatergreaterequal
: Opc
= BO_ShrAssign
; break;
14861 case tok::ampequal
: Opc
= BO_AndAssign
; break;
14862 case tok::caretequal
: Opc
= BO_XorAssign
; break;
14863 case tok::pipeequal
: Opc
= BO_OrAssign
; break;
14864 case tok::comma
: Opc
= BO_Comma
; break;
14869 static inline UnaryOperatorKind
ConvertTokenKindToUnaryOpcode(
14870 tok::TokenKind Kind
) {
14871 UnaryOperatorKind Opc
;
14873 default: llvm_unreachable("Unknown unary op!");
14874 case tok::plusplus
: Opc
= UO_PreInc
; break;
14875 case tok::minusminus
: Opc
= UO_PreDec
; break;
14876 case tok::amp
: Opc
= UO_AddrOf
; break;
14877 case tok::star
: Opc
= UO_Deref
; break;
14878 case tok::plus
: Opc
= UO_Plus
; break;
14879 case tok::minus
: Opc
= UO_Minus
; break;
14880 case tok::tilde
: Opc
= UO_Not
; break;
14881 case tok::exclaim
: Opc
= UO_LNot
; break;
14882 case tok::kw___real
: Opc
= UO_Real
; break;
14883 case tok::kw___imag
: Opc
= UO_Imag
; break;
14884 case tok::kw___extension__
: Opc
= UO_Extension
; break;
14890 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl
*SelfAssigned
) {
14891 // Explore the case for adding 'this->' to the LHS of a self assignment, very
14892 // common for setters.
14895 // -void setX(int X) { X = X; }
14896 // +void setX(int X) { this->X = X; }
14899 // Only consider parameters for self assignment fixes.
14900 if (!isa
<ParmVarDecl
>(SelfAssigned
))
14902 const auto *Method
=
14903 dyn_cast_or_null
<CXXMethodDecl
>(getCurFunctionDecl(true));
14907 const CXXRecordDecl
*Parent
= Method
->getParent();
14908 // In theory this is fixable if the lambda explicitly captures this, but
14909 // that's added complexity that's rarely going to be used.
14910 if (Parent
->isLambda())
14913 // FIXME: Use an actual Lookup operation instead of just traversing fields
14914 // in order to get base class fields.
14916 llvm::find_if(Parent
->fields(),
14917 [Name(SelfAssigned
->getDeclName())](const FieldDecl
*F
) {
14918 return F
->getDeclName() == Name
;
14920 return (Field
!= Parent
->field_end()) ? *Field
: nullptr;
14923 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
14924 /// This warning suppressed in the event of macro expansions.
14925 static void DiagnoseSelfAssignment(Sema
&S
, Expr
*LHSExpr
, Expr
*RHSExpr
,
14926 SourceLocation OpLoc
, bool IsBuiltin
) {
14927 if (S
.inTemplateInstantiation())
14929 if (S
.isUnevaluatedContext())
14931 if (OpLoc
.isInvalid() || OpLoc
.isMacroID())
14933 LHSExpr
= LHSExpr
->IgnoreParenImpCasts();
14934 RHSExpr
= RHSExpr
->IgnoreParenImpCasts();
14935 const DeclRefExpr
*LHSDeclRef
= dyn_cast
<DeclRefExpr
>(LHSExpr
);
14936 const DeclRefExpr
*RHSDeclRef
= dyn_cast
<DeclRefExpr
>(RHSExpr
);
14937 if (!LHSDeclRef
|| !RHSDeclRef
||
14938 LHSDeclRef
->getLocation().isMacroID() ||
14939 RHSDeclRef
->getLocation().isMacroID())
14941 const ValueDecl
*LHSDecl
=
14942 cast
<ValueDecl
>(LHSDeclRef
->getDecl()->getCanonicalDecl());
14943 const ValueDecl
*RHSDecl
=
14944 cast
<ValueDecl
>(RHSDeclRef
->getDecl()->getCanonicalDecl());
14945 if (LHSDecl
!= RHSDecl
)
14947 if (LHSDecl
->getType().isVolatileQualified())
14949 if (const ReferenceType
*RefTy
= LHSDecl
->getType()->getAs
<ReferenceType
>())
14950 if (RefTy
->getPointeeType().isVolatileQualified())
14953 auto Diag
= S
.Diag(OpLoc
, IsBuiltin
? diag::warn_self_assignment_builtin
14954 : diag::warn_self_assignment_overloaded
)
14955 << LHSDeclRef
->getType() << LHSExpr
->getSourceRange()
14956 << RHSExpr
->getSourceRange();
14957 if (const FieldDecl
*SelfAssignField
=
14958 S
.getSelfAssignmentClassMemberCandidate(RHSDecl
))
14959 Diag
<< 1 << SelfAssignField
14960 << FixItHint::CreateInsertion(LHSDeclRef
->getBeginLoc(), "this->");
14965 /// Check if a bitwise-& is performed on an Objective-C pointer. This
14966 /// is usually indicative of introspection within the Objective-C pointer.
14967 static void checkObjCPointerIntrospection(Sema
&S
, ExprResult
&L
, ExprResult
&R
,
14968 SourceLocation OpLoc
) {
14969 if (!S
.getLangOpts().ObjC
)
14972 const Expr
*ObjCPointerExpr
= nullptr, *OtherExpr
= nullptr;
14973 const Expr
*LHS
= L
.get();
14974 const Expr
*RHS
= R
.get();
14976 if (LHS
->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14977 ObjCPointerExpr
= LHS
;
14980 else if (RHS
->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
14981 ObjCPointerExpr
= RHS
;
14985 // This warning is deliberately made very specific to reduce false
14986 // positives with logic that uses '&' for hashing. This logic mainly
14987 // looks for code trying to introspect into tagged pointers, which
14988 // code should generally never do.
14989 if (ObjCPointerExpr
&& isa
<IntegerLiteral
>(OtherExpr
->IgnoreParenCasts())) {
14990 unsigned Diag
= diag::warn_objc_pointer_masking
;
14991 // Determine if we are introspecting the result of performSelectorXXX.
14992 const Expr
*Ex
= ObjCPointerExpr
->IgnoreParenCasts();
14993 // Special case messages to -performSelector and friends, which
14994 // can return non-pointer values boxed in a pointer value.
14995 // Some clients may wish to silence warnings in this subcase.
14996 if (const ObjCMessageExpr
*ME
= dyn_cast
<ObjCMessageExpr
>(Ex
)) {
14997 Selector S
= ME
->getSelector();
14998 StringRef SelArg0
= S
.getNameForSlot(0);
14999 if (SelArg0
.startswith("performSelector"))
15000 Diag
= diag::warn_objc_pointer_masking_performSelector
;
15003 S
.Diag(OpLoc
, Diag
)
15004 << ObjCPointerExpr
->getSourceRange();
15008 static NamedDecl
*getDeclFromExpr(Expr
*E
) {
15011 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
))
15012 return DRE
->getDecl();
15013 if (auto *ME
= dyn_cast
<MemberExpr
>(E
))
15014 return ME
->getMemberDecl();
15015 if (auto *IRE
= dyn_cast
<ObjCIvarRefExpr
>(E
))
15016 return IRE
->getDecl();
15020 // This helper function promotes a binary operator's operands (which are of a
15021 // half vector type) to a vector of floats and then truncates the result to
15022 // a vector of either half or short.
15023 static ExprResult
convertHalfVecBinOp(Sema
&S
, ExprResult LHS
, ExprResult RHS
,
15024 BinaryOperatorKind Opc
, QualType ResultTy
,
15025 ExprValueKind VK
, ExprObjectKind OK
,
15026 bool IsCompAssign
, SourceLocation OpLoc
,
15027 FPOptionsOverride FPFeatures
) {
15028 auto &Context
= S
.getASTContext();
15029 assert((isVector(ResultTy
, Context
.HalfTy
) ||
15030 isVector(ResultTy
, Context
.ShortTy
)) &&
15031 "Result must be a vector of half or short");
15032 assert(isVector(LHS
.get()->getType(), Context
.HalfTy
) &&
15033 isVector(RHS
.get()->getType(), Context
.HalfTy
) &&
15034 "both operands expected to be a half vector");
15036 RHS
= convertVector(RHS
.get(), Context
.FloatTy
, S
);
15037 QualType BinOpResTy
= RHS
.get()->getType();
15039 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15040 // change BinOpResTy to a vector of ints.
15041 if (isVector(ResultTy
, Context
.ShortTy
))
15042 BinOpResTy
= S
.GetSignedVectorType(BinOpResTy
);
15045 return CompoundAssignOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
,
15046 ResultTy
, VK
, OK
, OpLoc
, FPFeatures
,
15047 BinOpResTy
, BinOpResTy
);
15049 LHS
= convertVector(LHS
.get(), Context
.FloatTy
, S
);
15050 auto *BO
= BinaryOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
,
15051 BinOpResTy
, VK
, OK
, OpLoc
, FPFeatures
);
15052 return convertVector(BO
, ResultTy
->castAs
<VectorType
>()->getElementType(), S
);
15055 static std::pair
<ExprResult
, ExprResult
>
15056 CorrectDelayedTyposInBinOp(Sema
&S
, BinaryOperatorKind Opc
, Expr
*LHSExpr
,
15058 ExprResult LHS
= LHSExpr
, RHS
= RHSExpr
;
15059 if (!S
.Context
.isDependenceAllowed()) {
15060 // C cannot handle TypoExpr nodes on either side of a binop because it
15061 // doesn't handle dependent types properly, so make sure any TypoExprs have
15062 // been dealt with before checking the operands.
15063 LHS
= S
.CorrectDelayedTyposInExpr(LHS
);
15064 RHS
= S
.CorrectDelayedTyposInExpr(
15065 RHS
, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15066 [Opc
, LHS
](Expr
*E
) {
15067 if (Opc
!= BO_Assign
)
15068 return ExprResult(E
);
15069 // Avoid correcting the RHS to the same Expr as the LHS.
15070 Decl
*D
= getDeclFromExpr(E
);
15071 return (D
&& D
== getDeclFromExpr(LHS
.get())) ? ExprError() : E
;
15074 return std::make_pair(LHS
, RHS
);
15077 /// Returns true if conversion between vectors of halfs and vectors of floats
15079 static bool needsConversionOfHalfVec(bool OpRequiresConversion
, ASTContext
&Ctx
,
15080 Expr
*E0
, Expr
*E1
= nullptr) {
15081 if (!OpRequiresConversion
|| Ctx
.getLangOpts().NativeHalfType
||
15082 Ctx
.getTargetInfo().useFP16ConversionIntrinsics())
15085 auto HasVectorOfHalfType
= [&Ctx
](Expr
*E
) {
15086 QualType Ty
= E
->IgnoreImplicit()->getType();
15088 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15089 // to vectors of floats. Although the element type of the vectors is __fp16,
15090 // the vectors shouldn't be treated as storage-only types. See the
15091 // discussion here: https://reviews.llvm.org/rG825235c140e7
15092 if (const VectorType
*VT
= Ty
->getAs
<VectorType
>()) {
15093 if (VT
->getVectorKind() == VectorType::NeonVector
)
15095 return VT
->getElementType().getCanonicalType() == Ctx
.HalfTy
;
15100 return HasVectorOfHalfType(E0
) && (!E1
|| HasVectorOfHalfType(E1
));
15103 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
15104 /// operator @p Opc at location @c TokLoc. This routine only supports
15105 /// built-in operations; ActOnBinOp handles overloaded operators.
15106 ExprResult
Sema::CreateBuiltinBinOp(SourceLocation OpLoc
,
15107 BinaryOperatorKind Opc
,
15108 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15109 if (getLangOpts().CPlusPlus11
&& isa
<InitListExpr
>(RHSExpr
)) {
15110 // The syntax only allows initializer lists on the RHS of assignment,
15111 // so we don't need to worry about accepting invalid code for
15112 // non-assignment operators.
15114 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15115 // of x = {} is x = T().
15116 InitializationKind Kind
= InitializationKind::CreateDirectList(
15117 RHSExpr
->getBeginLoc(), RHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
15118 InitializedEntity Entity
=
15119 InitializedEntity::InitializeTemporary(LHSExpr
->getType());
15120 InitializationSequence
InitSeq(*this, Entity
, Kind
, RHSExpr
);
15121 ExprResult Init
= InitSeq
.Perform(*this, Entity
, Kind
, RHSExpr
);
15122 if (Init
.isInvalid())
15124 RHSExpr
= Init
.get();
15127 ExprResult LHS
= LHSExpr
, RHS
= RHSExpr
;
15128 QualType ResultTy
; // Result type of the binary operator.
15129 // The following two variables are used for compound assignment operators
15130 QualType CompLHSTy
; // Type of LHS after promotions for computation
15131 QualType CompResultTy
; // Type of computation result
15132 ExprValueKind VK
= VK_PRValue
;
15133 ExprObjectKind OK
= OK_Ordinary
;
15134 bool ConvertHalfVec
= false;
15136 std::tie(LHS
, RHS
) = CorrectDelayedTyposInBinOp(*this, Opc
, LHSExpr
, RHSExpr
);
15137 if (!LHS
.isUsable() || !RHS
.isUsable())
15138 return ExprError();
15140 if (getLangOpts().OpenCL
) {
15141 QualType LHSTy
= LHSExpr
->getType();
15142 QualType RHSTy
= RHSExpr
->getType();
15143 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15144 // the ATOMIC_VAR_INIT macro.
15145 if (LHSTy
->isAtomicType() || RHSTy
->isAtomicType()) {
15146 SourceRange
SR(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
15147 if (BO_Assign
== Opc
)
15148 Diag(OpLoc
, diag::err_opencl_atomic_init
) << 0 << SR
;
15150 ResultTy
= InvalidOperands(OpLoc
, LHS
, RHS
);
15151 return ExprError();
15154 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15155 // only with a builtin functions and therefore should be disallowed here.
15156 if (LHSTy
->isImageType() || RHSTy
->isImageType() ||
15157 LHSTy
->isSamplerT() || RHSTy
->isSamplerT() ||
15158 LHSTy
->isPipeType() || RHSTy
->isPipeType() ||
15159 LHSTy
->isBlockPointerType() || RHSTy
->isBlockPointerType()) {
15160 ResultTy
= InvalidOperands(OpLoc
, LHS
, RHS
);
15161 return ExprError();
15165 checkTypeSupport(LHSExpr
->getType(), OpLoc
, /*ValueDecl*/ nullptr);
15166 checkTypeSupport(RHSExpr
->getType(), OpLoc
, /*ValueDecl*/ nullptr);
15170 ResultTy
= CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, QualType(), Opc
);
15171 if (getLangOpts().CPlusPlus
&&
15172 LHS
.get()->getObjectKind() != OK_ObjCProperty
) {
15173 VK
= LHS
.get()->getValueKind();
15174 OK
= LHS
.get()->getObjectKind();
15176 if (!ResultTy
.isNull()) {
15177 DiagnoseSelfAssignment(*this, LHS
.get(), RHS
.get(), OpLoc
, true);
15178 DiagnoseSelfMove(LHS
.get(), RHS
.get(), OpLoc
);
15180 // Avoid copying a block to the heap if the block is assigned to a local
15181 // auto variable that is declared in the same scope as the block. This
15182 // optimization is unsafe if the local variable is declared in an outer
15183 // scope. For example:
15189 // // It is unsafe to invoke the block here if it wasn't copied to the
15193 if (auto *BE
= dyn_cast
<BlockExpr
>(RHS
.get()->IgnoreParens()))
15194 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(LHS
.get()->IgnoreParens()))
15195 if (auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl()))
15196 if (VD
->hasLocalStorage() && getCurScope()->isDeclScope(VD
))
15197 BE
->getBlockDecl()->setCanAvoidCopyToHeap();
15199 if (LHS
.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15200 checkNonTrivialCUnion(LHS
.get()->getType(), LHS
.get()->getExprLoc(),
15201 NTCUC_Assignment
, NTCUK_Copy
);
15203 RecordModifiableNonNullParam(*this, LHS
.get());
15207 ResultTy
= CheckPointerToMemberOperands(LHS
, RHS
, VK
, OpLoc
,
15208 Opc
== BO_PtrMemI
);
15212 ConvertHalfVec
= true;
15213 ResultTy
= CheckMultiplyDivideOperands(LHS
, RHS
, OpLoc
, false,
15217 ResultTy
= CheckRemainderOperands(LHS
, RHS
, OpLoc
);
15220 ConvertHalfVec
= true;
15221 ResultTy
= CheckAdditionOperands(LHS
, RHS
, OpLoc
, Opc
);
15224 ConvertHalfVec
= true;
15225 ResultTy
= CheckSubtractionOperands(LHS
, RHS
, OpLoc
);
15229 ResultTy
= CheckShiftOperands(LHS
, RHS
, OpLoc
, Opc
);
15235 ConvertHalfVec
= true;
15236 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
15240 ConvertHalfVec
= true;
15241 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
15244 ConvertHalfVec
= true;
15245 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
15246 assert(ResultTy
.isNull() || ResultTy
->getAsCXXRecordDecl());
15249 checkObjCPointerIntrospection(*this, LHS
, RHS
, OpLoc
);
15253 ResultTy
= CheckBitwiseOperands(LHS
, RHS
, OpLoc
, Opc
);
15257 ConvertHalfVec
= true;
15258 ResultTy
= CheckLogicalOperands(LHS
, RHS
, OpLoc
, Opc
);
15262 ConvertHalfVec
= true;
15263 CompResultTy
= CheckMultiplyDivideOperands(LHS
, RHS
, OpLoc
, true,
15264 Opc
== BO_DivAssign
);
15265 CompLHSTy
= CompResultTy
;
15266 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15268 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15271 CompResultTy
= CheckRemainderOperands(LHS
, RHS
, OpLoc
, true);
15272 CompLHSTy
= CompResultTy
;
15273 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15275 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15278 ConvertHalfVec
= true;
15279 CompResultTy
= CheckAdditionOperands(LHS
, RHS
, OpLoc
, Opc
, &CompLHSTy
);
15280 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15282 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15285 ConvertHalfVec
= true;
15286 CompResultTy
= CheckSubtractionOperands(LHS
, RHS
, OpLoc
, &CompLHSTy
);
15287 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15289 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15293 CompResultTy
= CheckShiftOperands(LHS
, RHS
, OpLoc
, Opc
, true);
15294 CompLHSTy
= CompResultTy
;
15295 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15297 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15300 case BO_OrAssign
: // fallthrough
15301 DiagnoseSelfAssignment(*this, LHS
.get(), RHS
.get(), OpLoc
, true);
15304 CompResultTy
= CheckBitwiseOperands(LHS
, RHS
, OpLoc
, Opc
);
15305 CompLHSTy
= CompResultTy
;
15306 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15308 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15311 ResultTy
= CheckCommaOperands(*this, LHS
, RHS
, OpLoc
);
15312 if (getLangOpts().CPlusPlus
&& !RHS
.isInvalid()) {
15313 VK
= RHS
.get()->getValueKind();
15314 OK
= RHS
.get()->getObjectKind();
15318 if (ResultTy
.isNull() || LHS
.isInvalid() || RHS
.isInvalid())
15319 return ExprError();
15321 // Some of the binary operations require promoting operands of half vector to
15322 // float vectors and truncating the result back to half vector. For now, we do
15323 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15326 (Opc
== BO_Comma
|| isVector(RHS
.get()->getType(), Context
.HalfTy
) ==
15327 isVector(LHS
.get()->getType(), Context
.HalfTy
)) &&
15328 "both sides are half vectors or neither sides are");
15330 needsConversionOfHalfVec(ConvertHalfVec
, Context
, LHS
.get(), RHS
.get());
15332 // Check for array bounds violations for both sides of the BinaryOperator
15333 CheckArrayAccess(LHS
.get());
15334 CheckArrayAccess(RHS
.get());
15336 if (const ObjCIsaExpr
*OISA
= dyn_cast
<ObjCIsaExpr
>(LHS
.get()->IgnoreParenCasts())) {
15337 NamedDecl
*ObjectSetClass
= LookupSingleName(TUScope
,
15338 &Context
.Idents
.get("object_setClass"),
15339 SourceLocation(), LookupOrdinaryName
);
15340 if (ObjectSetClass
&& isa
<ObjCIsaExpr
>(LHS
.get())) {
15341 SourceLocation RHSLocEnd
= getLocForEndOfToken(RHS
.get()->getEndLoc());
15342 Diag(LHS
.get()->getExprLoc(), diag::warn_objc_isa_assign
)
15343 << FixItHint::CreateInsertion(LHS
.get()->getBeginLoc(),
15344 "object_setClass(")
15345 << FixItHint::CreateReplacement(SourceRange(OISA
->getOpLoc(), OpLoc
),
15347 << FixItHint::CreateInsertion(RHSLocEnd
, ")");
15350 Diag(LHS
.get()->getExprLoc(), diag::warn_objc_isa_assign
);
15352 else if (const ObjCIvarRefExpr
*OIRE
=
15353 dyn_cast
<ObjCIvarRefExpr
>(LHS
.get()->IgnoreParenCasts()))
15354 DiagnoseDirectIsaAccess(*this, OIRE
, OpLoc
, RHS
.get());
15356 // Opc is not a compound assignment if CompResultTy is null.
15357 if (CompResultTy
.isNull()) {
15358 if (ConvertHalfVec
)
15359 return convertHalfVecBinOp(*this, LHS
, RHS
, Opc
, ResultTy
, VK
, OK
, false,
15360 OpLoc
, CurFPFeatureOverrides());
15361 return BinaryOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
, ResultTy
,
15362 VK
, OK
, OpLoc
, CurFPFeatureOverrides());
15365 // Handle compound assignments.
15366 if (getLangOpts().CPlusPlus
&& LHS
.get()->getObjectKind() !=
15369 OK
= LHS
.get()->getObjectKind();
15372 // The LHS is not converted to the result type for fixed-point compound
15373 // assignment as the common type is computed on demand. Reset the CompLHSTy
15374 // to the LHS type we would have gotten after unary conversions.
15375 if (CompResultTy
->isFixedPointType())
15376 CompLHSTy
= UsualUnaryConversions(LHS
.get()).get()->getType();
15378 if (ConvertHalfVec
)
15379 return convertHalfVecBinOp(*this, LHS
, RHS
, Opc
, ResultTy
, VK
, OK
, true,
15380 OpLoc
, CurFPFeatureOverrides());
15382 return CompoundAssignOperator::Create(
15383 Context
, LHS
.get(), RHS
.get(), Opc
, ResultTy
, VK
, OK
, OpLoc
,
15384 CurFPFeatureOverrides(), CompLHSTy
, CompResultTy
);
15387 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15388 /// operators are mixed in a way that suggests that the programmer forgot that
15389 /// comparison operators have higher precedence. The most typical example of
15390 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15391 static void DiagnoseBitwisePrecedence(Sema
&Self
, BinaryOperatorKind Opc
,
15392 SourceLocation OpLoc
, Expr
*LHSExpr
,
15394 BinaryOperator
*LHSBO
= dyn_cast
<BinaryOperator
>(LHSExpr
);
15395 BinaryOperator
*RHSBO
= dyn_cast
<BinaryOperator
>(RHSExpr
);
15397 // Check that one of the sides is a comparison operator and the other isn't.
15398 bool isLeftComp
= LHSBO
&& LHSBO
->isComparisonOp();
15399 bool isRightComp
= RHSBO
&& RHSBO
->isComparisonOp();
15400 if (isLeftComp
== isRightComp
)
15403 // Bitwise operations are sometimes used as eager logical ops.
15404 // Don't diagnose this.
15405 bool isLeftBitwise
= LHSBO
&& LHSBO
->isBitwiseOp();
15406 bool isRightBitwise
= RHSBO
&& RHSBO
->isBitwiseOp();
15407 if (isLeftBitwise
|| isRightBitwise
)
15410 SourceRange DiagRange
= isLeftComp
15411 ? SourceRange(LHSExpr
->getBeginLoc(), OpLoc
)
15412 : SourceRange(OpLoc
, RHSExpr
->getEndLoc());
15413 StringRef OpStr
= isLeftComp
? LHSBO
->getOpcodeStr() : RHSBO
->getOpcodeStr();
15414 SourceRange ParensRange
=
15416 ? SourceRange(LHSBO
->getRHS()->getBeginLoc(), RHSExpr
->getEndLoc())
15417 : SourceRange(LHSExpr
->getBeginLoc(), RHSBO
->getLHS()->getEndLoc());
15419 Self
.Diag(OpLoc
, diag::warn_precedence_bitwise_rel
)
15420 << DiagRange
<< BinaryOperator::getOpcodeStr(Opc
) << OpStr
;
15421 SuggestParentheses(Self
, OpLoc
,
15422 Self
.PDiag(diag::note_precedence_silence
) << OpStr
,
15423 (isLeftComp
? LHSExpr
: RHSExpr
)->getSourceRange());
15424 SuggestParentheses(Self
, OpLoc
,
15425 Self
.PDiag(diag::note_precedence_bitwise_first
)
15426 << BinaryOperator::getOpcodeStr(Opc
),
15430 /// It accepts a '&&' expr that is inside a '||' one.
15431 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15432 /// in parentheses.
15434 EmitDiagnosticForLogicalAndInLogicalOr(Sema
&Self
, SourceLocation OpLoc
,
15435 BinaryOperator
*Bop
) {
15436 assert(Bop
->getOpcode() == BO_LAnd
);
15437 Self
.Diag(Bop
->getOperatorLoc(), diag::warn_logical_and_in_logical_or
)
15438 << Bop
->getSourceRange() << OpLoc
;
15439 SuggestParentheses(Self
, Bop
->getOperatorLoc(),
15440 Self
.PDiag(diag::note_precedence_silence
)
15441 << Bop
->getOpcodeStr(),
15442 Bop
->getSourceRange());
15445 /// Look for '&&' in the left hand of a '||' expr.
15446 static void DiagnoseLogicalAndInLogicalOrLHS(Sema
&S
, SourceLocation OpLoc
,
15447 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15448 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(LHSExpr
)) {
15449 if (Bop
->getOpcode() == BO_LAnd
) {
15450 // If it's "string_literal && a || b" don't warn since the precedence
15452 if (!isa
<StringLiteral
>(Bop
->getLHS()->IgnoreParenImpCasts()))
15453 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, Bop
);
15454 } else if (Bop
->getOpcode() == BO_LOr
) {
15455 if (BinaryOperator
*RBop
= dyn_cast
<BinaryOperator
>(Bop
->getRHS())) {
15456 // If it's "a || b && string_literal || c" we didn't warn earlier for
15457 // "a || b && string_literal", but warn now.
15458 if (RBop
->getOpcode() == BO_LAnd
&&
15459 isa
<StringLiteral
>(RBop
->getRHS()->IgnoreParenImpCasts()))
15460 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, RBop
);
15466 /// Look for '&&' in the right hand of a '||' expr.
15467 static void DiagnoseLogicalAndInLogicalOrRHS(Sema
&S
, SourceLocation OpLoc
,
15468 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15469 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(RHSExpr
)) {
15470 if (Bop
->getOpcode() == BO_LAnd
) {
15471 // If it's "a || b && string_literal" don't warn since the precedence
15473 if (!isa
<StringLiteral
>(Bop
->getRHS()->IgnoreParenImpCasts()))
15474 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, Bop
);
15479 /// Look for bitwise op in the left or right hand of a bitwise op with
15480 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15481 /// the '&' expression in parentheses.
15482 static void DiagnoseBitwiseOpInBitwiseOp(Sema
&S
, BinaryOperatorKind Opc
,
15483 SourceLocation OpLoc
, Expr
*SubExpr
) {
15484 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(SubExpr
)) {
15485 if (Bop
->isBitwiseOp() && Bop
->getOpcode() < Opc
) {
15486 S
.Diag(Bop
->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op
)
15487 << Bop
->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc
)
15488 << Bop
->getSourceRange() << OpLoc
;
15489 SuggestParentheses(S
, Bop
->getOperatorLoc(),
15490 S
.PDiag(diag::note_precedence_silence
)
15491 << Bop
->getOpcodeStr(),
15492 Bop
->getSourceRange());
15497 static void DiagnoseAdditionInShift(Sema
&S
, SourceLocation OpLoc
,
15498 Expr
*SubExpr
, StringRef Shift
) {
15499 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(SubExpr
)) {
15500 if (Bop
->getOpcode() == BO_Add
|| Bop
->getOpcode() == BO_Sub
) {
15501 StringRef Op
= Bop
->getOpcodeStr();
15502 S
.Diag(Bop
->getOperatorLoc(), diag::warn_addition_in_bitshift
)
15503 << Bop
->getSourceRange() << OpLoc
<< Shift
<< Op
;
15504 SuggestParentheses(S
, Bop
->getOperatorLoc(),
15505 S
.PDiag(diag::note_precedence_silence
) << Op
,
15506 Bop
->getSourceRange());
15511 static void DiagnoseShiftCompare(Sema
&S
, SourceLocation OpLoc
,
15512 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15513 CXXOperatorCallExpr
*OCE
= dyn_cast
<CXXOperatorCallExpr
>(LHSExpr
);
15517 FunctionDecl
*FD
= OCE
->getDirectCallee();
15518 if (!FD
|| !FD
->isOverloadedOperator())
15521 OverloadedOperatorKind Kind
= FD
->getOverloadedOperator();
15522 if (Kind
!= OO_LessLess
&& Kind
!= OO_GreaterGreater
)
15525 S
.Diag(OpLoc
, diag::warn_overloaded_shift_in_comparison
)
15526 << LHSExpr
->getSourceRange() << RHSExpr
->getSourceRange()
15527 << (Kind
== OO_LessLess
);
15528 SuggestParentheses(S
, OCE
->getOperatorLoc(),
15529 S
.PDiag(diag::note_precedence_silence
)
15530 << (Kind
== OO_LessLess
? "<<" : ">>"),
15531 OCE
->getSourceRange());
15532 SuggestParentheses(
15533 S
, OpLoc
, S
.PDiag(diag::note_evaluate_comparison_first
),
15534 SourceRange(OCE
->getArg(1)->getBeginLoc(), RHSExpr
->getEndLoc()));
15537 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
15539 static void DiagnoseBinOpPrecedence(Sema
&Self
, BinaryOperatorKind Opc
,
15540 SourceLocation OpLoc
, Expr
*LHSExpr
,
15542 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
15543 if (BinaryOperator::isBitwiseOp(Opc
))
15544 DiagnoseBitwisePrecedence(Self
, Opc
, OpLoc
, LHSExpr
, RHSExpr
);
15546 // Diagnose "arg1 & arg2 | arg3"
15547 if ((Opc
== BO_Or
|| Opc
== BO_Xor
) &&
15548 !OpLoc
.isMacroID()/* Don't warn in macros. */) {
15549 DiagnoseBitwiseOpInBitwiseOp(Self
, Opc
, OpLoc
, LHSExpr
);
15550 DiagnoseBitwiseOpInBitwiseOp(Self
, Opc
, OpLoc
, RHSExpr
);
15553 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
15554 // We don't warn for 'assert(a || b && "bad")' since this is safe.
15555 if (Opc
== BO_LOr
&& !OpLoc
.isMacroID()/* Don't warn in macros. */) {
15556 DiagnoseLogicalAndInLogicalOrLHS(Self
, OpLoc
, LHSExpr
, RHSExpr
);
15557 DiagnoseLogicalAndInLogicalOrRHS(Self
, OpLoc
, LHSExpr
, RHSExpr
);
15560 if ((Opc
== BO_Shl
&& LHSExpr
->getType()->isIntegralType(Self
.getASTContext()))
15561 || Opc
== BO_Shr
) {
15562 StringRef Shift
= BinaryOperator::getOpcodeStr(Opc
);
15563 DiagnoseAdditionInShift(Self
, OpLoc
, LHSExpr
, Shift
);
15564 DiagnoseAdditionInShift(Self
, OpLoc
, RHSExpr
, Shift
);
15567 // Warn on overloaded shift operators and comparisons, such as:
15569 if (BinaryOperator::isComparisonOp(Opc
))
15570 DiagnoseShiftCompare(Self
, OpLoc
, LHSExpr
, RHSExpr
);
15573 // Binary Operators. 'Tok' is the token for the operator.
15574 ExprResult
Sema::ActOnBinOp(Scope
*S
, SourceLocation TokLoc
,
15575 tok::TokenKind Kind
,
15576 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15577 BinaryOperatorKind Opc
= ConvertTokenKindToBinaryOpcode(Kind
);
15578 assert(LHSExpr
&& "ActOnBinOp(): missing left expression");
15579 assert(RHSExpr
&& "ActOnBinOp(): missing right expression");
15581 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
15582 DiagnoseBinOpPrecedence(*this, Opc
, TokLoc
, LHSExpr
, RHSExpr
);
15584 return BuildBinOp(S
, TokLoc
, Opc
, LHSExpr
, RHSExpr
);
15587 void Sema::LookupBinOp(Scope
*S
, SourceLocation OpLoc
, BinaryOperatorKind Opc
,
15588 UnresolvedSetImpl
&Functions
) {
15589 OverloadedOperatorKind OverOp
= BinaryOperator::getOverloadedOperator(Opc
);
15590 if (OverOp
!= OO_None
&& OverOp
!= OO_Equal
)
15591 LookupOverloadedOperatorName(OverOp
, S
, Functions
);
15593 // In C++20 onwards, we may have a second operator to look up.
15594 if (getLangOpts().CPlusPlus20
) {
15595 if (OverloadedOperatorKind ExtraOp
= getRewrittenOverloadedOperator(OverOp
))
15596 LookupOverloadedOperatorName(ExtraOp
, S
, Functions
);
15600 /// Build an overloaded binary operator expression in the given scope.
15601 static ExprResult
BuildOverloadedBinOp(Sema
&S
, Scope
*Sc
, SourceLocation OpLoc
,
15602 BinaryOperatorKind Opc
,
15603 Expr
*LHS
, Expr
*RHS
) {
15612 DiagnoseSelfAssignment(S
, LHS
, RHS
, OpLoc
, false);
15613 CheckIdentityFieldAssignment(LHS
, RHS
, OpLoc
, S
);
15619 // Find all of the overloaded operators visible from this point.
15620 UnresolvedSet
<16> Functions
;
15621 S
.LookupBinOp(Sc
, OpLoc
, Opc
, Functions
);
15623 // Build the (potentially-overloaded, potentially-dependent)
15624 // binary operation.
15625 return S
.CreateOverloadedBinOp(OpLoc
, Opc
, Functions
, LHS
, RHS
);
15628 ExprResult
Sema::BuildBinOp(Scope
*S
, SourceLocation OpLoc
,
15629 BinaryOperatorKind Opc
,
15630 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15631 ExprResult LHS
, RHS
;
15632 std::tie(LHS
, RHS
) = CorrectDelayedTyposInBinOp(*this, Opc
, LHSExpr
, RHSExpr
);
15633 if (!LHS
.isUsable() || !RHS
.isUsable())
15634 return ExprError();
15635 LHSExpr
= LHS
.get();
15636 RHSExpr
= RHS
.get();
15638 // We want to end up calling one of checkPseudoObjectAssignment
15639 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
15640 // both expressions are overloadable or either is type-dependent),
15641 // or CreateBuiltinBinOp (in any other case). We also want to get
15642 // any placeholder types out of the way.
15644 // Handle pseudo-objects in the LHS.
15645 if (const BuiltinType
*pty
= LHSExpr
->getType()->getAsPlaceholderType()) {
15646 // Assignments with a pseudo-object l-value need special analysis.
15647 if (pty
->getKind() == BuiltinType::PseudoObject
&&
15648 BinaryOperator::isAssignmentOp(Opc
))
15649 return checkPseudoObjectAssignment(S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15651 // Don't resolve overloads if the other type is overloadable.
15652 if (getLangOpts().CPlusPlus
&& pty
->getKind() == BuiltinType::Overload
) {
15653 // We can't actually test that if we still have a placeholder,
15654 // though. Fortunately, none of the exceptions we see in that
15655 // code below are valid when the LHS is an overload set. Note
15656 // that an overload set can be dependently-typed, but it never
15657 // instantiates to having an overloadable type.
15658 ExprResult resolvedRHS
= CheckPlaceholderExpr(RHSExpr
);
15659 if (resolvedRHS
.isInvalid()) return ExprError();
15660 RHSExpr
= resolvedRHS
.get();
15662 if (RHSExpr
->isTypeDependent() ||
15663 RHSExpr
->getType()->isOverloadableType())
15664 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15667 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
15668 // template, diagnose the missing 'template' keyword instead of diagnosing
15669 // an invalid use of a bound member function.
15671 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
15672 // to C++1z [over.over]/1.4, but we already checked for that case above.
15673 if (Opc
== BO_LT
&& inTemplateInstantiation() &&
15674 (pty
->getKind() == BuiltinType::BoundMember
||
15675 pty
->getKind() == BuiltinType::Overload
)) {
15676 auto *OE
= dyn_cast
<OverloadExpr
>(LHSExpr
);
15677 if (OE
&& !OE
->hasTemplateKeyword() && !OE
->hasExplicitTemplateArgs() &&
15678 llvm::any_of(OE
->decls(), [](NamedDecl
*ND
) {
15679 return isa
<FunctionTemplateDecl
>(ND
);
15681 Diag(OE
->getQualifier() ? OE
->getQualifierLoc().getBeginLoc()
15682 : OE
->getNameLoc(),
15683 diag::err_template_kw_missing
)
15684 << OE
->getName().getAsString() << "";
15685 return ExprError();
15689 ExprResult LHS
= CheckPlaceholderExpr(LHSExpr
);
15690 if (LHS
.isInvalid()) return ExprError();
15691 LHSExpr
= LHS
.get();
15694 // Handle pseudo-objects in the RHS.
15695 if (const BuiltinType
*pty
= RHSExpr
->getType()->getAsPlaceholderType()) {
15696 // An overload in the RHS can potentially be resolved by the type
15697 // being assigned to.
15698 if (Opc
== BO_Assign
&& pty
->getKind() == BuiltinType::Overload
) {
15699 if (getLangOpts().CPlusPlus
&&
15700 (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent() ||
15701 LHSExpr
->getType()->isOverloadableType()))
15702 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15704 return CreateBuiltinBinOp(OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15707 // Don't resolve overloads if the other type is overloadable.
15708 if (getLangOpts().CPlusPlus
&& pty
->getKind() == BuiltinType::Overload
&&
15709 LHSExpr
->getType()->isOverloadableType())
15710 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15712 ExprResult resolvedRHS
= CheckPlaceholderExpr(RHSExpr
);
15713 if (!resolvedRHS
.isUsable()) return ExprError();
15714 RHSExpr
= resolvedRHS
.get();
15717 if (getLangOpts().CPlusPlus
) {
15718 // If either expression is type-dependent, always build an
15720 if (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent())
15721 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15723 // Otherwise, build an overloaded op if either expression has an
15724 // overloadable type.
15725 if (LHSExpr
->getType()->isOverloadableType() ||
15726 RHSExpr
->getType()->isOverloadableType())
15727 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15730 if (getLangOpts().RecoveryAST
&&
15731 (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent())) {
15732 assert(!getLangOpts().CPlusPlus
);
15733 assert((LHSExpr
->containsErrors() || RHSExpr
->containsErrors()) &&
15734 "Should only occur in error-recovery path.");
15735 if (BinaryOperator::isCompoundAssignmentOp(Opc
))
15737 // An assignment expression has the value of the left operand after the
15738 // assignment, but is not an lvalue.
15739 return CompoundAssignOperator::Create(
15740 Context
, LHSExpr
, RHSExpr
, Opc
,
15741 LHSExpr
->getType().getUnqualifiedType(), VK_PRValue
, OK_Ordinary
,
15742 OpLoc
, CurFPFeatureOverrides());
15743 QualType ResultType
;
15746 ResultType
= LHSExpr
->getType().getUnqualifiedType();
15756 // These operators have a fixed result type regardless of operands.
15757 ResultType
= Context
.IntTy
;
15760 ResultType
= RHSExpr
->getType();
15763 ResultType
= Context
.DependentTy
;
15766 return BinaryOperator::Create(Context
, LHSExpr
, RHSExpr
, Opc
, ResultType
,
15767 VK_PRValue
, OK_Ordinary
, OpLoc
,
15768 CurFPFeatureOverrides());
15771 // Build a built-in binary operation.
15772 return CreateBuiltinBinOp(OpLoc
, Opc
, LHSExpr
, RHSExpr
);
15775 static bool isOverflowingIntegerType(ASTContext
&Ctx
, QualType T
) {
15776 if (T
.isNull() || T
->isDependentType())
15779 if (!Ctx
.isPromotableIntegerType(T
))
15782 return Ctx
.getIntWidth(T
) >= Ctx
.getIntWidth(Ctx
.IntTy
);
15785 ExprResult
Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc
,
15786 UnaryOperatorKind Opc
, Expr
*InputExpr
,
15788 ExprResult Input
= InputExpr
;
15789 ExprValueKind VK
= VK_PRValue
;
15790 ExprObjectKind OK
= OK_Ordinary
;
15791 QualType resultType
;
15792 bool CanOverflow
= false;
15794 bool ConvertHalfVec
= false;
15795 if (getLangOpts().OpenCL
) {
15796 QualType Ty
= InputExpr
->getType();
15797 // The only legal unary operation for atomics is '&'.
15798 if ((Opc
!= UO_AddrOf
&& Ty
->isAtomicType()) ||
15799 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15800 // only with a builtin functions and therefore should be disallowed here.
15801 (Ty
->isImageType() || Ty
->isSamplerT() || Ty
->isPipeType()
15802 || Ty
->isBlockPointerType())) {
15803 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15804 << InputExpr
->getType()
15805 << Input
.get()->getSourceRange());
15809 if (getLangOpts().HLSL
&& OpLoc
.isValid()) {
15810 if (Opc
== UO_AddrOf
)
15811 return ExprError(Diag(OpLoc
, diag::err_hlsl_operator_unsupported
) << 0);
15812 if (Opc
== UO_Deref
)
15813 return ExprError(Diag(OpLoc
, diag::err_hlsl_operator_unsupported
) << 1);
15821 resultType
= CheckIncrementDecrementOperand(*this, Input
.get(), VK
, OK
,
15823 Opc
== UO_PreInc
||
15825 Opc
== UO_PreInc
||
15827 CanOverflow
= isOverflowingIntegerType(Context
, resultType
);
15830 resultType
= CheckAddressOfOperand(Input
, OpLoc
);
15831 CheckAddressOfNoDeref(InputExpr
);
15832 RecordModifiableNonNullParam(*this, InputExpr
);
15835 Input
= DefaultFunctionArrayLvalueConversion(Input
.get());
15836 if (Input
.isInvalid()) return ExprError();
15838 CheckIndirectionOperand(*this, Input
.get(), VK
, OpLoc
, IsAfterAmp
);
15843 CanOverflow
= Opc
== UO_Minus
&&
15844 isOverflowingIntegerType(Context
, Input
.get()->getType());
15845 Input
= UsualUnaryConversions(Input
.get());
15846 if (Input
.isInvalid()) return ExprError();
15847 // Unary plus and minus require promoting an operand of half vector to a
15848 // float vector and truncating the result back to a half vector. For now, we
15849 // do this only when HalfArgsAndReturns is set (that is, when the target is
15851 ConvertHalfVec
= needsConversionOfHalfVec(true, Context
, Input
.get());
15853 // If the operand is a half vector, promote it to a float vector.
15854 if (ConvertHalfVec
)
15855 Input
= convertVector(Input
.get(), Context
.FloatTy
, *this);
15856 resultType
= Input
.get()->getType();
15857 if (resultType
->isDependentType())
15859 if (resultType
->isArithmeticType()) // C99 6.5.3.3p1
15861 else if (resultType
->isVectorType() &&
15862 // The z vector extensions don't allow + or - with bool vectors.
15863 (!Context
.getLangOpts().ZVector
||
15864 resultType
->castAs
<VectorType
>()->getVectorKind() !=
15865 VectorType::AltiVecBool
))
15867 else if (resultType
->isVLSTBuiltinType()) // SVE vectors allow + and -
15869 else if (getLangOpts().CPlusPlus
&& // C++ [expr.unary.op]p6
15871 resultType
->isPointerType())
15874 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15875 << resultType
<< Input
.get()->getSourceRange());
15877 case UO_Not
: // bitwise complement
15878 Input
= UsualUnaryConversions(Input
.get());
15879 if (Input
.isInvalid())
15880 return ExprError();
15881 resultType
= Input
.get()->getType();
15882 if (resultType
->isDependentType())
15884 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
15885 if (resultType
->isComplexType() || resultType
->isComplexIntegerType())
15886 // C99 does not support '~' for complex conjugation.
15887 Diag(OpLoc
, diag::ext_integer_complement_complex
)
15888 << resultType
<< Input
.get()->getSourceRange();
15889 else if (resultType
->hasIntegerRepresentation())
15891 else if (resultType
->isExtVectorType() && Context
.getLangOpts().OpenCL
) {
15892 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
15893 // on vector float types.
15894 QualType T
= resultType
->castAs
<ExtVectorType
>()->getElementType();
15895 if (!T
->isIntegerType())
15896 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15897 << resultType
<< Input
.get()->getSourceRange());
15899 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15900 << resultType
<< Input
.get()->getSourceRange());
15904 case UO_LNot
: // logical negation
15905 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
15906 Input
= DefaultFunctionArrayLvalueConversion(Input
.get());
15907 if (Input
.isInvalid()) return ExprError();
15908 resultType
= Input
.get()->getType();
15910 // Though we still have to promote half FP to float...
15911 if (resultType
->isHalfType() && !Context
.getLangOpts().NativeHalfType
) {
15912 Input
= ImpCastExprToType(Input
.get(), Context
.FloatTy
, CK_FloatingCast
).get();
15913 resultType
= Context
.FloatTy
;
15916 if (resultType
->isDependentType())
15918 if (resultType
->isScalarType() && !isScopedEnumerationType(resultType
)) {
15919 // C99 6.5.3.3p1: ok, fallthrough;
15920 if (Context
.getLangOpts().CPlusPlus
) {
15921 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
15922 // operand contextually converted to bool.
15923 Input
= ImpCastExprToType(Input
.get(), Context
.BoolTy
,
15924 ScalarTypeToBooleanCastKind(resultType
));
15925 } else if (Context
.getLangOpts().OpenCL
&&
15926 Context
.getLangOpts().OpenCLVersion
< 120) {
15927 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15928 // operate on scalar float types.
15929 if (!resultType
->isIntegerType() && !resultType
->isPointerType())
15930 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15931 << resultType
<< Input
.get()->getSourceRange());
15933 } else if (resultType
->isExtVectorType()) {
15934 if (Context
.getLangOpts().OpenCL
&&
15935 Context
.getLangOpts().getOpenCLCompatibleVersion() < 120) {
15936 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
15937 // operate on vector float types.
15938 QualType T
= resultType
->castAs
<ExtVectorType
>()->getElementType();
15939 if (!T
->isIntegerType())
15940 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15941 << resultType
<< Input
.get()->getSourceRange());
15943 // Vector logical not returns the signed variant of the operand type.
15944 resultType
= GetSignedVectorType(resultType
);
15946 } else if (Context
.getLangOpts().CPlusPlus
&& resultType
->isVectorType()) {
15947 const VectorType
*VTy
= resultType
->castAs
<VectorType
>();
15948 if (VTy
->getVectorKind() != VectorType::GenericVector
)
15949 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15950 << resultType
<< Input
.get()->getSourceRange());
15952 // Vector logical not returns the signed variant of the operand type.
15953 resultType
= GetSignedVectorType(resultType
);
15956 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
15957 << resultType
<< Input
.get()->getSourceRange());
15960 // LNot always has type int. C99 6.5.3.3p5.
15961 // In C++, it's bool. C++ 5.3.1p8
15962 resultType
= Context
.getLogicalOperationType();
15966 resultType
= CheckRealImagOperand(*this, Input
, OpLoc
, Opc
== UO_Real
);
15967 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
15968 // complex l-values to ordinary l-values and all other values to r-values.
15969 if (Input
.isInvalid()) return ExprError();
15970 if (Opc
== UO_Real
|| Input
.get()->getType()->isAnyComplexType()) {
15971 if (Input
.get()->isGLValue() &&
15972 Input
.get()->getObjectKind() == OK_Ordinary
)
15973 VK
= Input
.get()->getValueKind();
15974 } else if (!getLangOpts().CPlusPlus
) {
15975 // In C, a volatile scalar is read by __imag. In C++, it is not.
15976 Input
= DefaultLvalueConversion(Input
.get());
15980 resultType
= Input
.get()->getType();
15981 VK
= Input
.get()->getValueKind();
15982 OK
= Input
.get()->getObjectKind();
15985 // It's unnecessary to represent the pass-through operator co_await in the
15986 // AST; just return the input expression instead.
15987 assert(!Input
.get()->getType()->isDependentType() &&
15988 "the co_await expression must be non-dependant before "
15989 "building operator co_await");
15992 if (resultType
.isNull() || Input
.isInvalid())
15993 return ExprError();
15995 // Check for array bounds violations in the operand of the UnaryOperator,
15996 // except for the '*' and '&' operators that have to be handled specially
15997 // by CheckArrayAccess (as there are special cases like &array[arraysize]
15998 // that are explicitly defined as valid by the standard).
15999 if (Opc
!= UO_AddrOf
&& Opc
!= UO_Deref
)
16000 CheckArrayAccess(Input
.get());
16003 UnaryOperator::Create(Context
, Input
.get(), Opc
, resultType
, VK
, OK
,
16004 OpLoc
, CanOverflow
, CurFPFeatureOverrides());
16006 if (Opc
== UO_Deref
&& UO
->getType()->hasAttr(attr::NoDeref
) &&
16007 !isa
<ArrayType
>(UO
->getType().getDesugaredType(Context
)) &&
16008 !isUnevaluatedContext())
16009 ExprEvalContexts
.back().PossibleDerefs
.insert(UO
);
16011 // Convert the result back to a half vector.
16012 if (ConvertHalfVec
)
16013 return convertVector(UO
, Context
.HalfTy
, *this);
16017 /// Determine whether the given expression is a qualified member
16018 /// access expression, of a form that could be turned into a pointer to member
16019 /// with the address-of operator.
16020 bool Sema::isQualifiedMemberAccess(Expr
*E
) {
16021 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
16022 if (!DRE
->getQualifier())
16025 ValueDecl
*VD
= DRE
->getDecl();
16026 if (!VD
->isCXXClassMember())
16029 if (isa
<FieldDecl
>(VD
) || isa
<IndirectFieldDecl
>(VD
))
16031 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(VD
))
16032 return Method
->isInstance();
16037 if (UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(E
)) {
16038 if (!ULE
->getQualifier())
16041 for (NamedDecl
*D
: ULE
->decls()) {
16042 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
16043 if (Method
->isInstance())
16046 // Overload set does not contain methods.
16057 ExprResult
Sema::BuildUnaryOp(Scope
*S
, SourceLocation OpLoc
,
16058 UnaryOperatorKind Opc
, Expr
*Input
,
16060 // First things first: handle placeholders so that the
16061 // overloaded-operator check considers the right type.
16062 if (const BuiltinType
*pty
= Input
->getType()->getAsPlaceholderType()) {
16063 // Increment and decrement of pseudo-object references.
16064 if (pty
->getKind() == BuiltinType::PseudoObject
&&
16065 UnaryOperator::isIncrementDecrementOp(Opc
))
16066 return checkPseudoObjectIncDec(S
, OpLoc
, Opc
, Input
);
16068 // extension is always a builtin operator.
16069 if (Opc
== UO_Extension
)
16070 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
16072 // & gets special logic for several kinds of placeholder.
16073 // The builtin code knows what to do.
16074 if (Opc
== UO_AddrOf
&&
16075 (pty
->getKind() == BuiltinType::Overload
||
16076 pty
->getKind() == BuiltinType::UnknownAny
||
16077 pty
->getKind() == BuiltinType::BoundMember
))
16078 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
16080 // Anything else needs to be handled now.
16081 ExprResult Result
= CheckPlaceholderExpr(Input
);
16082 if (Result
.isInvalid()) return ExprError();
16083 Input
= Result
.get();
16086 if (getLangOpts().CPlusPlus
&& Input
->getType()->isOverloadableType() &&
16087 UnaryOperator::getOverloadedOperator(Opc
) != OO_None
&&
16088 !(Opc
== UO_AddrOf
&& isQualifiedMemberAccess(Input
))) {
16089 // Find all of the overloaded operators visible from this point.
16090 UnresolvedSet
<16> Functions
;
16091 OverloadedOperatorKind OverOp
= UnaryOperator::getOverloadedOperator(Opc
);
16092 if (S
&& OverOp
!= OO_None
)
16093 LookupOverloadedOperatorName(OverOp
, S
, Functions
);
16095 return CreateOverloadedUnaryOp(OpLoc
, Opc
, Functions
, Input
);
16098 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
, IsAfterAmp
);
16101 // Unary Operators. 'Tok' is the token for the operator.
16102 ExprResult
Sema::ActOnUnaryOp(Scope
*S
, SourceLocation OpLoc
, tok::TokenKind Op
,
16103 Expr
*Input
, bool IsAfterAmp
) {
16104 return BuildUnaryOp(S
, OpLoc
, ConvertTokenKindToUnaryOpcode(Op
), Input
,
16108 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16109 ExprResult
Sema::ActOnAddrLabel(SourceLocation OpLoc
, SourceLocation LabLoc
,
16110 LabelDecl
*TheDecl
) {
16111 TheDecl
->markUsed(Context
);
16112 // Create the AST node. The address of a label always has type 'void*'.
16113 auto *Res
= new (Context
) AddrLabelExpr(
16114 OpLoc
, LabLoc
, TheDecl
, Context
.getPointerType(Context
.VoidTy
));
16116 if (getCurFunction())
16117 getCurFunction()->AddrLabels
.push_back(Res
);
16122 void Sema::ActOnStartStmtExpr() {
16123 PushExpressionEvaluationContext(ExprEvalContexts
.back().Context
);
16126 void Sema::ActOnStmtExprError() {
16127 // Note that function is also called by TreeTransform when leaving a
16128 // StmtExpr scope without rebuilding anything.
16130 DiscardCleanupsInEvaluationContext();
16131 PopExpressionEvaluationContext();
16134 ExprResult
Sema::ActOnStmtExpr(Scope
*S
, SourceLocation LPLoc
, Stmt
*SubStmt
,
16135 SourceLocation RPLoc
) {
16136 return BuildStmtExpr(LPLoc
, SubStmt
, RPLoc
, getTemplateDepth(S
));
16139 ExprResult
Sema::BuildStmtExpr(SourceLocation LPLoc
, Stmt
*SubStmt
,
16140 SourceLocation RPLoc
, unsigned TemplateDepth
) {
16141 assert(SubStmt
&& isa
<CompoundStmt
>(SubStmt
) && "Invalid action invocation!");
16142 CompoundStmt
*Compound
= cast
<CompoundStmt
>(SubStmt
);
16144 if (hasAnyUnrecoverableErrorsInThisFunction())
16145 DiscardCleanupsInEvaluationContext();
16146 assert(!Cleanup
.exprNeedsCleanups() &&
16147 "cleanups within StmtExpr not correctly bound!");
16148 PopExpressionEvaluationContext();
16150 // FIXME: there are a variety of strange constraints to enforce here, for
16151 // example, it is not possible to goto into a stmt expression apparently.
16152 // More semantic analysis is needed.
16154 // If there are sub-stmts in the compound stmt, take the type of the last one
16155 // as the type of the stmtexpr.
16156 QualType Ty
= Context
.VoidTy
;
16157 bool StmtExprMayBindToTemp
= false;
16158 if (!Compound
->body_empty()) {
16159 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16160 if (const auto *LastStmt
=
16161 dyn_cast
<ValueStmt
>(Compound
->getStmtExprResult())) {
16162 if (const Expr
*Value
= LastStmt
->getExprStmt()) {
16163 StmtExprMayBindToTemp
= true;
16164 Ty
= Value
->getType();
16169 // FIXME: Check that expression type is complete/non-abstract; statement
16170 // expressions are not lvalues.
16171 Expr
*ResStmtExpr
=
16172 new (Context
) StmtExpr(Compound
, Ty
, LPLoc
, RPLoc
, TemplateDepth
);
16173 if (StmtExprMayBindToTemp
)
16174 return MaybeBindToTemporary(ResStmtExpr
);
16175 return ResStmtExpr
;
16178 ExprResult
Sema::ActOnStmtExprResult(ExprResult ER
) {
16179 if (ER
.isInvalid())
16180 return ExprError();
16182 // Do function/array conversion on the last expression, but not
16183 // lvalue-to-rvalue. However, initialize an unqualified type.
16184 ER
= DefaultFunctionArrayConversion(ER
.get());
16185 if (ER
.isInvalid())
16186 return ExprError();
16187 Expr
*E
= ER
.get();
16189 if (E
->isTypeDependent())
16192 // In ARC, if the final expression ends in a consume, splice
16193 // the consume out and bind it later. In the alternate case
16194 // (when dealing with a retainable type), the result
16195 // initialization will create a produce. In both cases the
16196 // result will be +1, and we'll need to balance that out with
16198 auto *Cast
= dyn_cast
<ImplicitCastExpr
>(E
);
16199 if (Cast
&& Cast
->getCastKind() == CK_ARCConsumeObject
)
16200 return Cast
->getSubExpr();
16202 // FIXME: Provide a better location for the initialization.
16203 return PerformCopyInitialization(
16204 InitializedEntity::InitializeStmtExprResult(
16205 E
->getBeginLoc(), E
->getType().getUnqualifiedType()),
16206 SourceLocation(), E
);
16209 ExprResult
Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc
,
16210 TypeSourceInfo
*TInfo
,
16211 ArrayRef
<OffsetOfComponent
> Components
,
16212 SourceLocation RParenLoc
) {
16213 QualType ArgTy
= TInfo
->getType();
16214 bool Dependent
= ArgTy
->isDependentType();
16215 SourceRange TypeRange
= TInfo
->getTypeLoc().getLocalSourceRange();
16217 // We must have at least one component that refers to the type, and the first
16218 // one is known to be a field designator. Verify that the ArgTy represents
16219 // a struct/union/class.
16220 if (!Dependent
&& !ArgTy
->isRecordType())
16221 return ExprError(Diag(BuiltinLoc
, diag::err_offsetof_record_type
)
16222 << ArgTy
<< TypeRange
);
16224 // Type must be complete per C99 7.17p3 because a declaring a variable
16225 // with an incomplete type would be ill-formed.
16227 && RequireCompleteType(BuiltinLoc
, ArgTy
,
16228 diag::err_offsetof_incomplete_type
, TypeRange
))
16229 return ExprError();
16231 bool DidWarnAboutNonPOD
= false;
16232 QualType CurrentType
= ArgTy
;
16233 SmallVector
<OffsetOfNode
, 4> Comps
;
16234 SmallVector
<Expr
*, 4> Exprs
;
16235 for (const OffsetOfComponent
&OC
: Components
) {
16236 if (OC
.isBrackets
) {
16237 // Offset of an array sub-field. TODO: Should we allow vector elements?
16238 if (!CurrentType
->isDependentType()) {
16239 const ArrayType
*AT
= Context
.getAsArrayType(CurrentType
);
16241 return ExprError(Diag(OC
.LocEnd
, diag::err_offsetof_array_type
)
16243 CurrentType
= AT
->getElementType();
16245 CurrentType
= Context
.DependentTy
;
16247 ExprResult IdxRval
= DefaultLvalueConversion(static_cast<Expr
*>(OC
.U
.E
));
16248 if (IdxRval
.isInvalid())
16249 return ExprError();
16250 Expr
*Idx
= IdxRval
.get();
16252 // The expression must be an integral expression.
16253 // FIXME: An integral constant expression?
16254 if (!Idx
->isTypeDependent() && !Idx
->isValueDependent() &&
16255 !Idx
->getType()->isIntegerType())
16257 Diag(Idx
->getBeginLoc(), diag::err_typecheck_subscript_not_integer
)
16258 << Idx
->getSourceRange());
16260 // Record this array index.
16261 Comps
.push_back(OffsetOfNode(OC
.LocStart
, Exprs
.size(), OC
.LocEnd
));
16262 Exprs
.push_back(Idx
);
16266 // Offset of a field.
16267 if (CurrentType
->isDependentType()) {
16268 // We have the offset of a field, but we can't look into the dependent
16269 // type. Just record the identifier of the field.
16270 Comps
.push_back(OffsetOfNode(OC
.LocStart
, OC
.U
.IdentInfo
, OC
.LocEnd
));
16271 CurrentType
= Context
.DependentTy
;
16275 // We need to have a complete type to look into.
16276 if (RequireCompleteType(OC
.LocStart
, CurrentType
,
16277 diag::err_offsetof_incomplete_type
))
16278 return ExprError();
16280 // Look for the designated field.
16281 const RecordType
*RC
= CurrentType
->getAs
<RecordType
>();
16283 return ExprError(Diag(OC
.LocEnd
, diag::err_offsetof_record_type
)
16285 RecordDecl
*RD
= RC
->getDecl();
16287 // C++ [lib.support.types]p5:
16288 // The macro offsetof accepts a restricted set of type arguments in this
16289 // International Standard. type shall be a POD structure or a POD union
16291 // C++11 [support.types]p4:
16292 // If type is not a standard-layout class (Clause 9), the results are
16294 if (CXXRecordDecl
*CRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
16295 bool IsSafe
= LangOpts
.CPlusPlus11
? CRD
->isStandardLayout() : CRD
->isPOD();
16297 LangOpts
.CPlusPlus11
? diag::ext_offsetof_non_standardlayout_type
16298 : diag::ext_offsetof_non_pod_type
;
16300 if (!IsSafe
&& !DidWarnAboutNonPOD
&&
16301 DiagRuntimeBehavior(BuiltinLoc
, nullptr,
16303 << SourceRange(Components
[0].LocStart
, OC
.LocEnd
)
16305 DidWarnAboutNonPOD
= true;
16308 // Look for the field.
16309 LookupResult
R(*this, OC
.U
.IdentInfo
, OC
.LocStart
, LookupMemberName
);
16310 LookupQualifiedName(R
, RD
);
16311 FieldDecl
*MemberDecl
= R
.getAsSingle
<FieldDecl
>();
16312 IndirectFieldDecl
*IndirectMemberDecl
= nullptr;
16314 if ((IndirectMemberDecl
= R
.getAsSingle
<IndirectFieldDecl
>()))
16315 MemberDecl
= IndirectMemberDecl
->getAnonField();
16319 return ExprError(Diag(BuiltinLoc
, diag::err_no_member
)
16320 << OC
.U
.IdentInfo
<< RD
<< SourceRange(OC
.LocStart
,
16324 // (If the specified member is a bit-field, the behavior is undefined.)
16326 // We diagnose this as an error.
16327 if (MemberDecl
->isBitField()) {
16328 Diag(OC
.LocEnd
, diag::err_offsetof_bitfield
)
16329 << MemberDecl
->getDeclName()
16330 << SourceRange(BuiltinLoc
, RParenLoc
);
16331 Diag(MemberDecl
->getLocation(), diag::note_bitfield_decl
);
16332 return ExprError();
16335 RecordDecl
*Parent
= MemberDecl
->getParent();
16336 if (IndirectMemberDecl
)
16337 Parent
= cast
<RecordDecl
>(IndirectMemberDecl
->getDeclContext());
16339 // If the member was found in a base class, introduce OffsetOfNodes for
16340 // the base class indirections.
16341 CXXBasePaths Paths
;
16342 if (IsDerivedFrom(OC
.LocStart
, CurrentType
, Context
.getTypeDeclType(Parent
),
16344 if (Paths
.getDetectedVirtual()) {
16345 Diag(OC
.LocEnd
, diag::err_offsetof_field_of_virtual_base
)
16346 << MemberDecl
->getDeclName()
16347 << SourceRange(BuiltinLoc
, RParenLoc
);
16348 return ExprError();
16351 CXXBasePath
&Path
= Paths
.front();
16352 for (const CXXBasePathElement
&B
: Path
)
16353 Comps
.push_back(OffsetOfNode(B
.Base
));
16356 if (IndirectMemberDecl
) {
16357 for (auto *FI
: IndirectMemberDecl
->chain()) {
16358 assert(isa
<FieldDecl
>(FI
));
16359 Comps
.push_back(OffsetOfNode(OC
.LocStart
,
16360 cast
<FieldDecl
>(FI
), OC
.LocEnd
));
16363 Comps
.push_back(OffsetOfNode(OC
.LocStart
, MemberDecl
, OC
.LocEnd
));
16365 CurrentType
= MemberDecl
->getType().getNonReferenceType();
16368 return OffsetOfExpr::Create(Context
, Context
.getSizeType(), BuiltinLoc
, TInfo
,
16369 Comps
, Exprs
, RParenLoc
);
16372 ExprResult
Sema::ActOnBuiltinOffsetOf(Scope
*S
,
16373 SourceLocation BuiltinLoc
,
16374 SourceLocation TypeLoc
,
16375 ParsedType ParsedArgTy
,
16376 ArrayRef
<OffsetOfComponent
> Components
,
16377 SourceLocation RParenLoc
) {
16379 TypeSourceInfo
*ArgTInfo
;
16380 QualType ArgTy
= GetTypeFromParser(ParsedArgTy
, &ArgTInfo
);
16381 if (ArgTy
.isNull())
16382 return ExprError();
16385 ArgTInfo
= Context
.getTrivialTypeSourceInfo(ArgTy
, TypeLoc
);
16387 return BuildBuiltinOffsetOf(BuiltinLoc
, ArgTInfo
, Components
, RParenLoc
);
16391 ExprResult
Sema::ActOnChooseExpr(SourceLocation BuiltinLoc
,
16393 Expr
*LHSExpr
, Expr
*RHSExpr
,
16394 SourceLocation RPLoc
) {
16395 assert((CondExpr
&& LHSExpr
&& RHSExpr
) && "Missing type argument(s)");
16397 ExprValueKind VK
= VK_PRValue
;
16398 ExprObjectKind OK
= OK_Ordinary
;
16400 bool CondIsTrue
= false;
16401 if (CondExpr
->isTypeDependent() || CondExpr
->isValueDependent()) {
16402 resType
= Context
.DependentTy
;
16404 // The conditional expression is required to be a constant expression.
16405 llvm::APSInt
condEval(32);
16406 ExprResult CondICE
= VerifyIntegerConstantExpression(
16407 CondExpr
, &condEval
, diag::err_typecheck_choose_expr_requires_constant
);
16408 if (CondICE
.isInvalid())
16409 return ExprError();
16410 CondExpr
= CondICE
.get();
16411 CondIsTrue
= condEval
.getZExtValue();
16413 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16414 Expr
*ActiveExpr
= CondIsTrue
? LHSExpr
: RHSExpr
;
16416 resType
= ActiveExpr
->getType();
16417 VK
= ActiveExpr
->getValueKind();
16418 OK
= ActiveExpr
->getObjectKind();
16421 return new (Context
) ChooseExpr(BuiltinLoc
, CondExpr
, LHSExpr
, RHSExpr
,
16422 resType
, VK
, OK
, RPLoc
, CondIsTrue
);
16425 //===----------------------------------------------------------------------===//
16426 // Clang Extensions.
16427 //===----------------------------------------------------------------------===//
16429 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16430 void Sema::ActOnBlockStart(SourceLocation CaretLoc
, Scope
*CurScope
) {
16431 BlockDecl
*Block
= BlockDecl::Create(Context
, CurContext
, CaretLoc
);
16433 if (LangOpts
.CPlusPlus
) {
16434 MangleNumberingContext
*MCtx
;
16435 Decl
*ManglingContextDecl
;
16436 std::tie(MCtx
, ManglingContextDecl
) =
16437 getCurrentMangleNumberContext(Block
->getDeclContext());
16439 unsigned ManglingNumber
= MCtx
->getManglingNumber(Block
);
16440 Block
->setBlockMangling(ManglingNumber
, ManglingContextDecl
);
16444 PushBlockScope(CurScope
, Block
);
16445 CurContext
->addDecl(Block
);
16447 PushDeclContext(CurScope
, Block
);
16449 CurContext
= Block
;
16451 getCurBlock()->HasImplicitReturnType
= true;
16453 // Enter a new evaluation context to insulate the block from any
16454 // cleanups from the enclosing full-expression.
16455 PushExpressionEvaluationContext(
16456 ExpressionEvaluationContext::PotentiallyEvaluated
);
16459 void Sema::ActOnBlockArguments(SourceLocation CaretLoc
, Declarator
&ParamInfo
,
16461 assert(ParamInfo
.getIdentifier() == nullptr &&
16462 "block-id should have no identifier!");
16463 assert(ParamInfo
.getContext() == DeclaratorContext::BlockLiteral
);
16464 BlockScopeInfo
*CurBlock
= getCurBlock();
16466 TypeSourceInfo
*Sig
= GetTypeForDeclarator(ParamInfo
, CurScope
);
16467 QualType T
= Sig
->getType();
16469 // FIXME: We should allow unexpanded parameter packs here, but that would,
16470 // in turn, make the block expression contain unexpanded parameter packs.
16471 if (DiagnoseUnexpandedParameterPack(CaretLoc
, Sig
, UPPC_Block
)) {
16472 // Drop the parameters.
16473 FunctionProtoType::ExtProtoInfo EPI
;
16474 EPI
.HasTrailingReturn
= false;
16475 EPI
.TypeQuals
.addConst();
16476 T
= Context
.getFunctionType(Context
.DependentTy
, std::nullopt
, EPI
);
16477 Sig
= Context
.getTrivialTypeSourceInfo(T
);
16480 // GetTypeForDeclarator always produces a function type for a block
16481 // literal signature. Furthermore, it is always a FunctionProtoType
16482 // unless the function was written with a typedef.
16483 assert(T
->isFunctionType() &&
16484 "GetTypeForDeclarator made a non-function block signature");
16486 // Look for an explicit signature in that function type.
16487 FunctionProtoTypeLoc ExplicitSignature
;
16489 if ((ExplicitSignature
= Sig
->getTypeLoc()
16490 .getAsAdjusted
<FunctionProtoTypeLoc
>())) {
16492 // Check whether that explicit signature was synthesized by
16493 // GetTypeForDeclarator. If so, don't save that as part of the
16494 // written signature.
16495 if (ExplicitSignature
.getLocalRangeBegin() ==
16496 ExplicitSignature
.getLocalRangeEnd()) {
16497 // This would be much cheaper if we stored TypeLocs instead of
16498 // TypeSourceInfos.
16499 TypeLoc Result
= ExplicitSignature
.getReturnLoc();
16500 unsigned Size
= Result
.getFullDataSize();
16501 Sig
= Context
.CreateTypeSourceInfo(Result
.getType(), Size
);
16502 Sig
->getTypeLoc().initializeFullCopy(Result
, Size
);
16504 ExplicitSignature
= FunctionProtoTypeLoc();
16508 CurBlock
->TheDecl
->setSignatureAsWritten(Sig
);
16509 CurBlock
->FunctionType
= T
;
16511 const auto *Fn
= T
->castAs
<FunctionType
>();
16512 QualType RetTy
= Fn
->getReturnType();
16514 (isa
<FunctionProtoType
>(Fn
) && cast
<FunctionProtoType
>(Fn
)->isVariadic());
16516 CurBlock
->TheDecl
->setIsVariadic(isVariadic
);
16518 // Context.DependentTy is used as a placeholder for a missing block
16519 // return type. TODO: what should we do with declarators like:
16521 // If the answer is "apply template argument deduction"....
16522 if (RetTy
!= Context
.DependentTy
) {
16523 CurBlock
->ReturnType
= RetTy
;
16524 CurBlock
->TheDecl
->setBlockMissingReturnType(false);
16525 CurBlock
->HasImplicitReturnType
= false;
16528 // Push block parameters from the declarator if we had them.
16529 SmallVector
<ParmVarDecl
*, 8> Params
;
16530 if (ExplicitSignature
) {
16531 for (unsigned I
= 0, E
= ExplicitSignature
.getNumParams(); I
!= E
; ++I
) {
16532 ParmVarDecl
*Param
= ExplicitSignature
.getParam(I
);
16533 if (Param
->getIdentifier() == nullptr && !Param
->isImplicit() &&
16534 !Param
->isInvalidDecl() && !getLangOpts().CPlusPlus
) {
16535 // Diagnose this as an extension in C17 and earlier.
16536 if (!getLangOpts().C2x
)
16537 Diag(Param
->getLocation(), diag::ext_parameter_name_omitted_c2x
);
16539 Params
.push_back(Param
);
16542 // Fake up parameter variables if we have a typedef, like
16543 // ^ fntype { ... }
16544 } else if (const FunctionProtoType
*Fn
= T
->getAs
<FunctionProtoType
>()) {
16545 for (const auto &I
: Fn
->param_types()) {
16546 ParmVarDecl
*Param
= BuildParmVarDeclForTypedef(
16547 CurBlock
->TheDecl
, ParamInfo
.getBeginLoc(), I
);
16548 Params
.push_back(Param
);
16552 // Set the parameters on the block decl.
16553 if (!Params
.empty()) {
16554 CurBlock
->TheDecl
->setParams(Params
);
16555 CheckParmsForFunctionDef(CurBlock
->TheDecl
->parameters(),
16556 /*CheckParameterNames=*/false);
16559 // Finally we can process decl attributes.
16560 ProcessDeclAttributes(CurScope
, CurBlock
->TheDecl
, ParamInfo
);
16562 // Put the parameter variables in scope.
16563 for (auto *AI
: CurBlock
->TheDecl
->parameters()) {
16564 AI
->setOwningFunction(CurBlock
->TheDecl
);
16566 // If this has an identifier, add it to the scope stack.
16567 if (AI
->getIdentifier()) {
16568 CheckShadow(CurBlock
->TheScope
, AI
);
16570 PushOnScopeChains(AI
, CurBlock
->TheScope
);
16575 /// ActOnBlockError - If there is an error parsing a block, this callback
16576 /// is invoked to pop the information about the block from the action impl.
16577 void Sema::ActOnBlockError(SourceLocation CaretLoc
, Scope
*CurScope
) {
16578 // Leave the expression-evaluation context.
16579 DiscardCleanupsInEvaluationContext();
16580 PopExpressionEvaluationContext();
16582 // Pop off CurBlock, handle nested blocks.
16584 PopFunctionScopeInfo();
16587 /// ActOnBlockStmtExpr - This is called when the body of a block statement
16588 /// literal was successfully completed. ^(int x){...}
16589 ExprResult
Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc
,
16590 Stmt
*Body
, Scope
*CurScope
) {
16591 // If blocks are disabled, emit an error.
16592 if (!LangOpts
.Blocks
)
16593 Diag(CaretLoc
, diag::err_blocks_disable
) << LangOpts
.OpenCL
;
16595 // Leave the expression-evaluation context.
16596 if (hasAnyUnrecoverableErrorsInThisFunction())
16597 DiscardCleanupsInEvaluationContext();
16598 assert(!Cleanup
.exprNeedsCleanups() &&
16599 "cleanups within block not correctly bound!");
16600 PopExpressionEvaluationContext();
16602 BlockScopeInfo
*BSI
= cast
<BlockScopeInfo
>(FunctionScopes
.back());
16603 BlockDecl
*BD
= BSI
->TheDecl
;
16605 if (BSI
->HasImplicitReturnType
)
16606 deduceClosureReturnType(*BSI
);
16608 QualType RetTy
= Context
.VoidTy
;
16609 if (!BSI
->ReturnType
.isNull())
16610 RetTy
= BSI
->ReturnType
;
16612 bool NoReturn
= BD
->hasAttr
<NoReturnAttr
>();
16615 // If the user wrote a function type in some form, try to use that.
16616 if (!BSI
->FunctionType
.isNull()) {
16617 const FunctionType
*FTy
= BSI
->FunctionType
->castAs
<FunctionType
>();
16619 FunctionType::ExtInfo Ext
= FTy
->getExtInfo();
16620 if (NoReturn
&& !Ext
.getNoReturn()) Ext
= Ext
.withNoReturn(true);
16622 // Turn protoless block types into nullary block types.
16623 if (isa
<FunctionNoProtoType
>(FTy
)) {
16624 FunctionProtoType::ExtProtoInfo EPI
;
16626 BlockTy
= Context
.getFunctionType(RetTy
, std::nullopt
, EPI
);
16628 // Otherwise, if we don't need to change anything about the function type,
16629 // preserve its sugar structure.
16630 } else if (FTy
->getReturnType() == RetTy
&&
16631 (!NoReturn
|| FTy
->getNoReturnAttr())) {
16632 BlockTy
= BSI
->FunctionType
;
16634 // Otherwise, make the minimal modifications to the function type.
16636 const FunctionProtoType
*FPT
= cast
<FunctionProtoType
>(FTy
);
16637 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
16638 EPI
.TypeQuals
= Qualifiers();
16640 BlockTy
= Context
.getFunctionType(RetTy
, FPT
->getParamTypes(), EPI
);
16643 // If we don't have a function type, just build one from nothing.
16645 FunctionProtoType::ExtProtoInfo EPI
;
16646 EPI
.ExtInfo
= FunctionType::ExtInfo().withNoReturn(NoReturn
);
16647 BlockTy
= Context
.getFunctionType(RetTy
, std::nullopt
, EPI
);
16650 DiagnoseUnusedParameters(BD
->parameters());
16651 BlockTy
= Context
.getBlockPointerType(BlockTy
);
16653 // If needed, diagnose invalid gotos and switches in the block.
16654 if (getCurFunction()->NeedsScopeChecking() &&
16655 !PP
.isCodeCompletionEnabled())
16656 DiagnoseInvalidJumps(cast
<CompoundStmt
>(Body
));
16658 BD
->setBody(cast
<CompoundStmt
>(Body
));
16660 if (Body
&& getCurFunction()->HasPotentialAvailabilityViolations
)
16661 DiagnoseUnguardedAvailabilityViolations(BD
);
16663 // Try to apply the named return value optimization. We have to check again
16664 // if we can do this, though, because blocks keep return statements around
16665 // to deduce an implicit return type.
16666 if (getLangOpts().CPlusPlus
&& RetTy
->isRecordType() &&
16667 !BD
->isDependentContext())
16668 computeNRVO(Body
, BSI
);
16670 if (RetTy
.hasNonTrivialToPrimitiveDestructCUnion() ||
16671 RetTy
.hasNonTrivialToPrimitiveCopyCUnion())
16672 checkNonTrivialCUnion(RetTy
, BD
->getCaretLocation(), NTCUC_FunctionReturn
,
16673 NTCUK_Destruct
|NTCUK_Copy
);
16677 // Set the captured variables on the block.
16678 SmallVector
<BlockDecl::Capture
, 4> Captures
;
16679 for (Capture
&Cap
: BSI
->Captures
) {
16680 if (Cap
.isInvalid() || Cap
.isThisCapture())
16682 // Cap.getVariable() is always a VarDecl because
16683 // blocks cannot capture structured bindings or other ValueDecl kinds.
16684 auto *Var
= cast
<VarDecl
>(Cap
.getVariable());
16685 Expr
*CopyExpr
= nullptr;
16686 if (getLangOpts().CPlusPlus
&& Cap
.isCopyCapture()) {
16687 if (const RecordType
*Record
=
16688 Cap
.getCaptureType()->getAs
<RecordType
>()) {
16689 // The capture logic needs the destructor, so make sure we mark it.
16690 // Usually this is unnecessary because most local variables have
16691 // their destructors marked at declaration time, but parameters are
16692 // an exception because it's technically only the call site that
16693 // actually requires the destructor.
16694 if (isa
<ParmVarDecl
>(Var
))
16695 FinalizeVarWithDestructor(Var
, Record
);
16697 // Enter a separate potentially-evaluated context while building block
16698 // initializers to isolate their cleanups from those of the block
16700 // FIXME: Is this appropriate even when the block itself occurs in an
16701 // unevaluated operand?
16702 EnterExpressionEvaluationContext
EvalContext(
16703 *this, ExpressionEvaluationContext::PotentiallyEvaluated
);
16705 SourceLocation Loc
= Cap
.getLocation();
16707 ExprResult Result
= BuildDeclarationNameExpr(
16708 CXXScopeSpec(), DeclarationNameInfo(Var
->getDeclName(), Loc
), Var
);
16710 // According to the blocks spec, the capture of a variable from
16711 // the stack requires a const copy constructor. This is not true
16712 // of the copy/move done to move a __block variable to the heap.
16713 if (!Result
.isInvalid() &&
16714 !Result
.get()->getType().isConstQualified()) {
16715 Result
= ImpCastExprToType(Result
.get(),
16716 Result
.get()->getType().withConst(),
16717 CK_NoOp
, VK_LValue
);
16720 if (!Result
.isInvalid()) {
16721 Result
= PerformCopyInitialization(
16722 InitializedEntity::InitializeBlock(Var
->getLocation(),
16723 Cap
.getCaptureType()),
16724 Loc
, Result
.get());
16727 // Build a full-expression copy expression if initialization
16728 // succeeded and used a non-trivial constructor. Recover from
16729 // errors by pretending that the copy isn't necessary.
16730 if (!Result
.isInvalid() &&
16731 !cast
<CXXConstructExpr
>(Result
.get())->getConstructor()
16733 Result
= MaybeCreateExprWithCleanups(Result
);
16734 CopyExpr
= Result
.get();
16739 BlockDecl::Capture
NewCap(Var
, Cap
.isBlockCapture(), Cap
.isNested(),
16741 Captures
.push_back(NewCap
);
16743 BD
->setCaptures(Context
, Captures
, BSI
->CXXThisCaptureIndex
!= 0);
16745 // Pop the block scope now but keep it alive to the end of this function.
16746 AnalysisBasedWarnings::Policy WP
= AnalysisWarnings
.getDefaultPolicy();
16747 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo(&WP
, BD
, BlockTy
);
16749 BlockExpr
*Result
= new (Context
) BlockExpr(BD
, BlockTy
);
16751 // If the block isn't obviously global, i.e. it captures anything at
16752 // all, then we need to do a few things in the surrounding context:
16753 if (Result
->getBlockDecl()->hasCaptures()) {
16754 // First, this expression has a new cleanup object.
16755 ExprCleanupObjects
.push_back(Result
->getBlockDecl());
16756 Cleanup
.setExprNeedsCleanups(true);
16758 // It also gets a branch-protected scope if any of the captured
16759 // variables needs destruction.
16760 for (const auto &CI
: Result
->getBlockDecl()->captures()) {
16761 const VarDecl
*var
= CI
.getVariable();
16762 if (var
->getType().isDestructedType() != QualType::DK_none
) {
16763 setFunctionHasBranchProtectedScope();
16769 if (getCurFunction())
16770 getCurFunction()->addBlock(BD
);
16775 ExprResult
Sema::ActOnVAArg(SourceLocation BuiltinLoc
, Expr
*E
, ParsedType Ty
,
16776 SourceLocation RPLoc
) {
16777 TypeSourceInfo
*TInfo
;
16778 GetTypeFromParser(Ty
, &TInfo
);
16779 return BuildVAArgExpr(BuiltinLoc
, E
, TInfo
, RPLoc
);
16782 ExprResult
Sema::BuildVAArgExpr(SourceLocation BuiltinLoc
,
16783 Expr
*E
, TypeSourceInfo
*TInfo
,
16784 SourceLocation RPLoc
) {
16785 Expr
*OrigExpr
= E
;
16788 // CUDA device code does not support varargs.
16789 if (getLangOpts().CUDA
&& getLangOpts().CUDAIsDevice
) {
16790 if (const FunctionDecl
*F
= dyn_cast
<FunctionDecl
>(CurContext
)) {
16791 CUDAFunctionTarget T
= IdentifyCUDATarget(F
);
16792 if (T
== CFT_Global
|| T
== CFT_Device
|| T
== CFT_HostDevice
)
16793 return ExprError(Diag(E
->getBeginLoc(), diag::err_va_arg_in_device
));
16797 // NVPTX does not support va_arg expression.
16798 if (getLangOpts().OpenMP
&& getLangOpts().OpenMPIsDevice
&&
16799 Context
.getTargetInfo().getTriple().isNVPTX())
16800 targetDiag(E
->getBeginLoc(), diag::err_va_arg_in_device
);
16802 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
16803 // as Microsoft ABI on an actual Microsoft platform, where
16804 // __builtin_ms_va_list and __builtin_va_list are the same.)
16805 if (!E
->isTypeDependent() && Context
.getTargetInfo().hasBuiltinMSVaList() &&
16806 Context
.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList
) {
16807 QualType MSVaListType
= Context
.getBuiltinMSVaListType();
16808 if (Context
.hasSameType(MSVaListType
, E
->getType())) {
16809 if (CheckForModifiableLvalue(E
, BuiltinLoc
, *this))
16810 return ExprError();
16815 // Get the va_list type
16816 QualType VaListType
= Context
.getBuiltinVaListType();
16818 if (VaListType
->isArrayType()) {
16819 // Deal with implicit array decay; for example, on x86-64,
16820 // va_list is an array, but it's supposed to decay to
16821 // a pointer for va_arg.
16822 VaListType
= Context
.getArrayDecayedType(VaListType
);
16823 // Make sure the input expression also decays appropriately.
16824 ExprResult Result
= UsualUnaryConversions(E
);
16825 if (Result
.isInvalid())
16826 return ExprError();
16828 } else if (VaListType
->isRecordType() && getLangOpts().CPlusPlus
) {
16829 // If va_list is a record type and we are compiling in C++ mode,
16830 // check the argument using reference binding.
16831 InitializedEntity Entity
= InitializedEntity::InitializeParameter(
16832 Context
, Context
.getLValueReferenceType(VaListType
), false);
16833 ExprResult Init
= PerformCopyInitialization(Entity
, SourceLocation(), E
);
16834 if (Init
.isInvalid())
16835 return ExprError();
16836 E
= Init
.getAs
<Expr
>();
16838 // Otherwise, the va_list argument must be an l-value because
16839 // it is modified by va_arg.
16840 if (!E
->isTypeDependent() &&
16841 CheckForModifiableLvalue(E
, BuiltinLoc
, *this))
16842 return ExprError();
16846 if (!IsMS
&& !E
->isTypeDependent() &&
16847 !Context
.hasSameType(VaListType
, E
->getType()))
16849 Diag(E
->getBeginLoc(),
16850 diag::err_first_argument_to_va_arg_not_of_type_va_list
)
16851 << OrigExpr
->getType() << E
->getSourceRange());
16853 if (!TInfo
->getType()->isDependentType()) {
16854 if (RequireCompleteType(TInfo
->getTypeLoc().getBeginLoc(), TInfo
->getType(),
16855 diag::err_second_parameter_to_va_arg_incomplete
,
16856 TInfo
->getTypeLoc()))
16857 return ExprError();
16859 if (RequireNonAbstractType(TInfo
->getTypeLoc().getBeginLoc(),
16861 diag::err_second_parameter_to_va_arg_abstract
,
16862 TInfo
->getTypeLoc()))
16863 return ExprError();
16865 if (!TInfo
->getType().isPODType(Context
)) {
16866 Diag(TInfo
->getTypeLoc().getBeginLoc(),
16867 TInfo
->getType()->isObjCLifetimeType()
16868 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
16869 : diag::warn_second_parameter_to_va_arg_not_pod
)
16870 << TInfo
->getType()
16871 << TInfo
->getTypeLoc().getSourceRange();
16874 // Check for va_arg where arguments of the given type will be promoted
16875 // (i.e. this va_arg is guaranteed to have undefined behavior).
16876 QualType PromoteType
;
16877 if (Context
.isPromotableIntegerType(TInfo
->getType())) {
16878 PromoteType
= Context
.getPromotedIntegerType(TInfo
->getType());
16879 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
16880 // and C2x 7.16.1.1p2 says, in part:
16881 // If type is not compatible with the type of the actual next argument
16882 // (as promoted according to the default argument promotions), the
16883 // behavior is undefined, except for the following cases:
16884 // - both types are pointers to qualified or unqualified versions of
16885 // compatible types;
16886 // - one type is a signed integer type, the other type is the
16887 // corresponding unsigned integer type, and the value is
16888 // representable in both types;
16889 // - one type is pointer to qualified or unqualified void and the
16890 // other is a pointer to a qualified or unqualified character type.
16891 // Given that type compatibility is the primary requirement (ignoring
16892 // qualifications), you would think we could call typesAreCompatible()
16893 // directly to test this. However, in C++, that checks for *same type*,
16894 // which causes false positives when passing an enumeration type to
16895 // va_arg. Instead, get the underlying type of the enumeration and pass
16897 QualType UnderlyingType
= TInfo
->getType();
16898 if (const auto *ET
= UnderlyingType
->getAs
<EnumType
>())
16899 UnderlyingType
= ET
->getDecl()->getIntegerType();
16900 if (Context
.typesAreCompatible(PromoteType
, UnderlyingType
,
16901 /*CompareUnqualified*/ true))
16902 PromoteType
= QualType();
16904 // If the types are still not compatible, we need to test whether the
16905 // promoted type and the underlying type are the same except for
16906 // signedness. Ask the AST for the correctly corresponding type and see
16907 // if that's compatible.
16908 if (!PromoteType
.isNull() && !UnderlyingType
->isBooleanType() &&
16909 PromoteType
->isUnsignedIntegerType() !=
16910 UnderlyingType
->isUnsignedIntegerType()) {
16912 UnderlyingType
->isUnsignedIntegerType()
16913 ? Context
.getCorrespondingSignedType(UnderlyingType
)
16914 : Context
.getCorrespondingUnsignedType(UnderlyingType
);
16915 if (Context
.typesAreCompatible(PromoteType
, UnderlyingType
,
16916 /*CompareUnqualified*/ true))
16917 PromoteType
= QualType();
16920 if (TInfo
->getType()->isSpecificBuiltinType(BuiltinType::Float
))
16921 PromoteType
= Context
.DoubleTy
;
16922 if (!PromoteType
.isNull())
16923 DiagRuntimeBehavior(TInfo
->getTypeLoc().getBeginLoc(), E
,
16924 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible
)
16925 << TInfo
->getType()
16927 << TInfo
->getTypeLoc().getSourceRange());
16930 QualType T
= TInfo
->getType().getNonLValueExprType(Context
);
16931 return new (Context
) VAArgExpr(BuiltinLoc
, E
, TInfo
, RPLoc
, T
, IsMS
);
16934 ExprResult
Sema::ActOnGNUNullExpr(SourceLocation TokenLoc
) {
16935 // The type of __null will be int or long, depending on the size of
16936 // pointers on the target.
16938 unsigned pw
= Context
.getTargetInfo().getPointerWidth(LangAS::Default
);
16939 if (pw
== Context
.getTargetInfo().getIntWidth())
16940 Ty
= Context
.IntTy
;
16941 else if (pw
== Context
.getTargetInfo().getLongWidth())
16942 Ty
= Context
.LongTy
;
16943 else if (pw
== Context
.getTargetInfo().getLongLongWidth())
16944 Ty
= Context
.LongLongTy
;
16946 llvm_unreachable("I don't know size of pointer!");
16949 return new (Context
) GNUNullExpr(Ty
, TokenLoc
);
16952 static CXXRecordDecl
*LookupStdSourceLocationImpl(Sema
&S
, SourceLocation Loc
) {
16953 CXXRecordDecl
*ImplDecl
= nullptr;
16955 // Fetch the std::source_location::__impl decl.
16956 if (NamespaceDecl
*Std
= S
.getStdNamespace()) {
16957 LookupResult
ResultSL(S
, &S
.PP
.getIdentifierTable().get("source_location"),
16958 Loc
, Sema::LookupOrdinaryName
);
16959 if (S
.LookupQualifiedName(ResultSL
, Std
)) {
16960 if (auto *SLDecl
= ResultSL
.getAsSingle
<RecordDecl
>()) {
16961 LookupResult
ResultImpl(S
, &S
.PP
.getIdentifierTable().get("__impl"),
16962 Loc
, Sema::LookupOrdinaryName
);
16963 if ((SLDecl
->isCompleteDefinition() || SLDecl
->isBeingDefined()) &&
16964 S
.LookupQualifiedName(ResultImpl
, SLDecl
)) {
16965 ImplDecl
= ResultImpl
.getAsSingle
<CXXRecordDecl
>();
16971 if (!ImplDecl
|| !ImplDecl
->isCompleteDefinition()) {
16972 S
.Diag(Loc
, diag::err_std_source_location_impl_not_found
);
16976 // Verify that __impl is a trivial struct type, with no base classes, and with
16977 // only the four expected fields.
16978 if (ImplDecl
->isUnion() || !ImplDecl
->isStandardLayout() ||
16979 ImplDecl
->getNumBases() != 0) {
16980 S
.Diag(Loc
, diag::err_std_source_location_impl_malformed
);
16984 unsigned Count
= 0;
16985 for (FieldDecl
*F
: ImplDecl
->fields()) {
16986 StringRef Name
= F
->getName();
16988 if (Name
== "_M_file_name") {
16989 if (F
->getType() !=
16990 S
.Context
.getPointerType(S
.Context
.CharTy
.withConst()))
16993 } else if (Name
== "_M_function_name") {
16994 if (F
->getType() !=
16995 S
.Context
.getPointerType(S
.Context
.CharTy
.withConst()))
16998 } else if (Name
== "_M_line") {
16999 if (!F
->getType()->isIntegerType())
17002 } else if (Name
== "_M_column") {
17003 if (!F
->getType()->isIntegerType())
17007 Count
= 100; // invalid
17012 S
.Diag(Loc
, diag::err_std_source_location_impl_malformed
);
17019 ExprResult
Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind
,
17020 SourceLocation BuiltinLoc
,
17021 SourceLocation RPLoc
) {
17024 case SourceLocExpr::File
:
17025 case SourceLocExpr::Function
: {
17026 QualType ArrTy
= Context
.getStringLiteralArrayType(Context
.CharTy
, 0);
17028 Context
.getPointerType(ArrTy
->getAsArrayTypeUnsafe()->getElementType());
17031 case SourceLocExpr::Line
:
17032 case SourceLocExpr::Column
:
17033 ResultTy
= Context
.UnsignedIntTy
;
17035 case SourceLocExpr::SourceLocStruct
:
17036 if (!StdSourceLocationImplDecl
) {
17037 StdSourceLocationImplDecl
=
17038 LookupStdSourceLocationImpl(*this, BuiltinLoc
);
17039 if (!StdSourceLocationImplDecl
)
17040 return ExprError();
17042 ResultTy
= Context
.getPointerType(
17043 Context
.getRecordType(StdSourceLocationImplDecl
).withConst());
17047 return BuildSourceLocExpr(Kind
, ResultTy
, BuiltinLoc
, RPLoc
, CurContext
);
17050 ExprResult
Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind
,
17052 SourceLocation BuiltinLoc
,
17053 SourceLocation RPLoc
,
17054 DeclContext
*ParentContext
) {
17055 return new (Context
)
17056 SourceLocExpr(Context
, Kind
, ResultTy
, BuiltinLoc
, RPLoc
, ParentContext
);
17059 bool Sema::CheckConversionToObjCLiteral(QualType DstType
, Expr
*&Exp
,
17061 if (!getLangOpts().ObjC
)
17064 const ObjCObjectPointerType
*PT
= DstType
->getAs
<ObjCObjectPointerType
>();
17067 const ObjCInterfaceDecl
*ID
= PT
->getInterfaceDecl();
17069 // Ignore any parens, implicit casts (should only be
17070 // array-to-pointer decays), and not-so-opaque values. The last is
17071 // important for making this trigger for property assignments.
17072 Expr
*SrcExpr
= Exp
->IgnoreParenImpCasts();
17073 if (OpaqueValueExpr
*OV
= dyn_cast
<OpaqueValueExpr
>(SrcExpr
))
17074 if (OV
->getSourceExpr())
17075 SrcExpr
= OV
->getSourceExpr()->IgnoreParenImpCasts();
17077 if (auto *SL
= dyn_cast
<StringLiteral
>(SrcExpr
)) {
17078 if (!PT
->isObjCIdType() &&
17079 !(ID
&& ID
->getIdentifier()->isStr("NSString")))
17081 if (!SL
->isOrdinary())
17085 Diag(SL
->getBeginLoc(), diag::err_missing_atsign_prefix
)
17086 << /*string*/0 << FixItHint::CreateInsertion(SL
->getBeginLoc(), "@");
17087 Exp
= BuildObjCStringLiteral(SL
->getBeginLoc(), SL
).get();
17092 if ((isa
<IntegerLiteral
>(SrcExpr
) || isa
<CharacterLiteral
>(SrcExpr
) ||
17093 isa
<FloatingLiteral
>(SrcExpr
) || isa
<ObjCBoolLiteralExpr
>(SrcExpr
) ||
17094 isa
<CXXBoolLiteralExpr
>(SrcExpr
)) &&
17095 !SrcExpr
->isNullPointerConstant(
17096 getASTContext(), Expr::NPC_NeverValueDependent
)) {
17097 if (!ID
|| !ID
->getIdentifier()->isStr("NSNumber"))
17100 Diag(SrcExpr
->getBeginLoc(), diag::err_missing_atsign_prefix
)
17102 << FixItHint::CreateInsertion(SrcExpr
->getBeginLoc(), "@");
17104 BuildObjCNumericLiteral(SrcExpr
->getBeginLoc(), SrcExpr
).get();
17114 static bool maybeDiagnoseAssignmentToFunction(Sema
&S
, QualType DstType
,
17115 const Expr
*SrcExpr
) {
17116 if (!DstType
->isFunctionPointerType() ||
17117 !SrcExpr
->getType()->isFunctionType())
17120 auto *DRE
= dyn_cast
<DeclRefExpr
>(SrcExpr
->IgnoreParenImpCasts());
17124 auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
17128 return !S
.checkAddressOfFunctionIsAvailable(FD
,
17130 SrcExpr
->getBeginLoc());
17133 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy
,
17134 SourceLocation Loc
,
17135 QualType DstType
, QualType SrcType
,
17136 Expr
*SrcExpr
, AssignmentAction Action
,
17137 bool *Complained
) {
17139 *Complained
= false;
17141 // Decode the result (notice that AST's are still created for extensions).
17142 bool CheckInferredResultType
= false;
17143 bool isInvalid
= false;
17144 unsigned DiagKind
= 0;
17145 ConversionFixItGenerator ConvHints
;
17146 bool MayHaveConvFixit
= false;
17147 bool MayHaveFunctionDiff
= false;
17148 const ObjCInterfaceDecl
*IFace
= nullptr;
17149 const ObjCProtocolDecl
*PDecl
= nullptr;
17153 DiagnoseAssignmentEnum(DstType
, SrcType
, SrcExpr
);
17157 if (getLangOpts().CPlusPlus
) {
17158 DiagKind
= diag::err_typecheck_convert_pointer_int
;
17161 DiagKind
= diag::ext_typecheck_convert_pointer_int
;
17163 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17164 MayHaveConvFixit
= true;
17167 if (getLangOpts().CPlusPlus
) {
17168 DiagKind
= diag::err_typecheck_convert_int_pointer
;
17171 DiagKind
= diag::ext_typecheck_convert_int_pointer
;
17173 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17174 MayHaveConvFixit
= true;
17176 case IncompatibleFunctionPointerStrict
:
17178 diag::warn_typecheck_convert_incompatible_function_pointer_strict
;
17179 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17180 MayHaveConvFixit
= true;
17182 case IncompatibleFunctionPointer
:
17183 if (getLangOpts().CPlusPlus
) {
17184 DiagKind
= diag::err_typecheck_convert_incompatible_function_pointer
;
17187 DiagKind
= diag::ext_typecheck_convert_incompatible_function_pointer
;
17189 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17190 MayHaveConvFixit
= true;
17192 case IncompatiblePointer
:
17193 if (Action
== AA_Passing_CFAudited
) {
17194 DiagKind
= diag::err_arc_typecheck_convert_incompatible_pointer
;
17195 } else if (getLangOpts().CPlusPlus
) {
17196 DiagKind
= diag::err_typecheck_convert_incompatible_pointer
;
17199 DiagKind
= diag::ext_typecheck_convert_incompatible_pointer
;
17201 CheckInferredResultType
= DstType
->isObjCObjectPointerType() &&
17202 SrcType
->isObjCObjectPointerType();
17203 if (!CheckInferredResultType
) {
17204 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17205 } else if (CheckInferredResultType
) {
17206 SrcType
= SrcType
.getUnqualifiedType();
17207 DstType
= DstType
.getUnqualifiedType();
17209 MayHaveConvFixit
= true;
17211 case IncompatiblePointerSign
:
17212 if (getLangOpts().CPlusPlus
) {
17213 DiagKind
= diag::err_typecheck_convert_incompatible_pointer_sign
;
17216 DiagKind
= diag::ext_typecheck_convert_incompatible_pointer_sign
;
17219 case FunctionVoidPointer
:
17220 if (getLangOpts().CPlusPlus
) {
17221 DiagKind
= diag::err_typecheck_convert_pointer_void_func
;
17224 DiagKind
= diag::ext_typecheck_convert_pointer_void_func
;
17227 case IncompatiblePointerDiscardsQualifiers
: {
17228 // Perform array-to-pointer decay if necessary.
17229 if (SrcType
->isArrayType()) SrcType
= Context
.getArrayDecayedType(SrcType
);
17233 Qualifiers lhq
= SrcType
->getPointeeType().getQualifiers();
17234 Qualifiers rhq
= DstType
->getPointeeType().getQualifiers();
17235 if (lhq
.getAddressSpace() != rhq
.getAddressSpace()) {
17236 DiagKind
= diag::err_typecheck_incompatible_address_space
;
17239 } else if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime()) {
17240 DiagKind
= diag::err_typecheck_incompatible_ownership
;
17244 llvm_unreachable("unknown error case for discarding qualifiers!");
17247 case CompatiblePointerDiscardsQualifiers
:
17248 // If the qualifiers lost were because we were applying the
17249 // (deprecated) C++ conversion from a string literal to a char*
17250 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17251 // Ideally, this check would be performed in
17252 // checkPointerTypesForAssignment. However, that would require a
17253 // bit of refactoring (so that the second argument is an
17254 // expression, rather than a type), which should be done as part
17255 // of a larger effort to fix checkPointerTypesForAssignment for
17257 if (getLangOpts().CPlusPlus
&&
17258 IsStringLiteralToNonConstPointerConversion(SrcExpr
, DstType
))
17260 if (getLangOpts().CPlusPlus
) {
17261 DiagKind
= diag::err_typecheck_convert_discards_qualifiers
;
17264 DiagKind
= diag::ext_typecheck_convert_discards_qualifiers
;
17268 case IncompatibleNestedPointerQualifiers
:
17269 if (getLangOpts().CPlusPlus
) {
17271 DiagKind
= diag::err_nested_pointer_qualifier_mismatch
;
17273 DiagKind
= diag::ext_nested_pointer_qualifier_mismatch
;
17276 case IncompatibleNestedPointerAddressSpaceMismatch
:
17277 DiagKind
= diag::err_typecheck_incompatible_nested_address_space
;
17280 case IntToBlockPointer
:
17281 DiagKind
= diag::err_int_to_block_pointer
;
17284 case IncompatibleBlockPointer
:
17285 DiagKind
= diag::err_typecheck_convert_incompatible_block_pointer
;
17288 case IncompatibleObjCQualifiedId
: {
17289 if (SrcType
->isObjCQualifiedIdType()) {
17290 const ObjCObjectPointerType
*srcOPT
=
17291 SrcType
->castAs
<ObjCObjectPointerType
>();
17292 for (auto *srcProto
: srcOPT
->quals()) {
17296 if (const ObjCInterfaceType
*IFaceT
=
17297 DstType
->castAs
<ObjCObjectPointerType
>()->getInterfaceType())
17298 IFace
= IFaceT
->getDecl();
17300 else if (DstType
->isObjCQualifiedIdType()) {
17301 const ObjCObjectPointerType
*dstOPT
=
17302 DstType
->castAs
<ObjCObjectPointerType
>();
17303 for (auto *dstProto
: dstOPT
->quals()) {
17307 if (const ObjCInterfaceType
*IFaceT
=
17308 SrcType
->castAs
<ObjCObjectPointerType
>()->getInterfaceType())
17309 IFace
= IFaceT
->getDecl();
17311 if (getLangOpts().CPlusPlus
) {
17312 DiagKind
= diag::err_incompatible_qualified_id
;
17315 DiagKind
= diag::warn_incompatible_qualified_id
;
17319 case IncompatibleVectors
:
17320 if (getLangOpts().CPlusPlus
) {
17321 DiagKind
= diag::err_incompatible_vectors
;
17324 DiagKind
= diag::warn_incompatible_vectors
;
17327 case IncompatibleObjCWeakRef
:
17328 DiagKind
= diag::err_arc_weak_unavailable_assign
;
17332 if (maybeDiagnoseAssignmentToFunction(*this, DstType
, SrcExpr
)) {
17334 *Complained
= true;
17338 DiagKind
= diag::err_typecheck_convert_incompatible
;
17339 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17340 MayHaveConvFixit
= true;
17342 MayHaveFunctionDiff
= true;
17346 QualType FirstType
, SecondType
;
17349 case AA_Initializing
:
17350 // The destination type comes first.
17351 FirstType
= DstType
;
17352 SecondType
= SrcType
;
17357 case AA_Passing_CFAudited
:
17358 case AA_Converting
:
17361 // The source type comes first.
17362 FirstType
= SrcType
;
17363 SecondType
= DstType
;
17367 PartialDiagnostic FDiag
= PDiag(DiagKind
);
17368 AssignmentAction ActionForDiag
= Action
;
17369 if (Action
== AA_Passing_CFAudited
)
17370 ActionForDiag
= AA_Passing
;
17372 FDiag
<< FirstType
<< SecondType
<< ActionForDiag
17373 << SrcExpr
->getSourceRange();
17375 if (DiagKind
== diag::ext_typecheck_convert_incompatible_pointer_sign
||
17376 DiagKind
== diag::err_typecheck_convert_incompatible_pointer_sign
) {
17377 auto isPlainChar
= [](const clang::Type
*Type
) {
17378 return Type
->isSpecificBuiltinType(BuiltinType::Char_S
) ||
17379 Type
->isSpecificBuiltinType(BuiltinType::Char_U
);
17381 FDiag
<< (isPlainChar(FirstType
->getPointeeOrArrayElementType()) ||
17382 isPlainChar(SecondType
->getPointeeOrArrayElementType()));
17385 // If we can fix the conversion, suggest the FixIts.
17386 if (!ConvHints
.isNull()) {
17387 for (FixItHint
&H
: ConvHints
.Hints
)
17391 if (MayHaveConvFixit
) { FDiag
<< (unsigned) (ConvHints
.Kind
); }
17393 if (MayHaveFunctionDiff
)
17394 HandleFunctionTypeMismatch(FDiag
, SecondType
, FirstType
);
17397 if ((DiagKind
== diag::warn_incompatible_qualified_id
||
17398 DiagKind
== diag::err_incompatible_qualified_id
) &&
17399 PDecl
&& IFace
&& !IFace
->hasDefinition())
17400 Diag(IFace
->getLocation(), diag::note_incomplete_class_and_qualified_id
)
17403 if (SecondType
== Context
.OverloadTy
)
17404 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr
).Expression
,
17405 FirstType
, /*TakingAddress=*/true);
17407 if (CheckInferredResultType
)
17408 EmitRelatedResultTypeNote(SrcExpr
);
17410 if (Action
== AA_Returning
&& ConvTy
== IncompatiblePointer
)
17411 EmitRelatedResultTypeNoteForReturn(DstType
);
17414 *Complained
= true;
17418 ExprResult
Sema::VerifyIntegerConstantExpression(Expr
*E
,
17419 llvm::APSInt
*Result
,
17420 AllowFoldKind CanFold
) {
17421 class SimpleICEDiagnoser
: public VerifyICEDiagnoser
{
17423 SemaDiagnosticBuilder
diagnoseNotICEType(Sema
&S
, SourceLocation Loc
,
17424 QualType T
) override
{
17425 return S
.Diag(Loc
, diag::err_ice_not_integral
)
17426 << T
<< S
.LangOpts
.CPlusPlus
;
17428 SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
, SourceLocation Loc
) override
{
17429 return S
.Diag(Loc
, diag::err_expr_not_ice
) << S
.LangOpts
.CPlusPlus
;
17433 return VerifyIntegerConstantExpression(E
, Result
, Diagnoser
, CanFold
);
17436 ExprResult
Sema::VerifyIntegerConstantExpression(Expr
*E
,
17437 llvm::APSInt
*Result
,
17439 AllowFoldKind CanFold
) {
17440 class IDDiagnoser
: public VerifyICEDiagnoser
{
17444 IDDiagnoser(unsigned DiagID
)
17445 : VerifyICEDiagnoser(DiagID
== 0), DiagID(DiagID
) { }
17447 SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
, SourceLocation Loc
) override
{
17448 return S
.Diag(Loc
, DiagID
);
17450 } Diagnoser(DiagID
);
17452 return VerifyIntegerConstantExpression(E
, Result
, Diagnoser
, CanFold
);
17455 Sema::SemaDiagnosticBuilder
17456 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema
&S
, SourceLocation Loc
,
17458 return diagnoseNotICE(S
, Loc
);
17461 Sema::SemaDiagnosticBuilder
17462 Sema::VerifyICEDiagnoser::diagnoseFold(Sema
&S
, SourceLocation Loc
) {
17463 return S
.Diag(Loc
, diag::ext_expr_not_ice
) << S
.LangOpts
.CPlusPlus
;
17467 Sema::VerifyIntegerConstantExpression(Expr
*E
, llvm::APSInt
*Result
,
17468 VerifyICEDiagnoser
&Diagnoser
,
17469 AllowFoldKind CanFold
) {
17470 SourceLocation DiagLoc
= E
->getBeginLoc();
17472 if (getLangOpts().CPlusPlus11
) {
17473 // C++11 [expr.const]p5:
17474 // If an expression of literal class type is used in a context where an
17475 // integral constant expression is required, then that class type shall
17476 // have a single non-explicit conversion function to an integral or
17477 // unscoped enumeration type
17478 ExprResult Converted
;
17479 class CXX11ConvertDiagnoser
: public ICEConvertDiagnoser
{
17480 VerifyICEDiagnoser
&BaseDiagnoser
;
17482 CXX11ConvertDiagnoser(VerifyICEDiagnoser
&BaseDiagnoser
)
17483 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
17484 BaseDiagnoser
.Suppress
, true),
17485 BaseDiagnoser(BaseDiagnoser
) {}
17487 SemaDiagnosticBuilder
diagnoseNotInt(Sema
&S
, SourceLocation Loc
,
17488 QualType T
) override
{
17489 return BaseDiagnoser
.diagnoseNotICEType(S
, Loc
, T
);
17492 SemaDiagnosticBuilder
diagnoseIncomplete(
17493 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
17494 return S
.Diag(Loc
, diag::err_ice_incomplete_type
) << T
;
17497 SemaDiagnosticBuilder
diagnoseExplicitConv(
17498 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
17499 return S
.Diag(Loc
, diag::err_ice_explicit_conversion
) << T
<< ConvTy
;
17502 SemaDiagnosticBuilder
noteExplicitConv(
17503 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
17504 return S
.Diag(Conv
->getLocation(), diag::note_ice_conversion_here
)
17505 << ConvTy
->isEnumeralType() << ConvTy
;
17508 SemaDiagnosticBuilder
diagnoseAmbiguous(
17509 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
17510 return S
.Diag(Loc
, diag::err_ice_ambiguous_conversion
) << T
;
17513 SemaDiagnosticBuilder
noteAmbiguous(
17514 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
17515 return S
.Diag(Conv
->getLocation(), diag::note_ice_conversion_here
)
17516 << ConvTy
->isEnumeralType() << ConvTy
;
17519 SemaDiagnosticBuilder
diagnoseConversion(
17520 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
17521 llvm_unreachable("conversion functions are permitted");
17523 } ConvertDiagnoser(Diagnoser
);
17525 Converted
= PerformContextualImplicitConversion(DiagLoc
, E
,
17527 if (Converted
.isInvalid())
17529 E
= Converted
.get();
17530 if (!E
->getType()->isIntegralOrUnscopedEnumerationType())
17531 return ExprError();
17532 } else if (!E
->getType()->isIntegralOrUnscopedEnumerationType()) {
17533 // An ICE must be of integral or unscoped enumeration type.
17534 if (!Diagnoser
.Suppress
)
17535 Diagnoser
.diagnoseNotICEType(*this, DiagLoc
, E
->getType())
17536 << E
->getSourceRange();
17537 return ExprError();
17540 ExprResult RValueExpr
= DefaultLvalueConversion(E
);
17541 if (RValueExpr
.isInvalid())
17542 return ExprError();
17544 E
= RValueExpr
.get();
17546 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
17547 // in the non-ICE case.
17548 if (!getLangOpts().CPlusPlus11
&& E
->isIntegerConstantExpr(Context
)) {
17550 *Result
= E
->EvaluateKnownConstIntCheckOverflow(Context
);
17551 if (!isa
<ConstantExpr
>(E
))
17552 E
= Result
? ConstantExpr::Create(Context
, E
, APValue(*Result
))
17553 : ConstantExpr::Create(Context
, E
);
17557 Expr::EvalResult EvalResult
;
17558 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
17559 EvalResult
.Diag
= &Notes
;
17561 // Try to evaluate the expression, and produce diagnostics explaining why it's
17562 // not a constant expression as a side-effect.
17564 E
->EvaluateAsRValue(EvalResult
, Context
, /*isConstantContext*/ true) &&
17565 EvalResult
.Val
.isInt() && !EvalResult
.HasSideEffects
;
17567 if (!isa
<ConstantExpr
>(E
))
17568 E
= ConstantExpr::Create(Context
, E
, EvalResult
.Val
);
17570 // In C++11, we can rely on diagnostics being produced for any expression
17571 // which is not a constant expression. If no diagnostics were produced, then
17572 // this is a constant expression.
17573 if (Folded
&& getLangOpts().CPlusPlus11
&& Notes
.empty()) {
17575 *Result
= EvalResult
.Val
.getInt();
17579 // If our only note is the usual "invalid subexpression" note, just point
17580 // the caret at its location rather than producing an essentially
17582 if (Notes
.size() == 1 && Notes
[0].second
.getDiagID() ==
17583 diag::note_invalid_subexpr_in_const_expr
) {
17584 DiagLoc
= Notes
[0].first
;
17588 if (!Folded
|| !CanFold
) {
17589 if (!Diagnoser
.Suppress
) {
17590 Diagnoser
.diagnoseNotICE(*this, DiagLoc
) << E
->getSourceRange();
17591 for (const PartialDiagnosticAt
&Note
: Notes
)
17592 Diag(Note
.first
, Note
.second
);
17595 return ExprError();
17598 Diagnoser
.diagnoseFold(*this, DiagLoc
) << E
->getSourceRange();
17599 for (const PartialDiagnosticAt
&Note
: Notes
)
17600 Diag(Note
.first
, Note
.second
);
17603 *Result
= EvalResult
.Val
.getInt();
17608 // Handle the case where we conclude a expression which we speculatively
17609 // considered to be unevaluated is actually evaluated.
17610 class TransformToPE
: public TreeTransform
<TransformToPE
> {
17611 typedef TreeTransform
<TransformToPE
> BaseTransform
;
17614 TransformToPE(Sema
&SemaRef
) : BaseTransform(SemaRef
) { }
17616 // Make sure we redo semantic analysis
17617 bool AlwaysRebuild() { return true; }
17618 bool ReplacingOriginal() { return true; }
17620 // We need to special-case DeclRefExprs referring to FieldDecls which
17621 // are not part of a member pointer formation; normal TreeTransforming
17622 // doesn't catch this case because of the way we represent them in the AST.
17623 // FIXME: This is a bit ugly; is it really the best way to handle this
17626 // Error on DeclRefExprs referring to FieldDecls.
17627 ExprResult
TransformDeclRefExpr(DeclRefExpr
*E
) {
17628 if (isa
<FieldDecl
>(E
->getDecl()) &&
17629 !SemaRef
.isUnevaluatedContext())
17630 return SemaRef
.Diag(E
->getLocation(),
17631 diag::err_invalid_non_static_member_use
)
17632 << E
->getDecl() << E
->getSourceRange();
17634 return BaseTransform::TransformDeclRefExpr(E
);
17637 // Exception: filter out member pointer formation
17638 ExprResult
TransformUnaryOperator(UnaryOperator
*E
) {
17639 if (E
->getOpcode() == UO_AddrOf
&& E
->getType()->isMemberPointerType())
17642 return BaseTransform::TransformUnaryOperator(E
);
17645 // The body of a lambda-expression is in a separate expression evaluation
17646 // context so never needs to be transformed.
17647 // FIXME: Ideally we wouldn't transform the closure type either, and would
17648 // just recreate the capture expressions and lambda expression.
17649 StmtResult
TransformLambdaBody(LambdaExpr
*E
, Stmt
*Body
) {
17650 return SkipLambdaBody(E
, Body
);
17655 ExprResult
Sema::TransformToPotentiallyEvaluated(Expr
*E
) {
17656 assert(isUnevaluatedContext() &&
17657 "Should only transform unevaluated expressions");
17658 ExprEvalContexts
.back().Context
=
17659 ExprEvalContexts
[ExprEvalContexts
.size()-2].Context
;
17660 if (isUnevaluatedContext())
17662 return TransformToPE(*this).TransformExpr(E
);
17665 TypeSourceInfo
*Sema::TransformToPotentiallyEvaluated(TypeSourceInfo
*TInfo
) {
17666 assert(isUnevaluatedContext() &&
17667 "Should only transform unevaluated expressions");
17668 ExprEvalContexts
.back().Context
=
17669 ExprEvalContexts
[ExprEvalContexts
.size() - 2].Context
;
17670 if (isUnevaluatedContext())
17672 return TransformToPE(*this).TransformType(TInfo
);
17676 Sema::PushExpressionEvaluationContext(
17677 ExpressionEvaluationContext NewContext
, Decl
*LambdaContextDecl
,
17678 ExpressionEvaluationContextRecord::ExpressionKind ExprContext
) {
17679 ExprEvalContexts
.emplace_back(NewContext
, ExprCleanupObjects
.size(), Cleanup
,
17680 LambdaContextDecl
, ExprContext
);
17682 // Discarded statements and immediate contexts nested in other
17683 // discarded statements or immediate context are themselves
17684 // a discarded statement or an immediate context, respectively.
17685 ExprEvalContexts
.back().InDiscardedStatement
=
17686 ExprEvalContexts
[ExprEvalContexts
.size() - 2]
17687 .isDiscardedStatementContext();
17688 ExprEvalContexts
.back().InImmediateFunctionContext
=
17689 ExprEvalContexts
[ExprEvalContexts
.size() - 2]
17690 .isImmediateFunctionContext();
17693 if (!MaybeODRUseExprs
.empty())
17694 std::swap(MaybeODRUseExprs
, ExprEvalContexts
.back().SavedMaybeODRUseExprs
);
17698 Sema::PushExpressionEvaluationContext(
17699 ExpressionEvaluationContext NewContext
, ReuseLambdaContextDecl_t
,
17700 ExpressionEvaluationContextRecord::ExpressionKind ExprContext
) {
17701 Decl
*ClosureContextDecl
= ExprEvalContexts
.back().ManglingContextDecl
;
17702 PushExpressionEvaluationContext(NewContext
, ClosureContextDecl
, ExprContext
);
17707 const DeclRefExpr
*CheckPossibleDeref(Sema
&S
, const Expr
*PossibleDeref
) {
17708 PossibleDeref
= PossibleDeref
->IgnoreParenImpCasts();
17709 if (const auto *E
= dyn_cast
<UnaryOperator
>(PossibleDeref
)) {
17710 if (E
->getOpcode() == UO_Deref
)
17711 return CheckPossibleDeref(S
, E
->getSubExpr());
17712 } else if (const auto *E
= dyn_cast
<ArraySubscriptExpr
>(PossibleDeref
)) {
17713 return CheckPossibleDeref(S
, E
->getBase());
17714 } else if (const auto *E
= dyn_cast
<MemberExpr
>(PossibleDeref
)) {
17715 return CheckPossibleDeref(S
, E
->getBase());
17716 } else if (const auto E
= dyn_cast
<DeclRefExpr
>(PossibleDeref
)) {
17718 QualType Ty
= E
->getType();
17719 if (const auto *Ptr
= Ty
->getAs
<PointerType
>())
17720 Inner
= Ptr
->getPointeeType();
17721 else if (const auto *Arr
= S
.Context
.getAsArrayType(Ty
))
17722 Inner
= Arr
->getElementType();
17726 if (Inner
->hasAttr(attr::NoDeref
))
17734 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord
&Rec
) {
17735 for (const Expr
*E
: Rec
.PossibleDerefs
) {
17736 const DeclRefExpr
*DeclRef
= CheckPossibleDeref(*this, E
);
17738 const ValueDecl
*Decl
= DeclRef
->getDecl();
17739 Diag(E
->getExprLoc(), diag::warn_dereference_of_noderef_type
)
17740 << Decl
->getName() << E
->getSourceRange();
17741 Diag(Decl
->getLocation(), diag::note_previous_decl
) << Decl
->getName();
17743 Diag(E
->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl
)
17744 << E
->getSourceRange();
17747 Rec
.PossibleDerefs
.clear();
17750 /// Check whether E, which is either a discarded-value expression or an
17751 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
17752 /// and if so, remove it from the list of volatile-qualified assignments that
17753 /// we are going to warn are deprecated.
17754 void Sema::CheckUnusedVolatileAssignment(Expr
*E
) {
17755 if (!E
->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20
)
17758 // Note: ignoring parens here is not justified by the standard rules, but
17759 // ignoring parentheses seems like a more reasonable approach, and this only
17760 // drives a deprecation warning so doesn't affect conformance.
17761 if (auto *BO
= dyn_cast
<BinaryOperator
>(E
->IgnoreParenImpCasts())) {
17762 if (BO
->getOpcode() == BO_Assign
) {
17763 auto &LHSs
= ExprEvalContexts
.back().VolatileAssignmentLHSs
;
17764 llvm::erase_value(LHSs
, BO
->getLHS());
17769 ExprResult
Sema::CheckForImmediateInvocation(ExprResult E
, FunctionDecl
*Decl
) {
17770 if (isUnevaluatedContext() || !E
.isUsable() || !Decl
||
17771 !Decl
->isConsteval() || isConstantEvaluated() ||
17772 isCheckingDefaultArgumentOrInitializer() ||
17773 RebuildingImmediateInvocation
|| isImmediateFunctionContext())
17776 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
17777 /// It's OK if this fails; we'll also remove this in
17778 /// HandleImmediateInvocations, but catching it here allows us to avoid
17779 /// walking the AST looking for it in simple cases.
17780 if (auto *Call
= dyn_cast
<CallExpr
>(E
.get()->IgnoreImplicit()))
17781 if (auto *DeclRef
=
17782 dyn_cast
<DeclRefExpr
>(Call
->getCallee()->IgnoreImplicit()))
17783 ExprEvalContexts
.back().ReferenceToConsteval
.erase(DeclRef
);
17785 E
= MaybeCreateExprWithCleanups(E
);
17787 ConstantExpr
*Res
= ConstantExpr::Create(
17788 getASTContext(), E
.get(),
17789 ConstantExpr::getStorageKind(Decl
->getReturnType().getTypePtr(),
17791 /*IsImmediateInvocation*/ true);
17792 /// Value-dependent constant expressions should not be immediately
17793 /// evaluated until they are instantiated.
17794 if (!Res
->isValueDependent())
17795 ExprEvalContexts
.back().ImmediateInvocationCandidates
.emplace_back(Res
, 0);
17799 static void EvaluateAndDiagnoseImmediateInvocation(
17800 Sema
&SemaRef
, Sema::ImmediateInvocationCandidate Candidate
) {
17801 llvm::SmallVector
<PartialDiagnosticAt
, 8> Notes
;
17802 Expr::EvalResult Eval
;
17803 Eval
.Diag
= &Notes
;
17804 ConstantExpr
*CE
= Candidate
.getPointer();
17805 bool Result
= CE
->EvaluateAsConstantExpr(
17806 Eval
, SemaRef
.getASTContext(), ConstantExprKind::ImmediateInvocation
);
17807 if (!Result
|| !Notes
.empty()) {
17808 Expr
*InnerExpr
= CE
->getSubExpr()->IgnoreImplicit();
17809 if (auto *FunctionalCast
= dyn_cast
<CXXFunctionalCastExpr
>(InnerExpr
))
17810 InnerExpr
= FunctionalCast
->getSubExpr();
17811 FunctionDecl
*FD
= nullptr;
17812 if (auto *Call
= dyn_cast
<CallExpr
>(InnerExpr
))
17813 FD
= cast
<FunctionDecl
>(Call
->getCalleeDecl());
17814 else if (auto *Call
= dyn_cast
<CXXConstructExpr
>(InnerExpr
))
17815 FD
= Call
->getConstructor();
17817 llvm_unreachable("unhandled decl kind");
17818 assert(FD
&& FD
->isConsteval());
17819 SemaRef
.Diag(CE
->getBeginLoc(), diag::err_invalid_consteval_call
) << FD
;
17821 SemaRef
.InnermostDeclarationWithDelayedImmediateInvocations()) {
17822 SemaRef
.Diag(Context
->Loc
, diag::note_invalid_consteval_initializer
)
17824 SemaRef
.Diag(Context
->Decl
->getBeginLoc(), diag::note_declared_at
);
17826 for (auto &Note
: Notes
)
17827 SemaRef
.Diag(Note
.first
, Note
.second
);
17830 CE
->MoveIntoResult(Eval
.Val
, SemaRef
.getASTContext());
17833 static void RemoveNestedImmediateInvocation(
17834 Sema
&SemaRef
, Sema::ExpressionEvaluationContextRecord
&Rec
,
17835 SmallVector
<Sema::ImmediateInvocationCandidate
, 4>::reverse_iterator It
) {
17836 struct ComplexRemove
: TreeTransform
<ComplexRemove
> {
17837 using Base
= TreeTransform
<ComplexRemove
>;
17838 llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DRSet
;
17839 SmallVector
<Sema::ImmediateInvocationCandidate
, 4> &IISet
;
17840 SmallVector
<Sema::ImmediateInvocationCandidate
, 4>::reverse_iterator
17842 ComplexRemove(Sema
&SemaRef
, llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DR
,
17843 SmallVector
<Sema::ImmediateInvocationCandidate
, 4> &II
,
17844 SmallVector
<Sema::ImmediateInvocationCandidate
,
17845 4>::reverse_iterator Current
)
17846 : Base(SemaRef
), DRSet(DR
), IISet(II
), CurrentII(Current
) {}
17847 void RemoveImmediateInvocation(ConstantExpr
* E
) {
17848 auto It
= std::find_if(CurrentII
, IISet
.rend(),
17849 [E
](Sema::ImmediateInvocationCandidate Elem
) {
17850 return Elem
.getPointer() == E
;
17852 assert(It
!= IISet
.rend() &&
17853 "ConstantExpr marked IsImmediateInvocation should "
17855 It
->setInt(1); // Mark as deleted
17857 ExprResult
TransformConstantExpr(ConstantExpr
*E
) {
17858 if (!E
->isImmediateInvocation())
17859 return Base::TransformConstantExpr(E
);
17860 RemoveImmediateInvocation(E
);
17861 return Base::TransformExpr(E
->getSubExpr());
17863 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
17864 /// we need to remove its DeclRefExpr from the DRSet.
17865 ExprResult
TransformCXXOperatorCallExpr(CXXOperatorCallExpr
*E
) {
17866 DRSet
.erase(cast
<DeclRefExpr
>(E
->getCallee()->IgnoreImplicit()));
17867 return Base::TransformCXXOperatorCallExpr(E
);
17869 /// Base::TransformInitializer skip ConstantExpr so we need to visit them
17871 ExprResult
TransformInitializer(Expr
*Init
, bool NotCopyInit
) {
17874 /// ConstantExpr are the first layer of implicit node to be removed so if
17875 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
17876 if (auto *CE
= dyn_cast
<ConstantExpr
>(Init
))
17877 if (CE
->isImmediateInvocation())
17878 RemoveImmediateInvocation(CE
);
17879 return Base::TransformInitializer(Init
, NotCopyInit
);
17881 ExprResult
TransformDeclRefExpr(DeclRefExpr
*E
) {
17885 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) {
17886 // Do not rebuild lambdas to avoid creating a new type.
17887 // Lambdas have already been processed inside their eval context.
17890 bool AlwaysRebuild() { return false; }
17891 bool ReplacingOriginal() { return true; }
17892 bool AllowSkippingCXXConstructExpr() {
17893 bool Res
= AllowSkippingFirstCXXConstructExpr
;
17894 AllowSkippingFirstCXXConstructExpr
= true;
17897 bool AllowSkippingFirstCXXConstructExpr
= true;
17898 } Transformer(SemaRef
, Rec
.ReferenceToConsteval
,
17899 Rec
.ImmediateInvocationCandidates
, It
);
17901 /// CXXConstructExpr with a single argument are getting skipped by
17902 /// TreeTransform in some situtation because they could be implicit. This
17903 /// can only occur for the top-level CXXConstructExpr because it is used
17904 /// nowhere in the expression being transformed therefore will not be rebuilt.
17905 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
17906 /// skipping the first CXXConstructExpr.
17907 if (isa
<CXXConstructExpr
>(It
->getPointer()->IgnoreImplicit()))
17908 Transformer
.AllowSkippingFirstCXXConstructExpr
= false;
17910 ExprResult Res
= Transformer
.TransformExpr(It
->getPointer()->getSubExpr());
17911 // The result may not be usable in case of previous compilation errors.
17912 // In this case evaluation of the expression may result in crash so just
17913 // don't do anything further with the result.
17914 if (Res
.isUsable()) {
17915 Res
= SemaRef
.MaybeCreateExprWithCleanups(Res
);
17916 It
->getPointer()->setSubExpr(Res
.get());
17921 HandleImmediateInvocations(Sema
&SemaRef
,
17922 Sema::ExpressionEvaluationContextRecord
&Rec
) {
17923 if ((Rec
.ImmediateInvocationCandidates
.size() == 0 &&
17924 Rec
.ReferenceToConsteval
.size() == 0) ||
17925 SemaRef
.RebuildingImmediateInvocation
)
17928 /// When we have more then 1 ImmediateInvocationCandidates we need to check
17929 /// for nested ImmediateInvocationCandidates. when we have only 1 we only
17930 /// need to remove ReferenceToConsteval in the immediate invocation.
17931 if (Rec
.ImmediateInvocationCandidates
.size() > 1) {
17933 /// Prevent sema calls during the tree transform from adding pointers that
17934 /// are already in the sets.
17935 llvm::SaveAndRestore
DisableIITracking(
17936 SemaRef
.RebuildingImmediateInvocation
, true);
17938 /// Prevent diagnostic during tree transfrom as they are duplicates
17939 Sema::TentativeAnalysisScope
DisableDiag(SemaRef
);
17941 for (auto It
= Rec
.ImmediateInvocationCandidates
.rbegin();
17942 It
!= Rec
.ImmediateInvocationCandidates
.rend(); It
++)
17944 RemoveNestedImmediateInvocation(SemaRef
, Rec
, It
);
17945 } else if (Rec
.ImmediateInvocationCandidates
.size() == 1 &&
17946 Rec
.ReferenceToConsteval
.size()) {
17947 struct SimpleRemove
: RecursiveASTVisitor
<SimpleRemove
> {
17948 llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DRSet
;
17949 SimpleRemove(llvm::SmallPtrSetImpl
<DeclRefExpr
*> &S
) : DRSet(S
) {}
17950 bool VisitDeclRefExpr(DeclRefExpr
*E
) {
17952 return DRSet
.size();
17954 } Visitor(Rec
.ReferenceToConsteval
);
17955 Visitor
.TraverseStmt(
17956 Rec
.ImmediateInvocationCandidates
.front().getPointer()->getSubExpr());
17958 for (auto CE
: Rec
.ImmediateInvocationCandidates
)
17960 EvaluateAndDiagnoseImmediateInvocation(SemaRef
, CE
);
17961 for (auto *DR
: Rec
.ReferenceToConsteval
) {
17962 auto *FD
= cast
<FunctionDecl
>(DR
->getDecl());
17963 SemaRef
.Diag(DR
->getBeginLoc(), diag::err_invalid_consteval_take_address
)
17965 SemaRef
.Diag(FD
->getLocation(), diag::note_declared_at
);
17969 void Sema::PopExpressionEvaluationContext() {
17970 ExpressionEvaluationContextRecord
& Rec
= ExprEvalContexts
.back();
17971 unsigned NumTypos
= Rec
.NumTypos
;
17973 if (!Rec
.Lambdas
.empty()) {
17974 using ExpressionKind
= ExpressionEvaluationContextRecord::ExpressionKind
;
17975 if (!getLangOpts().CPlusPlus20
&&
17976 (Rec
.ExprContext
== ExpressionKind::EK_TemplateArgument
||
17977 Rec
.isUnevaluated() ||
17978 (Rec
.isConstantEvaluated() && !getLangOpts().CPlusPlus17
))) {
17980 if (Rec
.isUnevaluated()) {
17981 // C++11 [expr.prim.lambda]p2:
17982 // A lambda-expression shall not appear in an unevaluated operand
17984 D
= diag::err_lambda_unevaluated_operand
;
17985 } else if (Rec
.isConstantEvaluated() && !getLangOpts().CPlusPlus17
) {
17986 // C++1y [expr.const]p2:
17987 // A conditional-expression e is a core constant expression unless the
17988 // evaluation of e, following the rules of the abstract machine, would
17989 // evaluate [...] a lambda-expression.
17990 D
= diag::err_lambda_in_constant_expression
;
17991 } else if (Rec
.ExprContext
== ExpressionKind::EK_TemplateArgument
) {
17992 // C++17 [expr.prim.lamda]p2:
17993 // A lambda-expression shall not appear [...] in a template-argument.
17994 D
= diag::err_lambda_in_invalid_context
;
17996 llvm_unreachable("Couldn't infer lambda error message.");
17998 for (const auto *L
: Rec
.Lambdas
)
17999 Diag(L
->getBeginLoc(), D
);
18003 WarnOnPendingNoDerefs(Rec
);
18004 HandleImmediateInvocations(*this, Rec
);
18006 // Warn on any volatile-qualified simple-assignments that are not discarded-
18007 // value expressions nor unevaluated operands (those cases get removed from
18008 // this list by CheckUnusedVolatileAssignment).
18009 for (auto *BO
: Rec
.VolatileAssignmentLHSs
)
18010 Diag(BO
->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile
)
18013 // When are coming out of an unevaluated context, clear out any
18014 // temporaries that we may have created as part of the evaluation of
18015 // the expression in that context: they aren't relevant because they
18016 // will never be constructed.
18017 if (Rec
.isUnevaluated() || Rec
.isConstantEvaluated()) {
18018 ExprCleanupObjects
.erase(ExprCleanupObjects
.begin() + Rec
.NumCleanupObjects
,
18019 ExprCleanupObjects
.end());
18020 Cleanup
= Rec
.ParentCleanup
;
18021 CleanupVarDeclMarking();
18022 std::swap(MaybeODRUseExprs
, Rec
.SavedMaybeODRUseExprs
);
18023 // Otherwise, merge the contexts together.
18025 Cleanup
.mergeFrom(Rec
.ParentCleanup
);
18026 MaybeODRUseExprs
.insert(Rec
.SavedMaybeODRUseExprs
.begin(),
18027 Rec
.SavedMaybeODRUseExprs
.end());
18030 // Pop the current expression evaluation context off the stack.
18031 ExprEvalContexts
.pop_back();
18033 // The global expression evaluation context record is never popped.
18034 ExprEvalContexts
.back().NumTypos
+= NumTypos
;
18037 void Sema::DiscardCleanupsInEvaluationContext() {
18038 ExprCleanupObjects
.erase(
18039 ExprCleanupObjects
.begin() + ExprEvalContexts
.back().NumCleanupObjects
,
18040 ExprCleanupObjects
.end());
18042 MaybeODRUseExprs
.clear();
18045 ExprResult
Sema::HandleExprEvaluationContextForTypeof(Expr
*E
) {
18046 ExprResult Result
= CheckPlaceholderExpr(E
);
18047 if (Result
.isInvalid())
18048 return ExprError();
18050 if (!E
->getType()->isVariablyModifiedType())
18052 return TransformToPotentiallyEvaluated(E
);
18055 /// Are we in a context that is potentially constant evaluated per C++20
18056 /// [expr.const]p12?
18057 static bool isPotentiallyConstantEvaluatedContext(Sema
&SemaRef
) {
18058 /// C++2a [expr.const]p12:
18059 // An expression or conversion is potentially constant evaluated if it is
18060 switch (SemaRef
.ExprEvalContexts
.back().Context
) {
18061 case Sema::ExpressionEvaluationContext::ConstantEvaluated
:
18062 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext
:
18064 // -- a manifestly constant-evaluated expression,
18065 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated
:
18066 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
18067 case Sema::ExpressionEvaluationContext::DiscardedStatement
:
18068 // -- a potentially-evaluated expression,
18069 case Sema::ExpressionEvaluationContext::UnevaluatedList
:
18070 // -- an immediate subexpression of a braced-init-list,
18072 // -- [FIXME] an expression of the form & cast-expression that occurs
18073 // within a templated entity
18074 // -- a subexpression of one of the above that is not a subexpression of
18075 // a nested unevaluated operand.
18078 case Sema::ExpressionEvaluationContext::Unevaluated
:
18079 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract
:
18080 // Expressions in this context are never evaluated.
18083 llvm_unreachable("Invalid context");
18086 /// Return true if this function has a calling convention that requires mangling
18087 /// in the size of the parameter pack.
18088 static bool funcHasParameterSizeMangling(Sema
&S
, FunctionDecl
*FD
) {
18089 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18090 // we don't need parameter type sizes.
18091 const llvm::Triple
&TT
= S
.Context
.getTargetInfo().getTriple();
18092 if (!TT
.isOSWindows() || !TT
.isX86())
18095 // If this is C++ and this isn't an extern "C" function, parameters do not
18096 // need to be complete. In this case, C++ mangling will apply, which doesn't
18097 // use the size of the parameters.
18098 if (S
.getLangOpts().CPlusPlus
&& !FD
->isExternC())
18101 // Stdcall, fastcall, and vectorcall need this special treatment.
18102 CallingConv CC
= FD
->getType()->castAs
<FunctionType
>()->getCallConv();
18104 case CC_X86StdCall
:
18105 case CC_X86FastCall
:
18106 case CC_X86VectorCall
:
18114 /// Require that all of the parameter types of function be complete. Normally,
18115 /// parameter types are only required to be complete when a function is called
18116 /// or defined, but to mangle functions with certain calling conventions, the
18117 /// mangler needs to know the size of the parameter list. In this situation,
18118 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18119 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18120 /// result in a linker error. Clang doesn't implement this behavior, and instead
18121 /// attempts to error at compile time.
18122 static void CheckCompleteParameterTypesForMangler(Sema
&S
, FunctionDecl
*FD
,
18123 SourceLocation Loc
) {
18124 class ParamIncompleteTypeDiagnoser
: public Sema::TypeDiagnoser
{
18126 ParmVarDecl
*Param
;
18129 ParamIncompleteTypeDiagnoser(FunctionDecl
*FD
, ParmVarDecl
*Param
)
18130 : FD(FD
), Param(Param
) {}
18132 void diagnose(Sema
&S
, SourceLocation Loc
, QualType T
) override
{
18133 CallingConv CC
= FD
->getType()->castAs
<FunctionType
>()->getCallConv();
18136 case CC_X86StdCall
:
18137 CCName
= "stdcall";
18139 case CC_X86FastCall
:
18140 CCName
= "fastcall";
18142 case CC_X86VectorCall
:
18143 CCName
= "vectorcall";
18146 llvm_unreachable("CC does not need mangling");
18149 S
.Diag(Loc
, diag::err_cconv_incomplete_param_type
)
18150 << Param
->getDeclName() << FD
->getDeclName() << CCName
;
18154 for (ParmVarDecl
*Param
: FD
->parameters()) {
18155 ParamIncompleteTypeDiagnoser
Diagnoser(FD
, Param
);
18156 S
.RequireCompleteType(Loc
, Param
->getType(), Diagnoser
);
18161 enum class OdrUseContext
{
18162 /// Declarations in this context are not odr-used.
18164 /// Declarations in this context are formally odr-used, but this is a
18165 /// dependent context.
18167 /// Declarations in this context are odr-used but not actually used (yet).
18169 /// Declarations in this context are used.
18174 /// Are we within a context in which references to resolved functions or to
18175 /// variables result in odr-use?
18176 static OdrUseContext
isOdrUseContext(Sema
&SemaRef
) {
18177 OdrUseContext Result
;
18179 switch (SemaRef
.ExprEvalContexts
.back().Context
) {
18180 case Sema::ExpressionEvaluationContext::Unevaluated
:
18181 case Sema::ExpressionEvaluationContext::UnevaluatedList
:
18182 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract
:
18183 return OdrUseContext::None
;
18185 case Sema::ExpressionEvaluationContext::ConstantEvaluated
:
18186 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext
:
18187 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated
:
18188 Result
= OdrUseContext::Used
;
18191 case Sema::ExpressionEvaluationContext::DiscardedStatement
:
18192 Result
= OdrUseContext::FormallyOdrUsed
;
18195 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
18196 // A default argument formally results in odr-use, but doesn't actually
18197 // result in a use in any real sense until it itself is used.
18198 Result
= OdrUseContext::FormallyOdrUsed
;
18202 if (SemaRef
.CurContext
->isDependentContext())
18203 return OdrUseContext::Dependent
;
18208 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl
*Func
) {
18209 if (!Func
->isConstexpr())
18212 if (Func
->isImplicitlyInstantiable() || !Func
->isUserProvided())
18214 auto *CCD
= dyn_cast
<CXXConstructorDecl
>(Func
);
18215 return CCD
&& CCD
->getInheritedConstructor();
18218 /// Mark a function referenced, and check whether it is odr-used
18219 /// (C++ [basic.def.odr]p2, C99 6.9p3)
18220 void Sema::MarkFunctionReferenced(SourceLocation Loc
, FunctionDecl
*Func
,
18221 bool MightBeOdrUse
) {
18222 assert(Func
&& "No function?");
18224 Func
->setReferenced();
18226 // Recursive functions aren't really used until they're used from some other
18228 bool IsRecursiveCall
= CurContext
== Func
;
18230 // C++11 [basic.def.odr]p3:
18231 // A function whose name appears as a potentially-evaluated expression is
18232 // odr-used if it is the unique lookup result or the selected member of a
18233 // set of overloaded functions [...].
18235 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18236 // can just check that here.
18237 OdrUseContext OdrUse
=
18238 MightBeOdrUse
? isOdrUseContext(*this) : OdrUseContext::None
;
18239 if (IsRecursiveCall
&& OdrUse
== OdrUseContext::Used
)
18240 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18242 // Trivial default constructors and destructors are never actually used.
18243 // FIXME: What about other special members?
18244 if (Func
->isTrivial() && !Func
->hasAttr
<DLLExportAttr
>() &&
18245 OdrUse
== OdrUseContext::Used
) {
18246 if (auto *Constructor
= dyn_cast
<CXXConstructorDecl
>(Func
))
18247 if (Constructor
->isDefaultConstructor())
18248 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18249 if (isa
<CXXDestructorDecl
>(Func
))
18250 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18253 // C++20 [expr.const]p12:
18254 // A function [...] is needed for constant evaluation if it is [...] a
18255 // constexpr function that is named by an expression that is potentially
18256 // constant evaluated
18257 bool NeededForConstantEvaluation
=
18258 isPotentiallyConstantEvaluatedContext(*this) &&
18259 isImplicitlyDefinableConstexprFunction(Func
);
18261 // Determine whether we require a function definition to exist, per
18262 // C++11 [temp.inst]p3:
18263 // Unless a function template specialization has been explicitly
18264 // instantiated or explicitly specialized, the function template
18265 // specialization is implicitly instantiated when the specialization is
18266 // referenced in a context that requires a function definition to exist.
18267 // C++20 [temp.inst]p7:
18268 // The existence of a definition of a [...] function is considered to
18269 // affect the semantics of the program if the [...] function is needed for
18270 // constant evaluation by an expression
18271 // C++20 [basic.def.odr]p10:
18272 // Every program shall contain exactly one definition of every non-inline
18273 // function or variable that is odr-used in that program outside of a
18274 // discarded statement
18275 // C++20 [special]p1:
18276 // The implementation will implicitly define [defaulted special members]
18277 // if they are odr-used or needed for constant evaluation.
18279 // Note that we skip the implicit instantiation of templates that are only
18280 // used in unused default arguments or by recursive calls to themselves.
18281 // This is formally non-conforming, but seems reasonable in practice.
18282 bool NeedDefinition
= !IsRecursiveCall
&& (OdrUse
== OdrUseContext::Used
||
18283 NeededForConstantEvaluation
);
18285 // C++14 [temp.expl.spec]p6:
18286 // If a template [...] is explicitly specialized then that specialization
18287 // shall be declared before the first use of that specialization that would
18288 // cause an implicit instantiation to take place, in every translation unit
18289 // in which such a use occurs
18290 if (NeedDefinition
&&
18291 (Func
->getTemplateSpecializationKind() != TSK_Undeclared
||
18292 Func
->getMemberSpecializationInfo()))
18293 checkSpecializationReachability(Loc
, Func
);
18295 if (getLangOpts().CUDA
)
18296 CheckCUDACall(Loc
, Func
);
18298 if (getLangOpts().SYCLIsDevice
)
18299 checkSYCLDeviceFunction(Loc
, Func
);
18301 // If we need a definition, try to create one.
18302 if (NeedDefinition
&& !Func
->getBody()) {
18303 runWithSufficientStackSpace(Loc
, [&] {
18304 if (CXXConstructorDecl
*Constructor
=
18305 dyn_cast
<CXXConstructorDecl
>(Func
)) {
18306 Constructor
= cast
<CXXConstructorDecl
>(Constructor
->getFirstDecl());
18307 if (Constructor
->isDefaulted() && !Constructor
->isDeleted()) {
18308 if (Constructor
->isDefaultConstructor()) {
18309 if (Constructor
->isTrivial() &&
18310 !Constructor
->hasAttr
<DLLExportAttr
>())
18312 DefineImplicitDefaultConstructor(Loc
, Constructor
);
18313 } else if (Constructor
->isCopyConstructor()) {
18314 DefineImplicitCopyConstructor(Loc
, Constructor
);
18315 } else if (Constructor
->isMoveConstructor()) {
18316 DefineImplicitMoveConstructor(Loc
, Constructor
);
18318 } else if (Constructor
->getInheritedConstructor()) {
18319 DefineInheritingConstructor(Loc
, Constructor
);
18321 } else if (CXXDestructorDecl
*Destructor
=
18322 dyn_cast
<CXXDestructorDecl
>(Func
)) {
18323 Destructor
= cast
<CXXDestructorDecl
>(Destructor
->getFirstDecl());
18324 if (Destructor
->isDefaulted() && !Destructor
->isDeleted()) {
18325 if (Destructor
->isTrivial() && !Destructor
->hasAttr
<DLLExportAttr
>())
18327 DefineImplicitDestructor(Loc
, Destructor
);
18329 if (Destructor
->isVirtual() && getLangOpts().AppleKext
)
18330 MarkVTableUsed(Loc
, Destructor
->getParent());
18331 } else if (CXXMethodDecl
*MethodDecl
= dyn_cast
<CXXMethodDecl
>(Func
)) {
18332 if (MethodDecl
->isOverloadedOperator() &&
18333 MethodDecl
->getOverloadedOperator() == OO_Equal
) {
18334 MethodDecl
= cast
<CXXMethodDecl
>(MethodDecl
->getFirstDecl());
18335 if (MethodDecl
->isDefaulted() && !MethodDecl
->isDeleted()) {
18336 if (MethodDecl
->isCopyAssignmentOperator())
18337 DefineImplicitCopyAssignment(Loc
, MethodDecl
);
18338 else if (MethodDecl
->isMoveAssignmentOperator())
18339 DefineImplicitMoveAssignment(Loc
, MethodDecl
);
18341 } else if (isa
<CXXConversionDecl
>(MethodDecl
) &&
18342 MethodDecl
->getParent()->isLambda()) {
18343 CXXConversionDecl
*Conversion
=
18344 cast
<CXXConversionDecl
>(MethodDecl
->getFirstDecl());
18345 if (Conversion
->isLambdaToBlockPointerConversion())
18346 DefineImplicitLambdaToBlockPointerConversion(Loc
, Conversion
);
18348 DefineImplicitLambdaToFunctionPointerConversion(Loc
, Conversion
);
18349 } else if (MethodDecl
->isVirtual() && getLangOpts().AppleKext
)
18350 MarkVTableUsed(Loc
, MethodDecl
->getParent());
18353 if (Func
->isDefaulted() && !Func
->isDeleted()) {
18354 DefaultedComparisonKind DCK
= getDefaultedComparisonKind(Func
);
18355 if (DCK
!= DefaultedComparisonKind::None
)
18356 DefineDefaultedComparison(Loc
, Func
, DCK
);
18359 // Implicit instantiation of function templates and member functions of
18360 // class templates.
18361 if (Func
->isImplicitlyInstantiable()) {
18362 TemplateSpecializationKind TSK
=
18363 Func
->getTemplateSpecializationKindForInstantiation();
18364 SourceLocation PointOfInstantiation
= Func
->getPointOfInstantiation();
18365 bool FirstInstantiation
= PointOfInstantiation
.isInvalid();
18366 if (FirstInstantiation
) {
18367 PointOfInstantiation
= Loc
;
18368 if (auto *MSI
= Func
->getMemberSpecializationInfo())
18369 MSI
->setPointOfInstantiation(Loc
);
18370 // FIXME: Notify listener.
18372 Func
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
18373 } else if (TSK
!= TSK_ImplicitInstantiation
) {
18374 // Use the point of use as the point of instantiation, instead of the
18375 // point of explicit instantiation (which we track as the actual point
18376 // of instantiation). This gives better backtraces in diagnostics.
18377 PointOfInstantiation
= Loc
;
18380 if (FirstInstantiation
|| TSK
!= TSK_ImplicitInstantiation
||
18381 Func
->isConstexpr()) {
18382 if (isa
<CXXRecordDecl
>(Func
->getDeclContext()) &&
18383 cast
<CXXRecordDecl
>(Func
->getDeclContext())->isLocalClass() &&
18384 CodeSynthesisContexts
.size())
18385 PendingLocalImplicitInstantiations
.push_back(
18386 std::make_pair(Func
, PointOfInstantiation
));
18387 else if (Func
->isConstexpr())
18388 // Do not defer instantiations of constexpr functions, to avoid the
18389 // expression evaluator needing to call back into Sema if it sees a
18390 // call to such a function.
18391 InstantiateFunctionDefinition(PointOfInstantiation
, Func
);
18393 Func
->setInstantiationIsPending(true);
18394 PendingInstantiations
.push_back(
18395 std::make_pair(Func
, PointOfInstantiation
));
18396 // Notify the consumer that a function was implicitly instantiated.
18397 Consumer
.HandleCXXImplicitFunctionInstantiation(Func
);
18401 // Walk redefinitions, as some of them may be instantiable.
18402 for (auto *i
: Func
->redecls()) {
18403 if (!i
->isUsed(false) && i
->isImplicitlyInstantiable())
18404 MarkFunctionReferenced(Loc
, i
, MightBeOdrUse
);
18410 // If a constructor was defined in the context of a default parameter
18411 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
18412 // context), its initializers may not be referenced yet.
18413 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Func
)) {
18414 for (CXXCtorInitializer
*Init
: Constructor
->inits()) {
18415 if (Init
->isInClassMemberInitializer())
18416 MarkDeclarationsReferencedInExpr(Init
->getInit());
18420 // C++14 [except.spec]p17:
18421 // An exception-specification is considered to be needed when:
18422 // - the function is odr-used or, if it appears in an unevaluated operand,
18423 // would be odr-used if the expression were potentially-evaluated;
18425 // Note, we do this even if MightBeOdrUse is false. That indicates that the
18426 // function is a pure virtual function we're calling, and in that case the
18427 // function was selected by overload resolution and we need to resolve its
18428 // exception specification for a different reason.
18429 const FunctionProtoType
*FPT
= Func
->getType()->getAs
<FunctionProtoType
>();
18430 if (FPT
&& isUnresolvedExceptionSpec(FPT
->getExceptionSpecType()))
18431 ResolveExceptionSpec(Loc
, FPT
);
18433 // If this is the first "real" use, act on that.
18434 if (OdrUse
== OdrUseContext::Used
&& !Func
->isUsed(/*CheckUsedAttr=*/false)) {
18435 // Keep track of used but undefined functions.
18436 if (!Func
->isDefined()) {
18437 if (mightHaveNonExternalLinkage(Func
))
18438 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
18439 else if (Func
->getMostRecentDecl()->isInlined() &&
18440 !LangOpts
.GNUInline
&&
18441 !Func
->getMostRecentDecl()->hasAttr
<GNUInlineAttr
>())
18442 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
18443 else if (isExternalWithNoLinkageType(Func
))
18444 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
18447 // Some x86 Windows calling conventions mangle the size of the parameter
18448 // pack into the name. Computing the size of the parameters requires the
18449 // parameter types to be complete. Check that now.
18450 if (funcHasParameterSizeMangling(*this, Func
))
18451 CheckCompleteParameterTypesForMangler(*this, Func
, Loc
);
18453 // In the MS C++ ABI, the compiler emits destructor variants where they are
18454 // used. If the destructor is used here but defined elsewhere, mark the
18455 // virtual base destructors referenced. If those virtual base destructors
18456 // are inline, this will ensure they are defined when emitting the complete
18457 // destructor variant. This checking may be redundant if the destructor is
18458 // provided later in this TU.
18459 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
18460 if (auto *Dtor
= dyn_cast
<CXXDestructorDecl
>(Func
)) {
18461 CXXRecordDecl
*Parent
= Dtor
->getParent();
18462 if (Parent
->getNumVBases() > 0 && !Dtor
->getBody())
18463 CheckCompleteDestructorVariant(Loc
, Dtor
);
18467 Func
->markUsed(Context
);
18471 /// Directly mark a variable odr-used. Given a choice, prefer to use
18472 /// MarkVariableReferenced since it does additional checks and then
18473 /// calls MarkVarDeclODRUsed.
18474 /// If the variable must be captured:
18475 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
18476 /// - else capture it in the DeclContext that maps to the
18477 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
18479 MarkVarDeclODRUsed(ValueDecl
*V
, SourceLocation Loc
, Sema
&SemaRef
,
18480 const unsigned *const FunctionScopeIndexToStopAt
= nullptr) {
18481 // Keep track of used but undefined variables.
18482 // FIXME: We shouldn't suppress this warning for static data members.
18483 VarDecl
*Var
= V
->getPotentiallyDecomposedVarDecl();
18484 assert(Var
&& "expected a capturable variable");
18486 if (Var
->hasDefinition(SemaRef
.Context
) == VarDecl::DeclarationOnly
&&
18487 (!Var
->isExternallyVisible() || Var
->isInline() ||
18488 SemaRef
.isExternalWithNoLinkageType(Var
)) &&
18489 !(Var
->isStaticDataMember() && Var
->hasInit())) {
18490 SourceLocation
&old
= SemaRef
.UndefinedButUsed
[Var
->getCanonicalDecl()];
18491 if (old
.isInvalid())
18494 QualType CaptureType
, DeclRefType
;
18495 if (SemaRef
.LangOpts
.OpenMP
)
18496 SemaRef
.tryCaptureOpenMPLambdas(V
);
18497 SemaRef
.tryCaptureVariable(V
, Loc
, Sema::TryCapture_Implicit
,
18498 /*EllipsisLoc*/ SourceLocation(),
18499 /*BuildAndDiagnose*/ true, CaptureType
,
18500 DeclRefType
, FunctionScopeIndexToStopAt
);
18502 if (SemaRef
.LangOpts
.CUDA
&& Var
->hasGlobalStorage()) {
18503 auto *FD
= dyn_cast_or_null
<FunctionDecl
>(SemaRef
.CurContext
);
18504 auto VarTarget
= SemaRef
.IdentifyCUDATarget(Var
);
18505 auto UserTarget
= SemaRef
.IdentifyCUDATarget(FD
);
18506 if (VarTarget
== Sema::CVT_Host
&&
18507 (UserTarget
== Sema::CFT_Device
|| UserTarget
== Sema::CFT_HostDevice
||
18508 UserTarget
== Sema::CFT_Global
)) {
18509 // Diagnose ODR-use of host global variables in device functions.
18510 // Reference of device global variables in host functions is allowed
18511 // through shadow variables therefore it is not diagnosed.
18512 if (SemaRef
.LangOpts
.CUDAIsDevice
) {
18513 SemaRef
.targetDiag(Loc
, diag::err_ref_bad_target
)
18514 << /*host*/ 2 << /*variable*/ 1 << Var
<< UserTarget
;
18515 SemaRef
.targetDiag(Var
->getLocation(),
18516 Var
->getType().isConstQualified()
18517 ? diag::note_cuda_const_var_unpromoted
18518 : diag::note_cuda_host_var
);
18520 } else if (VarTarget
== Sema::CVT_Device
&&
18521 (UserTarget
== Sema::CFT_Host
||
18522 UserTarget
== Sema::CFT_HostDevice
)) {
18523 // Record a CUDA/HIP device side variable if it is ODR-used
18524 // by host code. This is done conservatively, when the variable is
18525 // referenced in any of the following contexts:
18526 // - a non-function context
18527 // - a host function
18528 // - a host device function
18529 // This makes the ODR-use of the device side variable by host code to
18530 // be visible in the device compilation for the compiler to be able to
18531 // emit template variables instantiated by host code only and to
18532 // externalize the static device side variable ODR-used by host code.
18533 if (!Var
->hasExternalStorage())
18534 SemaRef
.getASTContext().CUDADeviceVarODRUsedByHost
.insert(Var
);
18535 else if (SemaRef
.LangOpts
.GPURelocatableDeviceCode
)
18536 SemaRef
.getASTContext().CUDAExternalDeviceDeclODRUsedByHost
.insert(Var
);
18540 V
->markUsed(SemaRef
.Context
);
18543 void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl
*Capture
,
18544 SourceLocation Loc
,
18545 unsigned CapturingScopeIndex
) {
18546 MarkVarDeclODRUsed(Capture
, Loc
, *this, &CapturingScopeIndex
);
18549 void diagnoseUncapturableValueReferenceOrBinding(Sema
&S
, SourceLocation loc
,
18551 DeclContext
*VarDC
= var
->getDeclContext();
18553 // If the parameter still belongs to the translation unit, then
18554 // we're actually just using one parameter in the declaration of
18556 if (isa
<ParmVarDecl
>(var
) &&
18557 isa
<TranslationUnitDecl
>(VarDC
))
18560 // For C code, don't diagnose about capture if we're not actually in code
18561 // right now; it's impossible to write a non-constant expression outside of
18562 // function context, so we'll get other (more useful) diagnostics later.
18564 // For C++, things get a bit more nasty... it would be nice to suppress this
18565 // diagnostic for certain cases like using a local variable in an array bound
18566 // for a member of a local class, but the correct predicate is not obvious.
18567 if (!S
.getLangOpts().CPlusPlus
&& !S
.CurContext
->isFunctionOrMethod())
18570 unsigned ValueKind
= isa
<BindingDecl
>(var
) ? 1 : 0;
18571 unsigned ContextKind
= 3; // unknown
18572 if (isa
<CXXMethodDecl
>(VarDC
) &&
18573 cast
<CXXRecordDecl
>(VarDC
->getParent())->isLambda()) {
18575 } else if (isa
<FunctionDecl
>(VarDC
)) {
18577 } else if (isa
<BlockDecl
>(VarDC
)) {
18581 S
.Diag(loc
, diag::err_reference_to_local_in_enclosing_context
)
18582 << var
<< ValueKind
<< ContextKind
<< VarDC
;
18583 S
.Diag(var
->getLocation(), diag::note_entity_declared_at
)
18586 // FIXME: Add additional diagnostic info about class etc. which prevents
18590 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo
*CSI
,
18592 bool &SubCapturesAreNested
,
18593 QualType
&CaptureType
,
18594 QualType
&DeclRefType
) {
18595 // Check whether we've already captured it.
18596 if (CSI
->CaptureMap
.count(Var
)) {
18597 // If we found a capture, any subcaptures are nested.
18598 SubCapturesAreNested
= true;
18600 // Retrieve the capture type for this variable.
18601 CaptureType
= CSI
->getCapture(Var
).getCaptureType();
18603 // Compute the type of an expression that refers to this variable.
18604 DeclRefType
= CaptureType
.getNonReferenceType();
18606 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
18607 // are mutable in the sense that user can change their value - they are
18608 // private instances of the captured declarations.
18609 const Capture
&Cap
= CSI
->getCapture(Var
);
18610 if (Cap
.isCopyCapture() &&
18611 !(isa
<LambdaScopeInfo
>(CSI
) && cast
<LambdaScopeInfo
>(CSI
)->Mutable
) &&
18612 !(isa
<CapturedRegionScopeInfo
>(CSI
) &&
18613 cast
<CapturedRegionScopeInfo
>(CSI
)->CapRegionKind
== CR_OpenMP
))
18614 DeclRefType
.addConst();
18620 // Only block literals, captured statements, and lambda expressions can
18621 // capture; other scopes don't work.
18622 static DeclContext
*getParentOfCapturingContextOrNull(DeclContext
*DC
,
18624 SourceLocation Loc
,
18625 const bool Diagnose
,
18627 if (isa
<BlockDecl
>(DC
) || isa
<CapturedDecl
>(DC
) || isLambdaCallOperator(DC
))
18628 return getLambdaAwareParentOfDeclContext(DC
);
18630 VarDecl
*Underlying
= Var
->getPotentiallyDecomposedVarDecl();
18632 if (Underlying
->hasLocalStorage() && Diagnose
)
18633 diagnoseUncapturableValueReferenceOrBinding(S
, Loc
, Var
);
18638 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
18639 // certain types of variables (unnamed, variably modified types etc.)
18640 // so check for eligibility.
18641 static bool isVariableCapturable(CapturingScopeInfo
*CSI
, ValueDecl
*Var
,
18642 SourceLocation Loc
, const bool Diagnose
,
18645 assert((isa
<VarDecl
, BindingDecl
>(Var
)) &&
18646 "Only variables and structured bindings can be captured");
18648 bool IsBlock
= isa
<BlockScopeInfo
>(CSI
);
18649 bool IsLambda
= isa
<LambdaScopeInfo
>(CSI
);
18651 // Lambdas are not allowed to capture unnamed variables
18652 // (e.g. anonymous unions).
18653 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
18654 // assuming that's the intent.
18655 if (IsLambda
&& !Var
->getDeclName()) {
18657 S
.Diag(Loc
, diag::err_lambda_capture_anonymous_var
);
18658 S
.Diag(Var
->getLocation(), diag::note_declared_at
);
18663 // Prohibit variably-modified types in blocks; they're difficult to deal with.
18664 if (Var
->getType()->isVariablyModifiedType() && IsBlock
) {
18666 S
.Diag(Loc
, diag::err_ref_vm_type
);
18667 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18671 // Prohibit structs with flexible array members too.
18672 // We cannot capture what is in the tail end of the struct.
18673 if (const RecordType
*VTTy
= Var
->getType()->getAs
<RecordType
>()) {
18674 if (VTTy
->getDecl()->hasFlexibleArrayMember()) {
18677 S
.Diag(Loc
, diag::err_ref_flexarray_type
);
18679 S
.Diag(Loc
, diag::err_lambda_capture_flexarray_type
) << Var
;
18680 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18685 const bool HasBlocksAttr
= Var
->hasAttr
<BlocksAttr
>();
18686 // Lambdas and captured statements are not allowed to capture __block
18687 // variables; they don't support the expected semantics.
18688 if (HasBlocksAttr
&& (IsLambda
|| isa
<CapturedRegionScopeInfo
>(CSI
))) {
18690 S
.Diag(Loc
, diag::err_capture_block_variable
) << Var
<< !IsLambda
;
18691 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18695 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
18696 if (S
.getLangOpts().OpenCL
&& IsBlock
&&
18697 Var
->getType()->isBlockPointerType()) {
18699 S
.Diag(Loc
, diag::err_opencl_block_ref_block
);
18703 if (isa
<BindingDecl
>(Var
)) {
18704 if (!IsLambda
|| !S
.getLangOpts().CPlusPlus
) {
18706 diagnoseUncapturableValueReferenceOrBinding(S
, Loc
, Var
);
18708 } else if (Diagnose
&& S
.getLangOpts().CPlusPlus
) {
18709 S
.Diag(Loc
, S
.LangOpts
.CPlusPlus20
18710 ? diag::warn_cxx17_compat_capture_binding
18711 : diag::ext_capture_binding
)
18713 S
.Diag(Var
->getLocation(), diag::note_entity_declared_at
) << Var
;
18720 // Returns true if the capture by block was successful.
18721 static bool captureInBlock(BlockScopeInfo
*BSI
, ValueDecl
*Var
,
18722 SourceLocation Loc
, const bool BuildAndDiagnose
,
18723 QualType
&CaptureType
, QualType
&DeclRefType
,
18724 const bool Nested
, Sema
&S
, bool Invalid
) {
18725 bool ByRef
= false;
18727 // Blocks are not allowed to capture arrays, excepting OpenCL.
18728 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
18729 // (decayed to pointers).
18730 if (!Invalid
&& !S
.getLangOpts().OpenCL
&& CaptureType
->isArrayType()) {
18731 if (BuildAndDiagnose
) {
18732 S
.Diag(Loc
, diag::err_ref_array_type
);
18733 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18740 // Forbid the block-capture of autoreleasing variables.
18742 CaptureType
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
) {
18743 if (BuildAndDiagnose
) {
18744 S
.Diag(Loc
, diag::err_arc_autoreleasing_capture
)
18746 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
18753 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
18754 if (const auto *PT
= CaptureType
->getAs
<PointerType
>()) {
18755 QualType PointeeTy
= PT
->getPointeeType();
18757 if (!Invalid
&& PointeeTy
->getAs
<ObjCObjectPointerType
>() &&
18758 PointeeTy
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
&&
18759 !S
.Context
.hasDirectOwnershipQualifier(PointeeTy
)) {
18760 if (BuildAndDiagnose
) {
18761 SourceLocation VarLoc
= Var
->getLocation();
18762 S
.Diag(Loc
, diag::warn_block_capture_autoreleasing
);
18763 S
.Diag(VarLoc
, diag::note_declare_parameter_strong
);
18768 const bool HasBlocksAttr
= Var
->hasAttr
<BlocksAttr
>();
18769 if (HasBlocksAttr
|| CaptureType
->isReferenceType() ||
18770 (S
.getLangOpts().OpenMP
&& S
.isOpenMPCapturedDecl(Var
))) {
18771 // Block capture by reference does not change the capture or
18772 // declaration reference types.
18775 // Block capture by copy introduces 'const'.
18776 CaptureType
= CaptureType
.getNonReferenceType().withConst();
18777 DeclRefType
= CaptureType
;
18780 // Actually capture the variable.
18781 if (BuildAndDiagnose
)
18782 BSI
->addCapture(Var
, HasBlocksAttr
, ByRef
, Nested
, Loc
, SourceLocation(),
18783 CaptureType
, Invalid
);
18788 /// Capture the given variable in the captured region.
18789 static bool captureInCapturedRegion(
18790 CapturedRegionScopeInfo
*RSI
, ValueDecl
*Var
, SourceLocation Loc
,
18791 const bool BuildAndDiagnose
, QualType
&CaptureType
, QualType
&DeclRefType
,
18792 const bool RefersToCapturedVariable
, Sema::TryCaptureKind Kind
,
18793 bool IsTopScope
, Sema
&S
, bool Invalid
) {
18794 // By default, capture variables by reference.
18796 if (IsTopScope
&& Kind
!= Sema::TryCapture_Implicit
) {
18797 ByRef
= (Kind
== Sema::TryCapture_ExplicitByRef
);
18798 } else if (S
.getLangOpts().OpenMP
&& RSI
->CapRegionKind
== CR_OpenMP
) {
18799 // Using an LValue reference type is consistent with Lambdas (see below).
18800 if (S
.isOpenMPCapturedDecl(Var
)) {
18801 bool HasConst
= DeclRefType
.isConstQualified();
18802 DeclRefType
= DeclRefType
.getUnqualifiedType();
18803 // Don't lose diagnostics about assignments to const.
18805 DeclRefType
.addConst();
18807 // Do not capture firstprivates in tasks.
18808 if (S
.isOpenMPPrivateDecl(Var
, RSI
->OpenMPLevel
, RSI
->OpenMPCaptureLevel
) !=
18811 ByRef
= S
.isOpenMPCapturedByRef(Var
, RSI
->OpenMPLevel
,
18812 RSI
->OpenMPCaptureLevel
);
18816 CaptureType
= S
.Context
.getLValueReferenceType(DeclRefType
);
18818 CaptureType
= DeclRefType
;
18820 // Actually capture the variable.
18821 if (BuildAndDiagnose
)
18822 RSI
->addCapture(Var
, /*isBlock*/ false, ByRef
, RefersToCapturedVariable
,
18823 Loc
, SourceLocation(), CaptureType
, Invalid
);
18828 /// Capture the given variable in the lambda.
18829 static bool captureInLambda(LambdaScopeInfo
*LSI
, ValueDecl
*Var
,
18830 SourceLocation Loc
, const bool BuildAndDiagnose
,
18831 QualType
&CaptureType
, QualType
&DeclRefType
,
18832 const bool RefersToCapturedVariable
,
18833 const Sema::TryCaptureKind Kind
,
18834 SourceLocation EllipsisLoc
, const bool IsTopScope
,
18835 Sema
&S
, bool Invalid
) {
18836 // Determine whether we are capturing by reference or by value.
18837 bool ByRef
= false;
18838 if (IsTopScope
&& Kind
!= Sema::TryCapture_Implicit
) {
18839 ByRef
= (Kind
== Sema::TryCapture_ExplicitByRef
);
18841 ByRef
= (LSI
->ImpCaptureStyle
== LambdaScopeInfo::ImpCap_LambdaByref
);
18844 BindingDecl
*BD
= dyn_cast
<BindingDecl
>(Var
);
18845 // FIXME: We should support capturing structured bindings in OpenMP.
18846 if (!Invalid
&& BD
&& S
.LangOpts
.OpenMP
) {
18847 if (BuildAndDiagnose
) {
18848 S
.Diag(Loc
, diag::err_capture_binding_openmp
) << Var
;
18849 S
.Diag(Var
->getLocation(), diag::note_entity_declared_at
) << Var
;
18854 // Compute the type of the field that will capture this variable.
18856 // C++11 [expr.prim.lambda]p15:
18857 // An entity is captured by reference if it is implicitly or
18858 // explicitly captured but not captured by copy. It is
18859 // unspecified whether additional unnamed non-static data
18860 // members are declared in the closure type for entities
18861 // captured by reference.
18863 // FIXME: It is not clear whether we want to build an lvalue reference
18864 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
18865 // to do the former, while EDG does the latter. Core issue 1249 will
18866 // clarify, but for now we follow GCC because it's a more permissive and
18867 // easily defensible position.
18868 CaptureType
= S
.Context
.getLValueReferenceType(DeclRefType
);
18870 // C++11 [expr.prim.lambda]p14:
18871 // For each entity captured by copy, an unnamed non-static
18872 // data member is declared in the closure type. The
18873 // declaration order of these members is unspecified. The type
18874 // of such a data member is the type of the corresponding
18875 // captured entity if the entity is not a reference to an
18876 // object, or the referenced type otherwise. [Note: If the
18877 // captured entity is a reference to a function, the
18878 // corresponding data member is also a reference to a
18879 // function. - end note ]
18880 if (const ReferenceType
*RefType
= CaptureType
->getAs
<ReferenceType
>()){
18881 if (!RefType
->getPointeeType()->isFunctionType())
18882 CaptureType
= RefType
->getPointeeType();
18885 // Forbid the lambda copy-capture of autoreleasing variables.
18887 CaptureType
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
) {
18888 if (BuildAndDiagnose
) {
18889 S
.Diag(Loc
, diag::err_arc_autoreleasing_capture
) << /*lambda*/ 1;
18890 S
.Diag(Var
->getLocation(), diag::note_previous_decl
)
18891 << Var
->getDeclName();
18898 // Make sure that by-copy captures are of a complete and non-abstract type.
18899 if (!Invalid
&& BuildAndDiagnose
) {
18900 if (!CaptureType
->isDependentType() &&
18901 S
.RequireCompleteSizedType(
18903 diag::err_capture_of_incomplete_or_sizeless_type
,
18904 Var
->getDeclName()))
18906 else if (S
.RequireNonAbstractType(Loc
, CaptureType
,
18907 diag::err_capture_of_abstract_type
))
18912 // Compute the type of a reference to this captured variable.
18914 DeclRefType
= CaptureType
.getNonReferenceType();
18916 // C++ [expr.prim.lambda]p5:
18917 // The closure type for a lambda-expression has a public inline
18918 // function call operator [...]. This function call operator is
18919 // declared const (9.3.1) if and only if the lambda-expression's
18920 // parameter-declaration-clause is not followed by mutable.
18921 DeclRefType
= CaptureType
.getNonReferenceType();
18922 if (!LSI
->Mutable
&& !CaptureType
->isReferenceType())
18923 DeclRefType
.addConst();
18926 // Add the capture.
18927 if (BuildAndDiagnose
)
18928 LSI
->addCapture(Var
, /*isBlock=*/false, ByRef
, RefersToCapturedVariable
,
18929 Loc
, EllipsisLoc
, CaptureType
, Invalid
);
18934 static bool canCaptureVariableByCopy(ValueDecl
*Var
,
18935 const ASTContext
&Context
) {
18936 // Offer a Copy fix even if the type is dependent.
18937 if (Var
->getType()->isDependentType())
18939 QualType T
= Var
->getType().getNonReferenceType();
18940 if (T
.isTriviallyCopyableType(Context
))
18942 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl()) {
18944 if (!(RD
= RD
->getDefinition()))
18946 if (RD
->hasSimpleCopyConstructor())
18948 if (RD
->hasUserDeclaredCopyConstructor())
18949 for (CXXConstructorDecl
*Ctor
: RD
->ctors())
18950 if (Ctor
->isCopyConstructor())
18951 return !Ctor
->isDeleted();
18956 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
18957 /// default capture. Fixes may be omitted if they aren't allowed by the
18958 /// standard, for example we can't emit a default copy capture fix-it if we
18959 /// already explicitly copy capture capture another variable.
18960 static void buildLambdaCaptureFixit(Sema
&Sema
, LambdaScopeInfo
*LSI
,
18962 assert(LSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
);
18963 // Don't offer Capture by copy of default capture by copy fixes if Var is
18964 // known not to be copy constructible.
18965 bool ShouldOfferCopyFix
= canCaptureVariableByCopy(Var
, Sema
.getASTContext());
18967 SmallString
<32> FixBuffer
;
18968 StringRef Separator
= LSI
->NumExplicitCaptures
> 0 ? ", " : "";
18969 if (Var
->getDeclName().isIdentifier() && !Var
->getName().empty()) {
18970 SourceLocation VarInsertLoc
= LSI
->IntroducerRange
.getEnd();
18971 if (ShouldOfferCopyFix
) {
18972 // Offer fixes to insert an explicit capture for the variable.
18974 // [OtherCapture] -> [OtherCapture, VarName]
18975 FixBuffer
.assign({Separator
, Var
->getName()});
18976 Sema
.Diag(VarInsertLoc
, diag::note_lambda_variable_capture_fixit
)
18977 << Var
<< /*value*/ 0
18978 << FixItHint::CreateInsertion(VarInsertLoc
, FixBuffer
);
18980 // As above but capture by reference.
18981 FixBuffer
.assign({Separator
, "&", Var
->getName()});
18982 Sema
.Diag(VarInsertLoc
, diag::note_lambda_variable_capture_fixit
)
18983 << Var
<< /*reference*/ 1
18984 << FixItHint::CreateInsertion(VarInsertLoc
, FixBuffer
);
18987 // Only try to offer default capture if there are no captures excluding this
18988 // and init captures.
18991 // [&A, &B]: Don't offer.
18992 // [A, B]: Don't offer.
18993 if (llvm::any_of(LSI
->Captures
, [](Capture
&C
) {
18994 return !C
.isThisCapture() && !C
.isInitCapture();
18998 // The default capture specifiers, '=' or '&', must appear first in the
19000 SourceLocation DefaultInsertLoc
=
19001 LSI
->IntroducerRange
.getBegin().getLocWithOffset(1);
19003 if (ShouldOfferCopyFix
) {
19004 bool CanDefaultCopyCapture
= true;
19005 // [=, *this] OK since c++17
19006 // [=, this] OK since c++20
19007 if (LSI
->isCXXThisCaptured() && !Sema
.getLangOpts().CPlusPlus20
)
19008 CanDefaultCopyCapture
= Sema
.getLangOpts().CPlusPlus17
19009 ? LSI
->getCXXThisCapture().isCopyCapture()
19011 // We can't use default capture by copy if any captures already specified
19012 // capture by copy.
19013 if (CanDefaultCopyCapture
&& llvm::none_of(LSI
->Captures
, [](Capture
&C
) {
19014 return !C
.isThisCapture() && !C
.isInitCapture() && C
.isCopyCapture();
19016 FixBuffer
.assign({"=", Separator
});
19017 Sema
.Diag(DefaultInsertLoc
, diag::note_lambda_default_capture_fixit
)
19019 << FixItHint::CreateInsertion(DefaultInsertLoc
, FixBuffer
);
19023 // We can't use default capture by reference if any captures already specified
19024 // capture by reference.
19025 if (llvm::none_of(LSI
->Captures
, [](Capture
&C
) {
19026 return !C
.isInitCapture() && C
.isReferenceCapture() &&
19027 !C
.isThisCapture();
19029 FixBuffer
.assign({"&", Separator
});
19030 Sema
.Diag(DefaultInsertLoc
, diag::note_lambda_default_capture_fixit
)
19032 << FixItHint::CreateInsertion(DefaultInsertLoc
, FixBuffer
);
19036 bool Sema::tryCaptureVariable(
19037 ValueDecl
*Var
, SourceLocation ExprLoc
, TryCaptureKind Kind
,
19038 SourceLocation EllipsisLoc
, bool BuildAndDiagnose
, QualType
&CaptureType
,
19039 QualType
&DeclRefType
, const unsigned *const FunctionScopeIndexToStopAt
) {
19040 // An init-capture is notionally from the context surrounding its
19041 // declaration, but its parent DC is the lambda class.
19042 DeclContext
*VarDC
= Var
->getDeclContext();
19043 const auto *VD
= dyn_cast
<VarDecl
>(Var
);
19045 if (VD
->isInitCapture())
19046 VarDC
= VarDC
->getParent();
19048 VD
= Var
->getPotentiallyDecomposedVarDecl();
19050 assert(VD
&& "Cannot capture a null variable");
19052 DeclContext
*DC
= CurContext
;
19053 const unsigned MaxFunctionScopesIndex
= FunctionScopeIndexToStopAt
19054 ? *FunctionScopeIndexToStopAt
: FunctionScopes
.size() - 1;
19055 // We need to sync up the Declaration Context with the
19056 // FunctionScopeIndexToStopAt
19057 if (FunctionScopeIndexToStopAt
) {
19058 unsigned FSIndex
= FunctionScopes
.size() - 1;
19059 while (FSIndex
!= MaxFunctionScopesIndex
) {
19060 DC
= getLambdaAwareParentOfDeclContext(DC
);
19066 // If the variable is declared in the current context, there is no need to
19068 if (VarDC
== DC
) return true;
19070 // Capture global variables if it is required to use private copy of this
19072 bool IsGlobal
= !VD
->hasLocalStorage();
19074 !(LangOpts
.OpenMP
&& isOpenMPCapturedDecl(Var
, /*CheckScopeInfo=*/true,
19075 MaxFunctionScopesIndex
)))
19078 if (isa
<VarDecl
>(Var
))
19079 Var
= cast
<VarDecl
>(Var
->getCanonicalDecl());
19081 // Walk up the stack to determine whether we can capture the variable,
19082 // performing the "simple" checks that don't depend on type. We stop when
19083 // we've either hit the declared scope of the variable or find an existing
19084 // capture of that variable. We start from the innermost capturing-entity
19085 // (the DC) and ensure that all intervening capturing-entities
19086 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19087 // declcontext can either capture the variable or have already captured
19089 CaptureType
= Var
->getType();
19090 DeclRefType
= CaptureType
.getNonReferenceType();
19091 bool Nested
= false;
19092 bool Explicit
= (Kind
!= TryCapture_Implicit
);
19093 unsigned FunctionScopesIndex
= MaxFunctionScopesIndex
;
19095 // Only block literals, captured statements, and lambda expressions can
19096 // capture; other scopes don't work.
19097 DeclContext
*ParentDC
= getParentOfCapturingContextOrNull(DC
, Var
,
19101 // We need to check for the parent *first* because, if we *have*
19102 // private-captured a global variable, we need to recursively capture it in
19103 // intermediate blocks, lambdas, etc.
19106 FunctionScopesIndex
= MaxFunctionScopesIndex
- 1;
19112 FunctionScopeInfo
*FSI
= FunctionScopes
[FunctionScopesIndex
];
19113 CapturingScopeInfo
*CSI
= cast
<CapturingScopeInfo
>(FSI
);
19116 // Check whether we've already captured it.
19117 if (isVariableAlreadyCapturedInScopeInfo(CSI
, Var
, Nested
, CaptureType
,
19119 CSI
->getCapture(Var
).markUsed(BuildAndDiagnose
);
19122 // If we are instantiating a generic lambda call operator body,
19123 // we do not want to capture new variables. What was captured
19124 // during either a lambdas transformation or initial parsing
19126 if (isGenericLambdaCallOperatorSpecialization(DC
)) {
19127 if (BuildAndDiagnose
) {
19128 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(CSI
);
19129 if (LSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
) {
19130 Diag(ExprLoc
, diag::err_lambda_impcap
) << Var
;
19131 Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19132 Diag(LSI
->Lambda
->getBeginLoc(), diag::note_lambda_decl
);
19133 buildLambdaCaptureFixit(*this, LSI
, Var
);
19135 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc
, Var
);
19140 // Try to capture variable-length arrays types.
19141 if (Var
->getType()->isVariablyModifiedType()) {
19142 // We're going to walk down into the type and look for VLA
19144 QualType QTy
= Var
->getType();
19145 if (ParmVarDecl
*PVD
= dyn_cast_or_null
<ParmVarDecl
>(Var
))
19146 QTy
= PVD
->getOriginalType();
19147 captureVariablyModifiedType(Context
, QTy
, CSI
);
19150 if (getLangOpts().OpenMP
) {
19151 if (auto *RSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
)) {
19152 // OpenMP private variables should not be captured in outer scope, so
19153 // just break here. Similarly, global variables that are captured in a
19154 // target region should not be captured outside the scope of the region.
19155 if (RSI
->CapRegionKind
== CR_OpenMP
) {
19156 OpenMPClauseKind IsOpenMPPrivateDecl
= isOpenMPPrivateDecl(
19157 Var
, RSI
->OpenMPLevel
, RSI
->OpenMPCaptureLevel
);
19158 // If the variable is private (i.e. not captured) and has variably
19159 // modified type, we still need to capture the type for correct
19160 // codegen in all regions, associated with the construct. Currently,
19161 // it is captured in the innermost captured region only.
19162 if (IsOpenMPPrivateDecl
!= OMPC_unknown
&&
19163 Var
->getType()->isVariablyModifiedType()) {
19164 QualType QTy
= Var
->getType();
19165 if (ParmVarDecl
*PVD
= dyn_cast_or_null
<ParmVarDecl
>(Var
))
19166 QTy
= PVD
->getOriginalType();
19167 for (int I
= 1, E
= getNumberOfConstructScopes(RSI
->OpenMPLevel
);
19169 auto *OuterRSI
= cast
<CapturedRegionScopeInfo
>(
19170 FunctionScopes
[FunctionScopesIndex
- I
]);
19171 assert(RSI
->OpenMPLevel
== OuterRSI
->OpenMPLevel
&&
19172 "Wrong number of captured regions associated with the "
19173 "OpenMP construct.");
19174 captureVariablyModifiedType(Context
, QTy
, OuterRSI
);
19178 IsOpenMPPrivateDecl
!= OMPC_private
&&
19179 isOpenMPTargetCapturedDecl(Var
, RSI
->OpenMPLevel
,
19180 RSI
->OpenMPCaptureLevel
);
19181 // Do not capture global if it is not privatized in outer regions.
19183 IsGlobal
&& isOpenMPGlobalCapturedDecl(Var
, RSI
->OpenMPLevel
,
19184 RSI
->OpenMPCaptureLevel
);
19186 // When we detect target captures we are looking from inside the
19187 // target region, therefore we need to propagate the capture from the
19188 // enclosing region. Therefore, the capture is not initially nested.
19190 adjustOpenMPTargetScopeIndex(FunctionScopesIndex
, RSI
->OpenMPLevel
);
19192 if (IsTargetCap
|| IsOpenMPPrivateDecl
== OMPC_private
||
19193 (IsGlobal
&& !IsGlobalCap
)) {
19194 Nested
= !IsTargetCap
;
19195 bool HasConst
= DeclRefType
.isConstQualified();
19196 DeclRefType
= DeclRefType
.getUnqualifiedType();
19197 // Don't lose diagnostics about assignments to const.
19199 DeclRefType
.addConst();
19200 CaptureType
= Context
.getLValueReferenceType(DeclRefType
);
19206 if (CSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
&& !Explicit
) {
19207 // No capture-default, and this is not an explicit capture
19208 // so cannot capture this variable.
19209 if (BuildAndDiagnose
) {
19210 Diag(ExprLoc
, diag::err_lambda_impcap
) << Var
;
19211 Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19212 auto *LSI
= cast
<LambdaScopeInfo
>(CSI
);
19214 Diag(LSI
->Lambda
->getBeginLoc(), diag::note_lambda_decl
);
19215 buildLambdaCaptureFixit(*this, LSI
, Var
);
19217 // FIXME: If we error out because an outer lambda can not implicitly
19218 // capture a variable that an inner lambda explicitly captures, we
19219 // should have the inner lambda do the explicit capture - because
19220 // it makes for cleaner diagnostics later. This would purely be done
19221 // so that the diagnostic does not misleadingly claim that a variable
19222 // can not be captured by a lambda implicitly even though it is captured
19223 // explicitly. Suggestion:
19224 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19225 // at the function head
19226 // - cache the StartingDeclContext - this must be a lambda
19227 // - captureInLambda in the innermost lambda the variable.
19232 FunctionScopesIndex
--;
19235 } while (!VarDC
->Equals(DC
));
19237 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19238 // computing the type of the capture at each step, checking type-specific
19239 // requirements, and adding captures if requested.
19240 // If the variable had already been captured previously, we start capturing
19241 // at the lambda nested within that one.
19242 bool Invalid
= false;
19243 for (unsigned I
= ++FunctionScopesIndex
, N
= MaxFunctionScopesIndex
+ 1; I
!= N
;
19245 CapturingScopeInfo
*CSI
= cast
<CapturingScopeInfo
>(FunctionScopes
[I
]);
19247 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19248 // certain types of variables (unnamed, variably modified types etc.)
19249 // so check for eligibility.
19252 !isVariableCapturable(CSI
, Var
, ExprLoc
, BuildAndDiagnose
, *this);
19254 // After encountering an error, if we're actually supposed to capture, keep
19255 // capturing in nested contexts to suppress any follow-on diagnostics.
19256 if (Invalid
&& !BuildAndDiagnose
)
19259 if (BlockScopeInfo
*BSI
= dyn_cast
<BlockScopeInfo
>(CSI
)) {
19260 Invalid
= !captureInBlock(BSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
,
19261 DeclRefType
, Nested
, *this, Invalid
);
19263 } else if (CapturedRegionScopeInfo
*RSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
)) {
19264 Invalid
= !captureInCapturedRegion(
19265 RSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
, DeclRefType
, Nested
,
19266 Kind
, /*IsTopScope*/ I
== N
- 1, *this, Invalid
);
19269 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(CSI
);
19271 !captureInLambda(LSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
,
19272 DeclRefType
, Nested
, Kind
, EllipsisLoc
,
19273 /*IsTopScope*/ I
== N
- 1, *this, Invalid
);
19277 if (Invalid
&& !BuildAndDiagnose
)
19283 bool Sema::tryCaptureVariable(ValueDecl
*Var
, SourceLocation Loc
,
19284 TryCaptureKind Kind
, SourceLocation EllipsisLoc
) {
19285 QualType CaptureType
;
19286 QualType DeclRefType
;
19287 return tryCaptureVariable(Var
, Loc
, Kind
, EllipsisLoc
,
19288 /*BuildAndDiagnose=*/true, CaptureType
,
19289 DeclRefType
, nullptr);
19292 bool Sema::NeedToCaptureVariable(ValueDecl
*Var
, SourceLocation Loc
) {
19293 QualType CaptureType
;
19294 QualType DeclRefType
;
19295 return !tryCaptureVariable(Var
, Loc
, TryCapture_Implicit
, SourceLocation(),
19296 /*BuildAndDiagnose=*/false, CaptureType
,
19297 DeclRefType
, nullptr);
19300 QualType
Sema::getCapturedDeclRefType(ValueDecl
*Var
, SourceLocation Loc
) {
19301 QualType CaptureType
;
19302 QualType DeclRefType
;
19304 // Determine whether we can capture this variable.
19305 if (tryCaptureVariable(Var
, Loc
, TryCapture_Implicit
, SourceLocation(),
19306 /*BuildAndDiagnose=*/false, CaptureType
,
19307 DeclRefType
, nullptr))
19310 return DeclRefType
;
19314 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
19315 // The produced TemplateArgumentListInfo* points to data stored within this
19316 // object, so should only be used in contexts where the pointer will not be
19317 // used after the CopiedTemplateArgs object is destroyed.
19318 class CopiedTemplateArgs
{
19320 TemplateArgumentListInfo TemplateArgStorage
;
19322 template<typename RefExpr
>
19323 CopiedTemplateArgs(RefExpr
*E
) : HasArgs(E
->hasExplicitTemplateArgs()) {
19325 E
->copyTemplateArgumentsInto(TemplateArgStorage
);
19327 operator TemplateArgumentListInfo
*()
19328 #ifdef __has_cpp_attribute
19329 #if __has_cpp_attribute(clang::lifetimebound)
19330 [[clang::lifetimebound
]]
19334 return HasArgs
? &TemplateArgStorage
: nullptr;
19339 /// Walk the set of potential results of an expression and mark them all as
19340 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
19342 /// \return A new expression if we found any potential results, ExprEmpty() if
19343 /// not, and ExprError() if we diagnosed an error.
19344 static ExprResult
rebuildPotentialResultsAsNonOdrUsed(Sema
&S
, Expr
*E
,
19345 NonOdrUseReason NOUR
) {
19346 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
19347 // an object that satisfies the requirements for appearing in a
19348 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
19349 // is immediately applied." This function handles the lvalue-to-rvalue
19350 // conversion part.
19352 // If we encounter a node that claims to be an odr-use but shouldn't be, we
19353 // transform it into the relevant kind of non-odr-use node and rebuild the
19354 // tree of nodes leading to it.
19356 // This is a mini-TreeTransform that only transforms a restricted subset of
19357 // nodes (and only certain operands of them).
19359 // Rebuild a subexpression.
19360 auto Rebuild
= [&](Expr
*Sub
) {
19361 return rebuildPotentialResultsAsNonOdrUsed(S
, Sub
, NOUR
);
19364 // Check whether a potential result satisfies the requirements of NOUR.
19365 auto IsPotentialResultOdrUsed
= [&](NamedDecl
*D
) {
19366 // Any entity other than a VarDecl is always odr-used whenever it's named
19367 // in a potentially-evaluated expression.
19368 auto *VD
= dyn_cast
<VarDecl
>(D
);
19372 // C++2a [basic.def.odr]p4:
19373 // A variable x whose name appears as a potentially-evalauted expression
19374 // e is odr-used by e unless
19375 // -- x is a reference that is usable in constant expressions, or
19376 // -- x is a variable of non-reference type that is usable in constant
19377 // expressions and has no mutable subobjects, and e is an element of
19378 // the set of potential results of an expression of
19379 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19380 // conversion is applied, or
19381 // -- x is a variable of non-reference type, and e is an element of the
19382 // set of potential results of a discarded-value expression to which
19383 // the lvalue-to-rvalue conversion is not applied
19385 // We check the first bullet and the "potentially-evaluated" condition in
19386 // BuildDeclRefExpr. We check the type requirements in the second bullet
19387 // in CheckLValueToRValueConversionOperand below.
19390 case NOUR_Unevaluated
:
19391 llvm_unreachable("unexpected non-odr-use-reason");
19393 case NOUR_Constant
:
19394 // Constant references were handled when they were built.
19395 if (VD
->getType()->isReferenceType())
19397 if (auto *RD
= VD
->getType()->getAsCXXRecordDecl())
19398 if (RD
->hasMutableFields())
19400 if (!VD
->isUsableInConstantExpressions(S
.Context
))
19404 case NOUR_Discarded
:
19405 if (VD
->getType()->isReferenceType())
19412 // Mark that this expression does not constitute an odr-use.
19413 auto MarkNotOdrUsed
= [&] {
19414 S
.MaybeODRUseExprs
.remove(E
);
19415 if (LambdaScopeInfo
*LSI
= S
.getCurLambda())
19416 LSI
->markVariableExprAsNonODRUsed(E
);
19419 // C++2a [basic.def.odr]p2:
19420 // The set of potential results of an expression e is defined as follows:
19421 switch (E
->getStmtClass()) {
19422 // -- If e is an id-expression, ...
19423 case Expr::DeclRefExprClass
: {
19424 auto *DRE
= cast
<DeclRefExpr
>(E
);
19425 if (DRE
->isNonOdrUse() || IsPotentialResultOdrUsed(DRE
->getDecl()))
19428 // Rebuild as a non-odr-use DeclRefExpr.
19430 return DeclRefExpr::Create(
19431 S
.Context
, DRE
->getQualifierLoc(), DRE
->getTemplateKeywordLoc(),
19432 DRE
->getDecl(), DRE
->refersToEnclosingVariableOrCapture(),
19433 DRE
->getNameInfo(), DRE
->getType(), DRE
->getValueKind(),
19434 DRE
->getFoundDecl(), CopiedTemplateArgs(DRE
), NOUR
);
19437 case Expr::FunctionParmPackExprClass
: {
19438 auto *FPPE
= cast
<FunctionParmPackExpr
>(E
);
19439 // If any of the declarations in the pack is odr-used, then the expression
19440 // as a whole constitutes an odr-use.
19441 for (VarDecl
*D
: *FPPE
)
19442 if (IsPotentialResultOdrUsed(D
))
19443 return ExprEmpty();
19445 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
19446 // nothing cares about whether we marked this as an odr-use, but it might
19447 // be useful for non-compiler tools.
19452 // -- If e is a subscripting operation with an array operand...
19453 case Expr::ArraySubscriptExprClass
: {
19454 auto *ASE
= cast
<ArraySubscriptExpr
>(E
);
19455 Expr
*OldBase
= ASE
->getBase()->IgnoreImplicit();
19456 if (!OldBase
->getType()->isArrayType())
19458 ExprResult Base
= Rebuild(OldBase
);
19459 if (!Base
.isUsable())
19461 Expr
*LHS
= ASE
->getBase() == ASE
->getLHS() ? Base
.get() : ASE
->getLHS();
19462 Expr
*RHS
= ASE
->getBase() == ASE
->getRHS() ? Base
.get() : ASE
->getRHS();
19463 SourceLocation LBracketLoc
= ASE
->getBeginLoc(); // FIXME: Not stored.
19464 return S
.ActOnArraySubscriptExpr(nullptr, LHS
, LBracketLoc
, RHS
,
19465 ASE
->getRBracketLoc());
19468 case Expr::MemberExprClass
: {
19469 auto *ME
= cast
<MemberExpr
>(E
);
19470 // -- If e is a class member access expression [...] naming a non-static
19472 if (isa
<FieldDecl
>(ME
->getMemberDecl())) {
19473 ExprResult Base
= Rebuild(ME
->getBase());
19474 if (!Base
.isUsable())
19476 return MemberExpr::Create(
19477 S
.Context
, Base
.get(), ME
->isArrow(), ME
->getOperatorLoc(),
19478 ME
->getQualifierLoc(), ME
->getTemplateKeywordLoc(),
19479 ME
->getMemberDecl(), ME
->getFoundDecl(), ME
->getMemberNameInfo(),
19480 CopiedTemplateArgs(ME
), ME
->getType(), ME
->getValueKind(),
19481 ME
->getObjectKind(), ME
->isNonOdrUse());
19484 if (ME
->getMemberDecl()->isCXXInstanceMember())
19487 // -- If e is a class member access expression naming a static data member,
19489 if (ME
->isNonOdrUse() || IsPotentialResultOdrUsed(ME
->getMemberDecl()))
19492 // Rebuild as a non-odr-use MemberExpr.
19494 return MemberExpr::Create(
19495 S
.Context
, ME
->getBase(), ME
->isArrow(), ME
->getOperatorLoc(),
19496 ME
->getQualifierLoc(), ME
->getTemplateKeywordLoc(), ME
->getMemberDecl(),
19497 ME
->getFoundDecl(), ME
->getMemberNameInfo(), CopiedTemplateArgs(ME
),
19498 ME
->getType(), ME
->getValueKind(), ME
->getObjectKind(), NOUR
);
19501 case Expr::BinaryOperatorClass
: {
19502 auto *BO
= cast
<BinaryOperator
>(E
);
19503 Expr
*LHS
= BO
->getLHS();
19504 Expr
*RHS
= BO
->getRHS();
19505 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
19506 if (BO
->getOpcode() == BO_PtrMemD
) {
19507 ExprResult Sub
= Rebuild(LHS
);
19508 if (!Sub
.isUsable())
19511 // -- If e is a comma expression, ...
19512 } else if (BO
->getOpcode() == BO_Comma
) {
19513 ExprResult Sub
= Rebuild(RHS
);
19514 if (!Sub
.isUsable())
19520 return S
.BuildBinOp(nullptr, BO
->getOperatorLoc(), BO
->getOpcode(),
19524 // -- If e has the form (e1)...
19525 case Expr::ParenExprClass
: {
19526 auto *PE
= cast
<ParenExpr
>(E
);
19527 ExprResult Sub
= Rebuild(PE
->getSubExpr());
19528 if (!Sub
.isUsable())
19530 return S
.ActOnParenExpr(PE
->getLParen(), PE
->getRParen(), Sub
.get());
19533 // -- If e is a glvalue conditional expression, ...
19534 // We don't apply this to a binary conditional operator. FIXME: Should we?
19535 case Expr::ConditionalOperatorClass
: {
19536 auto *CO
= cast
<ConditionalOperator
>(E
);
19537 ExprResult LHS
= Rebuild(CO
->getLHS());
19538 if (LHS
.isInvalid())
19539 return ExprError();
19540 ExprResult RHS
= Rebuild(CO
->getRHS());
19541 if (RHS
.isInvalid())
19542 return ExprError();
19543 if (!LHS
.isUsable() && !RHS
.isUsable())
19544 return ExprEmpty();
19545 if (!LHS
.isUsable())
19546 LHS
= CO
->getLHS();
19547 if (!RHS
.isUsable())
19548 RHS
= CO
->getRHS();
19549 return S
.ActOnConditionalOp(CO
->getQuestionLoc(), CO
->getColonLoc(),
19550 CO
->getCond(), LHS
.get(), RHS
.get());
19553 // [Clang extension]
19554 // -- If e has the form __extension__ e1...
19555 case Expr::UnaryOperatorClass
: {
19556 auto *UO
= cast
<UnaryOperator
>(E
);
19557 if (UO
->getOpcode() != UO_Extension
)
19559 ExprResult Sub
= Rebuild(UO
->getSubExpr());
19560 if (!Sub
.isUsable())
19562 return S
.BuildUnaryOp(nullptr, UO
->getOperatorLoc(), UO_Extension
,
19566 // [Clang extension]
19567 // -- If e has the form _Generic(...), the set of potential results is the
19568 // union of the sets of potential results of the associated expressions.
19569 case Expr::GenericSelectionExprClass
: {
19570 auto *GSE
= cast
<GenericSelectionExpr
>(E
);
19572 SmallVector
<Expr
*, 4> AssocExprs
;
19573 bool AnyChanged
= false;
19574 for (Expr
*OrigAssocExpr
: GSE
->getAssocExprs()) {
19575 ExprResult AssocExpr
= Rebuild(OrigAssocExpr
);
19576 if (AssocExpr
.isInvalid())
19577 return ExprError();
19578 if (AssocExpr
.isUsable()) {
19579 AssocExprs
.push_back(AssocExpr
.get());
19582 AssocExprs
.push_back(OrigAssocExpr
);
19586 return AnyChanged
? S
.CreateGenericSelectionExpr(
19587 GSE
->getGenericLoc(), GSE
->getDefaultLoc(),
19588 GSE
->getRParenLoc(), GSE
->getControllingExpr(),
19589 GSE
->getAssocTypeSourceInfos(), AssocExprs
)
19593 // [Clang extension]
19594 // -- If e has the form __builtin_choose_expr(...), the set of potential
19595 // results is the union of the sets of potential results of the
19596 // second and third subexpressions.
19597 case Expr::ChooseExprClass
: {
19598 auto *CE
= cast
<ChooseExpr
>(E
);
19600 ExprResult LHS
= Rebuild(CE
->getLHS());
19601 if (LHS
.isInvalid())
19602 return ExprError();
19604 ExprResult RHS
= Rebuild(CE
->getLHS());
19605 if (RHS
.isInvalid())
19606 return ExprError();
19608 if (!LHS
.get() && !RHS
.get())
19609 return ExprEmpty();
19610 if (!LHS
.isUsable())
19611 LHS
= CE
->getLHS();
19612 if (!RHS
.isUsable())
19613 RHS
= CE
->getRHS();
19615 return S
.ActOnChooseExpr(CE
->getBuiltinLoc(), CE
->getCond(), LHS
.get(),
19616 RHS
.get(), CE
->getRParenLoc());
19619 // Step through non-syntactic nodes.
19620 case Expr::ConstantExprClass
: {
19621 auto *CE
= cast
<ConstantExpr
>(E
);
19622 ExprResult Sub
= Rebuild(CE
->getSubExpr());
19623 if (!Sub
.isUsable())
19625 return ConstantExpr::Create(S
.Context
, Sub
.get());
19628 // We could mostly rely on the recursive rebuilding to rebuild implicit
19629 // casts, but not at the top level, so rebuild them here.
19630 case Expr::ImplicitCastExprClass
: {
19631 auto *ICE
= cast
<ImplicitCastExpr
>(E
);
19632 // Only step through the narrow set of cast kinds we expect to encounter.
19633 // Anything else suggests we've left the region in which potential results
19635 switch (ICE
->getCastKind()) {
19637 case CK_DerivedToBase
:
19638 case CK_UncheckedDerivedToBase
: {
19639 ExprResult Sub
= Rebuild(ICE
->getSubExpr());
19640 if (!Sub
.isUsable())
19642 CXXCastPath
Path(ICE
->path());
19643 return S
.ImpCastExprToType(Sub
.get(), ICE
->getType(), ICE
->getCastKind(),
19644 ICE
->getValueKind(), &Path
);
19657 // Can't traverse through this node. Nothing to do.
19658 return ExprEmpty();
19661 ExprResult
Sema::CheckLValueToRValueConversionOperand(Expr
*E
) {
19662 // Check whether the operand is or contains an object of non-trivial C union
19664 if (E
->getType().isVolatileQualified() &&
19665 (E
->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
19666 E
->getType().hasNonTrivialToPrimitiveCopyCUnion()))
19667 checkNonTrivialCUnion(E
->getType(), E
->getExprLoc(),
19668 Sema::NTCUC_LValueToRValueVolatile
,
19669 NTCUK_Destruct
|NTCUK_Copy
);
19671 // C++2a [basic.def.odr]p4:
19672 // [...] an expression of non-volatile-qualified non-class type to which
19673 // the lvalue-to-rvalue conversion is applied [...]
19674 if (E
->getType().isVolatileQualified() || E
->getType()->getAs
<RecordType
>())
19677 ExprResult Result
=
19678 rebuildPotentialResultsAsNonOdrUsed(*this, E
, NOUR_Constant
);
19679 if (Result
.isInvalid())
19680 return ExprError();
19681 return Result
.get() ? Result
: E
;
19684 ExprResult
Sema::ActOnConstantExpression(ExprResult Res
) {
19685 Res
= CorrectDelayedTyposInExpr(Res
);
19687 if (!Res
.isUsable())
19690 // If a constant-expression is a reference to a variable where we delay
19691 // deciding whether it is an odr-use, just assume we will apply the
19692 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
19693 // (a non-type template argument), we have special handling anyway.
19694 return CheckLValueToRValueConversionOperand(Res
.get());
19697 void Sema::CleanupVarDeclMarking() {
19698 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
19700 MaybeODRUseExprSet LocalMaybeODRUseExprs
;
19701 std::swap(LocalMaybeODRUseExprs
, MaybeODRUseExprs
);
19703 for (Expr
*E
: LocalMaybeODRUseExprs
) {
19704 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
19705 MarkVarDeclODRUsed(cast
<VarDecl
>(DRE
->getDecl()),
19706 DRE
->getLocation(), *this);
19707 } else if (auto *ME
= dyn_cast
<MemberExpr
>(E
)) {
19708 MarkVarDeclODRUsed(cast
<VarDecl
>(ME
->getMemberDecl()), ME
->getMemberLoc(),
19710 } else if (auto *FP
= dyn_cast
<FunctionParmPackExpr
>(E
)) {
19711 for (VarDecl
*VD
: *FP
)
19712 MarkVarDeclODRUsed(VD
, FP
->getParameterPackLocation(), *this);
19714 llvm_unreachable("Unexpected expression");
19718 assert(MaybeODRUseExprs
.empty() &&
19719 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
19722 static void DoMarkPotentialCapture(Sema
&SemaRef
, SourceLocation Loc
,
19723 ValueDecl
*Var
, Expr
*E
) {
19724 VarDecl
*VD
= Var
->getPotentiallyDecomposedVarDecl();
19728 const bool RefersToEnclosingScope
=
19729 (SemaRef
.CurContext
!= VD
->getDeclContext() &&
19730 VD
->getDeclContext()->isFunctionOrMethod() && VD
->hasLocalStorage());
19731 if (RefersToEnclosingScope
) {
19732 LambdaScopeInfo
*const LSI
=
19733 SemaRef
.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
19734 if (LSI
&& (!LSI
->CallOperator
||
19735 !LSI
->CallOperator
->Encloses(Var
->getDeclContext()))) {
19736 // If a variable could potentially be odr-used, defer marking it so
19737 // until we finish analyzing the full expression for any
19738 // lvalue-to-rvalue
19739 // or discarded value conversions that would obviate odr-use.
19740 // Add it to the list of potential captures that will be analyzed
19741 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
19742 // unless the variable is a reference that was initialized by a constant
19743 // expression (this will never need to be captured or odr-used).
19745 // FIXME: We can simplify this a lot after implementing P0588R1.
19746 assert(E
&& "Capture variable should be used in an expression.");
19747 if (!Var
->getType()->isReferenceType() ||
19748 !VD
->isUsableInConstantExpressions(SemaRef
.Context
))
19749 LSI
->addPotentialCapture(E
->IgnoreParens());
19754 static void DoMarkVarDeclReferenced(
19755 Sema
&SemaRef
, SourceLocation Loc
, VarDecl
*Var
, Expr
*E
,
19756 llvm::DenseMap
<const VarDecl
*, int> &RefsMinusAssignments
) {
19757 assert((!E
|| isa
<DeclRefExpr
>(E
) || isa
<MemberExpr
>(E
) ||
19758 isa
<FunctionParmPackExpr
>(E
)) &&
19759 "Invalid Expr argument to DoMarkVarDeclReferenced");
19760 Var
->setReferenced();
19762 if (Var
->isInvalidDecl())
19765 auto *MSI
= Var
->getMemberSpecializationInfo();
19766 TemplateSpecializationKind TSK
= MSI
? MSI
->getTemplateSpecializationKind()
19767 : Var
->getTemplateSpecializationKind();
19769 OdrUseContext OdrUse
= isOdrUseContext(SemaRef
);
19770 bool UsableInConstantExpr
=
19771 Var
->mightBeUsableInConstantExpressions(SemaRef
.Context
);
19773 if (Var
->isLocalVarDeclOrParm() && !Var
->hasExternalStorage()) {
19774 RefsMinusAssignments
.insert({Var
, 0}).first
->getSecond()++;
19777 // C++20 [expr.const]p12:
19778 // A variable [...] is needed for constant evaluation if it is [...] a
19779 // variable whose name appears as a potentially constant evaluated
19780 // expression that is either a contexpr variable or is of non-volatile
19781 // const-qualified integral type or of reference type
19782 bool NeededForConstantEvaluation
=
19783 isPotentiallyConstantEvaluatedContext(SemaRef
) && UsableInConstantExpr
;
19785 bool NeedDefinition
=
19786 OdrUse
== OdrUseContext::Used
|| NeededForConstantEvaluation
;
19788 assert(!isa
<VarTemplatePartialSpecializationDecl
>(Var
) &&
19789 "Can't instantiate a partial template specialization.");
19791 // If this might be a member specialization of a static data member, check
19792 // the specialization is visible. We already did the checks for variable
19793 // template specializations when we created them.
19794 if (NeedDefinition
&& TSK
!= TSK_Undeclared
&&
19795 !isa
<VarTemplateSpecializationDecl
>(Var
))
19796 SemaRef
.checkSpecializationVisibility(Loc
, Var
);
19798 // Perform implicit instantiation of static data members, static data member
19799 // templates of class templates, and variable template specializations. Delay
19800 // instantiations of variable templates, except for those that could be used
19801 // in a constant expression.
19802 if (NeedDefinition
&& isTemplateInstantiation(TSK
)) {
19803 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
19804 // instantiation declaration if a variable is usable in a constant
19805 // expression (among other cases).
19806 bool TryInstantiating
=
19807 TSK
== TSK_ImplicitInstantiation
||
19808 (TSK
== TSK_ExplicitInstantiationDeclaration
&& UsableInConstantExpr
);
19810 if (TryInstantiating
) {
19811 SourceLocation PointOfInstantiation
=
19812 MSI
? MSI
->getPointOfInstantiation() : Var
->getPointOfInstantiation();
19813 bool FirstInstantiation
= PointOfInstantiation
.isInvalid();
19814 if (FirstInstantiation
) {
19815 PointOfInstantiation
= Loc
;
19817 MSI
->setPointOfInstantiation(PointOfInstantiation
);
19818 // FIXME: Notify listener.
19820 Var
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
19823 if (UsableInConstantExpr
) {
19824 // Do not defer instantiations of variables that could be used in a
19825 // constant expression.
19826 SemaRef
.runWithSufficientStackSpace(PointOfInstantiation
, [&] {
19827 SemaRef
.InstantiateVariableDefinition(PointOfInstantiation
, Var
);
19830 // Re-set the member to trigger a recomputation of the dependence bits
19831 // for the expression.
19832 if (auto *DRE
= dyn_cast_or_null
<DeclRefExpr
>(E
))
19833 DRE
->setDecl(DRE
->getDecl());
19834 else if (auto *ME
= dyn_cast_or_null
<MemberExpr
>(E
))
19835 ME
->setMemberDecl(ME
->getMemberDecl());
19836 } else if (FirstInstantiation
||
19837 isa
<VarTemplateSpecializationDecl
>(Var
)) {
19838 // FIXME: For a specialization of a variable template, we don't
19839 // distinguish between "declaration and type implicitly instantiated"
19840 // and "implicit instantiation of definition requested", so we have
19841 // no direct way to avoid enqueueing the pending instantiation
19843 SemaRef
.PendingInstantiations
19844 .push_back(std::make_pair(Var
, PointOfInstantiation
));
19849 // C++2a [basic.def.odr]p4:
19850 // A variable x whose name appears as a potentially-evaluated expression e
19851 // is odr-used by e unless
19852 // -- x is a reference that is usable in constant expressions
19853 // -- x is a variable of non-reference type that is usable in constant
19854 // expressions and has no mutable subobjects [FIXME], and e is an
19855 // element of the set of potential results of an expression of
19856 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
19857 // conversion is applied
19858 // -- x is a variable of non-reference type, and e is an element of the set
19859 // of potential results of a discarded-value expression to which the
19860 // lvalue-to-rvalue conversion is not applied [FIXME]
19862 // We check the first part of the second bullet here, and
19863 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
19864 // FIXME: To get the third bullet right, we need to delay this even for
19865 // variables that are not usable in constant expressions.
19867 // If we already know this isn't an odr-use, there's nothing more to do.
19868 if (DeclRefExpr
*DRE
= dyn_cast_or_null
<DeclRefExpr
>(E
))
19869 if (DRE
->isNonOdrUse())
19871 if (MemberExpr
*ME
= dyn_cast_or_null
<MemberExpr
>(E
))
19872 if (ME
->isNonOdrUse())
19876 case OdrUseContext::None
:
19877 // In some cases, a variable may not have been marked unevaluated, if it
19878 // appears in a defaukt initializer.
19879 assert((!E
|| isa
<FunctionParmPackExpr
>(E
) ||
19880 SemaRef
.isUnevaluatedContext()) &&
19881 "missing non-odr-use marking for unevaluated decl ref");
19884 case OdrUseContext::FormallyOdrUsed
:
19885 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
19889 case OdrUseContext::Used
:
19890 // If we might later find that this expression isn't actually an odr-use,
19891 // delay the marking.
19892 if (E
&& Var
->isUsableInConstantExpressions(SemaRef
.Context
))
19893 SemaRef
.MaybeODRUseExprs
.insert(E
);
19895 MarkVarDeclODRUsed(Var
, Loc
, SemaRef
);
19898 case OdrUseContext::Dependent
:
19899 // If this is a dependent context, we don't need to mark variables as
19900 // odr-used, but we may still need to track them for lambda capture.
19901 // FIXME: Do we also need to do this inside dependent typeid expressions
19902 // (which are modeled as unevaluated at this point)?
19903 DoMarkPotentialCapture(SemaRef
, Loc
, Var
, E
);
19908 static void DoMarkBindingDeclReferenced(Sema
&SemaRef
, SourceLocation Loc
,
19909 BindingDecl
*BD
, Expr
*E
) {
19910 BD
->setReferenced();
19912 if (BD
->isInvalidDecl())
19915 OdrUseContext OdrUse
= isOdrUseContext(SemaRef
);
19916 if (OdrUse
== OdrUseContext::Used
) {
19917 QualType CaptureType
, DeclRefType
;
19918 SemaRef
.tryCaptureVariable(BD
, Loc
, Sema::TryCapture_Implicit
,
19919 /*EllipsisLoc*/ SourceLocation(),
19920 /*BuildAndDiagnose*/ true, CaptureType
,
19922 /*FunctionScopeIndexToStopAt*/ nullptr);
19923 } else if (OdrUse
== OdrUseContext::Dependent
) {
19924 DoMarkPotentialCapture(SemaRef
, Loc
, BD
, E
);
19928 /// Mark a variable referenced, and check whether it is odr-used
19929 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
19930 /// used directly for normal expressions referring to VarDecl.
19931 void Sema::MarkVariableReferenced(SourceLocation Loc
, VarDecl
*Var
) {
19932 DoMarkVarDeclReferenced(*this, Loc
, Var
, nullptr, RefsMinusAssignments
);
19936 MarkExprReferenced(Sema
&SemaRef
, SourceLocation Loc
, Decl
*D
, Expr
*E
,
19937 bool MightBeOdrUse
,
19938 llvm::DenseMap
<const VarDecl
*, int> &RefsMinusAssignments
) {
19939 if (SemaRef
.isInOpenMPDeclareTargetContext())
19940 SemaRef
.checkDeclIsAllowedInOpenMPTarget(E
, D
);
19942 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(D
)) {
19943 DoMarkVarDeclReferenced(SemaRef
, Loc
, Var
, E
, RefsMinusAssignments
);
19947 if (BindingDecl
*Decl
= dyn_cast
<BindingDecl
>(D
)) {
19948 DoMarkBindingDeclReferenced(SemaRef
, Loc
, Decl
, E
);
19952 SemaRef
.MarkAnyDeclReferenced(Loc
, D
, MightBeOdrUse
);
19954 // If this is a call to a method via a cast, also mark the method in the
19955 // derived class used in case codegen can devirtualize the call.
19956 const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
);
19959 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(ME
->getMemberDecl());
19962 // Only attempt to devirtualize if this is truly a virtual call.
19963 bool IsVirtualCall
= MD
->isVirtual() &&
19964 ME
->performsVirtualDispatch(SemaRef
.getLangOpts());
19965 if (!IsVirtualCall
)
19968 // If it's possible to devirtualize the call, mark the called function
19970 CXXMethodDecl
*DM
= MD
->getDevirtualizedMethod(
19971 ME
->getBase(), SemaRef
.getLangOpts().AppleKext
);
19973 SemaRef
.MarkAnyDeclReferenced(Loc
, DM
, MightBeOdrUse
);
19976 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
19978 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
19979 /// handled with care if the DeclRefExpr is not newly-created.
19980 void Sema::MarkDeclRefReferenced(DeclRefExpr
*E
, const Expr
*Base
) {
19981 // TODO: update this with DR# once a defect report is filed.
19982 // C++11 defect. The address of a pure member should not be an ODR use, even
19983 // if it's a qualified reference.
19984 bool OdrUse
= true;
19985 if (const CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(E
->getDecl()))
19986 if (Method
->isVirtual() &&
19987 !Method
->getDevirtualizedMethod(Base
, getLangOpts().AppleKext
))
19990 if (auto *FD
= dyn_cast
<FunctionDecl
>(E
->getDecl()))
19991 if (!isUnevaluatedContext() && !isConstantEvaluated() &&
19992 !isImmediateFunctionContext() &&
19993 !isCheckingDefaultArgumentOrInitializer() && FD
->isConsteval() &&
19994 !RebuildingImmediateInvocation
&& !FD
->isDependentContext())
19995 ExprEvalContexts
.back().ReferenceToConsteval
.insert(E
);
19996 MarkExprReferenced(*this, E
->getLocation(), E
->getDecl(), E
, OdrUse
,
19997 RefsMinusAssignments
);
20000 /// Perform reference-marking and odr-use handling for a MemberExpr.
20001 void Sema::MarkMemberReferenced(MemberExpr
*E
) {
20002 // C++11 [basic.def.odr]p2:
20003 // A non-overloaded function whose name appears as a potentially-evaluated
20004 // expression or a member of a set of candidate functions, if selected by
20005 // overload resolution when referred to from a potentially-evaluated
20006 // expression, is odr-used, unless it is a pure virtual function and its
20007 // name is not explicitly qualified.
20008 bool MightBeOdrUse
= true;
20009 if (E
->performsVirtualDispatch(getLangOpts())) {
20010 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(E
->getMemberDecl()))
20011 if (Method
->isPure())
20012 MightBeOdrUse
= false;
20014 SourceLocation Loc
=
20015 E
->getMemberLoc().isValid() ? E
->getMemberLoc() : E
->getBeginLoc();
20016 MarkExprReferenced(*this, Loc
, E
->getMemberDecl(), E
, MightBeOdrUse
,
20017 RefsMinusAssignments
);
20020 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20021 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr
*E
) {
20022 for (VarDecl
*VD
: *E
)
20023 MarkExprReferenced(*this, E
->getParameterPackLocation(), VD
, E
, true,
20024 RefsMinusAssignments
);
20027 /// Perform marking for a reference to an arbitrary declaration. It
20028 /// marks the declaration referenced, and performs odr-use checking for
20029 /// functions and variables. This method should not be used when building a
20030 /// normal expression which refers to a variable.
20031 void Sema::MarkAnyDeclReferenced(SourceLocation Loc
, Decl
*D
,
20032 bool MightBeOdrUse
) {
20033 if (MightBeOdrUse
) {
20034 if (auto *VD
= dyn_cast
<VarDecl
>(D
)) {
20035 MarkVariableReferenced(Loc
, VD
);
20039 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
20040 MarkFunctionReferenced(Loc
, FD
, MightBeOdrUse
);
20043 D
->setReferenced();
20047 // Mark all of the declarations used by a type as referenced.
20048 // FIXME: Not fully implemented yet! We need to have a better understanding
20049 // of when we're entering a context we should not recurse into.
20050 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20051 // TreeTransforms rebuilding the type in a new context. Rather than
20052 // duplicating the TreeTransform logic, we should consider reusing it here.
20053 // Currently that causes problems when rebuilding LambdaExprs.
20054 class MarkReferencedDecls
: public RecursiveASTVisitor
<MarkReferencedDecls
> {
20056 SourceLocation Loc
;
20059 typedef RecursiveASTVisitor
<MarkReferencedDecls
> Inherited
;
20061 MarkReferencedDecls(Sema
&S
, SourceLocation Loc
) : S(S
), Loc(Loc
) { }
20063 bool TraverseTemplateArgument(const TemplateArgument
&Arg
);
20067 bool MarkReferencedDecls::TraverseTemplateArgument(
20068 const TemplateArgument
&Arg
) {
20070 // A non-type template argument is a constant-evaluated context.
20071 EnterExpressionEvaluationContext
Evaluated(
20072 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
20073 if (Arg
.getKind() == TemplateArgument::Declaration
) {
20074 if (Decl
*D
= Arg
.getAsDecl())
20075 S
.MarkAnyDeclReferenced(Loc
, D
, true);
20076 } else if (Arg
.getKind() == TemplateArgument::Expression
) {
20077 S
.MarkDeclarationsReferencedInExpr(Arg
.getAsExpr(), false);
20081 return Inherited::TraverseTemplateArgument(Arg
);
20084 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc
, QualType T
) {
20085 MarkReferencedDecls
Marker(*this, Loc
);
20086 Marker
.TraverseType(T
);
20090 /// Helper class that marks all of the declarations referenced by
20091 /// potentially-evaluated subexpressions as "referenced".
20092 class EvaluatedExprMarker
: public UsedDeclVisitor
<EvaluatedExprMarker
> {
20094 typedef UsedDeclVisitor
<EvaluatedExprMarker
> Inherited
;
20095 bool SkipLocalVariables
;
20096 ArrayRef
<const Expr
*> StopAt
;
20098 EvaluatedExprMarker(Sema
&S
, bool SkipLocalVariables
,
20099 ArrayRef
<const Expr
*> StopAt
)
20100 : Inherited(S
), SkipLocalVariables(SkipLocalVariables
), StopAt(StopAt
) {}
20102 void visitUsedDecl(SourceLocation Loc
, Decl
*D
) {
20103 S
.MarkFunctionReferenced(Loc
, cast
<FunctionDecl
>(D
));
20106 void Visit(Expr
*E
) {
20107 if (llvm::is_contained(StopAt
, E
))
20109 Inherited::Visit(E
);
20112 void VisitConstantExpr(ConstantExpr
*E
) {
20113 // Don't mark declarations within a ConstantExpression, as this expression
20114 // will be evaluated and folded to a value.
20117 void VisitDeclRefExpr(DeclRefExpr
*E
) {
20118 // If we were asked not to visit local variables, don't.
20119 if (SkipLocalVariables
) {
20120 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl()))
20121 if (VD
->hasLocalStorage())
20125 // FIXME: This can trigger the instantiation of the initializer of a
20126 // variable, which can cause the expression to become value-dependent
20127 // or error-dependent. Do we need to propagate the new dependence bits?
20128 S
.MarkDeclRefReferenced(E
);
20131 void VisitMemberExpr(MemberExpr
*E
) {
20132 S
.MarkMemberReferenced(E
);
20133 Visit(E
->getBase());
20138 /// Mark any declarations that appear within this expression or any
20139 /// potentially-evaluated subexpressions as "referenced".
20141 /// \param SkipLocalVariables If true, don't mark local variables as
20143 /// \param StopAt Subexpressions that we shouldn't recurse into.
20144 void Sema::MarkDeclarationsReferencedInExpr(Expr
*E
,
20145 bool SkipLocalVariables
,
20146 ArrayRef
<const Expr
*> StopAt
) {
20147 EvaluatedExprMarker(*this, SkipLocalVariables
, StopAt
).Visit(E
);
20150 /// Emit a diagnostic when statements are reachable.
20151 /// FIXME: check for reachability even in expressions for which we don't build a
20152 /// CFG (eg, in the initializer of a global or in a constant expression).
20154 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20155 bool Sema::DiagIfReachable(SourceLocation Loc
, ArrayRef
<const Stmt
*> Stmts
,
20156 const PartialDiagnostic
&PD
) {
20157 if (!Stmts
.empty() && getCurFunctionOrMethodDecl()) {
20158 if (!FunctionScopes
.empty())
20159 FunctionScopes
.back()->PossiblyUnreachableDiags
.push_back(
20160 sema::PossiblyUnreachableDiag(PD
, Loc
, Stmts
));
20164 // The initializer of a constexpr variable or of the first declaration of a
20165 // static data member is not syntactically a constant evaluated constant,
20166 // but nonetheless is always required to be a constant expression, so we
20167 // can skip diagnosing.
20168 // FIXME: Using the mangling context here is a hack.
20169 if (auto *VD
= dyn_cast_or_null
<VarDecl
>(
20170 ExprEvalContexts
.back().ManglingContextDecl
)) {
20171 if (VD
->isConstexpr() ||
20172 (VD
->isStaticDataMember() && VD
->isFirstDecl() && !VD
->isInline()))
20174 // FIXME: For any other kind of variable, we should build a CFG for its
20175 // initializer and check whether the context in question is reachable.
20182 /// Emit a diagnostic that describes an effect on the run-time behavior
20183 /// of the program being compiled.
20185 /// This routine emits the given diagnostic when the code currently being
20186 /// type-checked is "potentially evaluated", meaning that there is a
20187 /// possibility that the code will actually be executable. Code in sizeof()
20188 /// expressions, code used only during overload resolution, etc., are not
20189 /// potentially evaluated. This routine will suppress such diagnostics or,
20190 /// in the absolutely nutty case of potentially potentially evaluated
20191 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
20194 /// This routine should be used for all diagnostics that describe the run-time
20195 /// behavior of a program, such as passing a non-POD value through an ellipsis.
20196 /// Failure to do so will likely result in spurious diagnostics or failures
20197 /// during overload resolution or within sizeof/alignof/typeof/typeid.
20198 bool Sema::DiagRuntimeBehavior(SourceLocation Loc
, ArrayRef
<const Stmt
*> Stmts
,
20199 const PartialDiagnostic
&PD
) {
20201 if (ExprEvalContexts
.back().isDiscardedStatementContext())
20204 switch (ExprEvalContexts
.back().Context
) {
20205 case ExpressionEvaluationContext::Unevaluated
:
20206 case ExpressionEvaluationContext::UnevaluatedList
:
20207 case ExpressionEvaluationContext::UnevaluatedAbstract
:
20208 case ExpressionEvaluationContext::DiscardedStatement
:
20209 // The argument will never be evaluated, so don't complain.
20212 case ExpressionEvaluationContext::ConstantEvaluated
:
20213 case ExpressionEvaluationContext::ImmediateFunctionContext
:
20214 // Relevant diagnostics should be produced by constant evaluation.
20217 case ExpressionEvaluationContext::PotentiallyEvaluated
:
20218 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
20219 return DiagIfReachable(Loc
, Stmts
, PD
);
20225 bool Sema::DiagRuntimeBehavior(SourceLocation Loc
, const Stmt
*Statement
,
20226 const PartialDiagnostic
&PD
) {
20227 return DiagRuntimeBehavior(
20228 Loc
, Statement
? llvm::ArrayRef(Statement
) : std::nullopt
, PD
);
20231 bool Sema::CheckCallReturnType(QualType ReturnType
, SourceLocation Loc
,
20232 CallExpr
*CE
, FunctionDecl
*FD
) {
20233 if (ReturnType
->isVoidType() || !ReturnType
->isIncompleteType())
20236 // If we're inside a decltype's expression, don't check for a valid return
20237 // type or construct temporaries until we know whether this is the last call.
20238 if (ExprEvalContexts
.back().ExprContext
==
20239 ExpressionEvaluationContextRecord::EK_Decltype
) {
20240 ExprEvalContexts
.back().DelayedDecltypeCalls
.push_back(CE
);
20244 class CallReturnIncompleteDiagnoser
: public TypeDiagnoser
{
20249 CallReturnIncompleteDiagnoser(FunctionDecl
*FD
, CallExpr
*CE
)
20250 : FD(FD
), CE(CE
) { }
20252 void diagnose(Sema
&S
, SourceLocation Loc
, QualType T
) override
{
20254 S
.Diag(Loc
, diag::err_call_incomplete_return
)
20255 << T
<< CE
->getSourceRange();
20259 S
.Diag(Loc
, diag::err_call_function_incomplete_return
)
20260 << CE
->getSourceRange() << FD
<< T
;
20261 S
.Diag(FD
->getLocation(), diag::note_entity_declared_at
)
20262 << FD
->getDeclName();
20264 } Diagnoser(FD
, CE
);
20266 if (RequireCompleteType(Loc
, ReturnType
, Diagnoser
))
20272 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
20273 // will prevent this condition from triggering, which is what we want.
20274 void Sema::DiagnoseAssignmentAsCondition(Expr
*E
) {
20275 SourceLocation Loc
;
20277 unsigned diagnostic
= diag::warn_condition_is_assignment
;
20278 bool IsOrAssign
= false;
20280 if (BinaryOperator
*Op
= dyn_cast
<BinaryOperator
>(E
)) {
20281 if (Op
->getOpcode() != BO_Assign
&& Op
->getOpcode() != BO_OrAssign
)
20284 IsOrAssign
= Op
->getOpcode() == BO_OrAssign
;
20286 // Greylist some idioms by putting them into a warning subcategory.
20287 if (ObjCMessageExpr
*ME
20288 = dyn_cast
<ObjCMessageExpr
>(Op
->getRHS()->IgnoreParenCasts())) {
20289 Selector Sel
= ME
->getSelector();
20291 // self = [<foo> init...]
20292 if (isSelfExpr(Op
->getLHS()) && ME
->getMethodFamily() == OMF_init
)
20293 diagnostic
= diag::warn_condition_is_idiomatic_assignment
;
20295 // <foo> = [<bar> nextObject]
20296 else if (Sel
.isUnarySelector() && Sel
.getNameForSlot(0) == "nextObject")
20297 diagnostic
= diag::warn_condition_is_idiomatic_assignment
;
20300 Loc
= Op
->getOperatorLoc();
20301 } else if (CXXOperatorCallExpr
*Op
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
20302 if (Op
->getOperator() != OO_Equal
&& Op
->getOperator() != OO_PipeEqual
)
20305 IsOrAssign
= Op
->getOperator() == OO_PipeEqual
;
20306 Loc
= Op
->getOperatorLoc();
20307 } else if (PseudoObjectExpr
*POE
= dyn_cast
<PseudoObjectExpr
>(E
))
20308 return DiagnoseAssignmentAsCondition(POE
->getSyntacticForm());
20310 // Not an assignment.
20314 Diag(Loc
, diagnostic
) << E
->getSourceRange();
20316 SourceLocation Open
= E
->getBeginLoc();
20317 SourceLocation Close
= getLocForEndOfToken(E
->getSourceRange().getEnd());
20318 Diag(Loc
, diag::note_condition_assign_silence
)
20319 << FixItHint::CreateInsertion(Open
, "(")
20320 << FixItHint::CreateInsertion(Close
, ")");
20323 Diag(Loc
, diag::note_condition_or_assign_to_comparison
)
20324 << FixItHint::CreateReplacement(Loc
, "!=");
20326 Diag(Loc
, diag::note_condition_assign_to_comparison
)
20327 << FixItHint::CreateReplacement(Loc
, "==");
20330 /// Redundant parentheses over an equality comparison can indicate
20331 /// that the user intended an assignment used as condition.
20332 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr
*ParenE
) {
20333 // Don't warn if the parens came from a macro.
20334 SourceLocation parenLoc
= ParenE
->getBeginLoc();
20335 if (parenLoc
.isInvalid() || parenLoc
.isMacroID())
20337 // Don't warn for dependent expressions.
20338 if (ParenE
->isTypeDependent())
20341 Expr
*E
= ParenE
->IgnoreParens();
20343 if (BinaryOperator
*opE
= dyn_cast
<BinaryOperator
>(E
))
20344 if (opE
->getOpcode() == BO_EQ
&&
20345 opE
->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context
)
20346 == Expr::MLV_Valid
) {
20347 SourceLocation Loc
= opE
->getOperatorLoc();
20349 Diag(Loc
, diag::warn_equality_with_extra_parens
) << E
->getSourceRange();
20350 SourceRange ParenERange
= ParenE
->getSourceRange();
20351 Diag(Loc
, diag::note_equality_comparison_silence
)
20352 << FixItHint::CreateRemoval(ParenERange
.getBegin())
20353 << FixItHint::CreateRemoval(ParenERange
.getEnd());
20354 Diag(Loc
, diag::note_equality_comparison_to_assign
)
20355 << FixItHint::CreateReplacement(Loc
, "=");
20359 ExprResult
Sema::CheckBooleanCondition(SourceLocation Loc
, Expr
*E
,
20360 bool IsConstexpr
) {
20361 DiagnoseAssignmentAsCondition(E
);
20362 if (ParenExpr
*parenE
= dyn_cast
<ParenExpr
>(E
))
20363 DiagnoseEqualityWithExtraParens(parenE
);
20365 ExprResult result
= CheckPlaceholderExpr(E
);
20366 if (result
.isInvalid()) return ExprError();
20369 if (!E
->isTypeDependent()) {
20370 if (getLangOpts().CPlusPlus
)
20371 return CheckCXXBooleanCondition(E
, IsConstexpr
); // C++ 6.4p4
20373 ExprResult ERes
= DefaultFunctionArrayLvalueConversion(E
);
20374 if (ERes
.isInvalid())
20375 return ExprError();
20378 QualType T
= E
->getType();
20379 if (!T
->isScalarType()) { // C99 6.8.4.1p1
20380 Diag(Loc
, diag::err_typecheck_statement_requires_scalar
)
20381 << T
<< E
->getSourceRange();
20382 return ExprError();
20384 CheckBoolLikeConversion(E
, Loc
);
20390 Sema::ConditionResult
Sema::ActOnCondition(Scope
*S
, SourceLocation Loc
,
20391 Expr
*SubExpr
, ConditionKind CK
,
20393 // MissingOK indicates whether having no condition expression is valid
20394 // (for loop) or invalid (e.g. while loop).
20396 return MissingOK
? ConditionResult() : ConditionError();
20400 case ConditionKind::Boolean
:
20401 Cond
= CheckBooleanCondition(Loc
, SubExpr
);
20404 case ConditionKind::ConstexprIf
:
20405 Cond
= CheckBooleanCondition(Loc
, SubExpr
, true);
20408 case ConditionKind::Switch
:
20409 Cond
= CheckSwitchCondition(Loc
, SubExpr
);
20412 if (Cond
.isInvalid()) {
20413 Cond
= CreateRecoveryExpr(SubExpr
->getBeginLoc(), SubExpr
->getEndLoc(),
20414 {SubExpr
}, PreferredConditionType(CK
));
20416 return ConditionError();
20418 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
20419 FullExprArg FullExpr
= MakeFullExpr(Cond
.get(), Loc
);
20420 if (!FullExpr
.get())
20421 return ConditionError();
20423 return ConditionResult(*this, nullptr, FullExpr
,
20424 CK
== ConditionKind::ConstexprIf
);
20428 /// A visitor for rebuilding a call to an __unknown_any expression
20429 /// to have an appropriate type.
20430 struct RebuildUnknownAnyFunction
20431 : StmtVisitor
<RebuildUnknownAnyFunction
, ExprResult
> {
20435 RebuildUnknownAnyFunction(Sema
&S
) : S(S
) {}
20437 ExprResult
VisitStmt(Stmt
*S
) {
20438 llvm_unreachable("unexpected statement!");
20441 ExprResult
VisitExpr(Expr
*E
) {
20442 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_call
)
20443 << E
->getSourceRange();
20444 return ExprError();
20447 /// Rebuild an expression which simply semantically wraps another
20448 /// expression which it shares the type and value kind of.
20449 template <class T
> ExprResult
rebuildSugarExpr(T
*E
) {
20450 ExprResult SubResult
= Visit(E
->getSubExpr());
20451 if (SubResult
.isInvalid()) return ExprError();
20453 Expr
*SubExpr
= SubResult
.get();
20454 E
->setSubExpr(SubExpr
);
20455 E
->setType(SubExpr
->getType());
20456 E
->setValueKind(SubExpr
->getValueKind());
20457 assert(E
->getObjectKind() == OK_Ordinary
);
20461 ExprResult
VisitParenExpr(ParenExpr
*E
) {
20462 return rebuildSugarExpr(E
);
20465 ExprResult
VisitUnaryExtension(UnaryOperator
*E
) {
20466 return rebuildSugarExpr(E
);
20469 ExprResult
VisitUnaryAddrOf(UnaryOperator
*E
) {
20470 ExprResult SubResult
= Visit(E
->getSubExpr());
20471 if (SubResult
.isInvalid()) return ExprError();
20473 Expr
*SubExpr
= SubResult
.get();
20474 E
->setSubExpr(SubExpr
);
20475 E
->setType(S
.Context
.getPointerType(SubExpr
->getType()));
20476 assert(E
->isPRValue());
20477 assert(E
->getObjectKind() == OK_Ordinary
);
20481 ExprResult
resolveDecl(Expr
*E
, ValueDecl
*VD
) {
20482 if (!isa
<FunctionDecl
>(VD
)) return VisitExpr(E
);
20484 E
->setType(VD
->getType());
20486 assert(E
->isPRValue());
20487 if (S
.getLangOpts().CPlusPlus
&&
20488 !(isa
<CXXMethodDecl
>(VD
) &&
20489 cast
<CXXMethodDecl
>(VD
)->isInstance()))
20490 E
->setValueKind(VK_LValue
);
20495 ExprResult
VisitMemberExpr(MemberExpr
*E
) {
20496 return resolveDecl(E
, E
->getMemberDecl());
20499 ExprResult
VisitDeclRefExpr(DeclRefExpr
*E
) {
20500 return resolveDecl(E
, E
->getDecl());
20505 /// Given a function expression of unknown-any type, try to rebuild it
20506 /// to have a function type.
20507 static ExprResult
rebuildUnknownAnyFunction(Sema
&S
, Expr
*FunctionExpr
) {
20508 ExprResult Result
= RebuildUnknownAnyFunction(S
).Visit(FunctionExpr
);
20509 if (Result
.isInvalid()) return ExprError();
20510 return S
.DefaultFunctionArrayConversion(Result
.get());
20514 /// A visitor for rebuilding an expression of type __unknown_anytype
20515 /// into one which resolves the type directly on the referring
20516 /// expression. Strict preservation of the original source
20517 /// structure is not a goal.
20518 struct RebuildUnknownAnyExpr
20519 : StmtVisitor
<RebuildUnknownAnyExpr
, ExprResult
> {
20523 /// The current destination type.
20526 RebuildUnknownAnyExpr(Sema
&S
, QualType CastType
)
20527 : S(S
), DestType(CastType
) {}
20529 ExprResult
VisitStmt(Stmt
*S
) {
20530 llvm_unreachable("unexpected statement!");
20533 ExprResult
VisitExpr(Expr
*E
) {
20534 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_expr
)
20535 << E
->getSourceRange();
20536 return ExprError();
20539 ExprResult
VisitCallExpr(CallExpr
*E
);
20540 ExprResult
VisitObjCMessageExpr(ObjCMessageExpr
*E
);
20542 /// Rebuild an expression which simply semantically wraps another
20543 /// expression which it shares the type and value kind of.
20544 template <class T
> ExprResult
rebuildSugarExpr(T
*E
) {
20545 ExprResult SubResult
= Visit(E
->getSubExpr());
20546 if (SubResult
.isInvalid()) return ExprError();
20547 Expr
*SubExpr
= SubResult
.get();
20548 E
->setSubExpr(SubExpr
);
20549 E
->setType(SubExpr
->getType());
20550 E
->setValueKind(SubExpr
->getValueKind());
20551 assert(E
->getObjectKind() == OK_Ordinary
);
20555 ExprResult
VisitParenExpr(ParenExpr
*E
) {
20556 return rebuildSugarExpr(E
);
20559 ExprResult
VisitUnaryExtension(UnaryOperator
*E
) {
20560 return rebuildSugarExpr(E
);
20563 ExprResult
VisitUnaryAddrOf(UnaryOperator
*E
) {
20564 const PointerType
*Ptr
= DestType
->getAs
<PointerType
>();
20566 S
.Diag(E
->getOperatorLoc(), diag::err_unknown_any_addrof
)
20567 << E
->getSourceRange();
20568 return ExprError();
20571 if (isa
<CallExpr
>(E
->getSubExpr())) {
20572 S
.Diag(E
->getOperatorLoc(), diag::err_unknown_any_addrof_call
)
20573 << E
->getSourceRange();
20574 return ExprError();
20577 assert(E
->isPRValue());
20578 assert(E
->getObjectKind() == OK_Ordinary
);
20579 E
->setType(DestType
);
20581 // Build the sub-expression as if it were an object of the pointee type.
20582 DestType
= Ptr
->getPointeeType();
20583 ExprResult SubResult
= Visit(E
->getSubExpr());
20584 if (SubResult
.isInvalid()) return ExprError();
20585 E
->setSubExpr(SubResult
.get());
20589 ExprResult
VisitImplicitCastExpr(ImplicitCastExpr
*E
);
20591 ExprResult
resolveDecl(Expr
*E
, ValueDecl
*VD
);
20593 ExprResult
VisitMemberExpr(MemberExpr
*E
) {
20594 return resolveDecl(E
, E
->getMemberDecl());
20597 ExprResult
VisitDeclRefExpr(DeclRefExpr
*E
) {
20598 return resolveDecl(E
, E
->getDecl());
20603 /// Rebuilds a call expression which yielded __unknown_anytype.
20604 ExprResult
RebuildUnknownAnyExpr::VisitCallExpr(CallExpr
*E
) {
20605 Expr
*CalleeExpr
= E
->getCallee();
20609 FK_FunctionPointer
,
20614 QualType CalleeType
= CalleeExpr
->getType();
20615 if (CalleeType
== S
.Context
.BoundMemberTy
) {
20616 assert(isa
<CXXMemberCallExpr
>(E
) || isa
<CXXOperatorCallExpr
>(E
));
20617 Kind
= FK_MemberFunction
;
20618 CalleeType
= Expr::findBoundMemberType(CalleeExpr
);
20619 } else if (const PointerType
*Ptr
= CalleeType
->getAs
<PointerType
>()) {
20620 CalleeType
= Ptr
->getPointeeType();
20621 Kind
= FK_FunctionPointer
;
20623 CalleeType
= CalleeType
->castAs
<BlockPointerType
>()->getPointeeType();
20624 Kind
= FK_BlockPointer
;
20626 const FunctionType
*FnType
= CalleeType
->castAs
<FunctionType
>();
20628 // Verify that this is a legal result type of a function.
20629 if (DestType
->isArrayType() || DestType
->isFunctionType()) {
20630 unsigned diagID
= diag::err_func_returning_array_function
;
20631 if (Kind
== FK_BlockPointer
)
20632 diagID
= diag::err_block_returning_array_function
;
20634 S
.Diag(E
->getExprLoc(), diagID
)
20635 << DestType
->isFunctionType() << DestType
;
20636 return ExprError();
20639 // Otherwise, go ahead and set DestType as the call's result.
20640 E
->setType(DestType
.getNonLValueExprType(S
.Context
));
20641 E
->setValueKind(Expr::getValueKindForType(DestType
));
20642 assert(E
->getObjectKind() == OK_Ordinary
);
20644 // Rebuild the function type, replacing the result type with DestType.
20645 const FunctionProtoType
*Proto
= dyn_cast
<FunctionProtoType
>(FnType
);
20647 // __unknown_anytype(...) is a special case used by the debugger when
20648 // it has no idea what a function's signature is.
20650 // We want to build this call essentially under the K&R
20651 // unprototyped rules, but making a FunctionNoProtoType in C++
20652 // would foul up all sorts of assumptions. However, we cannot
20653 // simply pass all arguments as variadic arguments, nor can we
20654 // portably just call the function under a non-variadic type; see
20655 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
20656 // However, it turns out that in practice it is generally safe to
20657 // call a function declared as "A foo(B,C,D);" under the prototype
20658 // "A foo(B,C,D,...);". The only known exception is with the
20659 // Windows ABI, where any variadic function is implicitly cdecl
20660 // regardless of its normal CC. Therefore we change the parameter
20661 // types to match the types of the arguments.
20663 // This is a hack, but it is far superior to moving the
20664 // corresponding target-specific code from IR-gen to Sema/AST.
20666 ArrayRef
<QualType
> ParamTypes
= Proto
->getParamTypes();
20667 SmallVector
<QualType
, 8> ArgTypes
;
20668 if (ParamTypes
.empty() && Proto
->isVariadic()) { // the special case
20669 ArgTypes
.reserve(E
->getNumArgs());
20670 for (unsigned i
= 0, e
= E
->getNumArgs(); i
!= e
; ++i
) {
20671 ArgTypes
.push_back(S
.Context
.getReferenceQualifiedType(E
->getArg(i
)));
20673 ParamTypes
= ArgTypes
;
20675 DestType
= S
.Context
.getFunctionType(DestType
, ParamTypes
,
20676 Proto
->getExtProtoInfo());
20678 DestType
= S
.Context
.getFunctionNoProtoType(DestType
,
20679 FnType
->getExtInfo());
20682 // Rebuild the appropriate pointer-to-function type.
20684 case FK_MemberFunction
:
20688 case FK_FunctionPointer
:
20689 DestType
= S
.Context
.getPointerType(DestType
);
20692 case FK_BlockPointer
:
20693 DestType
= S
.Context
.getBlockPointerType(DestType
);
20697 // Finally, we can recurse.
20698 ExprResult CalleeResult
= Visit(CalleeExpr
);
20699 if (!CalleeResult
.isUsable()) return ExprError();
20700 E
->setCallee(CalleeResult
.get());
20702 // Bind a temporary if necessary.
20703 return S
.MaybeBindToTemporary(E
);
20706 ExprResult
RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr
*E
) {
20707 // Verify that this is a legal result type of a call.
20708 if (DestType
->isArrayType() || DestType
->isFunctionType()) {
20709 S
.Diag(E
->getExprLoc(), diag::err_func_returning_array_function
)
20710 << DestType
->isFunctionType() << DestType
;
20711 return ExprError();
20714 // Rewrite the method result type if available.
20715 if (ObjCMethodDecl
*Method
= E
->getMethodDecl()) {
20716 assert(Method
->getReturnType() == S
.Context
.UnknownAnyTy
);
20717 Method
->setReturnType(DestType
);
20720 // Change the type of the message.
20721 E
->setType(DestType
.getNonReferenceType());
20722 E
->setValueKind(Expr::getValueKindForType(DestType
));
20724 return S
.MaybeBindToTemporary(E
);
20727 ExprResult
RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr
*E
) {
20728 // The only case we should ever see here is a function-to-pointer decay.
20729 if (E
->getCastKind() == CK_FunctionToPointerDecay
) {
20730 assert(E
->isPRValue());
20731 assert(E
->getObjectKind() == OK_Ordinary
);
20733 E
->setType(DestType
);
20735 // Rebuild the sub-expression as the pointee (function) type.
20736 DestType
= DestType
->castAs
<PointerType
>()->getPointeeType();
20738 ExprResult Result
= Visit(E
->getSubExpr());
20739 if (!Result
.isUsable()) return ExprError();
20741 E
->setSubExpr(Result
.get());
20743 } else if (E
->getCastKind() == CK_LValueToRValue
) {
20744 assert(E
->isPRValue());
20745 assert(E
->getObjectKind() == OK_Ordinary
);
20747 assert(isa
<BlockPointerType
>(E
->getType()));
20749 E
->setType(DestType
);
20751 // The sub-expression has to be a lvalue reference, so rebuild it as such.
20752 DestType
= S
.Context
.getLValueReferenceType(DestType
);
20754 ExprResult Result
= Visit(E
->getSubExpr());
20755 if (!Result
.isUsable()) return ExprError();
20757 E
->setSubExpr(Result
.get());
20760 llvm_unreachable("Unhandled cast type!");
20764 ExprResult
RebuildUnknownAnyExpr::resolveDecl(Expr
*E
, ValueDecl
*VD
) {
20765 ExprValueKind ValueKind
= VK_LValue
;
20766 QualType Type
= DestType
;
20768 // We know how to make this work for certain kinds of decls:
20771 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(VD
)) {
20772 if (const PointerType
*Ptr
= Type
->getAs
<PointerType
>()) {
20773 DestType
= Ptr
->getPointeeType();
20774 ExprResult Result
= resolveDecl(E
, VD
);
20775 if (Result
.isInvalid()) return ExprError();
20776 return S
.ImpCastExprToType(Result
.get(), Type
, CK_FunctionToPointerDecay
,
20780 if (!Type
->isFunctionType()) {
20781 S
.Diag(E
->getExprLoc(), diag::err_unknown_any_function
)
20782 << VD
<< E
->getSourceRange();
20783 return ExprError();
20785 if (const FunctionProtoType
*FT
= Type
->getAs
<FunctionProtoType
>()) {
20786 // We must match the FunctionDecl's type to the hack introduced in
20787 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
20788 // type. See the lengthy commentary in that routine.
20789 QualType FDT
= FD
->getType();
20790 const FunctionType
*FnType
= FDT
->castAs
<FunctionType
>();
20791 const FunctionProtoType
*Proto
= dyn_cast_or_null
<FunctionProtoType
>(FnType
);
20792 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
);
20793 if (DRE
&& Proto
&& Proto
->getParamTypes().empty() && Proto
->isVariadic()) {
20794 SourceLocation Loc
= FD
->getLocation();
20795 FunctionDecl
*NewFD
= FunctionDecl::Create(
20796 S
.Context
, FD
->getDeclContext(), Loc
, Loc
,
20797 FD
->getNameInfo().getName(), DestType
, FD
->getTypeSourceInfo(),
20798 SC_None
, S
.getCurFPFeatures().isFPConstrained(),
20799 false /*isInlineSpecified*/, FD
->hasPrototype(),
20800 /*ConstexprKind*/ ConstexprSpecKind::Unspecified
);
20802 if (FD
->getQualifier())
20803 NewFD
->setQualifierInfo(FD
->getQualifierLoc());
20805 SmallVector
<ParmVarDecl
*, 16> Params
;
20806 for (const auto &AI
: FT
->param_types()) {
20807 ParmVarDecl
*Param
=
20808 S
.BuildParmVarDeclForTypedef(FD
, Loc
, AI
);
20809 Param
->setScopeInfo(0, Params
.size());
20810 Params
.push_back(Param
);
20812 NewFD
->setParams(Params
);
20813 DRE
->setDecl(NewFD
);
20814 VD
= DRE
->getDecl();
20818 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
))
20819 if (MD
->isInstance()) {
20820 ValueKind
= VK_PRValue
;
20821 Type
= S
.Context
.BoundMemberTy
;
20824 // Function references aren't l-values in C.
20825 if (!S
.getLangOpts().CPlusPlus
)
20826 ValueKind
= VK_PRValue
;
20829 } else if (isa
<VarDecl
>(VD
)) {
20830 if (const ReferenceType
*RefTy
= Type
->getAs
<ReferenceType
>()) {
20831 Type
= RefTy
->getPointeeType();
20832 } else if (Type
->isFunctionType()) {
20833 S
.Diag(E
->getExprLoc(), diag::err_unknown_any_var_function_type
)
20834 << VD
<< E
->getSourceRange();
20835 return ExprError();
20840 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_decl
)
20841 << VD
<< E
->getSourceRange();
20842 return ExprError();
20845 // Modifying the declaration like this is friendly to IR-gen but
20846 // also really dangerous.
20847 VD
->setType(DestType
);
20849 E
->setValueKind(ValueKind
);
20853 /// Check a cast of an unknown-any type. We intentionally only
20854 /// trigger this for C-style casts.
20855 ExprResult
Sema::checkUnknownAnyCast(SourceRange TypeRange
, QualType CastType
,
20856 Expr
*CastExpr
, CastKind
&CastKind
,
20857 ExprValueKind
&VK
, CXXCastPath
&Path
) {
20858 // The type we're casting to must be either void or complete.
20859 if (!CastType
->isVoidType() &&
20860 RequireCompleteType(TypeRange
.getBegin(), CastType
,
20861 diag::err_typecheck_cast_to_incomplete
))
20862 return ExprError();
20864 // Rewrite the casted expression from scratch.
20865 ExprResult result
= RebuildUnknownAnyExpr(*this, CastType
).Visit(CastExpr
);
20866 if (!result
.isUsable()) return ExprError();
20868 CastExpr
= result
.get();
20869 VK
= CastExpr
->getValueKind();
20870 CastKind
= CK_NoOp
;
20875 ExprResult
Sema::forceUnknownAnyToType(Expr
*E
, QualType ToType
) {
20876 return RebuildUnknownAnyExpr(*this, ToType
).Visit(E
);
20879 ExprResult
Sema::checkUnknownAnyArg(SourceLocation callLoc
,
20880 Expr
*arg
, QualType
¶mType
) {
20881 // If the syntactic form of the argument is not an explicit cast of
20882 // any sort, just do default argument promotion.
20883 ExplicitCastExpr
*castArg
= dyn_cast
<ExplicitCastExpr
>(arg
->IgnoreParens());
20885 ExprResult result
= DefaultArgumentPromotion(arg
);
20886 if (result
.isInvalid()) return ExprError();
20887 paramType
= result
.get()->getType();
20891 // Otherwise, use the type that was written in the explicit cast.
20892 assert(!arg
->hasPlaceholderType());
20893 paramType
= castArg
->getTypeAsWritten();
20895 // Copy-initialize a parameter of that type.
20896 InitializedEntity entity
=
20897 InitializedEntity::InitializeParameter(Context
, paramType
,
20898 /*consumed*/ false);
20899 return PerformCopyInitialization(entity
, callLoc
, arg
);
20902 static ExprResult
diagnoseUnknownAnyExpr(Sema
&S
, Expr
*E
) {
20904 unsigned diagID
= diag::err_uncasted_use_of_unknown_any
;
20906 E
= E
->IgnoreParenImpCasts();
20907 if (CallExpr
*call
= dyn_cast
<CallExpr
>(E
)) {
20908 E
= call
->getCallee();
20909 diagID
= diag::err_uncasted_call_of_unknown_any
;
20915 SourceLocation loc
;
20917 if (DeclRefExpr
*ref
= dyn_cast
<DeclRefExpr
>(E
)) {
20918 loc
= ref
->getLocation();
20919 d
= ref
->getDecl();
20920 } else if (MemberExpr
*mem
= dyn_cast
<MemberExpr
>(E
)) {
20921 loc
= mem
->getMemberLoc();
20922 d
= mem
->getMemberDecl();
20923 } else if (ObjCMessageExpr
*msg
= dyn_cast
<ObjCMessageExpr
>(E
)) {
20924 diagID
= diag::err_uncasted_call_of_unknown_any
;
20925 loc
= msg
->getSelectorStartLoc();
20926 d
= msg
->getMethodDecl();
20928 S
.Diag(loc
, diag::err_uncasted_send_to_unknown_any_method
)
20929 << static_cast<unsigned>(msg
->isClassMessage()) << msg
->getSelector()
20930 << orig
->getSourceRange();
20931 return ExprError();
20934 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_expr
)
20935 << E
->getSourceRange();
20936 return ExprError();
20939 S
.Diag(loc
, diagID
) << d
<< orig
->getSourceRange();
20941 // Never recoverable.
20942 return ExprError();
20945 /// Check for operands with placeholder types and complain if found.
20946 /// Returns ExprError() if there was an error and no recovery was possible.
20947 ExprResult
Sema::CheckPlaceholderExpr(Expr
*E
) {
20948 if (!Context
.isDependenceAllowed()) {
20949 // C cannot handle TypoExpr nodes on either side of a binop because it
20950 // doesn't handle dependent types properly, so make sure any TypoExprs have
20951 // been dealt with before checking the operands.
20952 ExprResult Result
= CorrectDelayedTyposInExpr(E
);
20953 if (!Result
.isUsable()) return ExprError();
20957 const BuiltinType
*placeholderType
= E
->getType()->getAsPlaceholderType();
20958 if (!placeholderType
) return E
;
20960 switch (placeholderType
->getKind()) {
20962 // Overloaded expressions.
20963 case BuiltinType::Overload
: {
20964 // Try to resolve a single function template specialization.
20965 // This is obligatory.
20966 ExprResult Result
= E
;
20967 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result
, false))
20970 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
20971 // leaves Result unchanged on failure.
20973 if (resolveAndFixAddressOfSingleOverloadCandidate(Result
))
20976 // If that failed, try to recover with a call.
20977 tryToRecoverWithCall(Result
, PDiag(diag::err_ovl_unresolvable
),
20978 /*complain*/ true);
20982 // Bound member functions.
20983 case BuiltinType::BoundMember
: {
20984 ExprResult result
= E
;
20985 const Expr
*BME
= E
->IgnoreParens();
20986 PartialDiagnostic PD
= PDiag(diag::err_bound_member_function
);
20987 // Try to give a nicer diagnostic if it is a bound member that we recognize.
20988 if (isa
<CXXPseudoDestructorExpr
>(BME
)) {
20989 PD
= PDiag(diag::err_dtor_expr_without_call
) << /*pseudo-destructor*/ 1;
20990 } else if (const auto *ME
= dyn_cast
<MemberExpr
>(BME
)) {
20991 if (ME
->getMemberNameInfo().getName().getNameKind() ==
20992 DeclarationName::CXXDestructorName
)
20993 PD
= PDiag(diag::err_dtor_expr_without_call
) << /*destructor*/ 0;
20995 tryToRecoverWithCall(result
, PD
,
20996 /*complain*/ true);
21000 // ARC unbridged casts.
21001 case BuiltinType::ARCUnbridgedCast
: {
21002 Expr
*realCast
= stripARCUnbridgedCast(E
);
21003 diagnoseARCUnbridgedCast(realCast
);
21007 // Expressions of unknown type.
21008 case BuiltinType::UnknownAny
:
21009 return diagnoseUnknownAnyExpr(*this, E
);
21012 case BuiltinType::PseudoObject
:
21013 return checkPseudoObjectRValue(E
);
21015 case BuiltinType::BuiltinFn
: {
21016 // Accept __noop without parens by implicitly converting it to a call expr.
21017 auto *DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts());
21019 auto *FD
= cast
<FunctionDecl
>(DRE
->getDecl());
21020 unsigned BuiltinID
= FD
->getBuiltinID();
21021 if (BuiltinID
== Builtin::BI__noop
) {
21022 E
= ImpCastExprToType(E
, Context
.getPointerType(FD
->getType()),
21023 CK_BuiltinFnToFnPtr
)
21025 return CallExpr::Create(Context
, E
, /*Args=*/{}, Context
.IntTy
,
21026 VK_PRValue
, SourceLocation(),
21027 FPOptionsOverride());
21030 if (Context
.BuiltinInfo
.isInStdNamespace(BuiltinID
)) {
21031 // Any use of these other than a direct call is ill-formed as of C++20,
21032 // because they are not addressable functions. In earlier language
21033 // modes, warn and force an instantiation of the real body.
21034 Diag(E
->getBeginLoc(),
21035 getLangOpts().CPlusPlus20
21036 ? diag::err_use_of_unaddressable_function
21037 : diag::warn_cxx20_compat_use_of_unaddressable_function
);
21038 if (FD
->isImplicitlyInstantiable()) {
21039 // Require a definition here because a normal attempt at
21040 // instantiation for a builtin will be ignored, and we won't try
21041 // again later. We assume that the definition of the template
21042 // precedes this use.
21043 InstantiateFunctionDefinition(E
->getBeginLoc(), FD
,
21044 /*Recursive=*/false,
21045 /*DefinitionRequired=*/true,
21046 /*AtEndOfTU=*/false);
21048 // Produce a properly-typed reference to the function.
21050 SS
.Adopt(DRE
->getQualifierLoc());
21051 TemplateArgumentListInfo TemplateArgs
;
21052 DRE
->copyTemplateArgumentsInto(TemplateArgs
);
21053 return BuildDeclRefExpr(
21054 FD
, FD
->getType(), VK_LValue
, DRE
->getNameInfo(),
21055 DRE
->hasQualifier() ? &SS
: nullptr, DRE
->getFoundDecl(),
21056 DRE
->getTemplateKeywordLoc(),
21057 DRE
->hasExplicitTemplateArgs() ? &TemplateArgs
: nullptr);
21061 Diag(E
->getBeginLoc(), diag::err_builtin_fn_use
);
21062 return ExprError();
21065 case BuiltinType::IncompleteMatrixIdx
:
21066 Diag(cast
<MatrixSubscriptExpr
>(E
->IgnoreParens())
21069 diag::err_matrix_incomplete_index
);
21070 return ExprError();
21072 // Expressions of unknown type.
21073 case BuiltinType::OMPArraySection
:
21074 Diag(E
->getBeginLoc(), diag::err_omp_array_section_use
);
21075 return ExprError();
21077 // Expressions of unknown type.
21078 case BuiltinType::OMPArrayShaping
:
21079 return ExprError(Diag(E
->getBeginLoc(), diag::err_omp_array_shaping_use
));
21081 case BuiltinType::OMPIterator
:
21082 return ExprError(Diag(E
->getBeginLoc(), diag::err_omp_iterator_use
));
21084 // Everything else should be impossible.
21085 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21086 case BuiltinType::Id:
21087 #include "clang/Basic/OpenCLImageTypes.def"
21088 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21089 case BuiltinType::Id:
21090 #include "clang/Basic/OpenCLExtensionTypes.def"
21091 #define SVE_TYPE(Name, Id, SingletonId) \
21092 case BuiltinType::Id:
21093 #include "clang/Basic/AArch64SVEACLETypes.def"
21094 #define PPC_VECTOR_TYPE(Name, Id, Size) \
21095 case BuiltinType::Id:
21096 #include "clang/Basic/PPCTypes.def"
21097 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21098 #include "clang/Basic/RISCVVTypes.def"
21099 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21100 #define PLACEHOLDER_TYPE(Id, SingletonId)
21101 #include "clang/AST/BuiltinTypes.def"
21105 llvm_unreachable("invalid placeholder type!");
21108 bool Sema::CheckCaseExpression(Expr
*E
) {
21109 if (E
->isTypeDependent())
21111 if (E
->isValueDependent() || E
->isIntegerConstantExpr(Context
))
21112 return E
->getType()->isIntegralOrEnumerationType();
21116 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21118 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc
, tok::TokenKind Kind
) {
21119 assert((Kind
== tok::kw___objc_yes
|| Kind
== tok::kw___objc_no
) &&
21120 "Unknown Objective-C Boolean value!");
21121 QualType BoolT
= Context
.ObjCBuiltinBoolTy
;
21122 if (!Context
.getBOOLDecl()) {
21123 LookupResult
Result(*this, &Context
.Idents
.get("BOOL"), OpLoc
,
21124 Sema::LookupOrdinaryName
);
21125 if (LookupName(Result
, getCurScope()) && Result
.isSingleResult()) {
21126 NamedDecl
*ND
= Result
.getFoundDecl();
21127 if (TypedefDecl
*TD
= dyn_cast
<TypedefDecl
>(ND
))
21128 Context
.setBOOLDecl(TD
);
21131 if (Context
.getBOOLDecl())
21132 BoolT
= Context
.getBOOLType();
21133 return new (Context
)
21134 ObjCBoolLiteralExpr(Kind
== tok::kw___objc_yes
, BoolT
, OpLoc
);
21137 ExprResult
Sema::ActOnObjCAvailabilityCheckExpr(
21138 llvm::ArrayRef
<AvailabilitySpec
> AvailSpecs
, SourceLocation AtLoc
,
21139 SourceLocation RParen
) {
21140 auto FindSpecVersion
=
21141 [&](StringRef Platform
) -> std::optional
<VersionTuple
> {
21142 auto Spec
= llvm::find_if(AvailSpecs
, [&](const AvailabilitySpec
&Spec
) {
21143 return Spec
.getPlatform() == Platform
;
21145 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21146 // for "maccatalyst" if "maccatalyst" is not specified.
21147 if (Spec
== AvailSpecs
.end() && Platform
== "maccatalyst") {
21148 Spec
= llvm::find_if(AvailSpecs
, [&](const AvailabilitySpec
&Spec
) {
21149 return Spec
.getPlatform() == "ios";
21152 if (Spec
== AvailSpecs
.end())
21153 return std::nullopt
;
21154 return Spec
->getVersion();
21157 VersionTuple Version
;
21158 if (auto MaybeVersion
=
21159 FindSpecVersion(Context
.getTargetInfo().getPlatformName()))
21160 Version
= *MaybeVersion
;
21162 // The use of `@available` in the enclosing context should be analyzed to
21163 // warn when it's used inappropriately (i.e. not if(@available)).
21164 if (FunctionScopeInfo
*Context
= getCurFunctionAvailabilityContext())
21165 Context
->HasPotentialAvailabilityViolations
= true;
21167 return new (Context
)
21168 ObjCAvailabilityCheckExpr(Version
, AtLoc
, RParen
, Context
.BoolTy
);
21171 ExprResult
Sema::CreateRecoveryExpr(SourceLocation Begin
, SourceLocation End
,
21172 ArrayRef
<Expr
*> SubExprs
, QualType T
) {
21173 if (!Context
.getLangOpts().RecoveryAST
)
21174 return ExprError();
21176 if (isSFINAEContext())
21177 return ExprError();
21179 if (T
.isNull() || T
->isUndeducedType() ||
21180 !Context
.getLangOpts().RecoveryASTType
)
21181 // We don't know the concrete type, fallback to dependent type.
21182 T
= Context
.DependentTy
;
21184 return RecoveryExpr::Create(Context
, T
, Begin
, End
, SubExprs
);