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/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/OperationKinds.h"
28 #include "clang/AST/ParentMapContext.h"
29 #include "clang/AST/RecursiveASTVisitor.h"
30 #include "clang/AST/Type.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/Builtins.h"
33 #include "clang/Basic/DiagnosticSema.h"
34 #include "clang/Basic/PartialDiagnostic.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "clang/Basic/TargetInfo.h"
38 #include "clang/Basic/TypeTraits.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/Designator.h"
45 #include "clang/Sema/EnterExpressionEvaluationContext.h"
46 #include "clang/Sema/Initialization.h"
47 #include "clang/Sema/Lookup.h"
48 #include "clang/Sema/Overload.h"
49 #include "clang/Sema/ParsedTemplate.h"
50 #include "clang/Sema/Scope.h"
51 #include "clang/Sema/ScopeInfo.h"
52 #include "clang/Sema/SemaFixItUtils.h"
53 #include "clang/Sema/SemaInternal.h"
54 #include "clang/Sema/Template.h"
55 #include "llvm/ADT/STLExtras.h"
56 #include "llvm/ADT/StringExtras.h"
57 #include "llvm/Support/Casting.h"
58 #include "llvm/Support/ConvertUTF.h"
59 #include "llvm/Support/SaveAndRestore.h"
60 #include "llvm/Support/TypeSize.h"
63 using namespace clang
;
66 /// Determine whether the use of this declaration is valid, without
67 /// emitting diagnostics.
68 bool Sema::CanUseDecl(NamedDecl
*D
, bool TreatUnavailableAsInvalid
) {
69 // See if this is an auto-typed variable whose initializer we are parsing.
70 if (ParsingInitForAutoVars
.count(D
))
73 // See if this is a deleted function.
74 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
78 // If the function has a deduced return type, and we can't deduce it,
79 // then we can't use it either.
80 if (getLangOpts().CPlusPlus14
&& FD
->getReturnType()->isUndeducedType() &&
81 DeduceReturnType(FD
, SourceLocation(), /*Diagnose*/ false))
84 // See if this is an aligned allocation/deallocation function that is
86 if (TreatUnavailableAsInvalid
&&
87 isUnavailableAlignedAllocationFunction(*FD
))
91 // See if this function is unavailable.
92 if (TreatUnavailableAsInvalid
&& D
->getAvailability() == AR_Unavailable
&&
93 cast
<Decl
>(CurContext
)->getAvailability() != AR_Unavailable
)
96 if (isa
<UnresolvedUsingIfExistsDecl
>(D
))
102 static void DiagnoseUnusedOfDecl(Sema
&S
, NamedDecl
*D
, SourceLocation Loc
) {
103 // Warn if this is used but marked unused.
104 if (const auto *A
= D
->getAttr
<UnusedAttr
>()) {
105 // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
106 // should diagnose them.
107 if (A
->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused
&&
108 A
->getSemanticSpelling() != UnusedAttr::C23_maybe_unused
) {
109 const Decl
*DC
= cast_or_null
<Decl
>(S
.getCurObjCLexicalContext());
110 if (DC
&& !DC
->hasAttr
<UnusedAttr
>())
111 S
.Diag(Loc
, diag::warn_used_but_marked_unused
) << D
;
116 /// Emit a note explaining that this function is deleted.
117 void Sema::NoteDeletedFunction(FunctionDecl
*Decl
) {
118 assert(Decl
&& Decl
->isDeleted());
120 if (Decl
->isDefaulted()) {
121 // If the method was explicitly defaulted, point at that declaration.
122 if (!Decl
->isImplicit())
123 Diag(Decl
->getLocation(), diag::note_implicitly_deleted
);
125 // Try to diagnose why this special member function was implicitly
126 // deleted. This might fail, if that reason no longer applies.
127 DiagnoseDeletedDefaultedFunction(Decl
);
131 auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(Decl
);
132 if (Ctor
&& Ctor
->isInheritingConstructor())
133 return NoteDeletedInheritingConstructor(Ctor
);
135 Diag(Decl
->getLocation(), diag::note_availability_specified_here
)
139 /// Determine whether a FunctionDecl was ever declared with an
140 /// explicit storage class.
141 static bool hasAnyExplicitStorageClass(const FunctionDecl
*D
) {
142 for (auto *I
: D
->redecls()) {
143 if (I
->getStorageClass() != SC_None
)
149 /// Check whether we're in an extern inline function and referring to a
150 /// variable or function with internal linkage (C11 6.7.4p3).
152 /// This is only a warning because we used to silently accept this code, but
153 /// in many cases it will not behave correctly. This is not enabled in C++ mode
154 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
155 /// and so while there may still be user mistakes, most of the time we can't
156 /// prove that there are errors.
157 static void diagnoseUseOfInternalDeclInInlineFunction(Sema
&S
,
159 SourceLocation Loc
) {
160 // This is disabled under C++; there are too many ways for this to fire in
161 // contexts where the warning is a false positive, or where it is technically
162 // correct but benign.
163 if (S
.getLangOpts().CPlusPlus
)
166 // Check if this is an inlined function or method.
167 FunctionDecl
*Current
= S
.getCurFunctionDecl();
170 if (!Current
->isInlined())
172 if (!Current
->isExternallyVisible())
175 // Check if the decl has internal linkage.
176 if (D
->getFormalLinkage() != Linkage::Internal
)
179 // Downgrade from ExtWarn to Extension if
180 // (1) the supposedly external inline function is in the main file,
181 // and probably won't be included anywhere else.
182 // (2) the thing we're referencing is a pure function.
183 // (3) the thing we're referencing is another inline function.
184 // This last can give us false negatives, but it's better than warning on
185 // wrappers for simple C library functions.
186 const FunctionDecl
*UsedFn
= dyn_cast
<FunctionDecl
>(D
);
187 bool DowngradeWarning
= S
.getSourceManager().isInMainFile(Loc
);
188 if (!DowngradeWarning
&& UsedFn
)
189 DowngradeWarning
= UsedFn
->isInlined() || UsedFn
->hasAttr
<ConstAttr
>();
191 S
.Diag(Loc
, DowngradeWarning
? diag::ext_internal_in_extern_inline_quiet
192 : diag::ext_internal_in_extern_inline
)
193 << /*IsVar=*/!UsedFn
<< D
;
195 S
.MaybeSuggestAddingStaticToDecl(Current
);
197 S
.Diag(D
->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at
)
201 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl
*Cur
) {
202 const FunctionDecl
*First
= Cur
->getFirstDecl();
204 // Suggest "static" on the function, if possible.
205 if (!hasAnyExplicitStorageClass(First
)) {
206 SourceLocation DeclBegin
= First
->getSourceRange().getBegin();
207 Diag(DeclBegin
, diag::note_convert_inline_to_static
)
208 << Cur
<< FixItHint::CreateInsertion(DeclBegin
, "static ");
212 /// Determine whether the use of this declaration is valid, and
213 /// emit any corresponding diagnostics.
215 /// This routine diagnoses various problems with referencing
216 /// declarations that can occur when using a declaration. For example,
217 /// it might warn if a deprecated or unavailable declaration is being
218 /// used, or produce an error (and return true) if a C++0x deleted
219 /// function is being used.
221 /// \returns true if there was an error (this declaration cannot be
222 /// referenced), false otherwise.
224 bool Sema::DiagnoseUseOfDecl(NamedDecl
*D
, ArrayRef
<SourceLocation
> Locs
,
225 const ObjCInterfaceDecl
*UnknownObjCClass
,
226 bool ObjCPropertyAccess
,
227 bool AvoidPartialAvailabilityChecks
,
228 ObjCInterfaceDecl
*ClassReceiver
,
229 bool SkipTrailingRequiresClause
) {
230 SourceLocation Loc
= Locs
.front();
231 if (getLangOpts().CPlusPlus
&& isa
<FunctionDecl
>(D
)) {
232 // If there were any diagnostics suppressed by template argument deduction,
234 auto Pos
= SuppressedDiagnostics
.find(D
->getCanonicalDecl());
235 if (Pos
!= SuppressedDiagnostics
.end()) {
236 for (const PartialDiagnosticAt
&Suppressed
: Pos
->second
)
237 Diag(Suppressed
.first
, Suppressed
.second
);
239 // Clear out the list of suppressed diagnostics, so that we don't emit
240 // them again for this specialization. However, we don't obsolete this
241 // entry from the table, because we want to avoid ever emitting these
242 // diagnostics again.
246 // C++ [basic.start.main]p3:
247 // The function 'main' shall not be used within a program.
248 if (cast
<FunctionDecl
>(D
)->isMain())
249 Diag(Loc
, diag::ext_main_used
);
251 diagnoseUnavailableAlignedAllocation(*cast
<FunctionDecl
>(D
), Loc
);
254 // See if this is an auto-typed variable whose initializer we are parsing.
255 if (ParsingInitForAutoVars
.count(D
)) {
256 if (isa
<BindingDecl
>(D
)) {
257 Diag(Loc
, diag::err_binding_cannot_appear_in_own_initializer
)
260 Diag(Loc
, diag::err_auto_variable_cannot_appear_in_own_initializer
)
261 << D
->getDeclName() << cast
<VarDecl
>(D
)->getType();
266 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
267 // See if this is a deleted function.
268 if (FD
->isDeleted()) {
269 auto *Ctor
= dyn_cast
<CXXConstructorDecl
>(FD
);
270 if (Ctor
&& Ctor
->isInheritingConstructor())
271 Diag(Loc
, diag::err_deleted_inherited_ctor_use
)
273 << Ctor
->getInheritedConstructor().getConstructor()->getParent();
275 Diag(Loc
, diag::err_deleted_function_use
);
276 NoteDeletedFunction(FD
);
281 // A program that refers explicitly or implicitly to a function with a
282 // trailing requires-clause whose constraint-expression is not satisfied,
283 // other than to declare it, is ill-formed. [...]
285 // See if this is a function with constraints that need to be satisfied.
286 // Check this before deducing the return type, as it might instantiate the
288 if (!SkipTrailingRequiresClause
&& FD
->getTrailingRequiresClause()) {
289 ConstraintSatisfaction Satisfaction
;
290 if (CheckFunctionConstraints(FD
, Satisfaction
, Loc
,
291 /*ForOverloadResolution*/ true))
292 // A diagnostic will have already been generated (non-constant
293 // constraint expression, for example)
295 if (!Satisfaction
.IsSatisfied
) {
297 diag::err_reference_to_function_with_unsatisfied_constraints
)
299 DiagnoseUnsatisfiedConstraint(Satisfaction
);
304 // If the function has a deduced return type, and we can't deduce it,
305 // then we can't use it either.
306 if (getLangOpts().CPlusPlus14
&& FD
->getReturnType()->isUndeducedType() &&
307 DeduceReturnType(FD
, Loc
))
310 if (getLangOpts().CUDA
&& !CheckCUDACall(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 (D
->hasAttr
<AvailableOnlyInDefaultEvalMethodAttr
>()) {
379 if (getLangOpts().getFPEvalMethod() !=
380 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine
&&
381 PP
.getLastFPEvalPragmaLocation().isValid() &&
382 PP
.getCurrentFPEvalMethod() != getLangOpts().getFPEvalMethod())
383 Diag(D
->getLocation(),
384 diag::err_type_available_only_in_default_eval_method
)
388 if (auto *VD
= dyn_cast
<ValueDecl
>(D
))
389 checkTypeSupport(VD
->getType(), Loc
, VD
);
391 if (LangOpts
.SYCLIsDevice
||
392 (LangOpts
.OpenMP
&& LangOpts
.OpenMPIsTargetDevice
)) {
393 if (!Context
.getTargetInfo().isTLSSupported())
394 if (const auto *VD
= dyn_cast
<VarDecl
>(D
))
395 if (VD
->getTLSKind() != VarDecl::TLS_None
)
396 targetDiag(*Locs
.begin(), diag::err_thread_unsupported
);
399 if (isa
<ParmVarDecl
>(D
) && isa
<RequiresExprBodyDecl
>(D
->getDeclContext()) &&
400 !isUnevaluatedContext()) {
401 // C++ [expr.prim.req.nested] p3
402 // A local parameter shall only appear as an unevaluated operand
403 // (Clause 8) within the constraint-expression.
404 Diag(Loc
, diag::err_requires_expr_parameter_referenced_in_evaluated_context
)
406 Diag(D
->getLocation(), diag::note_entity_declared_at
) << D
;
413 /// DiagnoseSentinelCalls - This routine checks whether a call or
414 /// message-send is to a declaration with the sentinel attribute, and
415 /// if so, it checks that the requirements of the sentinel are
417 void Sema::DiagnoseSentinelCalls(NamedDecl
*D
, SourceLocation Loc
,
418 ArrayRef
<Expr
*> Args
) {
419 const SentinelAttr
*attr
= D
->getAttr
<SentinelAttr
>();
423 // The number of formal parameters of the declaration.
424 unsigned numFormalParams
;
426 // The kind of declaration. This is also an index into a %select in
428 enum CalleeType
{ CT_Function
, CT_Method
, CT_Block
} calleeType
;
430 if (ObjCMethodDecl
*MD
= dyn_cast
<ObjCMethodDecl
>(D
)) {
431 numFormalParams
= MD
->param_size();
432 calleeType
= CT_Method
;
433 } else if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(D
)) {
434 numFormalParams
= FD
->param_size();
435 calleeType
= CT_Function
;
436 } else if (isa
<VarDecl
>(D
)) {
437 QualType type
= cast
<ValueDecl
>(D
)->getType();
438 const FunctionType
*fn
= nullptr;
439 if (const PointerType
*ptr
= type
->getAs
<PointerType
>()) {
440 fn
= ptr
->getPointeeType()->getAs
<FunctionType
>();
442 calleeType
= CT_Function
;
443 } else if (const BlockPointerType
*ptr
= type
->getAs
<BlockPointerType
>()) {
444 fn
= ptr
->getPointeeType()->castAs
<FunctionType
>();
445 calleeType
= CT_Block
;
450 if (const FunctionProtoType
*proto
= dyn_cast
<FunctionProtoType
>(fn
)) {
451 numFormalParams
= proto
->getNumParams();
459 // "nullPos" is the number of formal parameters at the end which
460 // effectively count as part of the variadic arguments. This is
461 // useful if you would prefer to not have *any* formal parameters,
462 // but the language forces you to have at least one.
463 unsigned nullPos
= attr
->getNullPos();
464 assert((nullPos
== 0 || nullPos
== 1) && "invalid null position on sentinel");
465 numFormalParams
= (nullPos
> numFormalParams
? 0 : numFormalParams
- nullPos
);
467 // The number of arguments which should follow the sentinel.
468 unsigned numArgsAfterSentinel
= attr
->getSentinel();
470 // If there aren't enough arguments for all the formal parameters,
471 // the sentinel, and the args after the sentinel, complain.
472 if (Args
.size() < numFormalParams
+ numArgsAfterSentinel
+ 1) {
473 Diag(Loc
, diag::warn_not_enough_argument
) << D
->getDeclName();
474 Diag(D
->getLocation(), diag::note_sentinel_here
) << int(calleeType
);
478 // Otherwise, find the sentinel expression.
479 Expr
*sentinelExpr
= Args
[Args
.size() - numArgsAfterSentinel
- 1];
480 if (!sentinelExpr
) return;
481 if (sentinelExpr
->isValueDependent()) return;
482 if (Context
.isSentinelNullExpr(sentinelExpr
)) return;
484 // Pick a reasonable string to insert. Optimistically use 'nil', 'nullptr',
485 // or 'NULL' if those are actually defined in the context. Only use
486 // 'nil' for ObjC methods, where it's much more likely that the
487 // variadic arguments form a list of object pointers.
488 SourceLocation MissingNilLoc
= getLocForEndOfToken(sentinelExpr
->getEndLoc());
489 std::string NullValue
;
490 if (calleeType
== CT_Method
&& PP
.isMacroDefined("nil"))
492 else if (getLangOpts().CPlusPlus11
)
493 NullValue
= "nullptr";
494 else if (PP
.isMacroDefined("NULL"))
497 NullValue
= "(void*) 0";
499 if (MissingNilLoc
.isInvalid())
500 Diag(Loc
, diag::warn_missing_sentinel
) << int(calleeType
);
502 Diag(MissingNilLoc
, diag::warn_missing_sentinel
)
504 << FixItHint::CreateInsertion(MissingNilLoc
, ", " + NullValue
);
505 Diag(D
->getLocation(), diag::note_sentinel_here
) << int(calleeType
);
508 SourceRange
Sema::getExprRange(Expr
*E
) const {
509 return E
? E
->getSourceRange() : SourceRange();
512 //===----------------------------------------------------------------------===//
513 // Standard Promotions and Conversions
514 //===----------------------------------------------------------------------===//
516 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 ExprResult
Sema::DefaultFunctionArrayConversion(Expr
*E
, bool Diagnose
) {
518 // Handle any placeholder expressions which made it here.
519 if (E
->hasPlaceholderType()) {
520 ExprResult result
= CheckPlaceholderExpr(E
);
521 if (result
.isInvalid()) return ExprError();
525 QualType Ty
= E
->getType();
526 assert(!Ty
.isNull() && "DefaultFunctionArrayConversion - missing type");
528 if (Ty
->isFunctionType()) {
529 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenCasts()))
530 if (auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl()))
531 if (!checkAddressOfFunctionIsAvailable(FD
, Diagnose
, E
->getExprLoc()))
534 E
= ImpCastExprToType(E
, Context
.getPointerType(Ty
),
535 CK_FunctionToPointerDecay
).get();
536 } else if (Ty
->isArrayType()) {
537 // In C90 mode, arrays only promote to pointers if the array expression is
538 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
539 // type 'array of type' is converted to an expression that has type 'pointer
540 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
541 // that has type 'array of type' ...". The relevant change is "an lvalue"
542 // (C90) to "an expression" (C99).
545 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
546 // T" can be converted to an rvalue of type "pointer to T".
548 if (getLangOpts().C99
|| getLangOpts().CPlusPlus
|| E
->isLValue()) {
549 ExprResult Res
= ImpCastExprToType(E
, Context
.getArrayDecayedType(Ty
),
550 CK_ArrayToPointerDecay
);
559 static void CheckForNullPointerDereference(Sema
&S
, Expr
*E
) {
560 // Check to see if we are dereferencing a null pointer. If so,
561 // and if not volatile-qualified, this is undefined behavior that the
562 // optimizer will delete, so warn about it. People sometimes try to use this
563 // to get a deterministic trap and are surprised by clang's behavior. This
564 // only handles the pattern "*null", which is a very syntactic check.
565 const auto *UO
= dyn_cast
<UnaryOperator
>(E
->IgnoreParenCasts());
566 if (UO
&& UO
->getOpcode() == UO_Deref
&&
567 UO
->getSubExpr()->getType()->isPointerType()) {
569 UO
->getSubExpr()->getType()->getPointeeType().getAddressSpace();
570 if ((!isTargetAddressSpace(AS
) ||
571 (isTargetAddressSpace(AS
) && toTargetAddressSpace(AS
) == 0)) &&
572 UO
->getSubExpr()->IgnoreParenCasts()->isNullPointerConstant(
573 S
.Context
, Expr::NPC_ValueDependentIsNotNull
) &&
574 !UO
->getType().isVolatileQualified()) {
575 S
.DiagRuntimeBehavior(UO
->getOperatorLoc(), UO
,
576 S
.PDiag(diag::warn_indirection_through_null
)
577 << UO
->getSubExpr()->getSourceRange());
578 S
.DiagRuntimeBehavior(UO
->getOperatorLoc(), UO
,
579 S
.PDiag(diag::note_indirection_through_null
));
584 static void DiagnoseDirectIsaAccess(Sema
&S
, const ObjCIvarRefExpr
*OIRE
,
585 SourceLocation AssignLoc
,
587 const ObjCIvarDecl
*IV
= OIRE
->getDecl();
591 DeclarationName MemberName
= IV
->getDeclName();
592 IdentifierInfo
*Member
= MemberName
.getAsIdentifierInfo();
593 if (!Member
|| !Member
->isStr("isa"))
596 const Expr
*Base
= OIRE
->getBase();
597 QualType BaseType
= Base
->getType();
599 BaseType
= BaseType
->getPointeeType();
600 if (const ObjCObjectType
*OTy
= BaseType
->getAs
<ObjCObjectType
>())
601 if (ObjCInterfaceDecl
*IDecl
= OTy
->getInterface()) {
602 ObjCInterfaceDecl
*ClassDeclared
= nullptr;
603 ObjCIvarDecl
*IV
= IDecl
->lookupInstanceVariable(Member
, ClassDeclared
);
604 if (!ClassDeclared
->getSuperClass()
605 && (*ClassDeclared
->ivar_begin()) == IV
) {
607 NamedDecl
*ObjectSetClass
=
608 S
.LookupSingleName(S
.TUScope
,
609 &S
.Context
.Idents
.get("object_setClass"),
610 SourceLocation(), S
.LookupOrdinaryName
);
611 if (ObjectSetClass
) {
612 SourceLocation RHSLocEnd
= S
.getLocForEndOfToken(RHS
->getEndLoc());
613 S
.Diag(OIRE
->getExprLoc(), diag::warn_objc_isa_assign
)
614 << FixItHint::CreateInsertion(OIRE
->getBeginLoc(),
616 << FixItHint::CreateReplacement(
617 SourceRange(OIRE
->getOpLoc(), AssignLoc
), ",")
618 << FixItHint::CreateInsertion(RHSLocEnd
, ")");
621 S
.Diag(OIRE
->getLocation(), diag::warn_objc_isa_assign
);
623 NamedDecl
*ObjectGetClass
=
624 S
.LookupSingleName(S
.TUScope
,
625 &S
.Context
.Idents
.get("object_getClass"),
626 SourceLocation(), S
.LookupOrdinaryName
);
628 S
.Diag(OIRE
->getExprLoc(), diag::warn_objc_isa_use
)
629 << FixItHint::CreateInsertion(OIRE
->getBeginLoc(),
631 << FixItHint::CreateReplacement(
632 SourceRange(OIRE
->getOpLoc(), OIRE
->getEndLoc()), ")");
634 S
.Diag(OIRE
->getLocation(), diag::warn_objc_isa_use
);
636 S
.Diag(IV
->getLocation(), diag::note_ivar_decl
);
641 ExprResult
Sema::DefaultLvalueConversion(Expr
*E
) {
642 // Handle any placeholder expressions which made it here.
643 if (E
->hasPlaceholderType()) {
644 ExprResult result
= CheckPlaceholderExpr(E
);
645 if (result
.isInvalid()) return ExprError();
649 // C++ [conv.lval]p1:
650 // A glvalue of a non-function, non-array type T can be
651 // converted to a prvalue.
652 if (!E
->isGLValue()) return E
;
654 QualType T
= E
->getType();
655 assert(!T
.isNull() && "r-value conversion on typeless expression?");
657 // lvalue-to-rvalue conversion cannot be applied to function or array types.
658 if (T
->isFunctionType() || T
->isArrayType())
661 // We don't want to throw lvalue-to-rvalue casts on top of
662 // expressions of certain types in C++.
663 if (getLangOpts().CPlusPlus
&&
664 (E
->getType() == Context
.OverloadTy
||
665 T
->isDependentType() ||
669 // The C standard is actually really unclear on this point, and
670 // DR106 tells us what the result should be but not why. It's
671 // generally best to say that void types just doesn't undergo
672 // lvalue-to-rvalue at all. Note that expressions of unqualified
673 // 'void' type are never l-values, but qualified void can be.
677 // OpenCL usually rejects direct accesses to values of 'half' type.
678 if (getLangOpts().OpenCL
&&
679 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
681 Diag(E
->getExprLoc(), diag::err_opencl_half_load_store
)
686 CheckForNullPointerDereference(*this, E
);
687 if (const ObjCIsaExpr
*OISA
= dyn_cast
<ObjCIsaExpr
>(E
->IgnoreParenCasts())) {
688 NamedDecl
*ObjectGetClass
= LookupSingleName(TUScope
,
689 &Context
.Idents
.get("object_getClass"),
690 SourceLocation(), LookupOrdinaryName
);
692 Diag(E
->getExprLoc(), diag::warn_objc_isa_use
)
693 << FixItHint::CreateInsertion(OISA
->getBeginLoc(), "object_getClass(")
694 << FixItHint::CreateReplacement(
695 SourceRange(OISA
->getOpLoc(), OISA
->getIsaMemberLoc()), ")");
697 Diag(E
->getExprLoc(), diag::warn_objc_isa_use
);
699 else if (const ObjCIvarRefExpr
*OIRE
=
700 dyn_cast
<ObjCIvarRefExpr
>(E
->IgnoreParenCasts()))
701 DiagnoseDirectIsaAccess(*this, OIRE
, SourceLocation(), /* Expr*/nullptr);
703 // C++ [conv.lval]p1:
704 // [...] If T is a non-class type, the type of the prvalue is the
705 // cv-unqualified version of T. Otherwise, the type of the
709 // If the lvalue has qualified type, the value has the unqualified
710 // version of the type of the lvalue; otherwise, the value has the
711 // type of the lvalue.
712 if (T
.hasQualifiers())
713 T
= T
.getUnqualifiedType();
715 // Under the MS ABI, lock down the inheritance model now.
716 if (T
->isMemberPointerType() &&
717 Context
.getTargetInfo().getCXXABI().isMicrosoft())
718 (void)isCompleteType(E
->getExprLoc(), T
);
720 ExprResult Res
= CheckLValueToRValueConversionOperand(E
);
725 // Loading a __weak object implicitly retains the value, so we need a cleanup to
727 if (E
->getType().getObjCLifetime() == Qualifiers::OCL_Weak
)
728 Cleanup
.setExprNeedsCleanups(true);
730 if (E
->getType().isDestructedType() == QualType::DK_nontrivial_c_struct
)
731 Cleanup
.setExprNeedsCleanups(true);
733 // C++ [conv.lval]p3:
734 // If T is cv std::nullptr_t, the result is a null pointer constant.
735 CastKind CK
= T
->isNullPtrType() ? CK_NullToPointer
: CK_LValueToRValue
;
736 Res
= ImplicitCastExpr::Create(Context
, T
, CK
, E
, nullptr, VK_PRValue
,
737 CurFPFeatureOverrides());
740 // ... if the lvalue has atomic type, the value has the non-atomic version
741 // of the type of the lvalue ...
742 if (const AtomicType
*Atomic
= T
->getAs
<AtomicType
>()) {
743 T
= Atomic
->getValueType().getUnqualifiedType();
744 Res
= ImplicitCastExpr::Create(Context
, T
, CK_AtomicToNonAtomic
, Res
.get(),
745 nullptr, VK_PRValue
, FPOptionsOverride());
751 ExprResult
Sema::DefaultFunctionArrayLvalueConversion(Expr
*E
, bool Diagnose
) {
752 ExprResult Res
= DefaultFunctionArrayConversion(E
, Diagnose
);
755 Res
= DefaultLvalueConversion(Res
.get());
761 /// CallExprUnaryConversions - a special case of an unary conversion
762 /// performed on a function designator of a call expression.
763 ExprResult
Sema::CallExprUnaryConversions(Expr
*E
) {
764 QualType Ty
= E
->getType();
766 // Only do implicit cast for a function type, but not for a pointer
768 if (Ty
->isFunctionType()) {
769 Res
= ImpCastExprToType(E
, Context
.getPointerType(Ty
),
770 CK_FunctionToPointerDecay
);
774 Res
= DefaultLvalueConversion(Res
.get());
780 /// UsualUnaryConversions - Performs various conversions that are common to most
781 /// operators (C99 6.3). The conversions of array and function types are
782 /// sometimes suppressed. For example, the array->pointer conversion doesn't
783 /// apply if the array is an argument to the sizeof or address (&) operators.
784 /// In these instances, this routine should *not* be called.
785 ExprResult
Sema::UsualUnaryConversions(Expr
*E
) {
786 // First, convert to an r-value.
787 ExprResult Res
= DefaultFunctionArrayLvalueConversion(E
);
792 QualType Ty
= E
->getType();
793 assert(!Ty
.isNull() && "UsualUnaryConversions - missing type");
795 LangOptions::FPEvalMethodKind EvalMethod
= CurFPFeatures
.getFPEvalMethod();
796 if (EvalMethod
!= LangOptions::FEM_Source
&& Ty
->isFloatingType() &&
797 (getLangOpts().getFPEvalMethod() !=
798 LangOptions::FPEvalMethodKind::FEM_UnsetOnCommandLine
||
799 PP
.getLastFPEvalPragmaLocation().isValid())) {
800 switch (EvalMethod
) {
802 llvm_unreachable("Unrecognized float evaluation method");
804 case LangOptions::FEM_UnsetOnCommandLine
:
805 llvm_unreachable("Float evaluation method should be set by now");
807 case LangOptions::FEM_Double
:
808 if (Context
.getFloatingTypeOrder(Context
.DoubleTy
, Ty
) > 0)
809 // Widen the expression to double.
810 return Ty
->isComplexType()
811 ? ImpCastExprToType(E
,
812 Context
.getComplexType(Context
.DoubleTy
),
813 CK_FloatingComplexCast
)
814 : ImpCastExprToType(E
, Context
.DoubleTy
, CK_FloatingCast
);
816 case LangOptions::FEM_Extended
:
817 if (Context
.getFloatingTypeOrder(Context
.LongDoubleTy
, Ty
) > 0)
818 // Widen the expression to long double.
819 return Ty
->isComplexType()
821 E
, Context
.getComplexType(Context
.LongDoubleTy
),
822 CK_FloatingComplexCast
)
823 : ImpCastExprToType(E
, Context
.LongDoubleTy
,
829 // Half FP have to be promoted to float unless it is natively supported
830 if (Ty
->isHalfType() && !getLangOpts().NativeHalfType
)
831 return ImpCastExprToType(Res
.get(), Context
.FloatTy
, CK_FloatingCast
);
833 // Try to perform integral promotions if the object has a theoretically
835 if (Ty
->isIntegralOrUnscopedEnumerationType()) {
838 // The following may be used in an expression wherever an int or
839 // unsigned int may be used:
840 // - an object or expression with an integer type whose integer
841 // conversion rank is less than or equal to the rank of int
843 // - A bit-field of type _Bool, int, signed int, or unsigned int.
845 // If an int can represent all values of the original type, the
846 // value is converted to an int; otherwise, it is converted to an
847 // unsigned int. These are called the integer promotions. All
848 // other types are unchanged by the integer promotions.
850 QualType PTy
= Context
.isPromotableBitField(E
);
852 E
= ImpCastExprToType(E
, PTy
, CK_IntegralCast
).get();
855 if (Context
.isPromotableIntegerType(Ty
)) {
856 QualType PT
= Context
.getPromotedIntegerType(Ty
);
857 E
= ImpCastExprToType(E
, PT
, CK_IntegralCast
).get();
864 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
865 /// do not have a prototype. Arguments that have type float or __fp16
866 /// are promoted to double. All other argument types are converted by
867 /// UsualUnaryConversions().
868 ExprResult
Sema::DefaultArgumentPromotion(Expr
*E
) {
869 QualType Ty
= E
->getType();
870 assert(!Ty
.isNull() && "DefaultArgumentPromotion - missing type");
872 ExprResult Res
= UsualUnaryConversions(E
);
877 // If this is a 'float' or '__fp16' (CVR qualified or typedef)
878 // promote to double.
879 // Note that default argument promotion applies only to float (and
880 // half/fp16); it does not apply to _Float16.
881 const BuiltinType
*BTy
= Ty
->getAs
<BuiltinType
>();
882 if (BTy
&& (BTy
->getKind() == BuiltinType::Half
||
883 BTy
->getKind() == BuiltinType::Float
)) {
884 if (getLangOpts().OpenCL
&&
885 !getOpenCLOptions().isAvailableOption("cl_khr_fp64", getLangOpts())) {
886 if (BTy
->getKind() == BuiltinType::Half
) {
887 E
= ImpCastExprToType(E
, Context
.FloatTy
, CK_FloatingCast
).get();
890 E
= ImpCastExprToType(E
, Context
.DoubleTy
, CK_FloatingCast
).get();
894 getLangOpts().getExtendIntArgs() ==
895 LangOptions::ExtendArgsKind::ExtendTo64
&&
896 Context
.getTargetInfo().supportsExtendIntArgs() && Ty
->isIntegerType() &&
897 Context
.getTypeSizeInChars(BTy
) <
898 Context
.getTypeSizeInChars(Context
.LongLongTy
)) {
899 E
= (Ty
->isUnsignedIntegerType())
900 ? ImpCastExprToType(E
, Context
.UnsignedLongLongTy
, CK_IntegralCast
)
902 : ImpCastExprToType(E
, Context
.LongLongTy
, CK_IntegralCast
).get();
903 assert(8 == Context
.getTypeSizeInChars(Context
.LongLongTy
).getQuantity() &&
904 "Unexpected typesize for LongLongTy");
907 // C++ performs lvalue-to-rvalue conversion as a default argument
908 // promotion, even on class types, but note:
909 // C++11 [conv.lval]p2:
910 // When an lvalue-to-rvalue conversion occurs in an unevaluated
911 // operand or a subexpression thereof the value contained in the
912 // referenced object is not accessed. Otherwise, if the glvalue
913 // has a class type, the conversion copy-initializes a temporary
914 // of type T from the glvalue and the result of the conversion
915 // is a prvalue for the temporary.
916 // FIXME: add some way to gate this entire thing for correctness in
917 // potentially potentially evaluated contexts.
918 if (getLangOpts().CPlusPlus
&& E
->isGLValue() && !isUnevaluatedContext()) {
919 ExprResult Temp
= PerformCopyInitialization(
920 InitializedEntity::InitializeTemporary(E
->getType()),
922 if (Temp
.isInvalid())
930 /// Determine the degree of POD-ness for an expression.
931 /// Incomplete types are considered POD, since this check can be performed
932 /// when we're in an unevaluated context.
933 Sema::VarArgKind
Sema::isValidVarArgType(const QualType
&Ty
) {
934 if (Ty
->isIncompleteType()) {
935 // C++11 [expr.call]p7:
936 // After these conversions, if the argument does not have arithmetic,
937 // enumeration, pointer, pointer to member, or class type, the program
940 // Since we've already performed array-to-pointer and function-to-pointer
941 // decay, the only such type in C++ is cv void. This also handles
942 // initializer lists as variadic arguments.
943 if (Ty
->isVoidType())
946 if (Ty
->isObjCObjectType())
951 if (Ty
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
954 if (Context
.getTargetInfo().getTriple().isWasm() &&
955 Ty
.isWebAssemblyReferenceType()) {
959 if (Ty
.isCXX98PODType(Context
))
962 // C++11 [expr.call]p7:
963 // Passing a potentially-evaluated argument of class type (Clause 9)
964 // having a non-trivial copy constructor, a non-trivial move constructor,
965 // or a non-trivial destructor, with no corresponding parameter,
966 // is conditionally-supported with implementation-defined semantics.
967 if (getLangOpts().CPlusPlus11
&& !Ty
->isDependentType())
968 if (CXXRecordDecl
*Record
= Ty
->getAsCXXRecordDecl())
969 if (!Record
->hasNonTrivialCopyConstructor() &&
970 !Record
->hasNonTrivialMoveConstructor() &&
971 !Record
->hasNonTrivialDestructor())
972 return VAK_ValidInCXX11
;
974 if (getLangOpts().ObjCAutoRefCount
&& Ty
->isObjCLifetimeType())
977 if (Ty
->isObjCObjectType())
980 if (getLangOpts().MSVCCompat
)
981 return VAK_MSVCUndefined
;
983 // FIXME: In C++11, these cases are conditionally-supported, meaning we're
984 // permitted to reject them. We should consider doing so.
985 return VAK_Undefined
;
988 void Sema::checkVariadicArgument(const Expr
*E
, VariadicCallType CT
) {
989 // Don't allow one to pass an Objective-C interface to a vararg.
990 const QualType
&Ty
= E
->getType();
991 VarArgKind VAK
= isValidVarArgType(Ty
);
993 // Complain about passing non-POD types through varargs.
995 case VAK_ValidInCXX11
:
997 E
->getBeginLoc(), nullptr,
998 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg
) << Ty
<< CT
);
1001 if (Ty
->isRecordType()) {
1002 // This is unlikely to be what the user intended. If the class has a
1003 // 'c_str' member function, the user probably meant to call that.
1004 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
1005 PDiag(diag::warn_pass_class_arg_to_vararg
)
1006 << Ty
<< CT
<< hasCStrMethod(E
) << ".c_str()");
1011 case VAK_MSVCUndefined
:
1012 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
1013 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg
)
1014 << getLangOpts().CPlusPlus11
<< Ty
<< CT
);
1018 if (Ty
.isDestructedType() == QualType::DK_nontrivial_c_struct
)
1019 Diag(E
->getBeginLoc(),
1020 diag::err_cannot_pass_non_trivial_c_struct_to_vararg
)
1022 else if (Ty
->isObjCObjectType())
1023 DiagRuntimeBehavior(E
->getBeginLoc(), nullptr,
1024 PDiag(diag::err_cannot_pass_objc_interface_to_vararg
)
1027 Diag(E
->getBeginLoc(), diag::err_cannot_pass_to_vararg
)
1028 << isa
<InitListExpr
>(E
) << Ty
<< CT
;
1033 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
1034 /// will create a trap if the resulting type is not a POD type.
1035 ExprResult
Sema::DefaultVariadicArgumentPromotion(Expr
*E
, VariadicCallType CT
,
1036 FunctionDecl
*FDecl
) {
1037 if (const BuiltinType
*PlaceholderTy
= E
->getType()->getAsPlaceholderType()) {
1038 // Strip the unbridged-cast placeholder expression off, if applicable.
1039 if (PlaceholderTy
->getKind() == BuiltinType::ARCUnbridgedCast
&&
1040 (CT
== VariadicMethod
||
1041 (FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>()))) {
1042 E
= stripARCUnbridgedCast(E
);
1044 // Otherwise, do normal placeholder checking.
1046 ExprResult ExprRes
= CheckPlaceholderExpr(E
);
1047 if (ExprRes
.isInvalid())
1053 ExprResult ExprRes
= DefaultArgumentPromotion(E
);
1054 if (ExprRes
.isInvalid())
1057 // Copy blocks to the heap.
1058 if (ExprRes
.get()->getType()->isBlockPointerType())
1059 maybeExtendBlockObject(ExprRes
);
1063 // Diagnostics regarding non-POD argument types are
1064 // emitted along with format string checking in Sema::CheckFunctionCall().
1065 if (isValidVarArgType(E
->getType()) == VAK_Undefined
) {
1066 // Turn this into a trap.
1068 SourceLocation TemplateKWLoc
;
1070 Name
.setIdentifier(PP
.getIdentifierInfo("__builtin_trap"),
1072 ExprResult TrapFn
= ActOnIdExpression(TUScope
, SS
, TemplateKWLoc
, Name
,
1073 /*HasTrailingLParen=*/true,
1074 /*IsAddressOfOperand=*/false);
1075 if (TrapFn
.isInvalid())
1078 ExprResult Call
= BuildCallExpr(TUScope
, TrapFn
.get(), E
->getBeginLoc(),
1079 std::nullopt
, E
->getEndLoc());
1080 if (Call
.isInvalid())
1084 ActOnBinOp(TUScope
, E
->getBeginLoc(), tok::comma
, Call
.get(), E
);
1085 if (Comma
.isInvalid())
1090 if (!getLangOpts().CPlusPlus
&&
1091 RequireCompleteType(E
->getExprLoc(), E
->getType(),
1092 diag::err_call_incomplete_argument
))
1098 /// Converts an integer to complex float type. Helper function of
1099 /// UsualArithmeticConversions()
1101 /// \return false if the integer expression is an integer type and is
1102 /// successfully converted to the complex type.
1103 static bool handleIntegerToComplexFloatConversion(Sema
&S
, ExprResult
&IntExpr
,
1104 ExprResult
&ComplexExpr
,
1108 if (IntTy
->isComplexType() || IntTy
->isRealFloatingType()) return true;
1109 if (SkipCast
) return false;
1110 if (IntTy
->isIntegerType()) {
1111 QualType fpTy
= ComplexTy
->castAs
<ComplexType
>()->getElementType();
1112 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), fpTy
, CK_IntegralToFloating
);
1113 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), ComplexTy
,
1114 CK_FloatingRealToComplex
);
1116 assert(IntTy
->isComplexIntegerType());
1117 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), ComplexTy
,
1118 CK_IntegralComplexToFloatingComplex
);
1123 // This handles complex/complex, complex/float, or float/complex.
1124 // When both operands are complex, the shorter operand is converted to the
1125 // type of the longer, and that is the type of the result. This corresponds
1126 // to what is done when combining two real floating-point operands.
1127 // The fun begins when size promotion occur across type domains.
1128 // From H&S 6.3.4: When one operand is complex and the other is a real
1129 // floating-point type, the less precise type is converted, within it's
1130 // real or complex domain, to the precision of the other type. For example,
1131 // when combining a "long double" with a "double _Complex", the
1132 // "double _Complex" is promoted to "long double _Complex".
1133 static QualType
handleComplexFloatConversion(Sema
&S
, ExprResult
&Shorter
,
1134 QualType ShorterType
,
1135 QualType LongerType
,
1136 bool PromotePrecision
) {
1137 bool LongerIsComplex
= isa
<ComplexType
>(LongerType
.getCanonicalType());
1139 LongerIsComplex
? LongerType
: S
.Context
.getComplexType(LongerType
);
1141 if (PromotePrecision
) {
1142 if (isa
<ComplexType
>(ShorterType
.getCanonicalType())) {
1144 S
.ImpCastExprToType(Shorter
.get(), Result
, CK_FloatingComplexCast
);
1146 if (LongerIsComplex
)
1147 LongerType
= LongerType
->castAs
<ComplexType
>()->getElementType();
1148 Shorter
= S
.ImpCastExprToType(Shorter
.get(), LongerType
, CK_FloatingCast
);
1154 /// Handle arithmetic conversion with complex types. Helper function of
1155 /// UsualArithmeticConversions()
1156 static QualType
handleComplexConversion(Sema
&S
, ExprResult
&LHS
,
1157 ExprResult
&RHS
, QualType LHSType
,
1158 QualType RHSType
, bool IsCompAssign
) {
1159 // if we have an integer operand, the result is the complex type.
1160 if (!handleIntegerToComplexFloatConversion(S
, RHS
, LHS
, RHSType
, LHSType
,
1161 /*SkipCast=*/false))
1163 if (!handleIntegerToComplexFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
1164 /*SkipCast=*/IsCompAssign
))
1167 // Compute the rank of the two types, regardless of whether they are complex.
1168 int Order
= S
.Context
.getFloatingTypeOrder(LHSType
, RHSType
);
1170 // Promote the precision of the LHS if not an assignment.
1171 return handleComplexFloatConversion(S
, LHS
, LHSType
, RHSType
,
1172 /*PromotePrecision=*/!IsCompAssign
);
1173 // Promote the precision of the RHS unless it is already the same as the LHS.
1174 return handleComplexFloatConversion(S
, RHS
, RHSType
, LHSType
,
1175 /*PromotePrecision=*/Order
> 0);
1178 /// Handle arithmetic conversion from integer to float. Helper function
1179 /// of UsualArithmeticConversions()
1180 static QualType
handleIntToFloatConversion(Sema
&S
, ExprResult
&FloatExpr
,
1181 ExprResult
&IntExpr
,
1182 QualType FloatTy
, QualType IntTy
,
1183 bool ConvertFloat
, bool ConvertInt
) {
1184 if (IntTy
->isIntegerType()) {
1186 // Convert intExpr to the lhs floating point type.
1187 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), FloatTy
,
1188 CK_IntegralToFloating
);
1192 // Convert both sides to the appropriate complex float.
1193 assert(IntTy
->isComplexIntegerType());
1194 QualType result
= S
.Context
.getComplexType(FloatTy
);
1196 // _Complex int -> _Complex float
1198 IntExpr
= S
.ImpCastExprToType(IntExpr
.get(), result
,
1199 CK_IntegralComplexToFloatingComplex
);
1201 // float -> _Complex float
1203 FloatExpr
= S
.ImpCastExprToType(FloatExpr
.get(), result
,
1204 CK_FloatingRealToComplex
);
1209 /// Handle arithmethic conversion with floating point types. Helper
1210 /// function of UsualArithmeticConversions()
1211 static QualType
handleFloatConversion(Sema
&S
, ExprResult
&LHS
,
1212 ExprResult
&RHS
, QualType LHSType
,
1213 QualType RHSType
, bool IsCompAssign
) {
1214 bool LHSFloat
= LHSType
->isRealFloatingType();
1215 bool RHSFloat
= RHSType
->isRealFloatingType();
1217 // N1169 4.1.4: If one of the operands has a floating type and the other
1218 // operand has a fixed-point type, the fixed-point operand
1219 // is converted to the floating type [...]
1220 if (LHSType
->isFixedPointType() || RHSType
->isFixedPointType()) {
1222 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSType
, CK_FixedPointToFloating
);
1223 else if (!IsCompAssign
)
1224 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSType
, CK_FixedPointToFloating
);
1225 return LHSFloat
? LHSType
: RHSType
;
1228 // If we have two real floating types, convert the smaller operand
1229 // to the bigger result.
1230 if (LHSFloat
&& RHSFloat
) {
1231 int order
= S
.Context
.getFloatingTypeOrder(LHSType
, RHSType
);
1233 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSType
, CK_FloatingCast
);
1237 assert(order
< 0 && "illegal float comparison");
1239 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSType
, CK_FloatingCast
);
1244 // Half FP has to be promoted to float unless it is natively supported
1245 if (LHSType
->isHalfType() && !S
.getLangOpts().NativeHalfType
)
1246 LHSType
= S
.Context
.FloatTy
;
1248 return handleIntToFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
1249 /*ConvertFloat=*/!IsCompAssign
,
1250 /*ConvertInt=*/ true);
1253 return handleIntToFloatConversion(S
, RHS
, LHS
, RHSType
, LHSType
,
1254 /*ConvertFloat=*/ true,
1255 /*ConvertInt=*/!IsCompAssign
);
1258 /// Diagnose attempts to convert between __float128, __ibm128 and
1259 /// long double if there is no support for such conversion.
1260 /// Helper function of UsualArithmeticConversions().
1261 static bool unsupportedTypeConversion(const Sema
&S
, QualType LHSType
,
1263 // No issue if either is not a floating point type.
1264 if (!LHSType
->isFloatingType() || !RHSType
->isFloatingType())
1267 // No issue if both have the same 128-bit float semantics.
1268 auto *LHSComplex
= LHSType
->getAs
<ComplexType
>();
1269 auto *RHSComplex
= RHSType
->getAs
<ComplexType
>();
1271 QualType LHSElem
= LHSComplex
? LHSComplex
->getElementType() : LHSType
;
1272 QualType RHSElem
= RHSComplex
? RHSComplex
->getElementType() : RHSType
;
1274 const llvm::fltSemantics
&LHSSem
= S
.Context
.getFloatTypeSemantics(LHSElem
);
1275 const llvm::fltSemantics
&RHSSem
= S
.Context
.getFloatTypeSemantics(RHSElem
);
1277 if ((&LHSSem
!= &llvm::APFloat::PPCDoubleDouble() ||
1278 &RHSSem
!= &llvm::APFloat::IEEEquad()) &&
1279 (&LHSSem
!= &llvm::APFloat::IEEEquad() ||
1280 &RHSSem
!= &llvm::APFloat::PPCDoubleDouble()))
1286 typedef ExprResult
PerformCastFn(Sema
&S
, Expr
*operand
, QualType toType
);
1289 /// These helper callbacks are placed in an anonymous namespace to
1290 /// permit their use as function template parameters.
1291 ExprResult
doIntegralCast(Sema
&S
, Expr
*op
, QualType toType
) {
1292 return S
.ImpCastExprToType(op
, toType
, CK_IntegralCast
);
1295 ExprResult
doComplexIntegralCast(Sema
&S
, Expr
*op
, QualType toType
) {
1296 return S
.ImpCastExprToType(op
, S
.Context
.getComplexType(toType
),
1297 CK_IntegralComplexCast
);
1301 /// Handle integer arithmetic conversions. Helper function of
1302 /// UsualArithmeticConversions()
1303 template <PerformCastFn doLHSCast
, PerformCastFn doRHSCast
>
1304 static QualType
handleIntegerConversion(Sema
&S
, ExprResult
&LHS
,
1305 ExprResult
&RHS
, QualType LHSType
,
1306 QualType RHSType
, bool IsCompAssign
) {
1307 // The rules for this case are in C99 6.3.1.8
1308 int order
= S
.Context
.getIntegerTypeOrder(LHSType
, RHSType
);
1309 bool LHSSigned
= LHSType
->hasSignedIntegerRepresentation();
1310 bool RHSSigned
= RHSType
->hasSignedIntegerRepresentation();
1311 if (LHSSigned
== RHSSigned
) {
1312 // Same signedness; use the higher-ranked type
1314 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1316 } else if (!IsCompAssign
)
1317 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1319 } else if (order
!= (LHSSigned
? 1 : -1)) {
1320 // The unsigned type has greater than or equal rank to the
1321 // signed type, so use the unsigned type
1323 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1325 } else if (!IsCompAssign
)
1326 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1328 } else if (S
.Context
.getIntWidth(LHSType
) != S
.Context
.getIntWidth(RHSType
)) {
1329 // The two types are different widths; if we are here, that
1330 // means the signed type is larger than the unsigned type, so
1331 // use the signed type.
1333 RHS
= (*doRHSCast
)(S
, RHS
.get(), LHSType
);
1335 } else if (!IsCompAssign
)
1336 LHS
= (*doLHSCast
)(S
, LHS
.get(), RHSType
);
1339 // The signed type is higher-ranked than the unsigned type,
1340 // but isn't actually any bigger (like unsigned int and long
1341 // on most 32-bit systems). Use the unsigned type corresponding
1342 // to the signed type.
1344 S
.Context
.getCorrespondingUnsignedType(LHSSigned
? LHSType
: RHSType
);
1345 RHS
= (*doRHSCast
)(S
, RHS
.get(), result
);
1347 LHS
= (*doLHSCast
)(S
, LHS
.get(), result
);
1352 /// Handle conversions with GCC complex int extension. Helper function
1353 /// of UsualArithmeticConversions()
1354 static QualType
handleComplexIntConversion(Sema
&S
, ExprResult
&LHS
,
1355 ExprResult
&RHS
, QualType LHSType
,
1357 bool IsCompAssign
) {
1358 const ComplexType
*LHSComplexInt
= LHSType
->getAsComplexIntegerType();
1359 const ComplexType
*RHSComplexInt
= RHSType
->getAsComplexIntegerType();
1361 if (LHSComplexInt
&& RHSComplexInt
) {
1362 QualType LHSEltType
= LHSComplexInt
->getElementType();
1363 QualType RHSEltType
= RHSComplexInt
->getElementType();
1364 QualType ScalarType
=
1365 handleIntegerConversion
<doComplexIntegralCast
, doComplexIntegralCast
>
1366 (S
, LHS
, RHS
, LHSEltType
, RHSEltType
, IsCompAssign
);
1368 return S
.Context
.getComplexType(ScalarType
);
1371 if (LHSComplexInt
) {
1372 QualType LHSEltType
= LHSComplexInt
->getElementType();
1373 QualType ScalarType
=
1374 handleIntegerConversion
<doComplexIntegralCast
, doIntegralCast
>
1375 (S
, LHS
, RHS
, LHSEltType
, RHSType
, IsCompAssign
);
1376 QualType ComplexType
= S
.Context
.getComplexType(ScalarType
);
1377 RHS
= S
.ImpCastExprToType(RHS
.get(), ComplexType
,
1378 CK_IntegralRealToComplex
);
1383 assert(RHSComplexInt
);
1385 QualType RHSEltType
= RHSComplexInt
->getElementType();
1386 QualType ScalarType
=
1387 handleIntegerConversion
<doIntegralCast
, doComplexIntegralCast
>
1388 (S
, LHS
, RHS
, LHSType
, RHSEltType
, IsCompAssign
);
1389 QualType ComplexType
= S
.Context
.getComplexType(ScalarType
);
1392 LHS
= S
.ImpCastExprToType(LHS
.get(), ComplexType
,
1393 CK_IntegralRealToComplex
);
1397 /// Return the rank of a given fixed point or integer type. The value itself
1398 /// doesn't matter, but the values must be increasing with proper increasing
1399 /// rank as described in N1169 4.1.1.
1400 static unsigned GetFixedPointRank(QualType Ty
) {
1401 const auto *BTy
= Ty
->getAs
<BuiltinType
>();
1402 assert(BTy
&& "Expected a builtin type.");
1404 switch (BTy
->getKind()) {
1405 case BuiltinType::ShortFract
:
1406 case BuiltinType::UShortFract
:
1407 case BuiltinType::SatShortFract
:
1408 case BuiltinType::SatUShortFract
:
1410 case BuiltinType::Fract
:
1411 case BuiltinType::UFract
:
1412 case BuiltinType::SatFract
:
1413 case BuiltinType::SatUFract
:
1415 case BuiltinType::LongFract
:
1416 case BuiltinType::ULongFract
:
1417 case BuiltinType::SatLongFract
:
1418 case BuiltinType::SatULongFract
:
1420 case BuiltinType::ShortAccum
:
1421 case BuiltinType::UShortAccum
:
1422 case BuiltinType::SatShortAccum
:
1423 case BuiltinType::SatUShortAccum
:
1425 case BuiltinType::Accum
:
1426 case BuiltinType::UAccum
:
1427 case BuiltinType::SatAccum
:
1428 case BuiltinType::SatUAccum
:
1430 case BuiltinType::LongAccum
:
1431 case BuiltinType::ULongAccum
:
1432 case BuiltinType::SatLongAccum
:
1433 case BuiltinType::SatULongAccum
:
1436 if (BTy
->isInteger())
1438 llvm_unreachable("Unexpected fixed point or integer type");
1442 /// handleFixedPointConversion - Fixed point operations between fixed
1443 /// point types and integers or other fixed point types do not fall under
1444 /// usual arithmetic conversion since these conversions could result in loss
1445 /// of precsision (N1169 4.1.4). These operations should be calculated with
1446 /// the full precision of their result type (N1169 4.1.6.2.1).
1447 static QualType
handleFixedPointConversion(Sema
&S
, QualType LHSTy
,
1449 assert((LHSTy
->isFixedPointType() || RHSTy
->isFixedPointType()) &&
1450 "Expected at least one of the operands to be a fixed point type");
1451 assert((LHSTy
->isFixedPointOrIntegerType() ||
1452 RHSTy
->isFixedPointOrIntegerType()) &&
1453 "Special fixed point arithmetic operation conversions are only "
1454 "applied to ints or other fixed point types");
1456 // If one operand has signed fixed-point type and the other operand has
1457 // unsigned fixed-point type, then the unsigned fixed-point operand is
1458 // converted to its corresponding signed fixed-point type and the resulting
1459 // type is the type of the converted operand.
1460 if (RHSTy
->isSignedFixedPointType() && LHSTy
->isUnsignedFixedPointType())
1461 LHSTy
= S
.Context
.getCorrespondingSignedFixedPointType(LHSTy
);
1462 else if (RHSTy
->isUnsignedFixedPointType() && LHSTy
->isSignedFixedPointType())
1463 RHSTy
= S
.Context
.getCorrespondingSignedFixedPointType(RHSTy
);
1465 // The result type is the type with the highest rank, whereby a fixed-point
1466 // conversion rank is always greater than an integer conversion rank; if the
1467 // type of either of the operands is a saturating fixedpoint type, the result
1468 // type shall be the saturating fixed-point type corresponding to the type
1469 // with the highest rank; the resulting value is converted (taking into
1470 // account rounding and overflow) to the precision of the resulting type.
1471 // Same ranks between signed and unsigned types are resolved earlier, so both
1472 // types are either signed or both unsigned at this point.
1473 unsigned LHSTyRank
= GetFixedPointRank(LHSTy
);
1474 unsigned RHSTyRank
= GetFixedPointRank(RHSTy
);
1476 QualType ResultTy
= LHSTyRank
> RHSTyRank
? LHSTy
: RHSTy
;
1478 if (LHSTy
->isSaturatedFixedPointType() || RHSTy
->isSaturatedFixedPointType())
1479 ResultTy
= S
.Context
.getCorrespondingSaturatedType(ResultTy
);
1484 /// Check that the usual arithmetic conversions can be performed on this pair of
1485 /// expressions that might be of enumeration type.
1486 static void checkEnumArithmeticConversions(Sema
&S
, Expr
*LHS
, Expr
*RHS
,
1488 Sema::ArithConvKind ACK
) {
1489 // C++2a [expr.arith.conv]p1:
1490 // If one operand is of enumeration type and the other operand is of a
1491 // different enumeration type or a floating-point type, this behavior is
1492 // deprecated ([depr.arith.conv.enum]).
1494 // Warn on this in all language modes. Produce a deprecation warning in C++20.
1495 // Eventually we will presumably reject these cases (in C++23 onwards?).
1496 QualType L
= LHS
->getType(), R
= RHS
->getType();
1497 bool LEnum
= L
->isUnscopedEnumerationType(),
1498 REnum
= R
->isUnscopedEnumerationType();
1499 bool IsCompAssign
= ACK
== Sema::ACK_CompAssign
;
1500 if ((!IsCompAssign
&& LEnum
&& R
->isFloatingType()) ||
1501 (REnum
&& L
->isFloatingType())) {
1502 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus20
1503 ? diag::warn_arith_conv_enum_float_cxx20
1504 : diag::warn_arith_conv_enum_float
)
1505 << LHS
->getSourceRange() << RHS
->getSourceRange()
1506 << (int)ACK
<< LEnum
<< L
<< R
;
1507 } else if (!IsCompAssign
&& LEnum
&& REnum
&&
1508 !S
.Context
.hasSameUnqualifiedType(L
, R
)) {
1510 if (!L
->castAs
<EnumType
>()->getDecl()->hasNameForLinkage() ||
1511 !R
->castAs
<EnumType
>()->getDecl()->hasNameForLinkage()) {
1512 // If either enumeration type is unnamed, it's less likely that the
1513 // user cares about this, but this situation is still deprecated in
1514 // C++2a. Use a different warning group.
1515 DiagID
= S
.getLangOpts().CPlusPlus20
1516 ? diag::warn_arith_conv_mixed_anon_enum_types_cxx20
1517 : diag::warn_arith_conv_mixed_anon_enum_types
;
1518 } else if (ACK
== Sema::ACK_Conditional
) {
1519 // Conditional expressions are separated out because they have
1520 // historically had a different warning flag.
1521 DiagID
= S
.getLangOpts().CPlusPlus20
1522 ? diag::warn_conditional_mixed_enum_types_cxx20
1523 : diag::warn_conditional_mixed_enum_types
;
1524 } else if (ACK
== Sema::ACK_Comparison
) {
1525 // Comparison expressions are separated out because they have
1526 // historically had a different warning flag.
1527 DiagID
= S
.getLangOpts().CPlusPlus20
1528 ? diag::warn_comparison_mixed_enum_types_cxx20
1529 : diag::warn_comparison_mixed_enum_types
;
1531 DiagID
= S
.getLangOpts().CPlusPlus20
1532 ? diag::warn_arith_conv_mixed_enum_types_cxx20
1533 : diag::warn_arith_conv_mixed_enum_types
;
1535 S
.Diag(Loc
, DiagID
) << LHS
->getSourceRange() << RHS
->getSourceRange()
1536 << (int)ACK
<< L
<< R
;
1540 /// UsualArithmeticConversions - Performs various conversions that are common to
1541 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1542 /// routine returns the first non-arithmetic type found. The client is
1543 /// responsible for emitting appropriate error diagnostics.
1544 QualType
Sema::UsualArithmeticConversions(ExprResult
&LHS
, ExprResult
&RHS
,
1546 ArithConvKind ACK
) {
1547 checkEnumArithmeticConversions(*this, LHS
.get(), RHS
.get(), Loc
, ACK
);
1549 if (ACK
!= ACK_CompAssign
) {
1550 LHS
= UsualUnaryConversions(LHS
.get());
1551 if (LHS
.isInvalid())
1555 RHS
= UsualUnaryConversions(RHS
.get());
1556 if (RHS
.isInvalid())
1559 // For conversion purposes, we ignore any qualifiers.
1560 // For example, "const float" and "float" are equivalent.
1561 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
1562 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
1564 // For conversion purposes, we ignore any atomic qualifier on the LHS.
1565 if (const AtomicType
*AtomicLHS
= LHSType
->getAs
<AtomicType
>())
1566 LHSType
= AtomicLHS
->getValueType();
1568 // If both types are identical, no conversion is needed.
1569 if (Context
.hasSameType(LHSType
, RHSType
))
1570 return Context
.getCommonSugaredType(LHSType
, RHSType
);
1572 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1573 // The caller can deal with this (e.g. pointer + int).
1574 if (!LHSType
->isArithmeticType() || !RHSType
->isArithmeticType())
1577 // Apply unary and bitfield promotions to the LHS's type.
1578 QualType LHSUnpromotedType
= LHSType
;
1579 if (Context
.isPromotableIntegerType(LHSType
))
1580 LHSType
= Context
.getPromotedIntegerType(LHSType
);
1581 QualType LHSBitfieldPromoteTy
= Context
.isPromotableBitField(LHS
.get());
1582 if (!LHSBitfieldPromoteTy
.isNull())
1583 LHSType
= LHSBitfieldPromoteTy
;
1584 if (LHSType
!= LHSUnpromotedType
&& ACK
!= ACK_CompAssign
)
1585 LHS
= ImpCastExprToType(LHS
.get(), LHSType
, CK_IntegralCast
);
1587 // If both types are identical, no conversion is needed.
1588 if (Context
.hasSameType(LHSType
, RHSType
))
1589 return Context
.getCommonSugaredType(LHSType
, RHSType
);
1591 // At this point, we have two different arithmetic types.
1593 // Diagnose attempts to convert between __ibm128, __float128 and long double
1594 // where such conversions currently can't be handled.
1595 if (unsupportedTypeConversion(*this, LHSType
, RHSType
))
1598 // Handle complex types first (C99 6.3.1.8p1).
1599 if (LHSType
->isComplexType() || RHSType
->isComplexType())
1600 return handleComplexConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1601 ACK
== ACK_CompAssign
);
1603 // Now handle "real" floating types (i.e. float, double, long double).
1604 if (LHSType
->isRealFloatingType() || RHSType
->isRealFloatingType())
1605 return handleFloatConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1606 ACK
== ACK_CompAssign
);
1608 // Handle GCC complex int extension.
1609 if (LHSType
->isComplexIntegerType() || RHSType
->isComplexIntegerType())
1610 return handleComplexIntConversion(*this, LHS
, RHS
, LHSType
, RHSType
,
1611 ACK
== ACK_CompAssign
);
1613 if (LHSType
->isFixedPointType() || RHSType
->isFixedPointType())
1614 return handleFixedPointConversion(*this, LHSType
, RHSType
);
1616 // Finally, we have two differing integer types.
1617 return handleIntegerConversion
<doIntegralCast
, doIntegralCast
>
1618 (*this, LHS
, RHS
, LHSType
, RHSType
, ACK
== ACK_CompAssign
);
1621 //===----------------------------------------------------------------------===//
1622 // Semantic Analysis for various Expression Types
1623 //===----------------------------------------------------------------------===//
1626 ExprResult
Sema::ActOnGenericSelectionExpr(
1627 SourceLocation KeyLoc
, SourceLocation DefaultLoc
, SourceLocation RParenLoc
,
1628 bool PredicateIsExpr
, void *ControllingExprOrType
,
1629 ArrayRef
<ParsedType
> ArgTypes
, ArrayRef
<Expr
*> ArgExprs
) {
1630 unsigned NumAssocs
= ArgTypes
.size();
1631 assert(NumAssocs
== ArgExprs
.size());
1633 TypeSourceInfo
**Types
= new TypeSourceInfo
*[NumAssocs
];
1634 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1636 (void) GetTypeFromParser(ArgTypes
[i
], &Types
[i
]);
1641 // If we have a controlling type, we need to convert it from a parsed type
1642 // into a semantic type and then pass that along.
1643 if (!PredicateIsExpr
) {
1644 TypeSourceInfo
*ControllingType
;
1645 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(ControllingExprOrType
),
1647 assert(ControllingType
&& "couldn't get the type out of the parser");
1648 ControllingExprOrType
= ControllingType
;
1651 ExprResult ER
= CreateGenericSelectionExpr(
1652 KeyLoc
, DefaultLoc
, RParenLoc
, PredicateIsExpr
, ControllingExprOrType
,
1653 llvm::ArrayRef(Types
, NumAssocs
), ArgExprs
);
1658 ExprResult
Sema::CreateGenericSelectionExpr(
1659 SourceLocation KeyLoc
, SourceLocation DefaultLoc
, SourceLocation RParenLoc
,
1660 bool PredicateIsExpr
, void *ControllingExprOrType
,
1661 ArrayRef
<TypeSourceInfo
*> Types
, ArrayRef
<Expr
*> Exprs
) {
1662 unsigned NumAssocs
= Types
.size();
1663 assert(NumAssocs
== Exprs
.size());
1664 assert(ControllingExprOrType
&&
1665 "Must have either a controlling expression or a controlling type");
1667 Expr
*ControllingExpr
= nullptr;
1668 TypeSourceInfo
*ControllingType
= nullptr;
1669 if (PredicateIsExpr
) {
1670 // Decay and strip qualifiers for the controlling expression type, and
1671 // handle placeholder type replacement. See committee discussion from WG14
1673 EnterExpressionEvaluationContext
Unevaluated(
1674 *this, Sema::ExpressionEvaluationContext::Unevaluated
);
1675 ExprResult R
= DefaultFunctionArrayLvalueConversion(
1676 reinterpret_cast<Expr
*>(ControllingExprOrType
));
1679 ControllingExpr
= R
.get();
1681 // The extension form uses the type directly rather than converting it.
1682 ControllingType
= reinterpret_cast<TypeSourceInfo
*>(ControllingExprOrType
);
1683 if (!ControllingType
)
1687 bool TypeErrorFound
= false,
1688 IsResultDependent
= ControllingExpr
1689 ? ControllingExpr
->isTypeDependent()
1690 : ControllingType
->getType()->isDependentType(),
1691 ContainsUnexpandedParameterPack
=
1693 ? ControllingExpr
->containsUnexpandedParameterPack()
1694 : ControllingType
->getType()->containsUnexpandedParameterPack();
1696 // The controlling expression is an unevaluated operand, so side effects are
1697 // likely unintended.
1698 if (!inTemplateInstantiation() && !IsResultDependent
&& ControllingExpr
&&
1699 ControllingExpr
->HasSideEffects(Context
, false))
1700 Diag(ControllingExpr
->getExprLoc(),
1701 diag::warn_side_effects_unevaluated_context
);
1703 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1704 if (Exprs
[i
]->containsUnexpandedParameterPack())
1705 ContainsUnexpandedParameterPack
= true;
1708 if (Types
[i
]->getType()->containsUnexpandedParameterPack())
1709 ContainsUnexpandedParameterPack
= true;
1711 if (Types
[i
]->getType()->isDependentType()) {
1712 IsResultDependent
= true;
1714 // We relax the restriction on use of incomplete types and non-object
1715 // types with the type-based extension of _Generic. Allowing incomplete
1716 // objects means those can be used as "tags" for a type-safe way to map
1717 // to a value. Similarly, matching on function types rather than
1718 // function pointer types can be useful. However, the restriction on VM
1719 // types makes sense to retain as there are open questions about how
1720 // the selection can be made at compile time.
1722 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1723 // complete object type other than a variably modified type."
1725 if (ControllingExpr
&& Types
[i
]->getType()->isIncompleteType())
1726 D
= diag::err_assoc_type_incomplete
;
1727 else if (ControllingExpr
&& !Types
[i
]->getType()->isObjectType())
1728 D
= diag::err_assoc_type_nonobject
;
1729 else if (Types
[i
]->getType()->isVariablyModifiedType())
1730 D
= diag::err_assoc_type_variably_modified
;
1731 else if (ControllingExpr
) {
1732 // Because the controlling expression undergoes lvalue conversion,
1733 // array conversion, and function conversion, an association which is
1734 // of array type, function type, or is qualified can never be
1735 // reached. We will warn about this so users are less surprised by
1736 // the unreachable association. However, we don't have to handle
1737 // function types; that's not an object type, so it's handled above.
1739 // The logic is somewhat different for C++ because C++ has different
1740 // lvalue to rvalue conversion rules than C. [conv.lvalue]p1 says,
1741 // If T is a non-class type, the type of the prvalue is the cv-
1742 // unqualified version of T. Otherwise, the type of the prvalue is T.
1743 // The result of these rules is that all qualified types in an
1744 // association in C are unreachable, and in C++, only qualified non-
1745 // class types are unreachable.
1747 // NB: this does not apply when the first operand is a type rather
1748 // than an expression, because the type form does not undergo
1750 unsigned Reason
= 0;
1751 QualType QT
= Types
[i
]->getType();
1752 if (QT
->isArrayType())
1754 else if (QT
.hasQualifiers() &&
1755 (!LangOpts
.CPlusPlus
|| !QT
->isRecordType()))
1759 Diag(Types
[i
]->getTypeLoc().getBeginLoc(),
1760 diag::warn_unreachable_association
)
1761 << QT
<< (Reason
- 1);
1765 Diag(Types
[i
]->getTypeLoc().getBeginLoc(), D
)
1766 << Types
[i
]->getTypeLoc().getSourceRange()
1767 << Types
[i
]->getType();
1768 TypeErrorFound
= true;
1771 // C11 6.5.1.1p2 "No two generic associations in the same generic
1772 // selection shall specify compatible types."
1773 for (unsigned j
= i
+1; j
< NumAssocs
; ++j
)
1774 if (Types
[j
] && !Types
[j
]->getType()->isDependentType() &&
1775 Context
.typesAreCompatible(Types
[i
]->getType(),
1776 Types
[j
]->getType())) {
1777 Diag(Types
[j
]->getTypeLoc().getBeginLoc(),
1778 diag::err_assoc_compatible_types
)
1779 << Types
[j
]->getTypeLoc().getSourceRange()
1780 << Types
[j
]->getType()
1781 << Types
[i
]->getType();
1782 Diag(Types
[i
]->getTypeLoc().getBeginLoc(),
1783 diag::note_compat_assoc
)
1784 << Types
[i
]->getTypeLoc().getSourceRange()
1785 << Types
[i
]->getType();
1786 TypeErrorFound
= true;
1794 // If we determined that the generic selection is result-dependent, don't
1795 // try to compute the result expression.
1796 if (IsResultDependent
) {
1797 if (ControllingExpr
)
1798 return GenericSelectionExpr::Create(Context
, KeyLoc
, ControllingExpr
,
1799 Types
, Exprs
, DefaultLoc
, RParenLoc
,
1800 ContainsUnexpandedParameterPack
);
1801 return GenericSelectionExpr::Create(Context
, KeyLoc
, ControllingType
, Types
,
1802 Exprs
, DefaultLoc
, RParenLoc
,
1803 ContainsUnexpandedParameterPack
);
1806 SmallVector
<unsigned, 1> CompatIndices
;
1807 unsigned DefaultIndex
= -1U;
1808 // Look at the canonical type of the controlling expression in case it was a
1809 // deduced type like __auto_type. However, when issuing diagnostics, use the
1810 // type the user wrote in source rather than the canonical one.
1811 for (unsigned i
= 0; i
< NumAssocs
; ++i
) {
1814 else if (ControllingExpr
&&
1815 Context
.typesAreCompatible(
1816 ControllingExpr
->getType().getCanonicalType(),
1817 Types
[i
]->getType()))
1818 CompatIndices
.push_back(i
);
1819 else if (ControllingType
&&
1820 Context
.typesAreCompatible(
1821 ControllingType
->getType().getCanonicalType(),
1822 Types
[i
]->getType()))
1823 CompatIndices
.push_back(i
);
1826 auto GetControllingRangeAndType
= [](Expr
*ControllingExpr
,
1827 TypeSourceInfo
*ControllingType
) {
1828 // We strip parens here because the controlling expression is typically
1829 // parenthesized in macro definitions.
1830 if (ControllingExpr
)
1831 ControllingExpr
= ControllingExpr
->IgnoreParens();
1833 SourceRange SR
= ControllingExpr
1834 ? ControllingExpr
->getSourceRange()
1835 : ControllingType
->getTypeLoc().getSourceRange();
1836 QualType QT
= ControllingExpr
? ControllingExpr
->getType()
1837 : ControllingType
->getType();
1839 return std::make_pair(SR
, QT
);
1842 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1843 // type compatible with at most one of the types named in its generic
1844 // association list."
1845 if (CompatIndices
.size() > 1) {
1846 auto P
= GetControllingRangeAndType(ControllingExpr
, ControllingType
);
1847 SourceRange SR
= P
.first
;
1848 Diag(SR
.getBegin(), diag::err_generic_sel_multi_match
)
1849 << SR
<< P
.second
<< (unsigned)CompatIndices
.size();
1850 for (unsigned I
: CompatIndices
) {
1851 Diag(Types
[I
]->getTypeLoc().getBeginLoc(),
1852 diag::note_compat_assoc
)
1853 << Types
[I
]->getTypeLoc().getSourceRange()
1854 << Types
[I
]->getType();
1859 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1860 // its controlling expression shall have type compatible with exactly one of
1861 // the types named in its generic association list."
1862 if (DefaultIndex
== -1U && CompatIndices
.size() == 0) {
1863 auto P
= GetControllingRangeAndType(ControllingExpr
, ControllingType
);
1864 SourceRange SR
= P
.first
;
1865 Diag(SR
.getBegin(), diag::err_generic_sel_no_match
) << SR
<< P
.second
;
1869 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1870 // type name that is compatible with the type of the controlling expression,
1871 // then the result expression of the generic selection is the expression
1872 // in that generic association. Otherwise, the result expression of the
1873 // generic selection is the expression in the default generic association."
1874 unsigned ResultIndex
=
1875 CompatIndices
.size() ? CompatIndices
[0] : DefaultIndex
;
1877 if (ControllingExpr
) {
1878 return GenericSelectionExpr::Create(
1879 Context
, KeyLoc
, ControllingExpr
, Types
, Exprs
, DefaultLoc
, RParenLoc
,
1880 ContainsUnexpandedParameterPack
, ResultIndex
);
1882 return GenericSelectionExpr::Create(
1883 Context
, KeyLoc
, ControllingType
, Types
, Exprs
, DefaultLoc
, RParenLoc
,
1884 ContainsUnexpandedParameterPack
, ResultIndex
);
1887 static PredefinedExpr::IdentKind
getPredefinedExprKind(tok::TokenKind Kind
) {
1890 llvm_unreachable("unexpected TokenKind");
1891 case tok::kw___func__
:
1892 return PredefinedExpr::Func
; // [C99 6.4.2.2]
1893 case tok::kw___FUNCTION__
:
1894 return PredefinedExpr::Function
;
1895 case tok::kw___FUNCDNAME__
:
1896 return PredefinedExpr::FuncDName
; // [MS]
1897 case tok::kw___FUNCSIG__
:
1898 return PredefinedExpr::FuncSig
; // [MS]
1899 case tok::kw_L__FUNCTION__
:
1900 return PredefinedExpr::LFunction
; // [MS]
1901 case tok::kw_L__FUNCSIG__
:
1902 return PredefinedExpr::LFuncSig
; // [MS]
1903 case tok::kw___PRETTY_FUNCTION__
:
1904 return PredefinedExpr::PrettyFunction
; // [GNU]
1908 /// getPredefinedExprDecl - Returns Decl of a given DeclContext that can be used
1909 /// to determine the value of a PredefinedExpr. This can be either a
1910 /// block, lambda, captured statement, function, otherwise a nullptr.
1911 static Decl
*getPredefinedExprDecl(DeclContext
*DC
) {
1912 while (DC
&& !isa
<BlockDecl
, CapturedDecl
, FunctionDecl
, ObjCMethodDecl
>(DC
))
1913 DC
= DC
->getParent();
1914 return cast_or_null
<Decl
>(DC
);
1917 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1918 /// location of the token and the offset of the ud-suffix within it.
1919 static SourceLocation
getUDSuffixLoc(Sema
&S
, SourceLocation TokLoc
,
1921 return Lexer::AdvanceToTokenCharacter(TokLoc
, Offset
, S
.getSourceManager(),
1925 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1926 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1927 static ExprResult
BuildCookedLiteralOperatorCall(Sema
&S
, Scope
*Scope
,
1928 IdentifierInfo
*UDSuffix
,
1929 SourceLocation UDSuffixLoc
,
1930 ArrayRef
<Expr
*> Args
,
1931 SourceLocation LitEndLoc
) {
1932 assert(Args
.size() <= 2 && "too many arguments for literal operator");
1935 for (unsigned ArgIdx
= 0; ArgIdx
!= Args
.size(); ++ArgIdx
) {
1936 ArgTy
[ArgIdx
] = Args
[ArgIdx
]->getType();
1937 if (ArgTy
[ArgIdx
]->isArrayType())
1938 ArgTy
[ArgIdx
] = S
.Context
.getArrayDecayedType(ArgTy
[ArgIdx
]);
1941 DeclarationName OpName
=
1942 S
.Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
1943 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
1944 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
1946 LookupResult
R(S
, OpName
, UDSuffixLoc
, Sema::LookupOrdinaryName
);
1947 if (S
.LookupLiteralOperator(Scope
, R
, llvm::ArrayRef(ArgTy
, Args
.size()),
1948 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1949 /*AllowStringTemplatePack*/ false,
1950 /*DiagnoseMissing*/ true) == Sema::LOLR_Error
)
1953 return S
.BuildLiteralOperatorCall(R
, OpNameInfo
, Args
, LitEndLoc
);
1956 ExprResult
Sema::ActOnUnevaluatedStringLiteral(ArrayRef
<Token
> StringToks
) {
1957 // StringToks needs backing storage as it doesn't hold array elements itself
1958 std::vector
<Token
> ExpandedToks
;
1959 if (getLangOpts().MicrosoftExt
)
1960 StringToks
= ExpandedToks
= ExpandFunctionLocalPredefinedMacros(StringToks
);
1962 StringLiteralParser
Literal(StringToks
, PP
,
1963 StringLiteralEvalMethod::Unevaluated
);
1964 if (Literal
.hadError
)
1967 SmallVector
<SourceLocation
, 4> StringTokLocs
;
1968 for (const Token
&Tok
: StringToks
)
1969 StringTokLocs
.push_back(Tok
.getLocation());
1971 StringLiteral
*Lit
= StringLiteral::Create(
1972 Context
, Literal
.GetString(), StringLiteral::Unevaluated
, false, {},
1973 &StringTokLocs
[0], StringTokLocs
.size());
1975 if (!Literal
.getUDSuffix().empty()) {
1976 SourceLocation UDSuffixLoc
=
1977 getUDSuffixLoc(*this, StringTokLocs
[Literal
.getUDSuffixToken()],
1978 Literal
.getUDSuffixOffset());
1979 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_string_udl
));
1986 Sema::ExpandFunctionLocalPredefinedMacros(ArrayRef
<Token
> Toks
) {
1987 // MSVC treats some predefined identifiers (e.g. __FUNCTION__) as function
1988 // local macros that expand to string literals that may be concatenated.
1989 // These macros are expanded here (in Sema), because StringLiteralParser
1990 // (in Lex) doesn't know the enclosing function (because it hasn't been
1992 assert(getLangOpts().MicrosoftExt
);
1994 // Note: Although function local macros are defined only inside functions,
1995 // we ensure a valid `CurrentDecl` even outside of a function. This allows
1996 // expansion of macros into empty string literals without additional checks.
1997 Decl
*CurrentDecl
= getPredefinedExprDecl(CurContext
);
1999 CurrentDecl
= Context
.getTranslationUnitDecl();
2001 std::vector
<Token
> ExpandedToks
;
2002 ExpandedToks
.reserve(Toks
.size());
2003 for (const Token
&Tok
: Toks
) {
2004 if (!isFunctionLocalStringLiteralMacro(Tok
.getKind(), getLangOpts())) {
2005 assert(tok::isStringLiteral(Tok
.getKind()));
2006 ExpandedToks
.emplace_back(Tok
);
2009 if (isa
<TranslationUnitDecl
>(CurrentDecl
))
2010 Diag(Tok
.getLocation(), diag::ext_predef_outside_function
);
2011 // Stringify predefined expression
2012 Diag(Tok
.getLocation(), diag::ext_string_literal_from_predefined
)
2014 SmallString
<64> Str
;
2015 llvm::raw_svector_ostream
OS(Str
);
2016 Token
&Exp
= ExpandedToks
.emplace_back();
2018 if (Tok
.getKind() == tok::kw_L__FUNCTION__
||
2019 Tok
.getKind() == tok::kw_L__FUNCSIG__
) {
2021 Exp
.setKind(tok::wide_string_literal
);
2023 Exp
.setKind(tok::string_literal
);
2026 << Lexer::Stringify(PredefinedExpr::ComputeName(
2027 getPredefinedExprKind(Tok
.getKind()), CurrentDecl
))
2029 PP
.CreateString(OS
.str(), Exp
, Tok
.getLocation(), Tok
.getEndLoc());
2031 return ExpandedToks
;
2034 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
2035 /// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
2036 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
2037 /// multiple tokens. However, the common case is that StringToks points to one
2041 Sema::ActOnStringLiteral(ArrayRef
<Token
> StringToks
, Scope
*UDLScope
) {
2042 assert(!StringToks
.empty() && "Must have at least one string!");
2044 // StringToks needs backing storage as it doesn't hold array elements itself
2045 std::vector
<Token
> ExpandedToks
;
2046 if (getLangOpts().MicrosoftExt
)
2047 StringToks
= ExpandedToks
= ExpandFunctionLocalPredefinedMacros(StringToks
);
2049 StringLiteralParser
Literal(StringToks
, PP
);
2050 if (Literal
.hadError
)
2053 SmallVector
<SourceLocation
, 4> StringTokLocs
;
2054 for (const Token
&Tok
: StringToks
)
2055 StringTokLocs
.push_back(Tok
.getLocation());
2057 QualType CharTy
= Context
.CharTy
;
2058 StringLiteral::StringKind Kind
= StringLiteral::Ordinary
;
2059 if (Literal
.isWide()) {
2060 CharTy
= Context
.getWideCharType();
2061 Kind
= StringLiteral::Wide
;
2062 } else if (Literal
.isUTF8()) {
2063 if (getLangOpts().Char8
)
2064 CharTy
= Context
.Char8Ty
;
2065 Kind
= StringLiteral::UTF8
;
2066 } else if (Literal
.isUTF16()) {
2067 CharTy
= Context
.Char16Ty
;
2068 Kind
= StringLiteral::UTF16
;
2069 } else if (Literal
.isUTF32()) {
2070 CharTy
= Context
.Char32Ty
;
2071 Kind
= StringLiteral::UTF32
;
2072 } else if (Literal
.isPascal()) {
2073 CharTy
= Context
.UnsignedCharTy
;
2076 // Warn on initializing an array of char from a u8 string literal; this
2077 // becomes ill-formed in C++2a.
2078 if (getLangOpts().CPlusPlus
&& !getLangOpts().CPlusPlus20
&&
2079 !getLangOpts().Char8
&& Kind
== StringLiteral::UTF8
) {
2080 Diag(StringTokLocs
.front(), diag::warn_cxx20_compat_utf8_string
);
2082 // Create removals for all 'u8' prefixes in the string literal(s). This
2083 // ensures C++2a compatibility (but may change the program behavior when
2084 // built by non-Clang compilers for which the execution character set is
2085 // not always UTF-8).
2086 auto RemovalDiag
= PDiag(diag::note_cxx20_compat_utf8_string_remove_u8
);
2087 SourceLocation RemovalDiagLoc
;
2088 for (const Token
&Tok
: StringToks
) {
2089 if (Tok
.getKind() == tok::utf8_string_literal
) {
2090 if (RemovalDiagLoc
.isInvalid())
2091 RemovalDiagLoc
= Tok
.getLocation();
2092 RemovalDiag
<< FixItHint::CreateRemoval(CharSourceRange::getCharRange(
2094 Lexer::AdvanceToTokenCharacter(Tok
.getLocation(), 2,
2095 getSourceManager(), getLangOpts())));
2098 Diag(RemovalDiagLoc
, RemovalDiag
);
2102 Context
.getStringLiteralArrayType(CharTy
, Literal
.GetNumStringChars());
2104 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
2105 StringLiteral
*Lit
= StringLiteral::Create(Context
, Literal
.GetString(),
2106 Kind
, Literal
.Pascal
, StrTy
,
2108 StringTokLocs
.size());
2109 if (Literal
.getUDSuffix().empty())
2112 // We're building a user-defined literal.
2113 IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
2114 SourceLocation UDSuffixLoc
=
2115 getUDSuffixLoc(*this, StringTokLocs
[Literal
.getUDSuffixToken()],
2116 Literal
.getUDSuffixOffset());
2118 // Make sure we're allowed user-defined literals here.
2120 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_string_udl
));
2122 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
2123 // operator "" X (str, len)
2124 QualType SizeType
= Context
.getSizeType();
2126 DeclarationName OpName
=
2127 Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
2128 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
2129 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
2131 QualType ArgTy
[] = {
2132 Context
.getArrayDecayedType(StrTy
), SizeType
2135 LookupResult
R(*this, OpName
, UDSuffixLoc
, LookupOrdinaryName
);
2136 switch (LookupLiteralOperator(UDLScope
, R
, ArgTy
,
2137 /*AllowRaw*/ false, /*AllowTemplate*/ true,
2138 /*AllowStringTemplatePack*/ true,
2139 /*DiagnoseMissing*/ true, Lit
)) {
2142 llvm::APInt
Len(Context
.getIntWidth(SizeType
), Literal
.GetNumStringChars());
2143 IntegerLiteral
*LenArg
= IntegerLiteral::Create(Context
, Len
, SizeType
,
2145 Expr
*Args
[] = { Lit
, LenArg
};
2147 return BuildLiteralOperatorCall(R
, OpNameInfo
, Args
, StringTokLocs
.back());
2150 case LOLR_Template
: {
2151 TemplateArgumentListInfo ExplicitArgs
;
2152 TemplateArgument
Arg(Lit
);
2153 TemplateArgumentLocInfo
ArgInfo(Lit
);
2154 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
2155 return BuildLiteralOperatorCall(R
, OpNameInfo
, std::nullopt
,
2156 StringTokLocs
.back(), &ExplicitArgs
);
2159 case LOLR_StringTemplatePack
: {
2160 TemplateArgumentListInfo ExplicitArgs
;
2162 unsigned CharBits
= Context
.getIntWidth(CharTy
);
2163 bool CharIsUnsigned
= CharTy
->isUnsignedIntegerType();
2164 llvm::APSInt
Value(CharBits
, CharIsUnsigned
);
2166 TemplateArgument
TypeArg(CharTy
);
2167 TemplateArgumentLocInfo
TypeArgInfo(Context
.getTrivialTypeSourceInfo(CharTy
));
2168 ExplicitArgs
.addArgument(TemplateArgumentLoc(TypeArg
, TypeArgInfo
));
2170 for (unsigned I
= 0, N
= Lit
->getLength(); I
!= N
; ++I
) {
2171 Value
= Lit
->getCodeUnit(I
);
2172 TemplateArgument
Arg(Context
, Value
, CharTy
);
2173 TemplateArgumentLocInfo ArgInfo
;
2174 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
2176 return BuildLiteralOperatorCall(R
, OpNameInfo
, std::nullopt
,
2177 StringTokLocs
.back(), &ExplicitArgs
);
2180 case LOLR_ErrorNoDiagnostic
:
2181 llvm_unreachable("unexpected literal operator lookup result");
2185 llvm_unreachable("unexpected literal operator lookup result");
2189 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2191 const CXXScopeSpec
*SS
) {
2192 DeclarationNameInfo
NameInfo(D
->getDeclName(), Loc
);
2193 return BuildDeclRefExpr(D
, Ty
, VK
, NameInfo
, SS
);
2197 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2198 const DeclarationNameInfo
&NameInfo
,
2199 const CXXScopeSpec
*SS
, NamedDecl
*FoundD
,
2200 SourceLocation TemplateKWLoc
,
2201 const TemplateArgumentListInfo
*TemplateArgs
) {
2202 NestedNameSpecifierLoc NNS
=
2203 SS
? SS
->getWithLocInContext(Context
) : NestedNameSpecifierLoc();
2204 return BuildDeclRefExpr(D
, Ty
, VK
, NameInfo
, NNS
, FoundD
, TemplateKWLoc
,
2208 // CUDA/HIP: Check whether a captured reference variable is referencing a
2209 // host variable in a device or host device lambda.
2210 static bool isCapturingReferenceToHostVarInCUDADeviceLambda(const Sema
&S
,
2212 if (!S
.getLangOpts().CUDA
|| !VD
->hasInit())
2214 assert(VD
->getType()->isReferenceType());
2216 // Check whether the reference variable is referencing a host variable.
2217 auto *DRE
= dyn_cast
<DeclRefExpr
>(VD
->getInit());
2220 auto *Referee
= dyn_cast
<VarDecl
>(DRE
->getDecl());
2221 if (!Referee
|| !Referee
->hasGlobalStorage() ||
2222 Referee
->hasAttr
<CUDADeviceAttr
>())
2225 // Check whether the current function is a device or host device lambda.
2226 // Check whether the reference variable is a capture by getDeclContext()
2227 // since refersToEnclosingVariableOrCapture() is not ready at this point.
2228 auto *MD
= dyn_cast_or_null
<CXXMethodDecl
>(S
.CurContext
);
2229 if (MD
&& MD
->getParent()->isLambda() &&
2230 MD
->getOverloadedOperator() == OO_Call
&& MD
->hasAttr
<CUDADeviceAttr
>() &&
2231 VD
->getDeclContext() != MD
)
2237 NonOdrUseReason
Sema::getNonOdrUseReasonInCurrentContext(ValueDecl
*D
) {
2238 // A declaration named in an unevaluated operand never constitutes an odr-use.
2239 if (isUnevaluatedContext())
2240 return NOUR_Unevaluated
;
2242 // C++2a [basic.def.odr]p4:
2243 // A variable x whose name appears as a potentially-evaluated expression e
2244 // is odr-used by e unless [...] x is a reference that is usable in
2245 // constant expressions.
2247 // If a reference variable referencing a host variable is captured in a
2248 // device or host device lambda, the value of the referee must be copied
2249 // to the capture and the reference variable must be treated as odr-use
2250 // since the value of the referee is not known at compile time and must
2251 // be loaded from the captured.
2252 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(D
)) {
2253 if (VD
->getType()->isReferenceType() &&
2254 !(getLangOpts().OpenMP
&& isOpenMPCapturedDecl(D
)) &&
2255 !isCapturingReferenceToHostVarInCUDADeviceLambda(*this, VD
) &&
2256 VD
->isUsableInConstantExpressions(Context
))
2257 return NOUR_Constant
;
2260 // All remaining non-variable cases constitute an odr-use. For variables, we
2261 // need to wait and see how the expression is used.
2265 /// BuildDeclRefExpr - Build an expression that references a
2266 /// declaration that does not require a closure capture.
2268 Sema::BuildDeclRefExpr(ValueDecl
*D
, QualType Ty
, ExprValueKind VK
,
2269 const DeclarationNameInfo
&NameInfo
,
2270 NestedNameSpecifierLoc NNS
, NamedDecl
*FoundD
,
2271 SourceLocation TemplateKWLoc
,
2272 const TemplateArgumentListInfo
*TemplateArgs
) {
2273 bool RefersToCapturedVariable
= isa
<VarDecl
, BindingDecl
>(D
) &&
2274 NeedToCaptureVariable(D
, NameInfo
.getLoc());
2276 DeclRefExpr
*E
= DeclRefExpr::Create(
2277 Context
, NNS
, TemplateKWLoc
, D
, RefersToCapturedVariable
, NameInfo
, Ty
,
2278 VK
, FoundD
, TemplateArgs
, getNonOdrUseReasonInCurrentContext(D
));
2279 MarkDeclRefReferenced(E
);
2281 // C++ [except.spec]p17:
2282 // An exception-specification is considered to be needed when:
2283 // - in an expression, the function is the unique lookup result or
2284 // the selected member of a set of overloaded functions.
2286 // We delay doing this until after we've built the function reference and
2287 // marked it as used so that:
2288 // a) if the function is defaulted, we get errors from defining it before /
2289 // instead of errors from computing its exception specification, and
2290 // b) if the function is a defaulted comparison, we can use the body we
2291 // build when defining it as input to the exception specification
2292 // computation rather than computing a new body.
2293 if (const auto *FPT
= Ty
->getAs
<FunctionProtoType
>()) {
2294 if (isUnresolvedExceptionSpec(FPT
->getExceptionSpecType())) {
2295 if (const auto *NewFPT
= ResolveExceptionSpec(NameInfo
.getLoc(), FPT
))
2296 E
->setType(Context
.getQualifiedType(NewFPT
, Ty
.getQualifiers()));
2300 if (getLangOpts().ObjCWeak
&& isa
<VarDecl
>(D
) &&
2301 Ty
.getObjCLifetime() == Qualifiers::OCL_Weak
&& !isUnevaluatedContext() &&
2302 !Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
, E
->getBeginLoc()))
2303 getCurFunction()->recordUseOfWeak(E
);
2305 const auto *FD
= dyn_cast
<FieldDecl
>(D
);
2306 if (const auto *IFD
= dyn_cast
<IndirectFieldDecl
>(D
))
2307 FD
= IFD
->getAnonField();
2309 UnusedPrivateFields
.remove(FD
);
2310 // Just in case we're building an illegal pointer-to-member.
2311 if (FD
->isBitField())
2312 E
->setObjectKind(OK_BitField
);
2315 // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
2316 // designates a bit-field.
2317 if (const auto *BD
= dyn_cast
<BindingDecl
>(D
))
2318 if (const auto *BE
= BD
->getBinding())
2319 E
->setObjectKind(BE
->getObjectKind());
2324 /// Decomposes the given name into a DeclarationNameInfo, its location, and
2325 /// possibly a list of template arguments.
2327 /// If this produces template arguments, it is permitted to call
2328 /// DecomposeTemplateName.
2330 /// This actually loses a lot of source location information for
2331 /// non-standard name kinds; we should consider preserving that in
2334 Sema::DecomposeUnqualifiedId(const UnqualifiedId
&Id
,
2335 TemplateArgumentListInfo
&Buffer
,
2336 DeclarationNameInfo
&NameInfo
,
2337 const TemplateArgumentListInfo
*&TemplateArgs
) {
2338 if (Id
.getKind() == UnqualifiedIdKind::IK_TemplateId
) {
2339 Buffer
.setLAngleLoc(Id
.TemplateId
->LAngleLoc
);
2340 Buffer
.setRAngleLoc(Id
.TemplateId
->RAngleLoc
);
2342 ASTTemplateArgsPtr
TemplateArgsPtr(Id
.TemplateId
->getTemplateArgs(),
2343 Id
.TemplateId
->NumArgs
);
2344 translateTemplateArguments(TemplateArgsPtr
, Buffer
);
2346 TemplateName TName
= Id
.TemplateId
->Template
.get();
2347 SourceLocation TNameLoc
= Id
.TemplateId
->TemplateNameLoc
;
2348 NameInfo
= Context
.getNameForTemplate(TName
, TNameLoc
);
2349 TemplateArgs
= &Buffer
;
2351 NameInfo
= GetNameFromUnqualifiedId(Id
);
2352 TemplateArgs
= nullptr;
2356 static void emitEmptyLookupTypoDiagnostic(
2357 const TypoCorrection
&TC
, Sema
&SemaRef
, const CXXScopeSpec
&SS
,
2358 DeclarationName Typo
, SourceLocation TypoLoc
, ArrayRef
<Expr
*> Args
,
2359 unsigned DiagnosticID
, unsigned DiagnosticSuggestID
) {
2361 SS
.isEmpty() ? nullptr : SemaRef
.computeDeclContext(SS
, false);
2363 // Emit a special diagnostic for failed member lookups.
2364 // FIXME: computing the declaration context might fail here (?)
2366 SemaRef
.Diag(TypoLoc
, diag::err_no_member
) << Typo
<< Ctx
2369 SemaRef
.Diag(TypoLoc
, DiagnosticID
) << Typo
;
2373 std::string CorrectedStr
= TC
.getAsString(SemaRef
.getLangOpts());
2374 bool DroppedSpecifier
=
2375 TC
.WillReplaceSpecifier() && Typo
.getAsString() == CorrectedStr
;
2376 unsigned NoteID
= TC
.getCorrectionDeclAs
<ImplicitParamDecl
>()
2377 ? diag::note_implicit_param_decl
2378 : diag::note_previous_decl
;
2380 SemaRef
.diagnoseTypo(TC
, SemaRef
.PDiag(DiagnosticSuggestID
) << Typo
,
2381 SemaRef
.PDiag(NoteID
));
2383 SemaRef
.diagnoseTypo(TC
, SemaRef
.PDiag(diag::err_no_member_suggest
)
2384 << Typo
<< Ctx
<< DroppedSpecifier
2386 SemaRef
.PDiag(NoteID
));
2389 /// Diagnose a lookup that found results in an enclosing class during error
2390 /// recovery. This usually indicates that the results were found in a dependent
2391 /// base class that could not be searched as part of a template definition.
2392 /// Always issues a diagnostic (though this may be only a warning in MS
2393 /// compatibility mode).
2395 /// Return \c true if the error is unrecoverable, or \c false if the caller
2396 /// should attempt to recover using these lookup results.
2397 bool Sema::DiagnoseDependentMemberLookup(const LookupResult
&R
) {
2398 // During a default argument instantiation the CurContext points
2399 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
2400 // function parameter list, hence add an explicit check.
2401 bool isDefaultArgument
=
2402 !CodeSynthesisContexts
.empty() &&
2403 CodeSynthesisContexts
.back().Kind
==
2404 CodeSynthesisContext::DefaultFunctionArgumentInstantiation
;
2405 const auto *CurMethod
= dyn_cast
<CXXMethodDecl
>(CurContext
);
2406 bool isInstance
= CurMethod
&& CurMethod
->isInstance() &&
2407 R
.getNamingClass() == CurMethod
->getParent() &&
2410 // There are two ways we can find a class-scope declaration during template
2411 // instantiation that we did not find in the template definition: if it is a
2412 // member of a dependent base class, or if it is declared after the point of
2413 // use in the same class. Distinguish these by comparing the class in which
2414 // the member was found to the naming class of the lookup.
2415 unsigned DiagID
= diag::err_found_in_dependent_base
;
2416 unsigned NoteID
= diag::note_member_declared_at
;
2417 if (R
.getRepresentativeDecl()->getDeclContext()->Equals(R
.getNamingClass())) {
2418 DiagID
= getLangOpts().MSVCCompat
? diag::ext_found_later_in_class
2419 : diag::err_found_later_in_class
;
2420 } else if (getLangOpts().MSVCCompat
) {
2421 DiagID
= diag::ext_found_in_dependent_base
;
2422 NoteID
= diag::note_dependent_member_use
;
2426 // Give a code modification hint to insert 'this->'.
2427 Diag(R
.getNameLoc(), DiagID
)
2428 << R
.getLookupName()
2429 << FixItHint::CreateInsertion(R
.getNameLoc(), "this->");
2430 CheckCXXThisCapture(R
.getNameLoc());
2432 // FIXME: Add a FixItHint to insert 'Base::' or 'Derived::' (assuming
2433 // they're not shadowed).
2434 Diag(R
.getNameLoc(), DiagID
) << R
.getLookupName();
2437 for (const NamedDecl
*D
: R
)
2438 Diag(D
->getLocation(), NoteID
);
2440 // Return true if we are inside a default argument instantiation
2441 // and the found name refers to an instance member function, otherwise
2442 // the caller will try to create an implicit member call and this is wrong
2443 // for default arguments.
2445 // FIXME: Is this special case necessary? We could allow the caller to
2447 if (isDefaultArgument
&& ((*R
.begin())->isCXXInstanceMember())) {
2448 Diag(R
.getNameLoc(), diag::err_member_call_without_object
) << 0;
2452 // Tell the callee to try to recover.
2456 /// Diagnose an empty lookup.
2458 /// \return false if new lookup candidates were found
2459 bool Sema::DiagnoseEmptyLookup(Scope
*S
, CXXScopeSpec
&SS
, LookupResult
&R
,
2460 CorrectionCandidateCallback
&CCC
,
2461 TemplateArgumentListInfo
*ExplicitTemplateArgs
,
2462 ArrayRef
<Expr
*> Args
, DeclContext
*LookupCtx
,
2464 DeclarationName Name
= R
.getLookupName();
2466 unsigned diagnostic
= diag::err_undeclared_var_use
;
2467 unsigned diagnostic_suggest
= diag::err_undeclared_var_use_suggest
;
2468 if (Name
.getNameKind() == DeclarationName::CXXOperatorName
||
2469 Name
.getNameKind() == DeclarationName::CXXLiteralOperatorName
||
2470 Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
) {
2471 diagnostic
= diag::err_undeclared_use
;
2472 diagnostic_suggest
= diag::err_undeclared_use_suggest
;
2475 // If the original lookup was an unqualified lookup, fake an
2476 // unqualified lookup. This is useful when (for example) the
2477 // original lookup would not have found something because it was a
2480 LookupCtx
? LookupCtx
: (SS
.isEmpty() ? CurContext
: nullptr);
2482 if (isa
<CXXRecordDecl
>(DC
)) {
2483 LookupQualifiedName(R
, DC
);
2486 // Don't give errors about ambiguities in this lookup.
2487 R
.suppressDiagnostics();
2489 // If there's a best viable function among the results, only mention
2490 // that one in the notes.
2491 OverloadCandidateSet
Candidates(R
.getNameLoc(),
2492 OverloadCandidateSet::CSK_Normal
);
2493 AddOverloadedCallCandidates(R
, ExplicitTemplateArgs
, Args
, Candidates
);
2494 OverloadCandidateSet::iterator Best
;
2495 if (Candidates
.BestViableFunction(*this, R
.getNameLoc(), Best
) ==
2498 R
.addDecl(Best
->FoundDecl
.getDecl(), Best
->FoundDecl
.getAccess());
2502 return DiagnoseDependentMemberLookup(R
);
2508 DC
= DC
->getLookupParent();
2511 // We didn't find anything, so try to correct for a typo.
2512 TypoCorrection Corrected
;
2514 SourceLocation TypoLoc
= R
.getNameLoc();
2515 assert(!ExplicitTemplateArgs
&&
2516 "Diagnosing an empty lookup with explicit template args!");
2517 *Out
= CorrectTypoDelayed(
2518 R
.getLookupNameInfo(), R
.getLookupKind(), S
, &SS
, CCC
,
2519 [=](const TypoCorrection
&TC
) {
2520 emitEmptyLookupTypoDiagnostic(TC
, *this, SS
, Name
, TypoLoc
, Args
,
2521 diagnostic
, diagnostic_suggest
);
2523 nullptr, CTK_ErrorRecovery
, LookupCtx
);
2526 } else if (S
&& (Corrected
=
2527 CorrectTypo(R
.getLookupNameInfo(), R
.getLookupKind(), S
,
2528 &SS
, CCC
, CTK_ErrorRecovery
, LookupCtx
))) {
2529 std::string
CorrectedStr(Corrected
.getAsString(getLangOpts()));
2530 bool DroppedSpecifier
=
2531 Corrected
.WillReplaceSpecifier() && Name
.getAsString() == CorrectedStr
;
2532 R
.setLookupName(Corrected
.getCorrection());
2534 bool AcceptableWithRecovery
= false;
2535 bool AcceptableWithoutRecovery
= false;
2536 NamedDecl
*ND
= Corrected
.getFoundDecl();
2538 if (Corrected
.isOverloaded()) {
2539 OverloadCandidateSet
OCS(R
.getNameLoc(),
2540 OverloadCandidateSet::CSK_Normal
);
2541 OverloadCandidateSet::iterator Best
;
2542 for (NamedDecl
*CD
: Corrected
) {
2543 if (FunctionTemplateDecl
*FTD
=
2544 dyn_cast
<FunctionTemplateDecl
>(CD
))
2545 AddTemplateOverloadCandidate(
2546 FTD
, DeclAccessPair::make(FTD
, AS_none
), ExplicitTemplateArgs
,
2548 else if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(CD
))
2549 if (!ExplicitTemplateArgs
|| ExplicitTemplateArgs
->size() == 0)
2550 AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, AS_none
),
2553 switch (OCS
.BestViableFunction(*this, R
.getNameLoc(), Best
)) {
2555 ND
= Best
->FoundDecl
;
2556 Corrected
.setCorrectionDecl(ND
);
2559 // FIXME: Arbitrarily pick the first declaration for the note.
2560 Corrected
.setCorrectionDecl(ND
);
2565 if (getLangOpts().CPlusPlus
&& ND
->isCXXClassMember()) {
2566 CXXRecordDecl
*Record
= nullptr;
2567 if (Corrected
.getCorrectionSpecifier()) {
2568 const Type
*Ty
= Corrected
.getCorrectionSpecifier()->getAsType();
2569 Record
= Ty
->getAsCXXRecordDecl();
2572 Record
= cast
<CXXRecordDecl
>(
2573 ND
->getDeclContext()->getRedeclContext());
2574 R
.setNamingClass(Record
);
2577 auto *UnderlyingND
= ND
->getUnderlyingDecl();
2578 AcceptableWithRecovery
= isa
<ValueDecl
>(UnderlyingND
) ||
2579 isa
<FunctionTemplateDecl
>(UnderlyingND
);
2580 // FIXME: If we ended up with a typo for a type name or
2581 // Objective-C class name, we're in trouble because the parser
2582 // is in the wrong place to recover. Suggest the typo
2583 // correction, but don't make it a fix-it since we're not going
2584 // to recover well anyway.
2585 AcceptableWithoutRecovery
= isa
<TypeDecl
>(UnderlyingND
) ||
2586 getAsTypeTemplateDecl(UnderlyingND
) ||
2587 isa
<ObjCInterfaceDecl
>(UnderlyingND
);
2589 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2590 // because we aren't able to recover.
2591 AcceptableWithoutRecovery
= true;
2594 if (AcceptableWithRecovery
|| AcceptableWithoutRecovery
) {
2595 unsigned NoteID
= Corrected
.getCorrectionDeclAs
<ImplicitParamDecl
>()
2596 ? diag::note_implicit_param_decl
2597 : diag::note_previous_decl
;
2599 diagnoseTypo(Corrected
, PDiag(diagnostic_suggest
) << Name
,
2600 PDiag(NoteID
), AcceptableWithRecovery
);
2602 diagnoseTypo(Corrected
, PDiag(diag::err_no_member_suggest
)
2603 << Name
<< computeDeclContext(SS
, false)
2604 << DroppedSpecifier
<< SS
.getRange(),
2605 PDiag(NoteID
), AcceptableWithRecovery
);
2607 // Tell the callee whether to try to recover.
2608 return !AcceptableWithRecovery
;
2613 // Emit a special diagnostic for failed member lookups.
2614 // FIXME: computing the declaration context might fail here (?)
2615 if (!SS
.isEmpty()) {
2616 Diag(R
.getNameLoc(), diag::err_no_member
)
2617 << Name
<< computeDeclContext(SS
, false)
2622 // Give up, we can't recover.
2623 Diag(R
.getNameLoc(), diagnostic
) << Name
;
2627 /// In Microsoft mode, if we are inside a template class whose parent class has
2628 /// dependent base classes, and we can't resolve an unqualified identifier, then
2629 /// assume the identifier is a member of a dependent base class. We can only
2630 /// recover successfully in static methods, instance methods, and other contexts
2631 /// where 'this' is available. This doesn't precisely match MSVC's
2632 /// instantiation model, but it's close enough.
2634 recoverFromMSUnqualifiedLookup(Sema
&S
, ASTContext
&Context
,
2635 DeclarationNameInfo
&NameInfo
,
2636 SourceLocation TemplateKWLoc
,
2637 const TemplateArgumentListInfo
*TemplateArgs
) {
2638 // Only try to recover from lookup into dependent bases in static methods or
2639 // contexts where 'this' is available.
2640 QualType ThisType
= S
.getCurrentThisType();
2641 const CXXRecordDecl
*RD
= nullptr;
2642 if (!ThisType
.isNull())
2643 RD
= ThisType
->getPointeeType()->getAsCXXRecordDecl();
2644 else if (auto *MD
= dyn_cast
<CXXMethodDecl
>(S
.CurContext
))
2645 RD
= MD
->getParent();
2646 if (!RD
|| !RD
->hasAnyDependentBases())
2649 // Diagnose this as unqualified lookup into a dependent base class. If 'this'
2650 // is available, suggest inserting 'this->' as a fixit.
2651 SourceLocation Loc
= NameInfo
.getLoc();
2652 auto DB
= S
.Diag(Loc
, diag::ext_undeclared_unqual_id_with_dependent_base
);
2653 DB
<< NameInfo
.getName() << RD
;
2655 if (!ThisType
.isNull()) {
2656 DB
<< FixItHint::CreateInsertion(Loc
, "this->");
2657 return CXXDependentScopeMemberExpr::Create(
2658 Context
, /*This=*/nullptr, ThisType
, /*IsArrow=*/true,
2659 /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc
,
2660 /*FirstQualifierFoundInScope=*/nullptr, NameInfo
, TemplateArgs
);
2663 // Synthesize a fake NNS that points to the derived class. This will
2664 // perform name lookup during template instantiation.
2667 NestedNameSpecifier::Create(Context
, nullptr, true, RD
->getTypeForDecl());
2668 SS
.MakeTrivial(Context
, NNS
, SourceRange(Loc
, Loc
));
2669 return DependentScopeDeclRefExpr::Create(
2670 Context
, SS
.getWithLocInContext(Context
), TemplateKWLoc
, NameInfo
,
2675 Sema::ActOnIdExpression(Scope
*S
, CXXScopeSpec
&SS
,
2676 SourceLocation TemplateKWLoc
, UnqualifiedId
&Id
,
2677 bool HasTrailingLParen
, bool IsAddressOfOperand
,
2678 CorrectionCandidateCallback
*CCC
,
2679 bool IsInlineAsmIdentifier
, Token
*KeywordReplacement
) {
2680 assert(!(IsAddressOfOperand
&& HasTrailingLParen
) &&
2681 "cannot be direct & operand and have a trailing lparen");
2685 TemplateArgumentListInfo TemplateArgsBuffer
;
2687 // Decompose the UnqualifiedId into the following data.
2688 DeclarationNameInfo NameInfo
;
2689 const TemplateArgumentListInfo
*TemplateArgs
;
2690 DecomposeUnqualifiedId(Id
, TemplateArgsBuffer
, NameInfo
, TemplateArgs
);
2692 DeclarationName Name
= NameInfo
.getName();
2693 IdentifierInfo
*II
= Name
.getAsIdentifierInfo();
2694 SourceLocation NameLoc
= NameInfo
.getLoc();
2696 if (II
&& II
->isEditorPlaceholder()) {
2697 // FIXME: When typed placeholders are supported we can create a typed
2698 // placeholder expression node.
2702 // C++ [temp.dep.expr]p3:
2703 // An id-expression is type-dependent if it contains:
2704 // -- an identifier that was declared with a dependent type,
2705 // (note: handled after lookup)
2706 // -- a template-id that is dependent,
2707 // (note: handled in BuildTemplateIdExpr)
2708 // -- a conversion-function-id that specifies a dependent type,
2709 // -- a nested-name-specifier that contains a class-name that
2710 // names a dependent type.
2711 // Determine whether this is a member of an unknown specialization;
2712 // we need to handle these differently.
2713 bool DependentID
= false;
2714 if (Name
.getNameKind() == DeclarationName::CXXConversionFunctionName
&&
2715 Name
.getCXXNameType()->isDependentType()) {
2717 } else if (SS
.isSet()) {
2718 if (DeclContext
*DC
= computeDeclContext(SS
, false)) {
2719 if (RequireCompleteDeclContext(SS
, DC
))
2727 return ActOnDependentIdExpression(SS
, TemplateKWLoc
, NameInfo
,
2728 IsAddressOfOperand
, TemplateArgs
);
2730 // Perform the required lookup.
2731 LookupResult
R(*this, NameInfo
,
2732 (Id
.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam
)
2733 ? LookupObjCImplicitSelfParam
2734 : LookupOrdinaryName
);
2735 if (TemplateKWLoc
.isValid() || TemplateArgs
) {
2736 // Lookup the template name again to correctly establish the context in
2737 // which it was found. This is really unfortunate as we already did the
2738 // lookup to determine that it was a template name in the first place. If
2739 // this becomes a performance hit, we can work harder to preserve those
2740 // results until we get here but it's likely not worth it.
2741 bool MemberOfUnknownSpecialization
;
2742 AssumedTemplateKind AssumedTemplate
;
2743 if (LookupTemplateName(R
, S
, SS
, QualType(), /*EnteringContext=*/false,
2744 MemberOfUnknownSpecialization
, TemplateKWLoc
,
2748 if (MemberOfUnknownSpecialization
||
2749 (R
.getResultKind() == LookupResult::NotFoundInCurrentInstantiation
))
2750 return ActOnDependentIdExpression(SS
, TemplateKWLoc
, NameInfo
,
2751 IsAddressOfOperand
, TemplateArgs
);
2753 bool IvarLookupFollowUp
= II
&& !SS
.isSet() && getCurMethodDecl();
2754 LookupParsedName(R
, S
, &SS
, !IvarLookupFollowUp
);
2756 // If the result might be in a dependent base class, this is a dependent
2758 if (R
.getResultKind() == LookupResult::NotFoundInCurrentInstantiation
)
2759 return ActOnDependentIdExpression(SS
, TemplateKWLoc
, NameInfo
,
2760 IsAddressOfOperand
, TemplateArgs
);
2762 // If this reference is in an Objective-C method, then we need to do
2763 // some special Objective-C lookup, too.
2764 if (IvarLookupFollowUp
) {
2765 ExprResult
E(LookupInObjCMethod(R
, S
, II
, true));
2769 if (Expr
*Ex
= E
.getAs
<Expr
>())
2774 if (R
.isAmbiguous())
2777 // This could be an implicitly declared function reference if the language
2778 // mode allows it as a feature.
2779 if (R
.empty() && HasTrailingLParen
&& II
&&
2780 getLangOpts().implicitFunctionsAllowed()) {
2781 NamedDecl
*D
= ImplicitlyDefineFunction(NameLoc
, *II
, S
);
2782 if (D
) R
.addDecl(D
);
2785 // Determine whether this name might be a candidate for
2786 // argument-dependent lookup.
2787 bool ADL
= UseArgumentDependentLookup(SS
, R
, HasTrailingLParen
);
2789 if (R
.empty() && !ADL
) {
2790 if (SS
.isEmpty() && getLangOpts().MSVCCompat
) {
2791 if (Expr
*E
= recoverFromMSUnqualifiedLookup(*this, Context
, NameInfo
,
2792 TemplateKWLoc
, TemplateArgs
))
2796 // Don't diagnose an empty lookup for inline assembly.
2797 if (IsInlineAsmIdentifier
)
2800 // If this name wasn't predeclared and if this is not a function
2801 // call, diagnose the problem.
2802 TypoExpr
*TE
= nullptr;
2803 DefaultFilterCCC
DefaultValidator(II
, SS
.isValid() ? SS
.getScopeRep()
2805 DefaultValidator
.IsAddressOfOperand
= IsAddressOfOperand
;
2806 assert((!CCC
|| CCC
->IsAddressOfOperand
== IsAddressOfOperand
) &&
2807 "Typo correction callback misconfigured");
2809 // Make sure the callback knows what the typo being diagnosed is.
2810 CCC
->setTypoName(II
);
2812 CCC
->setTypoNNS(SS
.getScopeRep());
2814 // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2815 // a template name, but we happen to have always already looked up the name
2816 // before we get here if it must be a template name.
2817 if (DiagnoseEmptyLookup(S
, SS
, R
, CCC
? *CCC
: DefaultValidator
, nullptr,
2818 std::nullopt
, nullptr, &TE
)) {
2819 if (TE
&& KeywordReplacement
) {
2820 auto &State
= getTypoExprState(TE
);
2821 auto BestTC
= State
.Consumer
->getNextCorrection();
2822 if (BestTC
.isKeyword()) {
2823 auto *II
= BestTC
.getCorrectionAsIdentifierInfo();
2824 if (State
.DiagHandler
)
2825 State
.DiagHandler(BestTC
);
2826 KeywordReplacement
->startToken();
2827 KeywordReplacement
->setKind(II
->getTokenID());
2828 KeywordReplacement
->setIdentifierInfo(II
);
2829 KeywordReplacement
->setLocation(BestTC
.getCorrectionRange().getBegin());
2830 // Clean up the state associated with the TypoExpr, since it has
2831 // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2832 clearDelayedTypo(TE
);
2833 // Signal that a correction to a keyword was performed by returning a
2834 // valid-but-null ExprResult.
2835 return (Expr
*)nullptr;
2837 State
.Consumer
->resetCorrectionStream();
2839 return TE
? TE
: ExprError();
2842 assert(!R
.empty() &&
2843 "DiagnoseEmptyLookup returned false but added no results");
2845 // If we found an Objective-C instance variable, let
2846 // LookupInObjCMethod build the appropriate expression to
2847 // reference the ivar.
2848 if (ObjCIvarDecl
*Ivar
= R
.getAsSingle
<ObjCIvarDecl
>()) {
2850 ExprResult
E(LookupInObjCMethod(R
, S
, Ivar
->getIdentifier()));
2851 // In a hopelessly buggy code, Objective-C instance variable
2852 // lookup fails and no expression will be built to reference it.
2853 if (!E
.isInvalid() && !E
.get())
2859 // This is guaranteed from this point on.
2860 assert(!R
.empty() || ADL
);
2862 // Check whether this might be a C++ implicit instance member access.
2863 // C++ [class.mfct.non-static]p3:
2864 // When an id-expression that is not part of a class member access
2865 // syntax and not used to form a pointer to member is used in the
2866 // body of a non-static member function of class X, if name lookup
2867 // resolves the name in the id-expression to a non-static non-type
2868 // member of some class C, the id-expression is transformed into a
2869 // class member access expression using (*this) as the
2870 // postfix-expression to the left of the . operator.
2872 // But we don't actually need to do this for '&' operands if R
2873 // resolved to a function or overloaded function set, because the
2874 // expression is ill-formed if it actually works out to be a
2875 // non-static member function:
2877 // C++ [expr.ref]p4:
2878 // Otherwise, if E1.E2 refers to a non-static member function. . .
2879 // [t]he expression can be used only as the left-hand operand of a
2880 // member function call.
2882 // There are other safeguards against such uses, but it's important
2883 // to get this right here so that we don't end up making a
2884 // spuriously dependent expression if we're inside a dependent
2886 if (!R
.empty() && (*R
.begin())->isCXXClassMember()) {
2887 bool MightBeImplicitMember
;
2888 if (!IsAddressOfOperand
)
2889 MightBeImplicitMember
= true;
2890 else if (!SS
.isEmpty())
2891 MightBeImplicitMember
= false;
2892 else if (R
.isOverloadedResult())
2893 MightBeImplicitMember
= false;
2894 else if (R
.isUnresolvableResult())
2895 MightBeImplicitMember
= true;
2897 MightBeImplicitMember
= isa
<FieldDecl
>(R
.getFoundDecl()) ||
2898 isa
<IndirectFieldDecl
>(R
.getFoundDecl()) ||
2899 isa
<MSPropertyDecl
>(R
.getFoundDecl());
2901 if (MightBeImplicitMember
)
2902 return BuildPossibleImplicitMemberExpr(SS
, TemplateKWLoc
,
2903 R
, TemplateArgs
, S
);
2906 if (TemplateArgs
|| TemplateKWLoc
.isValid()) {
2908 // In C++1y, if this is a variable template id, then check it
2909 // in BuildTemplateIdExpr().
2910 // The single lookup result must be a variable template declaration.
2911 if (Id
.getKind() == UnqualifiedIdKind::IK_TemplateId
&& Id
.TemplateId
&&
2912 Id
.TemplateId
->Kind
== TNK_Var_template
) {
2913 assert(R
.getAsSingle
<VarTemplateDecl
>() &&
2914 "There should only be one declaration found.");
2917 return BuildTemplateIdExpr(SS
, TemplateKWLoc
, R
, ADL
, TemplateArgs
);
2920 return BuildDeclarationNameExpr(SS
, R
, ADL
);
2923 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2924 /// declaration name, generally during template instantiation.
2925 /// There's a large number of things which don't need to be done along
2927 ExprResult
Sema::BuildQualifiedDeclarationNameExpr(
2928 CXXScopeSpec
&SS
, const DeclarationNameInfo
&NameInfo
,
2929 bool IsAddressOfOperand
, const Scope
*S
, TypeSourceInfo
**RecoveryTSI
) {
2930 if (NameInfo
.getName().isDependentName())
2931 return BuildDependentDeclRefExpr(SS
, /*TemplateKWLoc=*/SourceLocation(),
2932 NameInfo
, /*TemplateArgs=*/nullptr);
2934 DeclContext
*DC
= computeDeclContext(SS
, false);
2936 return BuildDependentDeclRefExpr(SS
, /*TemplateKWLoc=*/SourceLocation(),
2937 NameInfo
, /*TemplateArgs=*/nullptr);
2939 if (RequireCompleteDeclContext(SS
, DC
))
2942 LookupResult
R(*this, NameInfo
, LookupOrdinaryName
);
2943 LookupQualifiedName(R
, DC
);
2945 if (R
.isAmbiguous())
2948 if (R
.getResultKind() == LookupResult::NotFoundInCurrentInstantiation
)
2949 return BuildDependentDeclRefExpr(SS
, /*TemplateKWLoc=*/SourceLocation(),
2950 NameInfo
, /*TemplateArgs=*/nullptr);
2953 // Don't diagnose problems with invalid record decl, the secondary no_member
2954 // diagnostic during template instantiation is likely bogus, e.g. if a class
2955 // is invalid because it's derived from an invalid base class, then missing
2956 // members were likely supposed to be inherited.
2957 if (const auto *CD
= dyn_cast
<CXXRecordDecl
>(DC
))
2958 if (CD
->isInvalidDecl())
2960 Diag(NameInfo
.getLoc(), diag::err_no_member
)
2961 << NameInfo
.getName() << DC
<< SS
.getRange();
2965 if (const TypeDecl
*TD
= R
.getAsSingle
<TypeDecl
>()) {
2966 // Diagnose a missing typename if this resolved unambiguously to a type in
2967 // a dependent context. If we can recover with a type, downgrade this to
2968 // a warning in Microsoft compatibility mode.
2969 unsigned DiagID
= diag::err_typename_missing
;
2970 if (RecoveryTSI
&& getLangOpts().MSVCCompat
)
2971 DiagID
= diag::ext_typename_missing
;
2972 SourceLocation Loc
= SS
.getBeginLoc();
2973 auto D
= Diag(Loc
, DiagID
);
2974 D
<< SS
.getScopeRep() << NameInfo
.getName().getAsString()
2975 << SourceRange(Loc
, NameInfo
.getEndLoc());
2977 // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2982 // Only issue the fixit if we're prepared to recover.
2983 D
<< FixItHint::CreateInsertion(Loc
, "typename ");
2985 // Recover by pretending this was an elaborated type.
2986 QualType Ty
= Context
.getTypeDeclType(TD
);
2988 TLB
.pushTypeSpec(Ty
).setNameLoc(NameInfo
.getLoc());
2990 QualType ET
= getElaboratedType(ElaboratedTypeKeyword::None
, SS
, Ty
);
2991 ElaboratedTypeLoc QTL
= TLB
.push
<ElaboratedTypeLoc
>(ET
);
2992 QTL
.setElaboratedKeywordLoc(SourceLocation());
2993 QTL
.setQualifierLoc(SS
.getWithLocInContext(Context
));
2995 *RecoveryTSI
= TLB
.getTypeSourceInfo(Context
, ET
);
3000 // Defend against this resolving to an implicit member access. We usually
3001 // won't get here if this might be a legitimate a class member (we end up in
3002 // BuildMemberReferenceExpr instead), but this can be valid if we're forming
3003 // a pointer-to-member or in an unevaluated context in C++11.
3004 if (!R
.empty() && (*R
.begin())->isCXXClassMember() && !IsAddressOfOperand
)
3005 return BuildPossibleImplicitMemberExpr(SS
,
3006 /*TemplateKWLoc=*/SourceLocation(),
3007 R
, /*TemplateArgs=*/nullptr, S
);
3009 return BuildDeclarationNameExpr(SS
, R
, /* ADL */ false);
3012 /// The parser has read a name in, and Sema has detected that we're currently
3013 /// inside an ObjC method. Perform some additional checks and determine if we
3014 /// should form a reference to an ivar.
3016 /// Ideally, most of this would be done by lookup, but there's
3017 /// actually quite a lot of extra work involved.
3018 DeclResult
Sema::LookupIvarInObjCMethod(LookupResult
&Lookup
, Scope
*S
,
3019 IdentifierInfo
*II
) {
3020 SourceLocation Loc
= Lookup
.getNameLoc();
3021 ObjCMethodDecl
*CurMethod
= getCurMethodDecl();
3023 // Check for error condition which is already reported.
3025 return DeclResult(true);
3027 // There are two cases to handle here. 1) scoped lookup could have failed,
3028 // in which case we should look for an ivar. 2) scoped lookup could have
3029 // found a decl, but that decl is outside the current instance method (i.e.
3030 // a global variable). In these two cases, we do a lookup for an ivar with
3031 // this name, if the lookup sucedes, we replace it our current decl.
3033 // If we're in a class method, we don't normally want to look for
3034 // ivars. But if we don't find anything else, and there's an
3035 // ivar, that's an error.
3036 bool IsClassMethod
= CurMethod
->isClassMethod();
3040 LookForIvars
= true;
3041 else if (IsClassMethod
)
3042 LookForIvars
= false;
3044 LookForIvars
= (Lookup
.isSingleResult() &&
3045 Lookup
.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
3046 ObjCInterfaceDecl
*IFace
= nullptr;
3048 IFace
= CurMethod
->getClassInterface();
3049 ObjCInterfaceDecl
*ClassDeclared
;
3050 ObjCIvarDecl
*IV
= nullptr;
3051 if (IFace
&& (IV
= IFace
->lookupInstanceVariable(II
, ClassDeclared
))) {
3052 // Diagnose using an ivar in a class method.
3053 if (IsClassMethod
) {
3054 Diag(Loc
, diag::err_ivar_use_in_class_method
) << IV
->getDeclName();
3055 return DeclResult(true);
3058 // Diagnose the use of an ivar outside of the declaring class.
3059 if (IV
->getAccessControl() == ObjCIvarDecl::Private
&&
3060 !declaresSameEntity(ClassDeclared
, IFace
) &&
3061 !getLangOpts().DebuggerSupport
)
3062 Diag(Loc
, diag::err_private_ivar_access
) << IV
->getDeclName();
3067 } else if (CurMethod
->isInstanceMethod()) {
3068 // We should warn if a local variable hides an ivar.
3069 if (ObjCInterfaceDecl
*IFace
= CurMethod
->getClassInterface()) {
3070 ObjCInterfaceDecl
*ClassDeclared
;
3071 if (ObjCIvarDecl
*IV
= IFace
->lookupInstanceVariable(II
, ClassDeclared
)) {
3072 if (IV
->getAccessControl() != ObjCIvarDecl::Private
||
3073 declaresSameEntity(IFace
, ClassDeclared
))
3074 Diag(Loc
, diag::warn_ivar_use_hidden
) << IV
->getDeclName();
3077 } else if (Lookup
.isSingleResult() &&
3078 Lookup
.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
3079 // If accessing a stand-alone ivar in a class method, this is an error.
3080 if (const ObjCIvarDecl
*IV
=
3081 dyn_cast
<ObjCIvarDecl
>(Lookup
.getFoundDecl())) {
3082 Diag(Loc
, diag::err_ivar_use_in_class_method
) << IV
->getDeclName();
3083 return DeclResult(true);
3087 // Didn't encounter an error, didn't find an ivar.
3088 return DeclResult(false);
3091 ExprResult
Sema::BuildIvarRefExpr(Scope
*S
, SourceLocation Loc
,
3093 ObjCMethodDecl
*CurMethod
= getCurMethodDecl();
3094 assert(CurMethod
&& CurMethod
->isInstanceMethod() &&
3095 "should not reference ivar from this context");
3097 ObjCInterfaceDecl
*IFace
= CurMethod
->getClassInterface();
3098 assert(IFace
&& "should not reference ivar from this context");
3100 // If we're referencing an invalid decl, just return this as a silent
3101 // error node. The error diagnostic was already emitted on the decl.
3102 if (IV
->isInvalidDecl())
3105 // Check if referencing a field with __attribute__((deprecated)).
3106 if (DiagnoseUseOfDecl(IV
, Loc
))
3109 // FIXME: This should use a new expr for a direct reference, don't
3110 // turn this into Self->ivar, just return a BareIVarExpr or something.
3111 IdentifierInfo
&II
= Context
.Idents
.get("self");
3112 UnqualifiedId SelfName
;
3113 SelfName
.setImplicitSelfParam(&II
);
3114 CXXScopeSpec SelfScopeSpec
;
3115 SourceLocation TemplateKWLoc
;
3116 ExprResult SelfExpr
=
3117 ActOnIdExpression(S
, SelfScopeSpec
, TemplateKWLoc
, SelfName
,
3118 /*HasTrailingLParen=*/false,
3119 /*IsAddressOfOperand=*/false);
3120 if (SelfExpr
.isInvalid())
3123 SelfExpr
= DefaultLvalueConversion(SelfExpr
.get());
3124 if (SelfExpr
.isInvalid())
3127 MarkAnyDeclReferenced(Loc
, IV
, true);
3129 ObjCMethodFamily MF
= CurMethod
->getMethodFamily();
3130 if (MF
!= OMF_init
&& MF
!= OMF_dealloc
&& MF
!= OMF_finalize
&&
3131 !IvarBacksCurrentMethodAccessor(IFace
, CurMethod
, IV
))
3132 Diag(Loc
, diag::warn_direct_ivar_access
) << IV
->getDeclName();
3134 ObjCIvarRefExpr
*Result
= new (Context
)
3135 ObjCIvarRefExpr(IV
, IV
->getUsageType(SelfExpr
.get()->getType()), Loc
,
3136 IV
->getLocation(), SelfExpr
.get(), true, true);
3138 if (IV
->getType().getObjCLifetime() == Qualifiers::OCL_Weak
) {
3139 if (!isUnevaluatedContext() &&
3140 !Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
, Loc
))
3141 getCurFunction()->recordUseOfWeak(Result
);
3143 if (getLangOpts().ObjCAutoRefCount
&& !isUnevaluatedContext())
3144 if (const BlockDecl
*BD
= CurContext
->getInnermostBlockDecl())
3145 ImplicitlyRetainedSelfLocs
.push_back({Loc
, BD
});
3150 /// The parser has read a name in, and Sema has detected that we're currently
3151 /// inside an ObjC method. Perform some additional checks and determine if we
3152 /// should form a reference to an ivar. If so, build an expression referencing
3155 Sema::LookupInObjCMethod(LookupResult
&Lookup
, Scope
*S
,
3156 IdentifierInfo
*II
, bool AllowBuiltinCreation
) {
3157 // FIXME: Integrate this lookup step into LookupParsedName.
3158 DeclResult Ivar
= LookupIvarInObjCMethod(Lookup
, S
, II
);
3159 if (Ivar
.isInvalid())
3161 if (Ivar
.isUsable())
3162 return BuildIvarRefExpr(S
, Lookup
.getNameLoc(),
3163 cast
<ObjCIvarDecl
>(Ivar
.get()));
3165 if (Lookup
.empty() && II
&& AllowBuiltinCreation
)
3166 LookupBuiltin(Lookup
);
3168 // Sentinel value saying that we didn't do anything special.
3169 return ExprResult(false);
3172 /// Cast a base object to a member's actual type.
3174 /// There are two relevant checks:
3176 /// C++ [class.access.base]p7:
3178 /// If a class member access operator [...] is used to access a non-static
3179 /// data member or non-static member function, the reference is ill-formed if
3180 /// the left operand [...] cannot be implicitly converted to a pointer to the
3181 /// naming class of the right operand.
3183 /// C++ [expr.ref]p7:
3185 /// If E2 is a non-static data member or a non-static member function, the
3186 /// program is ill-formed if the class of which E2 is directly a member is an
3187 /// ambiguous base (11.8) of the naming class (11.9.3) of E2.
3189 /// Note that the latter check does not consider access; the access of the
3190 /// "real" base class is checked as appropriate when checking the access of the
3193 Sema::PerformObjectMemberConversion(Expr
*From
,
3194 NestedNameSpecifier
*Qualifier
,
3195 NamedDecl
*FoundDecl
,
3196 NamedDecl
*Member
) {
3197 const auto *RD
= dyn_cast
<CXXRecordDecl
>(Member
->getDeclContext());
3201 QualType DestRecordType
;
3203 QualType FromRecordType
;
3204 QualType FromType
= From
->getType();
3205 bool PointerConversions
= false;
3206 if (isa
<FieldDecl
>(Member
)) {
3207 DestRecordType
= Context
.getCanonicalType(Context
.getTypeDeclType(RD
));
3208 auto FromPtrType
= FromType
->getAs
<PointerType
>();
3209 DestRecordType
= Context
.getAddrSpaceQualType(
3210 DestRecordType
, FromPtrType
3211 ? FromType
->getPointeeType().getAddressSpace()
3212 : FromType
.getAddressSpace());
3215 DestType
= Context
.getPointerType(DestRecordType
);
3216 FromRecordType
= FromPtrType
->getPointeeType();
3217 PointerConversions
= true;
3219 DestType
= DestRecordType
;
3220 FromRecordType
= FromType
;
3222 } else if (const auto *Method
= dyn_cast
<CXXMethodDecl
>(Member
)) {
3223 if (!Method
->isImplicitObjectMemberFunction())
3226 DestType
= Method
->getThisType().getNonReferenceType();
3227 DestRecordType
= Method
->getFunctionObjectParameterType();
3229 if (FromType
->getAs
<PointerType
>()) {
3230 FromRecordType
= FromType
->getPointeeType();
3231 PointerConversions
= true;
3233 FromRecordType
= FromType
;
3234 DestType
= DestRecordType
;
3237 LangAS FromAS
= FromRecordType
.getAddressSpace();
3238 LangAS DestAS
= DestRecordType
.getAddressSpace();
3239 if (FromAS
!= DestAS
) {
3240 QualType FromRecordTypeWithoutAS
=
3241 Context
.removeAddrSpaceQualType(FromRecordType
);
3242 QualType FromTypeWithDestAS
=
3243 Context
.getAddrSpaceQualType(FromRecordTypeWithoutAS
, DestAS
);
3244 if (PointerConversions
)
3245 FromTypeWithDestAS
= Context
.getPointerType(FromTypeWithDestAS
);
3246 From
= ImpCastExprToType(From
, FromTypeWithDestAS
,
3247 CK_AddressSpaceConversion
, From
->getValueKind())
3251 // No conversion necessary.
3255 if (DestType
->isDependentType() || FromType
->isDependentType())
3258 // If the unqualified types are the same, no conversion is necessary.
3259 if (Context
.hasSameUnqualifiedType(FromRecordType
, DestRecordType
))
3262 SourceRange FromRange
= From
->getSourceRange();
3263 SourceLocation FromLoc
= FromRange
.getBegin();
3265 ExprValueKind VK
= From
->getValueKind();
3267 // C++ [class.member.lookup]p8:
3268 // [...] Ambiguities can often be resolved by qualifying a name with its
3271 // If the member was a qualified name and the qualified referred to a
3272 // specific base subobject type, we'll cast to that intermediate type
3273 // first and then to the object in which the member is declared. That allows
3274 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
3276 // class Base { public: int x; };
3277 // class Derived1 : public Base { };
3278 // class Derived2 : public Base { };
3279 // class VeryDerived : public Derived1, public Derived2 { void f(); };
3281 // void VeryDerived::f() {
3282 // x = 17; // error: ambiguous base subobjects
3283 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
3285 if (Qualifier
&& Qualifier
->getAsType()) {
3286 QualType QType
= QualType(Qualifier
->getAsType(), 0);
3287 assert(QType
->isRecordType() && "lookup done with non-record type");
3289 QualType QRecordType
= QualType(QType
->castAs
<RecordType
>(), 0);
3291 // In C++98, the qualifier type doesn't actually have to be a base
3292 // type of the object type, in which case we just ignore it.
3293 // Otherwise build the appropriate casts.
3294 if (IsDerivedFrom(FromLoc
, FromRecordType
, QRecordType
)) {
3295 CXXCastPath BasePath
;
3296 if (CheckDerivedToBaseConversion(FromRecordType
, QRecordType
,
3297 FromLoc
, FromRange
, &BasePath
))
3300 if (PointerConversions
)
3301 QType
= Context
.getPointerType(QType
);
3302 From
= ImpCastExprToType(From
, QType
, CK_UncheckedDerivedToBase
,
3303 VK
, &BasePath
).get();
3306 FromRecordType
= QRecordType
;
3308 // If the qualifier type was the same as the destination type,
3310 if (Context
.hasSameUnqualifiedType(FromRecordType
, DestRecordType
))
3315 CXXCastPath BasePath
;
3316 if (CheckDerivedToBaseConversion(FromRecordType
, DestRecordType
,
3317 FromLoc
, FromRange
, &BasePath
,
3318 /*IgnoreAccess=*/true))
3321 return ImpCastExprToType(From
, DestType
, CK_UncheckedDerivedToBase
,
3325 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec
&SS
,
3326 const LookupResult
&R
,
3327 bool HasTrailingLParen
) {
3328 // Only when used directly as the postfix-expression of a call.
3329 if (!HasTrailingLParen
)
3332 // Never if a scope specifier was provided.
3336 // Only in C++ or ObjC++.
3337 if (!getLangOpts().CPlusPlus
)
3340 // Turn off ADL when we find certain kinds of declarations during
3342 for (const NamedDecl
*D
: R
) {
3343 // C++0x [basic.lookup.argdep]p3:
3344 // -- a declaration of a class member
3345 // Since using decls preserve this property, we check this on the
3347 if (D
->isCXXClassMember())
3350 // C++0x [basic.lookup.argdep]p3:
3351 // -- a block-scope function declaration that is not a
3352 // using-declaration
3353 // NOTE: we also trigger this for function templates (in fact, we
3354 // don't check the decl type at all, since all other decl types
3355 // turn off ADL anyway).
3356 if (isa
<UsingShadowDecl
>(D
))
3357 D
= cast
<UsingShadowDecl
>(D
)->getTargetDecl();
3358 else if (D
->getLexicalDeclContext()->isFunctionOrMethod())
3361 // C++0x [basic.lookup.argdep]p3:
3362 // -- a declaration that is neither a function or a function
3364 // And also for builtin functions.
3365 if (const auto *FDecl
= dyn_cast
<FunctionDecl
>(D
)) {
3366 // But also builtin functions.
3367 if (FDecl
->getBuiltinID() && FDecl
->isImplicit())
3369 } else if (!isa
<FunctionTemplateDecl
>(D
))
3377 /// Diagnoses obvious problems with the use of the given declaration
3378 /// as an expression. This is only actually called for lookups that
3379 /// were not overloaded, and it doesn't promise that the declaration
3380 /// will in fact be used.
3381 static bool CheckDeclInExpr(Sema
&S
, SourceLocation Loc
, NamedDecl
*D
,
3382 bool AcceptInvalid
) {
3383 if (D
->isInvalidDecl() && !AcceptInvalid
)
3386 if (isa
<TypedefNameDecl
>(D
)) {
3387 S
.Diag(Loc
, diag::err_unexpected_typedef
) << D
->getDeclName();
3391 if (isa
<ObjCInterfaceDecl
>(D
)) {
3392 S
.Diag(Loc
, diag::err_unexpected_interface
) << D
->getDeclName();
3396 if (isa
<NamespaceDecl
>(D
)) {
3397 S
.Diag(Loc
, diag::err_unexpected_namespace
) << D
->getDeclName();
3404 // Certain multiversion types should be treated as overloaded even when there is
3406 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult
&R
) {
3407 assert(R
.isSingleResult() && "Expected only a single result");
3408 const auto *FD
= dyn_cast
<FunctionDecl
>(R
.getFoundDecl());
3410 (FD
->isCPUDispatchMultiVersion() || FD
->isCPUSpecificMultiVersion());
3413 ExprResult
Sema::BuildDeclarationNameExpr(const CXXScopeSpec
&SS
,
3414 LookupResult
&R
, bool NeedsADL
,
3415 bool AcceptInvalidDecl
) {
3416 // If this is a single, fully-resolved result and we don't need ADL,
3417 // just build an ordinary singleton decl ref.
3418 if (!NeedsADL
&& R
.isSingleResult() &&
3419 !R
.getAsSingle
<FunctionTemplateDecl
>() &&
3420 !ShouldLookupResultBeMultiVersionOverload(R
))
3421 return BuildDeclarationNameExpr(SS
, R
.getLookupNameInfo(), R
.getFoundDecl(),
3422 R
.getRepresentativeDecl(), nullptr,
3425 // We only need to check the declaration if there's exactly one
3426 // result, because in the overloaded case the results can only be
3427 // functions and function templates.
3428 if (R
.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R
) &&
3429 CheckDeclInExpr(*this, R
.getNameLoc(), R
.getFoundDecl(),
3433 // Otherwise, just build an unresolved lookup expression. Suppress
3434 // any lookup-related diagnostics; we'll hash these out later, when
3435 // we've picked a target.
3436 R
.suppressDiagnostics();
3438 UnresolvedLookupExpr
*ULE
3439 = UnresolvedLookupExpr::Create(Context
, R
.getNamingClass(),
3440 SS
.getWithLocInContext(Context
),
3441 R
.getLookupNameInfo(),
3442 NeedsADL
, R
.isOverloadedResult(),
3443 R
.begin(), R
.end());
3448 static void diagnoseUncapturableValueReferenceOrBinding(Sema
&S
,
3452 /// Complete semantic analysis for a reference to the given declaration.
3453 ExprResult
Sema::BuildDeclarationNameExpr(
3454 const CXXScopeSpec
&SS
, const DeclarationNameInfo
&NameInfo
, NamedDecl
*D
,
3455 NamedDecl
*FoundD
, const TemplateArgumentListInfo
*TemplateArgs
,
3456 bool AcceptInvalidDecl
) {
3457 assert(D
&& "Cannot refer to a NULL declaration");
3458 assert(!isa
<FunctionTemplateDecl
>(D
) &&
3459 "Cannot refer unambiguously to a function template");
3461 SourceLocation Loc
= NameInfo
.getLoc();
3462 if (CheckDeclInExpr(*this, Loc
, D
, AcceptInvalidDecl
)) {
3463 // Recovery from invalid cases (e.g. D is an invalid Decl).
3464 // We use the dependent type for the RecoveryExpr to prevent bogus follow-up
3465 // diagnostics, as invalid decls use int as a fallback type.
3466 return CreateRecoveryExpr(NameInfo
.getBeginLoc(), NameInfo
.getEndLoc(), {});
3469 if (TemplateDecl
*Template
= dyn_cast
<TemplateDecl
>(D
)) {
3470 // Specifically diagnose references to class templates that are missing
3471 // a template argument list.
3472 diagnoseMissingTemplateArguments(TemplateName(Template
), Loc
);
3476 // Make sure that we're referring to a value.
3477 if (!isa
<ValueDecl
, UnresolvedUsingIfExistsDecl
>(D
)) {
3478 Diag(Loc
, diag::err_ref_non_value
) << D
<< SS
.getRange();
3479 Diag(D
->getLocation(), diag::note_declared_at
);
3483 // Check whether this declaration can be used. Note that we suppress
3484 // this check when we're going to perform argument-dependent lookup
3485 // on this function name, because this might not be the function
3486 // that overload resolution actually selects.
3487 if (DiagnoseUseOfDecl(D
, Loc
))
3490 auto *VD
= cast
<ValueDecl
>(D
);
3492 // Only create DeclRefExpr's for valid Decl's.
3493 if (VD
->isInvalidDecl() && !AcceptInvalidDecl
)
3496 // Handle members of anonymous structs and unions. If we got here,
3497 // and the reference is to a class member indirect field, then this
3498 // must be the subject of a pointer-to-member expression.
3499 if (auto *IndirectField
= dyn_cast
<IndirectFieldDecl
>(VD
);
3500 IndirectField
&& !IndirectField
->isCXXClassMember())
3501 return BuildAnonymousStructUnionMemberReference(SS
, NameInfo
.getLoc(),
3504 QualType type
= VD
->getType();
3507 ExprValueKind valueKind
= VK_PRValue
;
3509 // In 'T ...V;', the type of the declaration 'V' is 'T...', but the type of
3510 // a reference to 'V' is simply (unexpanded) 'T'. The type, like the value,
3511 // is expanded by some outer '...' in the context of the use.
3512 type
= type
.getNonPackExpansionType();
3514 switch (D
->getKind()) {
3515 // Ignore all the non-ValueDecl kinds.
3516 #define ABSTRACT_DECL(kind)
3517 #define VALUE(type, base)
3518 #define DECL(type, base) case Decl::type:
3519 #include "clang/AST/DeclNodes.inc"
3520 llvm_unreachable("invalid value decl kind");
3522 // These shouldn't make it here.
3523 case Decl::ObjCAtDefsField
:
3524 llvm_unreachable("forming non-member reference to ivar?");
3526 // Enum constants are always r-values and never references.
3527 // Unresolved using declarations are dependent.
3528 case Decl::EnumConstant
:
3529 case Decl::UnresolvedUsingValue
:
3530 case Decl::OMPDeclareReduction
:
3531 case Decl::OMPDeclareMapper
:
3532 valueKind
= VK_PRValue
;
3535 // Fields and indirect fields that got here must be for
3536 // pointer-to-member expressions; we just call them l-values for
3537 // internal consistency, because this subexpression doesn't really
3538 // exist in the high-level semantics.
3540 case Decl::IndirectField
:
3541 case Decl::ObjCIvar
:
3542 assert(getLangOpts().CPlusPlus
&& "building reference to field in C?");
3544 // These can't have reference type in well-formed programs, but
3545 // for internal consistency we do this anyway.
3546 type
= type
.getNonReferenceType();
3547 valueKind
= VK_LValue
;
3550 // Non-type template parameters are either l-values or r-values
3551 // depending on the type.
3552 case Decl::NonTypeTemplateParm
: {
3553 if (const ReferenceType
*reftype
= type
->getAs
<ReferenceType
>()) {
3554 type
= reftype
->getPointeeType();
3555 valueKind
= VK_LValue
; // even if the parameter is an r-value reference
3559 // [expr.prim.id.unqual]p2:
3560 // If the entity is a template parameter object for a template
3561 // parameter of type T, the type of the expression is const T.
3562 // [...] The expression is an lvalue if the entity is a [...] template
3563 // parameter object.
3564 if (type
->isRecordType()) {
3565 type
= type
.getUnqualifiedType().withConst();
3566 valueKind
= VK_LValue
;
3570 // For non-references, we need to strip qualifiers just in case
3571 // the template parameter was declared as 'const int' or whatever.
3572 valueKind
= VK_PRValue
;
3573 type
= type
.getUnqualifiedType();
3578 case Decl::VarTemplateSpecialization
:
3579 case Decl::VarTemplatePartialSpecialization
:
3580 case Decl::Decomposition
:
3581 case Decl::OMPCapturedExpr
:
3582 // In C, "extern void blah;" is valid and is an r-value.
3583 if (!getLangOpts().CPlusPlus
&& !type
.hasQualifiers() &&
3584 type
->isVoidType()) {
3585 valueKind
= VK_PRValue
;
3590 case Decl::ImplicitParam
:
3591 case Decl::ParmVar
: {
3592 // These are always l-values.
3593 valueKind
= VK_LValue
;
3594 type
= type
.getNonReferenceType();
3596 // FIXME: Does the addition of const really only apply in
3597 // potentially-evaluated contexts? Since the variable isn't actually
3598 // captured in an unevaluated context, it seems that the answer is no.
3599 if (!isUnevaluatedContext()) {
3600 QualType CapturedType
= getCapturedDeclRefType(cast
<VarDecl
>(VD
), Loc
);
3601 if (!CapturedType
.isNull())
3602 type
= CapturedType
;
3609 // These are always lvalues.
3610 valueKind
= VK_LValue
;
3611 type
= type
.getNonReferenceType();
3614 case Decl::Function
: {
3615 if (unsigned BID
= cast
<FunctionDecl
>(VD
)->getBuiltinID()) {
3616 if (!Context
.BuiltinInfo
.isDirectlyAddressable(BID
)) {
3617 type
= Context
.BuiltinFnTy
;
3618 valueKind
= VK_PRValue
;
3623 const FunctionType
*fty
= type
->castAs
<FunctionType
>();
3625 // If we're referring to a function with an __unknown_anytype
3626 // result type, make the entire expression __unknown_anytype.
3627 if (fty
->getReturnType() == Context
.UnknownAnyTy
) {
3628 type
= Context
.UnknownAnyTy
;
3629 valueKind
= VK_PRValue
;
3633 // Functions are l-values in C++.
3634 if (getLangOpts().CPlusPlus
) {
3635 valueKind
= VK_LValue
;
3639 // C99 DR 316 says that, if a function type comes from a
3640 // function definition (without a prototype), that type is only
3641 // used for checking compatibility. Therefore, when referencing
3642 // the function, we pretend that we don't have the full function
3644 if (!cast
<FunctionDecl
>(VD
)->hasPrototype() && isa
<FunctionProtoType
>(fty
))
3645 type
= Context
.getFunctionNoProtoType(fty
->getReturnType(),
3648 // Functions are r-values in C.
3649 valueKind
= VK_PRValue
;
3653 case Decl::CXXDeductionGuide
:
3654 llvm_unreachable("building reference to deduction guide");
3656 case Decl::MSProperty
:
3658 case Decl::TemplateParamObject
:
3659 // FIXME: Should MSGuidDecl and template parameter objects be subject to
3660 // capture in OpenMP, or duplicated between host and device?
3661 valueKind
= VK_LValue
;
3664 case Decl::UnnamedGlobalConstant
:
3665 valueKind
= VK_LValue
;
3668 case Decl::CXXMethod
:
3669 // If we're referring to a method with an __unknown_anytype
3670 // result type, make the entire expression __unknown_anytype.
3671 // This should only be possible with a type written directly.
3672 if (const FunctionProtoType
*proto
=
3673 dyn_cast
<FunctionProtoType
>(VD
->getType()))
3674 if (proto
->getReturnType() == Context
.UnknownAnyTy
) {
3675 type
= Context
.UnknownAnyTy
;
3676 valueKind
= VK_PRValue
;
3680 // C++ methods are l-values if static, r-values if non-static.
3681 if (cast
<CXXMethodDecl
>(VD
)->isStatic()) {
3682 valueKind
= VK_LValue
;
3687 case Decl::CXXConversion
:
3688 case Decl::CXXDestructor
:
3689 case Decl::CXXConstructor
:
3690 valueKind
= VK_PRValue
;
3695 BuildDeclRefExpr(VD
, type
, valueKind
, NameInfo
, &SS
, FoundD
,
3696 /*FIXME: TemplateKWLoc*/ SourceLocation(), TemplateArgs
);
3697 // Clang AST consumers assume a DeclRefExpr refers to a valid decl. We
3698 // wrap a DeclRefExpr referring to an invalid decl with a dependent-type
3699 // RecoveryExpr to avoid follow-up semantic analysis (thus prevent bogus
3701 if (VD
->isInvalidDecl() && E
)
3702 return CreateRecoveryExpr(E
->getBeginLoc(), E
->getEndLoc(), {E
});
3706 static void ConvertUTF8ToWideString(unsigned CharByteWidth
, StringRef Source
,
3707 SmallString
<32> &Target
) {
3708 Target
.resize(CharByteWidth
* (Source
.size() + 1));
3709 char *ResultPtr
= &Target
[0];
3710 const llvm::UTF8
*ErrorPtr
;
3712 llvm::ConvertUTF8toWide(CharByteWidth
, Source
, ResultPtr
, ErrorPtr
);
3715 Target
.resize(ResultPtr
- &Target
[0]);
3718 ExprResult
Sema::BuildPredefinedExpr(SourceLocation Loc
,
3719 PredefinedExpr::IdentKind IK
) {
3720 Decl
*currentDecl
= getPredefinedExprDecl(CurContext
);
3722 Diag(Loc
, diag::ext_predef_outside_function
);
3723 currentDecl
= Context
.getTranslationUnitDecl();
3727 StringLiteral
*SL
= nullptr;
3728 if (cast
<DeclContext
>(currentDecl
)->isDependentContext())
3729 ResTy
= Context
.DependentTy
;
3731 // Pre-defined identifiers are of type char[x], where x is the length of
3733 auto Str
= PredefinedExpr::ComputeName(IK
, currentDecl
);
3734 unsigned Length
= Str
.length();
3736 llvm::APInt
LengthI(32, Length
+ 1);
3737 if (IK
== PredefinedExpr::LFunction
|| IK
== PredefinedExpr::LFuncSig
) {
3739 Context
.adjustStringLiteralBaseType(Context
.WideCharTy
.withConst());
3740 SmallString
<32> RawChars
;
3741 ConvertUTF8ToWideString(Context
.getTypeSizeInChars(ResTy
).getQuantity(),
3743 ResTy
= Context
.getConstantArrayType(ResTy
, LengthI
, nullptr,
3744 ArraySizeModifier::Normal
,
3745 /*IndexTypeQuals*/ 0);
3746 SL
= StringLiteral::Create(Context
, RawChars
, StringLiteral::Wide
,
3747 /*Pascal*/ false, ResTy
, Loc
);
3749 ResTy
= Context
.adjustStringLiteralBaseType(Context
.CharTy
.withConst());
3750 ResTy
= Context
.getConstantArrayType(ResTy
, LengthI
, nullptr,
3751 ArraySizeModifier::Normal
,
3752 /*IndexTypeQuals*/ 0);
3753 SL
= StringLiteral::Create(Context
, Str
, StringLiteral::Ordinary
,
3754 /*Pascal*/ false, ResTy
, Loc
);
3758 return PredefinedExpr::Create(Context
, Loc
, ResTy
, IK
, LangOpts
.MicrosoftExt
,
3762 ExprResult
Sema::BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc
,
3763 SourceLocation LParen
,
3764 SourceLocation RParen
,
3765 TypeSourceInfo
*TSI
) {
3766 return SYCLUniqueStableNameExpr::Create(Context
, OpLoc
, LParen
, RParen
, TSI
);
3769 ExprResult
Sema::ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc
,
3770 SourceLocation LParen
,
3771 SourceLocation RParen
,
3772 ParsedType ParsedTy
) {
3773 TypeSourceInfo
*TSI
= nullptr;
3774 QualType Ty
= GetTypeFromParser(ParsedTy
, &TSI
);
3779 TSI
= Context
.getTrivialTypeSourceInfo(Ty
, LParen
);
3781 return BuildSYCLUniqueStableNameExpr(OpLoc
, LParen
, RParen
, TSI
);
3784 ExprResult
Sema::ActOnPredefinedExpr(SourceLocation Loc
, tok::TokenKind Kind
) {
3785 return BuildPredefinedExpr(Loc
, getPredefinedExprKind(Kind
));
3788 ExprResult
Sema::ActOnCharacterConstant(const Token
&Tok
, Scope
*UDLScope
) {
3789 SmallString
<16> CharBuffer
;
3790 bool Invalid
= false;
3791 StringRef ThisTok
= PP
.getSpelling(Tok
, CharBuffer
, &Invalid
);
3795 CharLiteralParser
Literal(ThisTok
.begin(), ThisTok
.end(), Tok
.getLocation(),
3797 if (Literal
.hadError())
3801 if (Literal
.isWide())
3802 Ty
= Context
.WideCharTy
; // L'x' -> wchar_t in C and C++.
3803 else if (Literal
.isUTF8() && getLangOpts().C23
)
3804 Ty
= Context
.UnsignedCharTy
; // u8'x' -> unsigned char in C23
3805 else if (Literal
.isUTF8() && getLangOpts().Char8
)
3806 Ty
= Context
.Char8Ty
; // u8'x' -> char8_t when it exists.
3807 else if (Literal
.isUTF16())
3808 Ty
= Context
.Char16Ty
; // u'x' -> char16_t in C11 and C++11.
3809 else if (Literal
.isUTF32())
3810 Ty
= Context
.Char32Ty
; // U'x' -> char32_t in C11 and C++11.
3811 else if (!getLangOpts().CPlusPlus
|| Literal
.isMultiChar())
3812 Ty
= Context
.IntTy
; // 'x' -> int in C, 'wxyz' -> int in C++.
3814 Ty
= Context
.CharTy
; // 'x' -> char in C++;
3815 // u8'x' -> char in C11-C17 and in C++ without char8_t.
3817 CharacterLiteral::CharacterKind Kind
= CharacterLiteral::Ascii
;
3818 if (Literal
.isWide())
3819 Kind
= CharacterLiteral::Wide
;
3820 else if (Literal
.isUTF16())
3821 Kind
= CharacterLiteral::UTF16
;
3822 else if (Literal
.isUTF32())
3823 Kind
= CharacterLiteral::UTF32
;
3824 else if (Literal
.isUTF8())
3825 Kind
= CharacterLiteral::UTF8
;
3827 Expr
*Lit
= new (Context
) CharacterLiteral(Literal
.getValue(), Kind
, Ty
,
3830 if (Literal
.getUDSuffix().empty())
3833 // We're building a user-defined literal.
3834 IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
3835 SourceLocation UDSuffixLoc
=
3836 getUDSuffixLoc(*this, Tok
.getLocation(), Literal
.getUDSuffixOffset());
3838 // Make sure we're allowed user-defined literals here.
3840 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_character_udl
));
3842 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3843 // operator "" X (ch)
3844 return BuildCookedLiteralOperatorCall(*this, UDLScope
, UDSuffix
, UDSuffixLoc
,
3845 Lit
, Tok
.getLocation());
3848 ExprResult
Sema::ActOnIntegerConstant(SourceLocation Loc
, uint64_t Val
) {
3849 unsigned IntSize
= Context
.getTargetInfo().getIntWidth();
3850 return IntegerLiteral::Create(Context
, llvm::APInt(IntSize
, Val
),
3851 Context
.IntTy
, Loc
);
3854 static Expr
*BuildFloatingLiteral(Sema
&S
, NumericLiteralParser
&Literal
,
3855 QualType Ty
, SourceLocation Loc
) {
3856 const llvm::fltSemantics
&Format
= S
.Context
.getFloatTypeSemantics(Ty
);
3858 using llvm::APFloat
;
3859 APFloat
Val(Format
);
3861 APFloat::opStatus result
= Literal
.GetFloatValue(Val
);
3863 // Overflow is always an error, but underflow is only an error if
3864 // we underflowed to zero (APFloat reports denormals as underflow).
3865 if ((result
& APFloat::opOverflow
) ||
3866 ((result
& APFloat::opUnderflow
) && Val
.isZero())) {
3867 unsigned diagnostic
;
3868 SmallString
<20> buffer
;
3869 if (result
& APFloat::opOverflow
) {
3870 diagnostic
= diag::warn_float_overflow
;
3871 APFloat::getLargest(Format
).toString(buffer
);
3873 diagnostic
= diag::warn_float_underflow
;
3874 APFloat::getSmallest(Format
).toString(buffer
);
3877 S
.Diag(Loc
, diagnostic
)
3879 << StringRef(buffer
.data(), buffer
.size());
3882 bool isExact
= (result
== APFloat::opOK
);
3883 return FloatingLiteral::Create(S
.Context
, Val
, isExact
, Ty
, Loc
);
3886 bool Sema::CheckLoopHintExpr(Expr
*E
, SourceLocation Loc
) {
3887 assert(E
&& "Invalid expression");
3889 if (E
->isValueDependent())
3892 QualType QT
= E
->getType();
3893 if (!QT
->isIntegerType() || QT
->isBooleanType() || QT
->isCharType()) {
3894 Diag(E
->getExprLoc(), diag::err_pragma_loop_invalid_argument_type
) << QT
;
3898 llvm::APSInt ValueAPS
;
3899 ExprResult R
= VerifyIntegerConstantExpression(E
, &ValueAPS
);
3904 bool ValueIsPositive
= ValueAPS
.isStrictlyPositive();
3905 if (!ValueIsPositive
|| ValueAPS
.getActiveBits() > 31) {
3906 Diag(E
->getExprLoc(), diag::err_pragma_loop_invalid_argument_value
)
3907 << toString(ValueAPS
, 10) << ValueIsPositive
;
3914 ExprResult
Sema::ActOnNumericConstant(const Token
&Tok
, Scope
*UDLScope
) {
3915 // Fast path for a single digit (which is quite common). A single digit
3916 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3917 if (Tok
.getLength() == 1) {
3918 const char Val
= PP
.getSpellingOfSingleCharacterNumericConstant(Tok
);
3919 return ActOnIntegerConstant(Tok
.getLocation(), Val
-'0');
3922 SmallString
<128> SpellingBuffer
;
3923 // NumericLiteralParser wants to overread by one character. Add padding to
3924 // the buffer in case the token is copied to the buffer. If getSpelling()
3925 // returns a StringRef to the memory buffer, it should have a null char at
3926 // the EOF, so it is also safe.
3927 SpellingBuffer
.resize(Tok
.getLength() + 1);
3929 // Get the spelling of the token, which eliminates trigraphs, etc.
3930 bool Invalid
= false;
3931 StringRef TokSpelling
= PP
.getSpelling(Tok
, SpellingBuffer
, &Invalid
);
3935 NumericLiteralParser
Literal(TokSpelling
, Tok
.getLocation(),
3936 PP
.getSourceManager(), PP
.getLangOpts(),
3937 PP
.getTargetInfo(), PP
.getDiagnostics());
3938 if (Literal
.hadError
)
3941 if (Literal
.hasUDSuffix()) {
3942 // We're building a user-defined literal.
3943 const IdentifierInfo
*UDSuffix
= &Context
.Idents
.get(Literal
.getUDSuffix());
3944 SourceLocation UDSuffixLoc
=
3945 getUDSuffixLoc(*this, Tok
.getLocation(), Literal
.getUDSuffixOffset());
3947 // Make sure we're allowed user-defined literals here.
3949 return ExprError(Diag(UDSuffixLoc
, diag::err_invalid_numeric_udl
));
3952 if (Literal
.isFloatingLiteral()) {
3953 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3954 // long double, the literal is treated as a call of the form
3955 // operator "" X (f L)
3956 CookedTy
= Context
.LongDoubleTy
;
3958 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3959 // unsigned long long, the literal is treated as a call of the form
3960 // operator "" X (n ULL)
3961 CookedTy
= Context
.UnsignedLongLongTy
;
3964 DeclarationName OpName
=
3965 Context
.DeclarationNames
.getCXXLiteralOperatorName(UDSuffix
);
3966 DeclarationNameInfo
OpNameInfo(OpName
, UDSuffixLoc
);
3967 OpNameInfo
.setCXXLiteralOperatorNameLoc(UDSuffixLoc
);
3969 SourceLocation TokLoc
= Tok
.getLocation();
3971 // Perform literal operator lookup to determine if we're building a raw
3972 // literal or a cooked one.
3973 LookupResult
R(*this, OpName
, UDSuffixLoc
, LookupOrdinaryName
);
3974 switch (LookupLiteralOperator(UDLScope
, R
, CookedTy
,
3975 /*AllowRaw*/ true, /*AllowTemplate*/ true,
3976 /*AllowStringTemplatePack*/ false,
3977 /*DiagnoseMissing*/ !Literal
.isImaginary
)) {
3978 case LOLR_ErrorNoDiagnostic
:
3979 // Lookup failure for imaginary constants isn't fatal, there's still the
3980 // GNU extension producing _Complex types.
3986 if (Literal
.isFloatingLiteral()) {
3987 Lit
= BuildFloatingLiteral(*this, Literal
, CookedTy
, Tok
.getLocation());
3989 llvm::APInt
ResultVal(Context
.getTargetInfo().getLongLongWidth(), 0);
3990 if (Literal
.GetIntegerValue(ResultVal
))
3991 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
3992 << /* Unsigned */ 1;
3993 Lit
= IntegerLiteral::Create(Context
, ResultVal
, CookedTy
,
3996 return BuildLiteralOperatorCall(R
, OpNameInfo
, Lit
, TokLoc
);
4000 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
4001 // literal is treated as a call of the form
4002 // operator "" X ("n")
4003 unsigned Length
= Literal
.getUDSuffixOffset();
4004 QualType StrTy
= Context
.getConstantArrayType(
4005 Context
.adjustStringLiteralBaseType(Context
.CharTy
.withConst()),
4006 llvm::APInt(32, Length
+ 1), nullptr, ArraySizeModifier::Normal
, 0);
4008 StringLiteral::Create(Context
, StringRef(TokSpelling
.data(), Length
),
4009 StringLiteral::Ordinary
,
4010 /*Pascal*/ false, StrTy
, &TokLoc
, 1);
4011 return BuildLiteralOperatorCall(R
, OpNameInfo
, Lit
, TokLoc
);
4014 case LOLR_Template
: {
4015 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
4016 // template), L is treated as a call fo the form
4017 // operator "" X <'c1', 'c2', ... 'ck'>()
4018 // where n is the source character sequence c1 c2 ... ck.
4019 TemplateArgumentListInfo ExplicitArgs
;
4020 unsigned CharBits
= Context
.getIntWidth(Context
.CharTy
);
4021 bool CharIsUnsigned
= Context
.CharTy
->isUnsignedIntegerType();
4022 llvm::APSInt
Value(CharBits
, CharIsUnsigned
);
4023 for (unsigned I
= 0, N
= Literal
.getUDSuffixOffset(); I
!= N
; ++I
) {
4024 Value
= TokSpelling
[I
];
4025 TemplateArgument
Arg(Context
, Value
, Context
.CharTy
);
4026 TemplateArgumentLocInfo ArgInfo
;
4027 ExplicitArgs
.addArgument(TemplateArgumentLoc(Arg
, ArgInfo
));
4029 return BuildLiteralOperatorCall(R
, OpNameInfo
, std::nullopt
, TokLoc
,
4032 case LOLR_StringTemplatePack
:
4033 llvm_unreachable("unexpected literal operator lookup result");
4039 if (Literal
.isFixedPointLiteral()) {
4042 if (Literal
.isAccum
) {
4043 if (Literal
.isHalf
) {
4044 Ty
= Context
.ShortAccumTy
;
4045 } else if (Literal
.isLong
) {
4046 Ty
= Context
.LongAccumTy
;
4048 Ty
= Context
.AccumTy
;
4050 } else if (Literal
.isFract
) {
4051 if (Literal
.isHalf
) {
4052 Ty
= Context
.ShortFractTy
;
4053 } else if (Literal
.isLong
) {
4054 Ty
= Context
.LongFractTy
;
4056 Ty
= Context
.FractTy
;
4060 if (Literal
.isUnsigned
) Ty
= Context
.getCorrespondingUnsignedType(Ty
);
4062 bool isSigned
= !Literal
.isUnsigned
;
4063 unsigned scale
= Context
.getFixedPointScale(Ty
);
4064 unsigned bit_width
= Context
.getTypeInfo(Ty
).Width
;
4066 llvm::APInt
Val(bit_width
, 0, isSigned
);
4067 bool Overflowed
= Literal
.GetFixedPointValue(Val
, scale
);
4068 bool ValIsZero
= Val
.isZero() && !Overflowed
;
4070 auto MaxVal
= Context
.getFixedPointMax(Ty
).getValue();
4071 if (Literal
.isFract
&& Val
== MaxVal
+ 1 && !ValIsZero
)
4072 // Clause 6.4.4 - The value of a constant shall be in the range of
4073 // representable values for its type, with exception for constants of a
4074 // fract type with a value of exactly 1; such a constant shall denote
4075 // the maximal value for the type.
4077 else if (Val
.ugt(MaxVal
) || Overflowed
)
4078 Diag(Tok
.getLocation(), diag::err_too_large_for_fixed_point
);
4080 Res
= FixedPointLiteral::CreateFromRawInt(Context
, Val
, Ty
,
4081 Tok
.getLocation(), scale
);
4082 } else if (Literal
.isFloatingLiteral()) {
4084 if (Literal
.isHalf
){
4085 if (getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()))
4086 Ty
= Context
.HalfTy
;
4088 Diag(Tok
.getLocation(), diag::err_half_const_requires_fp16
);
4091 } else if (Literal
.isFloat
)
4092 Ty
= Context
.FloatTy
;
4093 else if (Literal
.isLong
)
4094 Ty
= Context
.LongDoubleTy
;
4095 else if (Literal
.isFloat16
)
4096 Ty
= Context
.Float16Ty
;
4097 else if (Literal
.isFloat128
)
4098 Ty
= Context
.Float128Ty
;
4100 Ty
= Context
.DoubleTy
;
4102 Res
= BuildFloatingLiteral(*this, Literal
, Ty
, Tok
.getLocation());
4104 if (Ty
== Context
.DoubleTy
) {
4105 if (getLangOpts().SinglePrecisionConstants
) {
4106 if (Ty
->castAs
<BuiltinType
>()->getKind() != BuiltinType::Float
) {
4107 Res
= ImpCastExprToType(Res
, Context
.FloatTy
, CK_FloatingCast
).get();
4109 } else if (getLangOpts().OpenCL
&& !getOpenCLOptions().isAvailableOption(
4110 "cl_khr_fp64", getLangOpts())) {
4111 // Impose single-precision float type when cl_khr_fp64 is not enabled.
4112 Diag(Tok
.getLocation(), diag::warn_double_const_requires_fp64
)
4113 << (getLangOpts().getOpenCLCompatibleVersion() >= 300);
4114 Res
= ImpCastExprToType(Res
, Context
.FloatTy
, CK_FloatingCast
).get();
4117 } else if (!Literal
.isIntegerLiteral()) {
4122 // 'z/uz' literals are a C++23 feature.
4123 if (Literal
.isSizeT
)
4124 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus
4125 ? getLangOpts().CPlusPlus23
4126 ? diag::warn_cxx20_compat_size_t_suffix
4127 : diag::ext_cxx23_size_t_suffix
4128 : diag::err_cxx23_size_t_suffix
);
4130 // 'wb/uwb' literals are a C23 feature. We support _BitInt as a type in C++,
4131 // but we do not currently support the suffix in C++ mode because it's not
4132 // entirely clear whether WG21 will prefer this suffix to return a library
4133 // type such as std::bit_int instead of returning a _BitInt.
4134 if (Literal
.isBitInt
&& !getLangOpts().CPlusPlus
)
4135 PP
.Diag(Tok
.getLocation(), getLangOpts().C23
4136 ? diag::warn_c23_compat_bitint_suffix
4137 : diag::ext_c23_bitint_suffix
);
4139 // Get the value in the widest-possible width. What is "widest" depends on
4140 // whether the literal is a bit-precise integer or not. For a bit-precise
4141 // integer type, try to scan the source to determine how many bits are
4142 // needed to represent the value. This may seem a bit expensive, but trying
4143 // to get the integer value from an overly-wide APInt is *extremely*
4144 // expensive, so the naive approach of assuming
4145 // llvm::IntegerType::MAX_INT_BITS is a big performance hit.
4146 unsigned BitsNeeded
=
4147 Literal
.isBitInt
? llvm::APInt::getSufficientBitsNeeded(
4148 Literal
.getLiteralDigits(), Literal
.getRadix())
4149 : Context
.getTargetInfo().getIntMaxTWidth();
4150 llvm::APInt
ResultVal(BitsNeeded
, 0);
4152 if (Literal
.GetIntegerValue(ResultVal
)) {
4153 // If this value didn't fit into uintmax_t, error and force to ull.
4154 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
4155 << /* Unsigned */ 1;
4156 Ty
= Context
.UnsignedLongLongTy
;
4157 assert(Context
.getTypeSize(Ty
) == ResultVal
.getBitWidth() &&
4158 "long long is not intmax_t?");
4160 // If this value fits into a ULL, try to figure out what else it fits into
4161 // according to the rules of C99 6.4.4.1p5.
4163 // Octal, Hexadecimal, and integers with a U suffix are allowed to
4164 // be an unsigned int.
4165 bool AllowUnsigned
= Literal
.isUnsigned
|| Literal
.getRadix() != 10;
4167 // Check from smallest to largest, picking the smallest type we can.
4170 // Microsoft specific integer suffixes are explicitly sized.
4171 if (Literal
.MicrosoftInteger
) {
4172 if (Literal
.MicrosoftInteger
== 8 && !Literal
.isUnsigned
) {
4174 Ty
= Context
.CharTy
;
4176 Width
= Literal
.MicrosoftInteger
;
4177 Ty
= Context
.getIntTypeForBitwidth(Width
,
4178 /*Signed=*/!Literal
.isUnsigned
);
4182 // Bit-precise integer literals are automagically-sized based on the
4183 // width required by the literal.
4184 if (Literal
.isBitInt
) {
4185 // The signed version has one more bit for the sign value. There are no
4186 // zero-width bit-precise integers, even if the literal value is 0.
4187 Width
= std::max(ResultVal
.getActiveBits(), 1u) +
4188 (Literal
.isUnsigned
? 0u : 1u);
4190 // Diagnose if the width of the constant is larger than BITINT_MAXWIDTH,
4191 // and reset the type to the largest supported width.
4192 unsigned int MaxBitIntWidth
=
4193 Context
.getTargetInfo().getMaxBitIntWidth();
4194 if (Width
> MaxBitIntWidth
) {
4195 Diag(Tok
.getLocation(), diag::err_integer_literal_too_large
)
4196 << Literal
.isUnsigned
;
4197 Width
= MaxBitIntWidth
;
4200 // Reset the result value to the smaller APInt and select the correct
4201 // type to be used. Note, we zext even for signed values because the
4202 // literal itself is always an unsigned value (a preceeding - is a
4203 // unary operator, not part of the literal).
4204 ResultVal
= ResultVal
.zextOrTrunc(Width
);
4205 Ty
= Context
.getBitIntType(Literal
.isUnsigned
, Width
);
4208 // Check C++23 size_t literals.
4209 if (Literal
.isSizeT
) {
4210 assert(!Literal
.MicrosoftInteger
&&
4211 "size_t literals can't be Microsoft literals");
4212 unsigned SizeTSize
= Context
.getTargetInfo().getTypeWidth(
4213 Context
.getTargetInfo().getSizeType());
4215 // Does it fit in size_t?
4216 if (ResultVal
.isIntN(SizeTSize
)) {
4217 // Does it fit in ssize_t?
4218 if (!Literal
.isUnsigned
&& ResultVal
[SizeTSize
- 1] == 0)
4219 Ty
= Context
.getSignedSizeType();
4220 else if (AllowUnsigned
)
4221 Ty
= Context
.getSizeType();
4226 if (Ty
.isNull() && !Literal
.isLong
&& !Literal
.isLongLong
&&
4228 // Are int/unsigned possibilities?
4229 unsigned IntSize
= Context
.getTargetInfo().getIntWidth();
4231 // Does it fit in a unsigned int?
4232 if (ResultVal
.isIntN(IntSize
)) {
4233 // Does it fit in a signed int?
4234 if (!Literal
.isUnsigned
&& ResultVal
[IntSize
-1] == 0)
4236 else if (AllowUnsigned
)
4237 Ty
= Context
.UnsignedIntTy
;
4242 // Are long/unsigned long possibilities?
4243 if (Ty
.isNull() && !Literal
.isLongLong
&& !Literal
.isSizeT
) {
4244 unsigned LongSize
= Context
.getTargetInfo().getLongWidth();
4246 // Does it fit in a unsigned long?
4247 if (ResultVal
.isIntN(LongSize
)) {
4248 // Does it fit in a signed long?
4249 if (!Literal
.isUnsigned
&& ResultVal
[LongSize
-1] == 0)
4250 Ty
= Context
.LongTy
;
4251 else if (AllowUnsigned
)
4252 Ty
= Context
.UnsignedLongTy
;
4253 // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
4255 else if (!getLangOpts().C99
&& !getLangOpts().CPlusPlus11
) {
4256 const unsigned LongLongSize
=
4257 Context
.getTargetInfo().getLongLongWidth();
4258 Diag(Tok
.getLocation(),
4259 getLangOpts().CPlusPlus
4261 ? diag::warn_old_implicitly_unsigned_long_cxx
4262 : /*C++98 UB*/ diag::
4263 ext_old_implicitly_unsigned_long_cxx
4264 : diag::warn_old_implicitly_unsigned_long
)
4265 << (LongLongSize
> LongSize
? /*will have type 'long long'*/ 0
4266 : /*will be ill-formed*/ 1);
4267 Ty
= Context
.UnsignedLongTy
;
4273 // Check long long if needed.
4274 if (Ty
.isNull() && !Literal
.isSizeT
) {
4275 unsigned LongLongSize
= Context
.getTargetInfo().getLongLongWidth();
4277 // Does it fit in a unsigned long long?
4278 if (ResultVal
.isIntN(LongLongSize
)) {
4279 // Does it fit in a signed long long?
4280 // To be compatible with MSVC, hex integer literals ending with the
4281 // LL or i64 suffix are always signed in Microsoft mode.
4282 if (!Literal
.isUnsigned
&& (ResultVal
[LongLongSize
-1] == 0 ||
4283 (getLangOpts().MSVCCompat
&& Literal
.isLongLong
)))
4284 Ty
= Context
.LongLongTy
;
4285 else if (AllowUnsigned
)
4286 Ty
= Context
.UnsignedLongLongTy
;
4287 Width
= LongLongSize
;
4289 // 'long long' is a C99 or C++11 feature, whether the literal
4290 // explicitly specified 'long long' or we needed the extra width.
4291 if (getLangOpts().CPlusPlus
)
4292 Diag(Tok
.getLocation(), getLangOpts().CPlusPlus11
4293 ? diag::warn_cxx98_compat_longlong
4294 : diag::ext_cxx11_longlong
);
4295 else if (!getLangOpts().C99
)
4296 Diag(Tok
.getLocation(), diag::ext_c99_longlong
);
4300 // If we still couldn't decide a type, we either have 'size_t' literal
4301 // that is out of range, or a decimal literal that does not fit in a
4302 // signed long long and has no U suffix.
4304 if (Literal
.isSizeT
)
4305 Diag(Tok
.getLocation(), diag::err_size_t_literal_too_large
)
4306 << Literal
.isUnsigned
;
4308 Diag(Tok
.getLocation(),
4309 diag::ext_integer_literal_too_large_for_signed
);
4310 Ty
= Context
.UnsignedLongLongTy
;
4311 Width
= Context
.getTargetInfo().getLongLongWidth();
4314 if (ResultVal
.getBitWidth() != Width
)
4315 ResultVal
= ResultVal
.trunc(Width
);
4317 Res
= IntegerLiteral::Create(Context
, ResultVal
, Ty
, Tok
.getLocation());
4320 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
4321 if (Literal
.isImaginary
) {
4322 Res
= new (Context
) ImaginaryLiteral(Res
,
4323 Context
.getComplexType(Res
->getType()));
4325 Diag(Tok
.getLocation(), diag::ext_imaginary_constant
);
4330 ExprResult
Sema::ActOnParenExpr(SourceLocation L
, SourceLocation R
, Expr
*E
) {
4331 assert(E
&& "ActOnParenExpr() missing expr");
4332 QualType ExprTy
= E
->getType();
4333 if (getLangOpts().ProtectParens
&& CurFPFeatures
.getAllowFPReassociate() &&
4334 !E
->isLValue() && ExprTy
->hasFloatingRepresentation())
4335 return BuildBuiltinCallExpr(R
, Builtin::BI__arithmetic_fence
, E
);
4336 return new (Context
) ParenExpr(L
, R
, E
);
4339 static bool CheckVecStepTraitOperandType(Sema
&S
, QualType T
,
4341 SourceRange ArgRange
) {
4342 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
4343 // scalar or vector data type argument..."
4344 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
4345 // type (C99 6.2.5p18) or void.
4346 if (!(T
->isArithmeticType() || T
->isVoidType() || T
->isVectorType())) {
4347 S
.Diag(Loc
, diag::err_vecstep_non_scalar_vector_type
)
4352 assert((T
->isVoidType() || !T
->isIncompleteType()) &&
4353 "Scalar types should always be complete");
4357 static bool CheckVectorElementsTraitOperandType(Sema
&S
, QualType T
,
4359 SourceRange ArgRange
) {
4360 // builtin_vectorelements supports both fixed-sized and scalable vectors.
4361 if (!T
->isVectorType() && !T
->isSizelessVectorType())
4362 return S
.Diag(Loc
, diag::err_builtin_non_vector_type
)
4364 << "__builtin_vectorelements" << T
<< ArgRange
;
4369 static bool CheckExtensionTraitOperandType(Sema
&S
, QualType T
,
4371 SourceRange ArgRange
,
4372 UnaryExprOrTypeTrait TraitKind
) {
4373 // Invalid types must be hard errors for SFINAE in C++.
4374 if (S
.LangOpts
.CPlusPlus
)
4378 if (T
->isFunctionType() &&
4379 (TraitKind
== UETT_SizeOf
|| TraitKind
== UETT_AlignOf
||
4380 TraitKind
== UETT_PreferredAlignOf
)) {
4381 // sizeof(function)/alignof(function) is allowed as an extension.
4382 S
.Diag(Loc
, diag::ext_sizeof_alignof_function_type
)
4383 << getTraitSpelling(TraitKind
) << ArgRange
;
4387 // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
4388 // this is an error (OpenCL v1.1 s6.3.k)
4389 if (T
->isVoidType()) {
4390 unsigned DiagID
= S
.LangOpts
.OpenCL
? diag::err_opencl_sizeof_alignof_type
4391 : diag::ext_sizeof_alignof_void_type
;
4392 S
.Diag(Loc
, DiagID
) << getTraitSpelling(TraitKind
) << ArgRange
;
4399 static bool CheckObjCTraitOperandConstraints(Sema
&S
, QualType T
,
4401 SourceRange ArgRange
,
4402 UnaryExprOrTypeTrait TraitKind
) {
4403 // Reject sizeof(interface) and sizeof(interface<proto>) if the
4404 // runtime doesn't allow it.
4405 if (!S
.LangOpts
.ObjCRuntime
.allowsSizeofAlignof() && T
->isObjCObjectType()) {
4406 S
.Diag(Loc
, diag::err_sizeof_nonfragile_interface
)
4407 << T
<< (TraitKind
== UETT_SizeOf
)
4415 /// Check whether E is a pointer from a decayed array type (the decayed
4416 /// pointer type is equal to T) and emit a warning if it is.
4417 static void warnOnSizeofOnArrayDecay(Sema
&S
, SourceLocation Loc
, QualType T
,
4419 // Don't warn if the operation changed the type.
4420 if (T
!= E
->getType())
4423 // Now look for array decays.
4424 const auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
);
4425 if (!ICE
|| ICE
->getCastKind() != CK_ArrayToPointerDecay
)
4428 S
.Diag(Loc
, diag::warn_sizeof_array_decay
) << ICE
->getSourceRange()
4430 << ICE
->getSubExpr()->getType();
4433 /// Check the constraints on expression operands to unary type expression
4434 /// and type traits.
4436 /// Completes any types necessary and validates the constraints on the operand
4437 /// expression. The logic mostly mirrors the type-based overload, but may modify
4438 /// the expression as it completes the type for that expression through template
4439 /// instantiation, etc.
4440 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr
*E
,
4441 UnaryExprOrTypeTrait ExprKind
) {
4442 QualType ExprTy
= E
->getType();
4443 assert(!ExprTy
->isReferenceType());
4445 bool IsUnevaluatedOperand
=
4446 (ExprKind
== UETT_SizeOf
|| ExprKind
== UETT_AlignOf
||
4447 ExprKind
== UETT_PreferredAlignOf
|| ExprKind
== UETT_VecStep
);
4448 if (IsUnevaluatedOperand
) {
4449 ExprResult Result
= CheckUnevaluatedOperand(E
);
4450 if (Result
.isInvalid())
4455 // The operand for sizeof and alignof is in an unevaluated expression context,
4456 // so side effects could result in unintended consequences.
4457 // Exclude instantiation-dependent expressions, because 'sizeof' is sometimes
4458 // used to build SFINAE gadgets.
4459 // FIXME: Should we consider instantiation-dependent operands to 'alignof'?
4460 if (IsUnevaluatedOperand
&& !inTemplateInstantiation() &&
4461 !E
->isInstantiationDependent() &&
4462 !E
->getType()->isVariableArrayType() &&
4463 E
->HasSideEffects(Context
, false))
4464 Diag(E
->getExprLoc(), diag::warn_side_effects_unevaluated_context
);
4466 if (ExprKind
== UETT_VecStep
)
4467 return CheckVecStepTraitOperandType(*this, ExprTy
, E
->getExprLoc(),
4468 E
->getSourceRange());
4470 if (ExprKind
== UETT_VectorElements
)
4471 return CheckVectorElementsTraitOperandType(*this, ExprTy
, E
->getExprLoc(),
4472 E
->getSourceRange());
4474 // Explicitly list some types as extensions.
4475 if (!CheckExtensionTraitOperandType(*this, ExprTy
, E
->getExprLoc(),
4476 E
->getSourceRange(), ExprKind
))
4479 // WebAssembly tables are always illegal operands to unary expressions and
4481 if (Context
.getTargetInfo().getTriple().isWasm() &&
4482 E
->getType()->isWebAssemblyTableType()) {
4483 Diag(E
->getExprLoc(), diag::err_wasm_table_invalid_uett_operand
)
4484 << getTraitSpelling(ExprKind
);
4488 // 'alignof' applied to an expression only requires the base element type of
4489 // the expression to be complete. 'sizeof' requires the expression's type to
4490 // be complete (and will attempt to complete it if it's an array of unknown
4492 if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
) {
4493 if (RequireCompleteSizedType(
4494 E
->getExprLoc(), Context
.getBaseElementType(E
->getType()),
4495 diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4496 getTraitSpelling(ExprKind
), E
->getSourceRange()))
4499 if (RequireCompleteSizedExprType(
4500 E
, diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4501 getTraitSpelling(ExprKind
), E
->getSourceRange()))
4505 // Completing the expression's type may have changed it.
4506 ExprTy
= E
->getType();
4507 assert(!ExprTy
->isReferenceType());
4509 if (ExprTy
->isFunctionType()) {
4510 Diag(E
->getExprLoc(), diag::err_sizeof_alignof_function_type
)
4511 << getTraitSpelling(ExprKind
) << E
->getSourceRange();
4515 if (CheckObjCTraitOperandConstraints(*this, ExprTy
, E
->getExprLoc(),
4516 E
->getSourceRange(), ExprKind
))
4519 if (ExprKind
== UETT_SizeOf
) {
4520 if (const auto *DeclRef
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParens())) {
4521 if (const auto *PVD
= dyn_cast
<ParmVarDecl
>(DeclRef
->getFoundDecl())) {
4522 QualType OType
= PVD
->getOriginalType();
4523 QualType Type
= PVD
->getType();
4524 if (Type
->isPointerType() && OType
->isArrayType()) {
4525 Diag(E
->getExprLoc(), diag::warn_sizeof_array_param
)
4527 Diag(PVD
->getLocation(), diag::note_declared_at
);
4532 // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
4533 // decays into a pointer and returns an unintended result. This is most
4534 // likely a typo for "sizeof(array) op x".
4535 if (const auto *BO
= dyn_cast
<BinaryOperator
>(E
->IgnoreParens())) {
4536 warnOnSizeofOnArrayDecay(*this, BO
->getOperatorLoc(), BO
->getType(),
4538 warnOnSizeofOnArrayDecay(*this, BO
->getOperatorLoc(), BO
->getType(),
4546 static bool CheckAlignOfExpr(Sema
&S
, Expr
*E
, UnaryExprOrTypeTrait ExprKind
) {
4547 // Cannot know anything else if the expression is dependent.
4548 if (E
->isTypeDependent())
4551 if (E
->getObjectKind() == OK_BitField
) {
4552 S
.Diag(E
->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield
)
4553 << 1 << E
->getSourceRange();
4557 ValueDecl
*D
= nullptr;
4558 Expr
*Inner
= E
->IgnoreParens();
4559 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Inner
)) {
4561 } else if (MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Inner
)) {
4562 D
= ME
->getMemberDecl();
4565 // If it's a field, require the containing struct to have a
4566 // complete definition so that we can compute the layout.
4568 // This can happen in C++11 onwards, either by naming the member
4569 // in a way that is not transformed into a member access expression
4570 // (in an unevaluated operand, for instance), or by naming the member
4571 // in a trailing-return-type.
4573 // For the record, since __alignof__ on expressions is a GCC
4574 // extension, GCC seems to permit this but always gives the
4575 // nonsensical answer 0.
4577 // We don't really need the layout here --- we could instead just
4578 // directly check for all the appropriate alignment-lowing
4579 // attributes --- but that would require duplicating a lot of
4580 // logic that just isn't worth duplicating for such a marginal
4582 if (FieldDecl
*FD
= dyn_cast_or_null
<FieldDecl
>(D
)) {
4583 // Fast path this check, since we at least know the record has a
4584 // definition if we can find a member of it.
4585 if (!FD
->getParent()->isCompleteDefinition()) {
4586 S
.Diag(E
->getExprLoc(), diag::err_alignof_member_of_incomplete_type
)
4587 << E
->getSourceRange();
4591 // Otherwise, if it's a field, and the field doesn't have
4592 // reference type, then it must have a complete type (or be a
4593 // flexible array member, which we explicitly want to
4594 // white-list anyway), which makes the following checks trivial.
4595 if (!FD
->getType()->isReferenceType())
4599 return S
.CheckUnaryExprOrTypeTraitOperand(E
, ExprKind
);
4602 bool Sema::CheckVecStepExpr(Expr
*E
) {
4603 E
= E
->IgnoreParens();
4605 // Cannot know anything else if the expression is dependent.
4606 if (E
->isTypeDependent())
4609 return CheckUnaryExprOrTypeTraitOperand(E
, UETT_VecStep
);
4612 static void captureVariablyModifiedType(ASTContext
&Context
, QualType T
,
4613 CapturingScopeInfo
*CSI
) {
4614 assert(T
->isVariablyModifiedType());
4615 assert(CSI
!= nullptr);
4617 // We're going to walk down into the type and look for VLA expressions.
4619 const Type
*Ty
= T
.getTypePtr();
4620 switch (Ty
->getTypeClass()) {
4621 #define TYPE(Class, Base)
4622 #define ABSTRACT_TYPE(Class, Base)
4623 #define NON_CANONICAL_TYPE(Class, Base)
4624 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4625 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4626 #include "clang/AST/TypeNodes.inc"
4629 // These types are never variably-modified.
4633 case Type::ExtVector
:
4634 case Type::ConstantMatrix
:
4637 case Type::TemplateSpecialization
:
4638 case Type::ObjCObject
:
4639 case Type::ObjCInterface
:
4640 case Type::ObjCObjectPointer
:
4641 case Type::ObjCTypeParam
:
4644 llvm_unreachable("type class is never variably-modified!");
4645 case Type::Elaborated
:
4646 T
= cast
<ElaboratedType
>(Ty
)->getNamedType();
4648 case Type::Adjusted
:
4649 T
= cast
<AdjustedType
>(Ty
)->getOriginalType();
4652 T
= cast
<DecayedType
>(Ty
)->getPointeeType();
4655 T
= cast
<PointerType
>(Ty
)->getPointeeType();
4657 case Type::BlockPointer
:
4658 T
= cast
<BlockPointerType
>(Ty
)->getPointeeType();
4660 case Type::LValueReference
:
4661 case Type::RValueReference
:
4662 T
= cast
<ReferenceType
>(Ty
)->getPointeeType();
4664 case Type::MemberPointer
:
4665 T
= cast
<MemberPointerType
>(Ty
)->getPointeeType();
4667 case Type::ConstantArray
:
4668 case Type::IncompleteArray
:
4669 // Losing element qualification here is fine.
4670 T
= cast
<ArrayType
>(Ty
)->getElementType();
4672 case Type::VariableArray
: {
4673 // Losing element qualification here is fine.
4674 const VariableArrayType
*VAT
= cast
<VariableArrayType
>(Ty
);
4676 // Unknown size indication requires no size computation.
4677 // Otherwise, evaluate and record it.
4678 auto Size
= VAT
->getSizeExpr();
4679 if (Size
&& !CSI
->isVLATypeCaptured(VAT
) &&
4680 (isa
<CapturedRegionScopeInfo
>(CSI
) || isa
<LambdaScopeInfo
>(CSI
)))
4681 CSI
->addVLATypeCapture(Size
->getExprLoc(), VAT
, Context
.getSizeType());
4683 T
= VAT
->getElementType();
4686 case Type::FunctionProto
:
4687 case Type::FunctionNoProto
:
4688 T
= cast
<FunctionType
>(Ty
)->getReturnType();
4692 case Type::UnaryTransform
:
4693 case Type::Attributed
:
4694 case Type::BTFTagAttributed
:
4695 case Type::SubstTemplateTypeParm
:
4696 case Type::MacroQualified
:
4697 // Keep walking after single level desugaring.
4698 T
= T
.getSingleStepDesugaredType(Context
);
4701 T
= cast
<TypedefType
>(Ty
)->desugar();
4703 case Type::Decltype
:
4704 T
= cast
<DecltypeType
>(Ty
)->desugar();
4707 T
= cast
<UsingType
>(Ty
)->desugar();
4710 case Type::DeducedTemplateSpecialization
:
4711 T
= cast
<DeducedType
>(Ty
)->getDeducedType();
4713 case Type::TypeOfExpr
:
4714 T
= cast
<TypeOfExprType
>(Ty
)->getUnderlyingExpr()->getType();
4717 T
= cast
<AtomicType
>(Ty
)->getValueType();
4720 } while (!T
.isNull() && T
->isVariablyModifiedType());
4723 /// Check the constraints on operands to unary expression and type
4726 /// This will complete any types necessary, and validate the various constraints
4727 /// on those operands.
4729 /// The UsualUnaryConversions() function is *not* called by this routine.
4730 /// C99 6.3.2.1p[2-4] all state:
4731 /// Except when it is the operand of the sizeof operator ...
4733 /// C++ [expr.sizeof]p4
4734 /// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
4735 /// standard conversions are not applied to the operand of sizeof.
4737 /// This policy is followed for all of the unary trait expressions.
4738 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType
,
4739 SourceLocation OpLoc
,
4740 SourceRange ExprRange
,
4741 UnaryExprOrTypeTrait ExprKind
,
4743 if (ExprType
->isDependentType())
4746 // C++ [expr.sizeof]p2:
4747 // When applied to a reference or a reference type, the result
4748 // is the size of the referenced type.
4749 // C++11 [expr.alignof]p3:
4750 // When alignof is applied to a reference type, the result
4751 // shall be the alignment of the referenced type.
4752 if (const ReferenceType
*Ref
= ExprType
->getAs
<ReferenceType
>())
4753 ExprType
= Ref
->getPointeeType();
4755 // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
4756 // When alignof or _Alignof is applied to an array type, the result
4757 // is the alignment of the element type.
4758 if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
||
4759 ExprKind
== UETT_OpenMPRequiredSimdAlign
)
4760 ExprType
= Context
.getBaseElementType(ExprType
);
4762 if (ExprKind
== UETT_VecStep
)
4763 return CheckVecStepTraitOperandType(*this, ExprType
, OpLoc
, ExprRange
);
4765 if (ExprKind
== UETT_VectorElements
)
4766 return CheckVectorElementsTraitOperandType(*this, ExprType
, OpLoc
,
4769 // Explicitly list some types as extensions.
4770 if (!CheckExtensionTraitOperandType(*this, ExprType
, OpLoc
, ExprRange
,
4774 if (RequireCompleteSizedType(
4775 OpLoc
, ExprType
, diag::err_sizeof_alignof_incomplete_or_sizeless_type
,
4779 if (ExprType
->isFunctionType()) {
4780 Diag(OpLoc
, diag::err_sizeof_alignof_function_type
) << KWName
<< ExprRange
;
4784 // WebAssembly tables are always illegal operands to unary expressions and
4786 if (Context
.getTargetInfo().getTriple().isWasm() &&
4787 ExprType
->isWebAssemblyTableType()) {
4788 Diag(OpLoc
, diag::err_wasm_table_invalid_uett_operand
)
4789 << getTraitSpelling(ExprKind
);
4793 if (CheckObjCTraitOperandConstraints(*this, ExprType
, OpLoc
, ExprRange
,
4797 if (ExprType
->isVariablyModifiedType() && FunctionScopes
.size() > 1) {
4798 if (auto *TT
= ExprType
->getAs
<TypedefType
>()) {
4799 for (auto I
= FunctionScopes
.rbegin(),
4800 E
= std::prev(FunctionScopes
.rend());
4802 auto *CSI
= dyn_cast
<CapturingScopeInfo
>(*I
);
4805 DeclContext
*DC
= nullptr;
4806 if (auto *LSI
= dyn_cast
<LambdaScopeInfo
>(CSI
))
4807 DC
= LSI
->CallOperator
;
4808 else if (auto *CRSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
))
4809 DC
= CRSI
->TheCapturedDecl
;
4810 else if (auto *BSI
= dyn_cast
<BlockScopeInfo
>(CSI
))
4813 if (DC
->containsDecl(TT
->getDecl()))
4815 captureVariablyModifiedType(Context
, ExprType
, CSI
);
4824 /// Build a sizeof or alignof expression given a type operand.
4825 ExprResult
Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo
*TInfo
,
4826 SourceLocation OpLoc
,
4827 UnaryExprOrTypeTrait ExprKind
,
4832 QualType T
= TInfo
->getType();
4834 if (!T
->isDependentType() &&
4835 CheckUnaryExprOrTypeTraitOperand(T
, OpLoc
, R
, ExprKind
,
4836 getTraitSpelling(ExprKind
)))
4839 // Adds overload of TransformToPotentiallyEvaluated for TypeSourceInfo to
4840 // properly deal with VLAs in nested calls of sizeof and typeof.
4841 if (isUnevaluatedContext() && ExprKind
== UETT_SizeOf
&&
4842 TInfo
->getType()->isVariablyModifiedType())
4843 TInfo
= TransformToPotentiallyEvaluated(TInfo
);
4845 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4846 return new (Context
) UnaryExprOrTypeTraitExpr(
4847 ExprKind
, TInfo
, Context
.getSizeType(), OpLoc
, R
.getEnd());
4850 /// Build a sizeof or alignof expression given an expression
4853 Sema::CreateUnaryExprOrTypeTraitExpr(Expr
*E
, SourceLocation OpLoc
,
4854 UnaryExprOrTypeTrait ExprKind
) {
4855 ExprResult PE
= CheckPlaceholderExpr(E
);
4861 // Verify that the operand is valid.
4862 bool isInvalid
= false;
4863 if (E
->isTypeDependent()) {
4864 // Delay type-checking for type-dependent expressions.
4865 } else if (ExprKind
== UETT_AlignOf
|| ExprKind
== UETT_PreferredAlignOf
) {
4866 isInvalid
= CheckAlignOfExpr(*this, E
, ExprKind
);
4867 } else if (ExprKind
== UETT_VecStep
) {
4868 isInvalid
= CheckVecStepExpr(E
);
4869 } else if (ExprKind
== UETT_OpenMPRequiredSimdAlign
) {
4870 Diag(E
->getExprLoc(), diag::err_openmp_default_simd_align_expr
);
4872 } else if (E
->refersToBitField()) { // C99 6.5.3.4p1.
4873 Diag(E
->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield
) << 0;
4875 } else if (ExprKind
== UETT_VectorElements
) {
4876 isInvalid
= CheckUnaryExprOrTypeTraitOperand(E
, UETT_VectorElements
);
4878 isInvalid
= CheckUnaryExprOrTypeTraitOperand(E
, UETT_SizeOf
);
4884 if (ExprKind
== UETT_SizeOf
&& E
->getType()->isVariableArrayType()) {
4885 PE
= TransformToPotentiallyEvaluated(E
);
4886 if (PE
.isInvalid()) return ExprError();
4890 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4891 return new (Context
) UnaryExprOrTypeTraitExpr(
4892 ExprKind
, E
, Context
.getSizeType(), OpLoc
, E
->getSourceRange().getEnd());
4895 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4896 /// expr and the same for @c alignof and @c __alignof
4897 /// Note that the ArgRange is invalid if isType is false.
4899 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc
,
4900 UnaryExprOrTypeTrait ExprKind
, bool IsType
,
4901 void *TyOrEx
, SourceRange ArgRange
) {
4902 // If error parsing type, ignore.
4903 if (!TyOrEx
) return ExprError();
4906 TypeSourceInfo
*TInfo
;
4907 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx
), &TInfo
);
4908 return CreateUnaryExprOrTypeTraitExpr(TInfo
, OpLoc
, ExprKind
, ArgRange
);
4911 Expr
*ArgEx
= (Expr
*)TyOrEx
;
4912 ExprResult Result
= CreateUnaryExprOrTypeTraitExpr(ArgEx
, OpLoc
, ExprKind
);
4916 bool Sema::CheckAlignasTypeArgument(StringRef KWName
, TypeSourceInfo
*TInfo
,
4917 SourceLocation OpLoc
, SourceRange R
) {
4920 return CheckUnaryExprOrTypeTraitOperand(TInfo
->getType(), OpLoc
, R
,
4921 UETT_AlignOf
, KWName
);
4924 /// ActOnAlignasTypeArgument - Handle @c alignas(type-id) and @c
4925 /// _Alignas(type-name) .
4926 /// [dcl.align] An alignment-specifier of the form
4927 /// alignas(type-id) has the same effect as alignas(alignof(type-id)).
4929 /// [N1570 6.7.5] _Alignas(type-name) is equivalent to
4930 /// _Alignas(_Alignof(type-name)).
4931 bool Sema::ActOnAlignasTypeArgument(StringRef KWName
, ParsedType Ty
,
4932 SourceLocation OpLoc
, SourceRange R
) {
4933 TypeSourceInfo
*TInfo
;
4934 (void)GetTypeFromParser(ParsedType::getFromOpaquePtr(Ty
.getAsOpaquePtr()),
4936 return CheckAlignasTypeArgument(KWName
, TInfo
, OpLoc
, R
);
4939 static QualType
CheckRealImagOperand(Sema
&S
, ExprResult
&V
, SourceLocation Loc
,
4941 if (V
.get()->isTypeDependent())
4942 return S
.Context
.DependentTy
;
4944 // _Real and _Imag are only l-values for normal l-values.
4945 if (V
.get()->getObjectKind() != OK_Ordinary
) {
4946 V
= S
.DefaultLvalueConversion(V
.get());
4951 // These operators return the element type of a complex type.
4952 if (const ComplexType
*CT
= V
.get()->getType()->getAs
<ComplexType
>())
4953 return CT
->getElementType();
4955 // Otherwise they pass through real integer and floating point types here.
4956 if (V
.get()->getType()->isArithmeticType())
4957 return V
.get()->getType();
4959 // Test for placeholders.
4960 ExprResult PR
= S
.CheckPlaceholderExpr(V
.get());
4961 if (PR
.isInvalid()) return QualType();
4962 if (PR
.get() != V
.get()) {
4964 return CheckRealImagOperand(S
, V
, Loc
, IsReal
);
4967 // Reject anything else.
4968 S
.Diag(Loc
, diag::err_realimag_invalid_type
) << V
.get()->getType()
4969 << (IsReal
? "__real" : "__imag");
4976 Sema::ActOnPostfixUnaryOp(Scope
*S
, SourceLocation OpLoc
,
4977 tok::TokenKind Kind
, Expr
*Input
) {
4978 UnaryOperatorKind Opc
;
4980 default: llvm_unreachable("Unknown unary op!");
4981 case tok::plusplus
: Opc
= UO_PostInc
; break;
4982 case tok::minusminus
: Opc
= UO_PostDec
; break;
4985 // Since this might is a postfix expression, get rid of ParenListExprs.
4986 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, Input
);
4987 if (Result
.isInvalid()) return ExprError();
4988 Input
= Result
.get();
4990 return BuildUnaryOp(S
, OpLoc
, Opc
, Input
);
4993 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4995 /// \return true on error
4996 static bool checkArithmeticOnObjCPointer(Sema
&S
,
4997 SourceLocation opLoc
,
4999 assert(op
->getType()->isObjCObjectPointerType());
5000 if (S
.LangOpts
.ObjCRuntime
.allowsPointerArithmetic() &&
5001 !S
.LangOpts
.ObjCSubscriptingLegacyRuntime
)
5004 S
.Diag(opLoc
, diag::err_arithmetic_nonfragile_interface
)
5005 << op
->getType()->castAs
<ObjCObjectPointerType
>()->getPointeeType()
5006 << op
->getSourceRange();
5010 static bool isMSPropertySubscriptExpr(Sema
&S
, Expr
*Base
) {
5011 auto *BaseNoParens
= Base
->IgnoreParens();
5012 if (auto *MSProp
= dyn_cast
<MSPropertyRefExpr
>(BaseNoParens
))
5013 return MSProp
->getPropertyDecl()->getType()->isArrayType();
5014 return isa
<MSPropertySubscriptExpr
>(BaseNoParens
);
5017 // Returns the type used for LHS[RHS], given one of LHS, RHS is type-dependent.
5018 // Typically this is DependentTy, but can sometimes be more precise.
5020 // There are cases when we could determine a non-dependent type:
5021 // - LHS and RHS may have non-dependent types despite being type-dependent
5022 // (e.g. unbounded array static members of the current instantiation)
5023 // - one may be a dependent-sized array with known element type
5024 // - one may be a dependent-typed valid index (enum in current instantiation)
5026 // We *always* return a dependent type, in such cases it is DependentTy.
5027 // This avoids creating type-dependent expressions with non-dependent types.
5028 // FIXME: is this important to avoid? See https://reviews.llvm.org/D107275
5029 static QualType
getDependentArraySubscriptType(Expr
*LHS
, Expr
*RHS
,
5030 const ASTContext
&Ctx
) {
5031 assert(LHS
->isTypeDependent() || RHS
->isTypeDependent());
5032 QualType LTy
= LHS
->getType(), RTy
= RHS
->getType();
5033 QualType Result
= Ctx
.DependentTy
;
5034 if (RTy
->isIntegralOrUnscopedEnumerationType()) {
5035 if (const PointerType
*PT
= LTy
->getAs
<PointerType
>())
5036 Result
= PT
->getPointeeType();
5037 else if (const ArrayType
*AT
= LTy
->getAsArrayTypeUnsafe())
5038 Result
= AT
->getElementType();
5039 } else if (LTy
->isIntegralOrUnscopedEnumerationType()) {
5040 if (const PointerType
*PT
= RTy
->getAs
<PointerType
>())
5041 Result
= PT
->getPointeeType();
5042 else if (const ArrayType
*AT
= RTy
->getAsArrayTypeUnsafe())
5043 Result
= AT
->getElementType();
5045 // Ensure we return a dependent type.
5046 return Result
->isDependentType() ? Result
: Ctx
.DependentTy
;
5049 static bool checkArgsForPlaceholders(Sema
&S
, MultiExprArg args
);
5051 ExprResult
Sema::ActOnArraySubscriptExpr(Scope
*S
, Expr
*base
,
5052 SourceLocation lbLoc
,
5053 MultiExprArg ArgExprs
,
5054 SourceLocation rbLoc
) {
5056 if (base
&& !base
->getType().isNull() &&
5057 base
->hasPlaceholderType(BuiltinType::OMPArraySection
))
5058 return ActOnOMPArraySectionExpr(base
, lbLoc
, ArgExprs
.front(), SourceLocation(),
5059 SourceLocation(), /*Length*/ nullptr,
5060 /*Stride=*/nullptr, rbLoc
);
5062 // Since this might be a postfix expression, get rid of ParenListExprs.
5063 if (isa
<ParenListExpr
>(base
)) {
5064 ExprResult result
= MaybeConvertParenListExprToParenExpr(S
, base
);
5065 if (result
.isInvalid())
5067 base
= result
.get();
5070 // Check if base and idx form a MatrixSubscriptExpr.
5072 // Helper to check for comma expressions, which are not allowed as indices for
5073 // matrix subscript expressions.
5074 auto CheckAndReportCommaError
= [this, base
, rbLoc
](Expr
*E
) {
5075 if (isa
<BinaryOperator
>(E
) && cast
<BinaryOperator
>(E
)->isCommaOp()) {
5076 Diag(E
->getExprLoc(), diag::err_matrix_subscript_comma
)
5077 << SourceRange(base
->getBeginLoc(), rbLoc
);
5082 // The matrix subscript operator ([][])is considered a single operator.
5083 // Separating the index expressions by parenthesis is not allowed.
5084 if (base
&& !base
->getType().isNull() &&
5085 base
->hasPlaceholderType(BuiltinType::IncompleteMatrixIdx
) &&
5086 !isa
<MatrixSubscriptExpr
>(base
)) {
5087 Diag(base
->getExprLoc(), diag::err_matrix_separate_incomplete_index
)
5088 << SourceRange(base
->getBeginLoc(), rbLoc
);
5091 // If the base is a MatrixSubscriptExpr, try to create a new
5092 // MatrixSubscriptExpr.
5093 auto *matSubscriptE
= dyn_cast
<MatrixSubscriptExpr
>(base
);
5094 if (matSubscriptE
) {
5095 assert(ArgExprs
.size() == 1);
5096 if (CheckAndReportCommaError(ArgExprs
.front()))
5099 assert(matSubscriptE
->isIncomplete() &&
5100 "base has to be an incomplete matrix subscript");
5101 return CreateBuiltinMatrixSubscriptExpr(matSubscriptE
->getBase(),
5102 matSubscriptE
->getRowIdx(),
5103 ArgExprs
.front(), rbLoc
);
5105 if (base
->getType()->isWebAssemblyTableType()) {
5106 Diag(base
->getExprLoc(), diag::err_wasm_table_art
)
5107 << SourceRange(base
->getBeginLoc(), rbLoc
) << 3;
5111 // Handle any non-overload placeholder types in the base and index
5112 // expressions. We can't handle overloads here because the other
5113 // operand might be an overloadable type, in which case the overload
5114 // resolution for the operator overload should get the first crack
5116 bool IsMSPropertySubscript
= false;
5117 if (base
->getType()->isNonOverloadPlaceholderType()) {
5118 IsMSPropertySubscript
= isMSPropertySubscriptExpr(*this, base
);
5119 if (!IsMSPropertySubscript
) {
5120 ExprResult result
= CheckPlaceholderExpr(base
);
5121 if (result
.isInvalid())
5123 base
= result
.get();
5127 // If the base is a matrix type, try to create a new MatrixSubscriptExpr.
5128 if (base
->getType()->isMatrixType()) {
5129 assert(ArgExprs
.size() == 1);
5130 if (CheckAndReportCommaError(ArgExprs
.front()))
5133 return CreateBuiltinMatrixSubscriptExpr(base
, ArgExprs
.front(), nullptr,
5137 if (ArgExprs
.size() == 1 && getLangOpts().CPlusPlus20
) {
5138 Expr
*idx
= ArgExprs
[0];
5139 if ((isa
<BinaryOperator
>(idx
) && cast
<BinaryOperator
>(idx
)->isCommaOp()) ||
5140 (isa
<CXXOperatorCallExpr
>(idx
) &&
5141 cast
<CXXOperatorCallExpr
>(idx
)->getOperator() == OO_Comma
)) {
5142 Diag(idx
->getExprLoc(), diag::warn_deprecated_comma_subscript
)
5143 << SourceRange(base
->getBeginLoc(), rbLoc
);
5147 if (ArgExprs
.size() == 1 &&
5148 ArgExprs
[0]->getType()->isNonOverloadPlaceholderType()) {
5149 ExprResult result
= CheckPlaceholderExpr(ArgExprs
[0]);
5150 if (result
.isInvalid())
5152 ArgExprs
[0] = result
.get();
5154 if (checkArgsForPlaceholders(*this, ArgExprs
))
5158 // Build an unanalyzed expression if either operand is type-dependent.
5159 if (getLangOpts().CPlusPlus
&& ArgExprs
.size() == 1 &&
5160 (base
->isTypeDependent() ||
5161 Expr::hasAnyTypeDependentArguments(ArgExprs
)) &&
5162 !isa
<PackExpansionExpr
>(ArgExprs
[0])) {
5163 return new (Context
) ArraySubscriptExpr(
5164 base
, ArgExprs
.front(),
5165 getDependentArraySubscriptType(base
, ArgExprs
.front(), getASTContext()),
5166 VK_LValue
, OK_Ordinary
, rbLoc
);
5169 // MSDN, property (C++)
5170 // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
5171 // This attribute can also be used in the declaration of an empty array in a
5172 // class or structure definition. For example:
5173 // __declspec(property(get=GetX, put=PutX)) int x[];
5174 // The above statement indicates that x[] can be used with one or more array
5175 // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
5176 // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
5177 if (IsMSPropertySubscript
) {
5178 assert(ArgExprs
.size() == 1);
5179 // Build MS property subscript expression if base is MS property reference
5180 // or MS property subscript.
5181 return new (Context
)
5182 MSPropertySubscriptExpr(base
, ArgExprs
.front(), Context
.PseudoObjectTy
,
5183 VK_LValue
, OK_Ordinary
, rbLoc
);
5186 // Use C++ overloaded-operator rules if either operand has record
5187 // type. The spec says to do this if either type is *overloadable*,
5188 // but enum types can't declare subscript operators or conversion
5189 // operators, so there's nothing interesting for overload resolution
5190 // to do if there aren't any record types involved.
5192 // ObjC pointers have their own subscripting logic that is not tied
5193 // to overload resolution and so should not take this path.
5194 if (getLangOpts().CPlusPlus
&& !base
->getType()->isObjCObjectPointerType() &&
5195 ((base
->getType()->isRecordType() ||
5196 (ArgExprs
.size() != 1 || isa
<PackExpansionExpr
>(ArgExprs
[0]) ||
5197 ArgExprs
[0]->getType()->isRecordType())))) {
5198 return CreateOverloadedArraySubscriptExpr(lbLoc
, rbLoc
, base
, ArgExprs
);
5202 CreateBuiltinArraySubscriptExpr(base
, lbLoc
, ArgExprs
.front(), rbLoc
);
5204 if (!Res
.isInvalid() && isa
<ArraySubscriptExpr
>(Res
.get()))
5205 CheckSubscriptAccessOfNoDeref(cast
<ArraySubscriptExpr
>(Res
.get()));
5210 ExprResult
Sema::tryConvertExprToType(Expr
*E
, QualType Ty
) {
5211 InitializedEntity Entity
= InitializedEntity::InitializeTemporary(Ty
);
5212 InitializationKind Kind
=
5213 InitializationKind::CreateCopy(E
->getBeginLoc(), SourceLocation());
5214 InitializationSequence
InitSeq(*this, Entity
, Kind
, E
);
5215 return InitSeq
.Perform(*this, Entity
, Kind
, E
);
5218 ExprResult
Sema::CreateBuiltinMatrixSubscriptExpr(Expr
*Base
, Expr
*RowIdx
,
5220 SourceLocation RBLoc
) {
5221 ExprResult BaseR
= CheckPlaceholderExpr(Base
);
5222 if (BaseR
.isInvalid())
5226 ExprResult RowR
= CheckPlaceholderExpr(RowIdx
);
5227 if (RowR
.isInvalid())
5229 RowIdx
= RowR
.get();
5232 return new (Context
) MatrixSubscriptExpr(
5233 Base
, RowIdx
, ColumnIdx
, Context
.IncompleteMatrixIdxTy
, RBLoc
);
5235 // Build an unanalyzed expression if any of the operands is type-dependent.
5236 if (Base
->isTypeDependent() || RowIdx
->isTypeDependent() ||
5237 ColumnIdx
->isTypeDependent())
5238 return new (Context
) MatrixSubscriptExpr(Base
, RowIdx
, ColumnIdx
,
5239 Context
.DependentTy
, RBLoc
);
5241 ExprResult ColumnR
= CheckPlaceholderExpr(ColumnIdx
);
5242 if (ColumnR
.isInvalid())
5244 ColumnIdx
= ColumnR
.get();
5246 // Check that IndexExpr is an integer expression. If it is a constant
5247 // expression, check that it is less than Dim (= the number of elements in the
5248 // corresponding dimension).
5249 auto IsIndexValid
= [&](Expr
*IndexExpr
, unsigned Dim
,
5250 bool IsColumnIdx
) -> Expr
* {
5251 if (!IndexExpr
->getType()->isIntegerType() &&
5252 !IndexExpr
->isTypeDependent()) {
5253 Diag(IndexExpr
->getBeginLoc(), diag::err_matrix_index_not_integer
)
5258 if (std::optional
<llvm::APSInt
> Idx
=
5259 IndexExpr
->getIntegerConstantExpr(Context
)) {
5260 if ((*Idx
< 0 || *Idx
>= Dim
)) {
5261 Diag(IndexExpr
->getBeginLoc(), diag::err_matrix_index_outside_range
)
5262 << IsColumnIdx
<< Dim
;
5267 ExprResult ConvExpr
=
5268 tryConvertExprToType(IndexExpr
, Context
.getSizeType());
5269 assert(!ConvExpr
.isInvalid() &&
5270 "should be able to convert any integer type to size type");
5271 return ConvExpr
.get();
5274 auto *MTy
= Base
->getType()->getAs
<ConstantMatrixType
>();
5275 RowIdx
= IsIndexValid(RowIdx
, MTy
->getNumRows(), false);
5276 ColumnIdx
= IsIndexValid(ColumnIdx
, MTy
->getNumColumns(), true);
5277 if (!RowIdx
|| !ColumnIdx
)
5280 return new (Context
) MatrixSubscriptExpr(Base
, RowIdx
, ColumnIdx
,
5281 MTy
->getElementType(), RBLoc
);
5284 void Sema::CheckAddressOfNoDeref(const Expr
*E
) {
5285 ExpressionEvaluationContextRecord
&LastRecord
= ExprEvalContexts
.back();
5286 const Expr
*StrippedExpr
= E
->IgnoreParenImpCasts();
5288 // For expressions like `&(*s).b`, the base is recorded and what should be
5290 const MemberExpr
*Member
= nullptr;
5291 while ((Member
= dyn_cast
<MemberExpr
>(StrippedExpr
)) && !Member
->isArrow())
5292 StrippedExpr
= Member
->getBase()->IgnoreParenImpCasts();
5294 LastRecord
.PossibleDerefs
.erase(StrippedExpr
);
5297 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr
*E
) {
5298 if (isUnevaluatedContext())
5301 QualType ResultTy
= E
->getType();
5302 ExpressionEvaluationContextRecord
&LastRecord
= ExprEvalContexts
.back();
5304 // Bail if the element is an array since it is not memory access.
5305 if (isa
<ArrayType
>(ResultTy
))
5308 if (ResultTy
->hasAttr(attr::NoDeref
)) {
5309 LastRecord
.PossibleDerefs
.insert(E
);
5313 // Check if the base type is a pointer to a member access of a struct
5314 // marked with noderef.
5315 const Expr
*Base
= E
->getBase();
5316 QualType BaseTy
= Base
->getType();
5317 if (!(isa
<ArrayType
>(BaseTy
) || isa
<PointerType
>(BaseTy
)))
5318 // Not a pointer access
5321 const MemberExpr
*Member
= nullptr;
5322 while ((Member
= dyn_cast
<MemberExpr
>(Base
->IgnoreParenCasts())) &&
5324 Base
= Member
->getBase();
5326 if (const auto *Ptr
= dyn_cast
<PointerType
>(Base
->getType())) {
5327 if (Ptr
->getPointeeType()->hasAttr(attr::NoDeref
))
5328 LastRecord
.PossibleDerefs
.insert(E
);
5332 ExprResult
Sema::ActOnOMPArraySectionExpr(Expr
*Base
, SourceLocation LBLoc
,
5334 SourceLocation ColonLocFirst
,
5335 SourceLocation ColonLocSecond
,
5336 Expr
*Length
, Expr
*Stride
,
5337 SourceLocation RBLoc
) {
5338 if (Base
->hasPlaceholderType() &&
5339 !Base
->hasPlaceholderType(BuiltinType::OMPArraySection
)) {
5340 ExprResult Result
= CheckPlaceholderExpr(Base
);
5341 if (Result
.isInvalid())
5343 Base
= Result
.get();
5345 if (LowerBound
&& LowerBound
->getType()->isNonOverloadPlaceholderType()) {
5346 ExprResult Result
= CheckPlaceholderExpr(LowerBound
);
5347 if (Result
.isInvalid())
5349 Result
= DefaultLvalueConversion(Result
.get());
5350 if (Result
.isInvalid())
5352 LowerBound
= Result
.get();
5354 if (Length
&& Length
->getType()->isNonOverloadPlaceholderType()) {
5355 ExprResult Result
= CheckPlaceholderExpr(Length
);
5356 if (Result
.isInvalid())
5358 Result
= DefaultLvalueConversion(Result
.get());
5359 if (Result
.isInvalid())
5361 Length
= Result
.get();
5363 if (Stride
&& Stride
->getType()->isNonOverloadPlaceholderType()) {
5364 ExprResult Result
= CheckPlaceholderExpr(Stride
);
5365 if (Result
.isInvalid())
5367 Result
= DefaultLvalueConversion(Result
.get());
5368 if (Result
.isInvalid())
5370 Stride
= Result
.get();
5373 // Build an unanalyzed expression if either operand is type-dependent.
5374 if (Base
->isTypeDependent() ||
5376 (LowerBound
->isTypeDependent() || LowerBound
->isValueDependent())) ||
5377 (Length
&& (Length
->isTypeDependent() || Length
->isValueDependent())) ||
5378 (Stride
&& (Stride
->isTypeDependent() || Stride
->isValueDependent()))) {
5379 return new (Context
) OMPArraySectionExpr(
5380 Base
, LowerBound
, Length
, Stride
, Context
.DependentTy
, VK_LValue
,
5381 OK_Ordinary
, ColonLocFirst
, ColonLocSecond
, RBLoc
);
5384 // Perform default conversions.
5385 QualType OriginalTy
= OMPArraySectionExpr::getBaseOriginalType(Base
);
5387 if (OriginalTy
->isAnyPointerType()) {
5388 ResultTy
= OriginalTy
->getPointeeType();
5389 } else if (OriginalTy
->isArrayType()) {
5390 ResultTy
= OriginalTy
->getAsArrayTypeUnsafe()->getElementType();
5393 Diag(Base
->getExprLoc(), diag::err_omp_typecheck_section_value
)
5394 << Base
->getSourceRange());
5398 auto Res
= PerformOpenMPImplicitIntegerConversion(LowerBound
->getExprLoc(),
5400 if (Res
.isInvalid())
5401 return ExprError(Diag(LowerBound
->getExprLoc(),
5402 diag::err_omp_typecheck_section_not_integer
)
5403 << 0 << LowerBound
->getSourceRange());
5404 LowerBound
= Res
.get();
5406 if (LowerBound
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
5407 LowerBound
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
5408 Diag(LowerBound
->getExprLoc(), diag::warn_omp_section_is_char
)
5409 << 0 << LowerBound
->getSourceRange();
5413 PerformOpenMPImplicitIntegerConversion(Length
->getExprLoc(), Length
);
5414 if (Res
.isInvalid())
5415 return ExprError(Diag(Length
->getExprLoc(),
5416 diag::err_omp_typecheck_section_not_integer
)
5417 << 1 << Length
->getSourceRange());
5420 if (Length
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
5421 Length
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
5422 Diag(Length
->getExprLoc(), diag::warn_omp_section_is_char
)
5423 << 1 << Length
->getSourceRange();
5427 PerformOpenMPImplicitIntegerConversion(Stride
->getExprLoc(), Stride
);
5428 if (Res
.isInvalid())
5429 return ExprError(Diag(Stride
->getExprLoc(),
5430 diag::err_omp_typecheck_section_not_integer
)
5431 << 1 << Stride
->getSourceRange());
5434 if (Stride
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
5435 Stride
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
5436 Diag(Stride
->getExprLoc(), diag::warn_omp_section_is_char
)
5437 << 1 << Stride
->getSourceRange();
5440 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
5441 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
5442 // type. Note that functions are not objects, and that (in C99 parlance)
5443 // incomplete types are not object types.
5444 if (ResultTy
->isFunctionType()) {
5445 Diag(Base
->getExprLoc(), diag::err_omp_section_function_type
)
5446 << ResultTy
<< Base
->getSourceRange();
5450 if (RequireCompleteType(Base
->getExprLoc(), ResultTy
,
5451 diag::err_omp_section_incomplete_type
, Base
))
5454 if (LowerBound
&& !OriginalTy
->isAnyPointerType()) {
5455 Expr::EvalResult Result
;
5456 if (LowerBound
->EvaluateAsInt(Result
, Context
)) {
5457 // OpenMP 5.0, [2.1.5 Array Sections]
5458 // The array section must be a subset of the original array.
5459 llvm::APSInt LowerBoundValue
= Result
.Val
.getInt();
5460 if (LowerBoundValue
.isNegative()) {
5461 Diag(LowerBound
->getExprLoc(), diag::err_omp_section_not_subset_of_array
)
5462 << LowerBound
->getSourceRange();
5469 Expr::EvalResult Result
;
5470 if (Length
->EvaluateAsInt(Result
, Context
)) {
5471 // OpenMP 5.0, [2.1.5 Array Sections]
5472 // The length must evaluate to non-negative integers.
5473 llvm::APSInt LengthValue
= Result
.Val
.getInt();
5474 if (LengthValue
.isNegative()) {
5475 Diag(Length
->getExprLoc(), diag::err_omp_section_length_negative
)
5476 << toString(LengthValue
, /*Radix=*/10, /*Signed=*/true)
5477 << Length
->getSourceRange();
5481 } else if (ColonLocFirst
.isValid() &&
5482 (OriginalTy
.isNull() || (!OriginalTy
->isConstantArrayType() &&
5483 !OriginalTy
->isVariableArrayType()))) {
5484 // OpenMP 5.0, [2.1.5 Array Sections]
5485 // When the size of the array dimension is not known, the length must be
5486 // specified explicitly.
5487 Diag(ColonLocFirst
, diag::err_omp_section_length_undefined
)
5488 << (!OriginalTy
.isNull() && OriginalTy
->isArrayType());
5493 Expr::EvalResult Result
;
5494 if (Stride
->EvaluateAsInt(Result
, Context
)) {
5495 // OpenMP 5.0, [2.1.5 Array Sections]
5496 // The stride must evaluate to a positive integer.
5497 llvm::APSInt StrideValue
= Result
.Val
.getInt();
5498 if (!StrideValue
.isStrictlyPositive()) {
5499 Diag(Stride
->getExprLoc(), diag::err_omp_section_stride_non_positive
)
5500 << toString(StrideValue
, /*Radix=*/10, /*Signed=*/true)
5501 << Stride
->getSourceRange();
5507 if (!Base
->hasPlaceholderType(BuiltinType::OMPArraySection
)) {
5508 ExprResult Result
= DefaultFunctionArrayLvalueConversion(Base
);
5509 if (Result
.isInvalid())
5511 Base
= Result
.get();
5513 return new (Context
) OMPArraySectionExpr(
5514 Base
, LowerBound
, Length
, Stride
, Context
.OMPArraySectionTy
, VK_LValue
,
5515 OK_Ordinary
, ColonLocFirst
, ColonLocSecond
, RBLoc
);
5518 ExprResult
Sema::ActOnOMPArrayShapingExpr(Expr
*Base
, SourceLocation LParenLoc
,
5519 SourceLocation RParenLoc
,
5520 ArrayRef
<Expr
*> Dims
,
5521 ArrayRef
<SourceRange
> Brackets
) {
5522 if (Base
->hasPlaceholderType()) {
5523 ExprResult Result
= CheckPlaceholderExpr(Base
);
5524 if (Result
.isInvalid())
5526 Result
= DefaultLvalueConversion(Result
.get());
5527 if (Result
.isInvalid())
5529 Base
= Result
.get();
5531 QualType BaseTy
= Base
->getType();
5532 // Delay analysis of the types/expressions if instantiation/specialization is
5534 if (!BaseTy
->isPointerType() && Base
->isTypeDependent())
5535 return OMPArrayShapingExpr::Create(Context
, Context
.DependentTy
, Base
,
5536 LParenLoc
, RParenLoc
, Dims
, Brackets
);
5537 if (!BaseTy
->isPointerType() ||
5538 (!Base
->isTypeDependent() &&
5539 BaseTy
->getPointeeType()->isIncompleteType()))
5540 return ExprError(Diag(Base
->getExprLoc(),
5541 diag::err_omp_non_pointer_type_array_shaping_base
)
5542 << Base
->getSourceRange());
5544 SmallVector
<Expr
*, 4> NewDims
;
5545 bool ErrorFound
= false;
5546 for (Expr
*Dim
: Dims
) {
5547 if (Dim
->hasPlaceholderType()) {
5548 ExprResult Result
= CheckPlaceholderExpr(Dim
);
5549 if (Result
.isInvalid()) {
5553 Result
= DefaultLvalueConversion(Result
.get());
5554 if (Result
.isInvalid()) {
5560 if (!Dim
->isTypeDependent()) {
5562 PerformOpenMPImplicitIntegerConversion(Dim
->getExprLoc(), Dim
);
5563 if (Result
.isInvalid()) {
5565 Diag(Dim
->getExprLoc(), diag::err_omp_typecheck_shaping_not_integer
)
5566 << Dim
->getSourceRange();
5570 Expr::EvalResult EvResult
;
5571 if (!Dim
->isValueDependent() && Dim
->EvaluateAsInt(EvResult
, Context
)) {
5572 // OpenMP 5.0, [2.1.4 Array Shaping]
5573 // Each si is an integral type expression that must evaluate to a
5574 // positive integer.
5575 llvm::APSInt Value
= EvResult
.Val
.getInt();
5576 if (!Value
.isStrictlyPositive()) {
5577 Diag(Dim
->getExprLoc(), diag::err_omp_shaping_dimension_not_positive
)
5578 << toString(Value
, /*Radix=*/10, /*Signed=*/true)
5579 << Dim
->getSourceRange();
5585 NewDims
.push_back(Dim
);
5589 return OMPArrayShapingExpr::Create(Context
, Context
.OMPArrayShapingTy
, Base
,
5590 LParenLoc
, RParenLoc
, NewDims
, Brackets
);
5593 ExprResult
Sema::ActOnOMPIteratorExpr(Scope
*S
, SourceLocation IteratorKwLoc
,
5594 SourceLocation LLoc
, SourceLocation RLoc
,
5595 ArrayRef
<OMPIteratorData
> Data
) {
5596 SmallVector
<OMPIteratorExpr::IteratorDefinition
, 4> ID
;
5597 bool IsCorrect
= true;
5598 for (const OMPIteratorData
&D
: Data
) {
5599 TypeSourceInfo
*TInfo
= nullptr;
5600 SourceLocation StartLoc
;
5602 if (!D
.Type
.getAsOpaquePtr()) {
5603 // OpenMP 5.0, 2.1.6 Iterators
5604 // In an iterator-specifier, if the iterator-type is not specified then
5605 // the type of that iterator is of int type.
5606 DeclTy
= Context
.IntTy
;
5607 StartLoc
= D
.DeclIdentLoc
;
5609 DeclTy
= GetTypeFromParser(D
.Type
, &TInfo
);
5610 StartLoc
= TInfo
->getTypeLoc().getBeginLoc();
5613 bool IsDeclTyDependent
= DeclTy
->isDependentType() ||
5614 DeclTy
->containsUnexpandedParameterPack() ||
5615 DeclTy
->isInstantiationDependentType();
5616 if (!IsDeclTyDependent
) {
5617 if (!DeclTy
->isIntegralType(Context
) && !DeclTy
->isAnyPointerType()) {
5618 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5619 // The iterator-type must be an integral or pointer type.
5620 Diag(StartLoc
, diag::err_omp_iterator_not_integral_or_pointer
)
5625 if (DeclTy
.isConstant(Context
)) {
5626 // OpenMP 5.0, 2.1.6 Iterators, Restrictions, C/C++
5627 // The iterator-type must not be const qualified.
5628 Diag(StartLoc
, diag::err_omp_iterator_not_integral_or_pointer
)
5635 // Iterator declaration.
5636 assert(D
.DeclIdent
&& "Identifier expected.");
5637 // Always try to create iterator declarator to avoid extra error messages
5638 // about unknown declarations use.
5639 auto *VD
= VarDecl::Create(Context
, CurContext
, StartLoc
, D
.DeclIdentLoc
,
5640 D
.DeclIdent
, DeclTy
, TInfo
, SC_None
);
5643 // Check for conflicting previous declaration.
5644 DeclarationNameInfo
NameInfo(VD
->getDeclName(), D
.DeclIdentLoc
);
5645 LookupResult
Previous(*this, NameInfo
, LookupOrdinaryName
,
5646 ForVisibleRedeclaration
);
5647 Previous
.suppressDiagnostics();
5648 LookupName(Previous
, S
);
5650 FilterLookupForScope(Previous
, CurContext
, S
, /*ConsiderLinkage=*/false,
5651 /*AllowInlineNamespace=*/false);
5652 if (!Previous
.empty()) {
5653 NamedDecl
*Old
= Previous
.getRepresentativeDecl();
5654 Diag(D
.DeclIdentLoc
, diag::err_redefinition
) << VD
->getDeclName();
5655 Diag(Old
->getLocation(), diag::note_previous_definition
);
5657 PushOnScopeChains(VD
, S
);
5660 CurContext
->addDecl(VD
);
5663 /// Act on the iterator variable declaration.
5664 ActOnOpenMPIteratorVarDecl(VD
);
5666 Expr
*Begin
= D
.Range
.Begin
;
5667 if (!IsDeclTyDependent
&& Begin
&& !Begin
->isTypeDependent()) {
5668 ExprResult BeginRes
=
5669 PerformImplicitConversion(Begin
, DeclTy
, AA_Converting
);
5670 Begin
= BeginRes
.get();
5672 Expr
*End
= D
.Range
.End
;
5673 if (!IsDeclTyDependent
&& End
&& !End
->isTypeDependent()) {
5674 ExprResult EndRes
= PerformImplicitConversion(End
, DeclTy
, AA_Converting
);
5677 Expr
*Step
= D
.Range
.Step
;
5678 if (!IsDeclTyDependent
&& Step
&& !Step
->isTypeDependent()) {
5679 if (!Step
->getType()->isIntegralType(Context
)) {
5680 Diag(Step
->getExprLoc(), diag::err_omp_iterator_step_not_integral
)
5681 << Step
<< Step
->getSourceRange();
5685 std::optional
<llvm::APSInt
> Result
=
5686 Step
->getIntegerConstantExpr(Context
);
5687 // OpenMP 5.0, 2.1.6 Iterators, Restrictions
5688 // If the step expression of a range-specification equals zero, the
5689 // behavior is unspecified.
5690 if (Result
&& Result
->isZero()) {
5691 Diag(Step
->getExprLoc(), diag::err_omp_iterator_step_constant_zero
)
5692 << Step
<< Step
->getSourceRange();
5697 if (!Begin
|| !End
|| !IsCorrect
) {
5701 OMPIteratorExpr::IteratorDefinition
&IDElem
= ID
.emplace_back();
5702 IDElem
.IteratorDecl
= VD
;
5703 IDElem
.AssignmentLoc
= D
.AssignLoc
;
5704 IDElem
.Range
.Begin
= Begin
;
5705 IDElem
.Range
.End
= End
;
5706 IDElem
.Range
.Step
= Step
;
5707 IDElem
.ColonLoc
= D
.ColonLoc
;
5708 IDElem
.SecondColonLoc
= D
.SecColonLoc
;
5711 // Invalidate all created iterator declarations if error is found.
5712 for (const OMPIteratorExpr::IteratorDefinition
&D
: ID
) {
5713 if (Decl
*ID
= D
.IteratorDecl
)
5714 ID
->setInvalidDecl();
5718 SmallVector
<OMPIteratorHelperData
, 4> Helpers
;
5719 if (!CurContext
->isDependentContext()) {
5720 // Build number of ityeration for each iteration range.
5721 // Ni = ((Stepi > 0) ? ((Endi + Stepi -1 - Begini)/Stepi) :
5722 // ((Begini-Stepi-1-Endi) / -Stepi);
5723 for (OMPIteratorExpr::IteratorDefinition
&D
: ID
) {
5725 ExprResult Res
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Sub
, D
.Range
.End
,
5727 if(!Res
.isUsable()) {
5734 // (Endi - Begini) + Stepi
5735 Res
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Add
, Res
.get(), St
.get());
5736 if (!Res
.isUsable()) {
5740 // (Endi - Begini) + Stepi - 1
5742 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Sub
, Res
.get(),
5743 ActOnIntegerConstant(D
.AssignmentLoc
, 1).get());
5744 if (!Res
.isUsable()) {
5748 // ((Endi - Begini) + Stepi - 1) / Stepi
5749 Res
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Div
, Res
.get(), St
.get());
5750 if (!Res
.isUsable()) {
5754 St1
= CreateBuiltinUnaryOp(D
.AssignmentLoc
, UO_Minus
, D
.Range
.Step
);
5756 ExprResult Res1
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Sub
,
5757 D
.Range
.Begin
, D
.Range
.End
);
5758 if (!Res1
.isUsable()) {
5762 // (Begini - Endi) - Stepi
5764 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Add
, Res1
.get(), St1
.get());
5765 if (!Res1
.isUsable()) {
5769 // (Begini - Endi) - Stepi - 1
5771 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Sub
, Res1
.get(),
5772 ActOnIntegerConstant(D
.AssignmentLoc
, 1).get());
5773 if (!Res1
.isUsable()) {
5777 // ((Begini - Endi) - Stepi - 1) / (-Stepi)
5779 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Div
, Res1
.get(), St1
.get());
5780 if (!Res1
.isUsable()) {
5786 CreateBuiltinBinOp(D
.AssignmentLoc
, BO_GT
, D
.Range
.Step
,
5787 ActOnIntegerConstant(D
.AssignmentLoc
, 0).get());
5788 if (!CmpRes
.isUsable()) {
5792 Res
= ActOnConditionalOp(D
.AssignmentLoc
, D
.AssignmentLoc
, CmpRes
.get(),
5793 Res
.get(), Res1
.get());
5794 if (!Res
.isUsable()) {
5799 Res
= ActOnFinishFullExpr(Res
.get(), /*DiscardedValue=*/false);
5800 if (!Res
.isUsable()) {
5805 // Build counter update.
5808 VarDecl::Create(Context
, CurContext
, D
.IteratorDecl
->getBeginLoc(),
5809 D
.IteratorDecl
->getBeginLoc(), nullptr,
5810 Res
.get()->getType(), nullptr, SC_None
);
5811 CounterVD
->setImplicit();
5813 BuildDeclRefExpr(CounterVD
, CounterVD
->getType(), VK_LValue
,
5814 D
.IteratorDecl
->getBeginLoc());
5815 // Build counter update.
5816 // I = Begini + counter * Stepi;
5817 ExprResult UpdateRes
;
5819 UpdateRes
= CreateBuiltinBinOp(
5820 D
.AssignmentLoc
, BO_Mul
,
5821 DefaultLvalueConversion(RefRes
.get()).get(), St
.get());
5823 UpdateRes
= DefaultLvalueConversion(RefRes
.get());
5825 if (!UpdateRes
.isUsable()) {
5829 UpdateRes
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Add
, D
.Range
.Begin
,
5831 if (!UpdateRes
.isUsable()) {
5836 BuildDeclRefExpr(cast
<VarDecl
>(D
.IteratorDecl
),
5837 cast
<VarDecl
>(D
.IteratorDecl
)->getType(), VK_LValue
,
5838 D
.IteratorDecl
->getBeginLoc());
5839 UpdateRes
= CreateBuiltinBinOp(D
.AssignmentLoc
, BO_Assign
, VDRes
.get(),
5841 if (!UpdateRes
.isUsable()) {
5846 ActOnFinishFullExpr(UpdateRes
.get(), /*DiscardedValue=*/true);
5847 if (!UpdateRes
.isUsable()) {
5851 ExprResult CounterUpdateRes
=
5852 CreateBuiltinUnaryOp(D
.AssignmentLoc
, UO_PreInc
, RefRes
.get());
5853 if (!CounterUpdateRes
.isUsable()) {
5858 ActOnFinishFullExpr(CounterUpdateRes
.get(), /*DiscardedValue=*/true);
5859 if (!CounterUpdateRes
.isUsable()) {
5863 OMPIteratorHelperData
&HD
= Helpers
.emplace_back();
5864 HD
.CounterVD
= CounterVD
;
5865 HD
.Upper
= Res
.get();
5866 HD
.Update
= UpdateRes
.get();
5867 HD
.CounterUpdate
= CounterUpdateRes
.get();
5870 Helpers
.assign(ID
.size(), {});
5873 // Invalidate all created iterator declarations if error is found.
5874 for (const OMPIteratorExpr::IteratorDefinition
&D
: ID
) {
5875 if (Decl
*ID
= D
.IteratorDecl
)
5876 ID
->setInvalidDecl();
5880 return OMPIteratorExpr::Create(Context
, Context
.OMPIteratorTy
, IteratorKwLoc
,
5881 LLoc
, RLoc
, ID
, Helpers
);
5885 Sema::CreateBuiltinArraySubscriptExpr(Expr
*Base
, SourceLocation LLoc
,
5886 Expr
*Idx
, SourceLocation RLoc
) {
5887 Expr
*LHSExp
= Base
;
5890 ExprValueKind VK
= VK_LValue
;
5891 ExprObjectKind OK
= OK_Ordinary
;
5893 // Per C++ core issue 1213, the result is an xvalue if either operand is
5894 // a non-lvalue array, and an lvalue otherwise.
5895 if (getLangOpts().CPlusPlus11
) {
5896 for (auto *Op
: {LHSExp
, RHSExp
}) {
5897 Op
= Op
->IgnoreImplicit();
5898 if (Op
->getType()->isArrayType() && !Op
->isLValue())
5903 // Perform default conversions.
5904 if (!LHSExp
->getType()->getAs
<VectorType
>()) {
5905 ExprResult Result
= DefaultFunctionArrayLvalueConversion(LHSExp
);
5906 if (Result
.isInvalid())
5908 LHSExp
= Result
.get();
5910 ExprResult Result
= DefaultFunctionArrayLvalueConversion(RHSExp
);
5911 if (Result
.isInvalid())
5913 RHSExp
= Result
.get();
5915 QualType LHSTy
= LHSExp
->getType(), RHSTy
= RHSExp
->getType();
5917 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
5918 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
5919 // in the subscript position. As a result, we need to derive the array base
5920 // and index from the expression types.
5921 Expr
*BaseExpr
, *IndexExpr
;
5922 QualType ResultType
;
5923 if (LHSTy
->isDependentType() || RHSTy
->isDependentType()) {
5927 getDependentArraySubscriptType(LHSExp
, RHSExp
, getASTContext());
5928 } else if (const PointerType
*PTy
= LHSTy
->getAs
<PointerType
>()) {
5931 ResultType
= PTy
->getPointeeType();
5932 } else if (const ObjCObjectPointerType
*PTy
=
5933 LHSTy
->getAs
<ObjCObjectPointerType
>()) {
5937 // Use custom logic if this should be the pseudo-object subscript
5939 if (!LangOpts
.isSubscriptPointerArithmetic())
5940 return BuildObjCSubscriptExpression(RLoc
, BaseExpr
, IndexExpr
, nullptr,
5943 ResultType
= PTy
->getPointeeType();
5944 } else if (const PointerType
*PTy
= RHSTy
->getAs
<PointerType
>()) {
5945 // Handle the uncommon case of "123[Ptr]".
5948 ResultType
= PTy
->getPointeeType();
5949 } else if (const ObjCObjectPointerType
*PTy
=
5950 RHSTy
->getAs
<ObjCObjectPointerType
>()) {
5951 // Handle the uncommon case of "123[Ptr]".
5954 ResultType
= PTy
->getPointeeType();
5955 if (!LangOpts
.isSubscriptPointerArithmetic()) {
5956 Diag(LLoc
, diag::err_subscript_nonfragile_interface
)
5957 << ResultType
<< BaseExpr
->getSourceRange();
5960 } else if (const VectorType
*VTy
= LHSTy
->getAs
<VectorType
>()) {
5961 BaseExpr
= LHSExp
; // vectors: V[123]
5963 // We apply C++ DR1213 to vector subscripting too.
5964 if (getLangOpts().CPlusPlus11
&& LHSExp
->isPRValue()) {
5965 ExprResult Materialized
= TemporaryMaterializationConversion(LHSExp
);
5966 if (Materialized
.isInvalid())
5968 LHSExp
= Materialized
.get();
5970 VK
= LHSExp
->getValueKind();
5971 if (VK
!= VK_PRValue
)
5972 OK
= OK_VectorComponent
;
5974 ResultType
= VTy
->getElementType();
5975 QualType BaseType
= BaseExpr
->getType();
5976 Qualifiers BaseQuals
= BaseType
.getQualifiers();
5977 Qualifiers MemberQuals
= ResultType
.getQualifiers();
5978 Qualifiers Combined
= BaseQuals
+ MemberQuals
;
5979 if (Combined
!= MemberQuals
)
5980 ResultType
= Context
.getQualifiedType(ResultType
, Combined
);
5981 } else if (LHSTy
->isBuiltinType() &&
5982 LHSTy
->getAs
<BuiltinType
>()->isSveVLSBuiltinType()) {
5983 const BuiltinType
*BTy
= LHSTy
->getAs
<BuiltinType
>();
5984 if (BTy
->isSVEBool())
5985 return ExprError(Diag(LLoc
, diag::err_subscript_svbool_t
)
5986 << LHSExp
->getSourceRange() << RHSExp
->getSourceRange());
5990 if (getLangOpts().CPlusPlus11
&& LHSExp
->isPRValue()) {
5991 ExprResult Materialized
= TemporaryMaterializationConversion(LHSExp
);
5992 if (Materialized
.isInvalid())
5994 LHSExp
= Materialized
.get();
5996 VK
= LHSExp
->getValueKind();
5997 if (VK
!= VK_PRValue
)
5998 OK
= OK_VectorComponent
;
6000 ResultType
= BTy
->getSveEltType(Context
);
6002 QualType BaseType
= BaseExpr
->getType();
6003 Qualifiers BaseQuals
= BaseType
.getQualifiers();
6004 Qualifiers MemberQuals
= ResultType
.getQualifiers();
6005 Qualifiers Combined
= BaseQuals
+ MemberQuals
;
6006 if (Combined
!= MemberQuals
)
6007 ResultType
= Context
.getQualifiedType(ResultType
, Combined
);
6008 } else if (LHSTy
->isArrayType()) {
6009 // If we see an array that wasn't promoted by
6010 // DefaultFunctionArrayLvalueConversion, it must be an array that
6011 // wasn't promoted because of the C90 rule that doesn't
6012 // allow promoting non-lvalue arrays. Warn, then
6013 // force the promotion here.
6014 Diag(LHSExp
->getBeginLoc(), diag::ext_subscript_non_lvalue
)
6015 << LHSExp
->getSourceRange();
6016 LHSExp
= ImpCastExprToType(LHSExp
, Context
.getArrayDecayedType(LHSTy
),
6017 CK_ArrayToPointerDecay
).get();
6018 LHSTy
= LHSExp
->getType();
6022 ResultType
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
6023 } else if (RHSTy
->isArrayType()) {
6024 // Same as previous, except for 123[f().a] case
6025 Diag(RHSExp
->getBeginLoc(), diag::ext_subscript_non_lvalue
)
6026 << RHSExp
->getSourceRange();
6027 RHSExp
= ImpCastExprToType(RHSExp
, Context
.getArrayDecayedType(RHSTy
),
6028 CK_ArrayToPointerDecay
).get();
6029 RHSTy
= RHSExp
->getType();
6033 ResultType
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
6035 return ExprError(Diag(LLoc
, diag::err_typecheck_subscript_value
)
6036 << LHSExp
->getSourceRange() << RHSExp
->getSourceRange());
6039 if (!IndexExpr
->getType()->isIntegerType() && !IndexExpr
->isTypeDependent())
6040 return ExprError(Diag(LLoc
, diag::err_typecheck_subscript_not_integer
)
6041 << IndexExpr
->getSourceRange());
6043 if ((IndexExpr
->getType()->isSpecificBuiltinType(BuiltinType::Char_S
) ||
6044 IndexExpr
->getType()->isSpecificBuiltinType(BuiltinType::Char_U
))
6045 && !IndexExpr
->isTypeDependent())
6046 Diag(LLoc
, diag::warn_subscript_is_char
) << IndexExpr
->getSourceRange();
6048 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
6049 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
6050 // type. Note that Functions are not objects, and that (in C99 parlance)
6051 // incomplete types are not object types.
6052 if (ResultType
->isFunctionType()) {
6053 Diag(BaseExpr
->getBeginLoc(), diag::err_subscript_function_type
)
6054 << ResultType
<< BaseExpr
->getSourceRange();
6058 if (ResultType
->isVoidType() && !getLangOpts().CPlusPlus
) {
6059 // GNU extension: subscripting on pointer to void
6060 Diag(LLoc
, diag::ext_gnu_subscript_void_type
)
6061 << BaseExpr
->getSourceRange();
6063 // C forbids expressions of unqualified void type from being l-values.
6064 // See IsCForbiddenLValueType.
6065 if (!ResultType
.hasQualifiers())
6067 } else if (!ResultType
->isDependentType() &&
6068 !ResultType
.isWebAssemblyReferenceType() &&
6069 RequireCompleteSizedType(
6071 diag::err_subscript_incomplete_or_sizeless_type
, BaseExpr
))
6074 assert(VK
== VK_PRValue
|| LangOpts
.CPlusPlus
||
6075 !ResultType
.isCForbiddenLValueType());
6077 if (LHSExp
->IgnoreParenImpCasts()->getType()->isVariablyModifiedType() &&
6078 FunctionScopes
.size() > 1) {
6080 LHSExp
->IgnoreParenImpCasts()->getType()->getAs
<TypedefType
>()) {
6081 for (auto I
= FunctionScopes
.rbegin(),
6082 E
= std::prev(FunctionScopes
.rend());
6084 auto *CSI
= dyn_cast
<CapturingScopeInfo
>(*I
);
6087 DeclContext
*DC
= nullptr;
6088 if (auto *LSI
= dyn_cast
<LambdaScopeInfo
>(CSI
))
6089 DC
= LSI
->CallOperator
;
6090 else if (auto *CRSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
))
6091 DC
= CRSI
->TheCapturedDecl
;
6092 else if (auto *BSI
= dyn_cast
<BlockScopeInfo
>(CSI
))
6095 if (DC
->containsDecl(TT
->getDecl()))
6097 captureVariablyModifiedType(
6098 Context
, LHSExp
->IgnoreParenImpCasts()->getType(), CSI
);
6104 return new (Context
)
6105 ArraySubscriptExpr(LHSExp
, RHSExp
, ResultType
, VK
, OK
, RLoc
);
6108 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc
, FunctionDecl
*FD
,
6109 ParmVarDecl
*Param
, Expr
*RewrittenInit
,
6110 bool SkipImmediateInvocations
) {
6111 if (Param
->hasUnparsedDefaultArg()) {
6112 assert(!RewrittenInit
&& "Should not have a rewritten init expression yet");
6113 // If we've already cleared out the location for the default argument,
6114 // that means we're parsing it right now.
6115 if (!UnparsedDefaultArgLocs
.count(Param
)) {
6116 Diag(Param
->getBeginLoc(), diag::err_recursive_default_argument
) << FD
;
6117 Diag(CallLoc
, diag::note_recursive_default_argument_used_here
);
6118 Param
->setInvalidDecl();
6122 Diag(CallLoc
, diag::err_use_of_default_argument_to_function_declared_later
)
6123 << FD
<< cast
<CXXRecordDecl
>(FD
->getDeclContext());
6124 Diag(UnparsedDefaultArgLocs
[Param
],
6125 diag::note_default_argument_declared_here
);
6129 if (Param
->hasUninstantiatedDefaultArg()) {
6130 assert(!RewrittenInit
&& "Should not have a rewitten init expression yet");
6131 if (InstantiateDefaultArgument(CallLoc
, FD
, Param
))
6135 Expr
*Init
= RewrittenInit
? RewrittenInit
: Param
->getInit();
6136 assert(Init
&& "default argument but no initializer?");
6138 // If the default expression creates temporaries, we need to
6139 // push them to the current stack of expression temporaries so they'll
6140 // be properly destroyed.
6141 // FIXME: We should really be rebuilding the default argument with new
6142 // bound temporaries; see the comment in PR5810.
6143 // We don't need to do that with block decls, though, because
6144 // blocks in default argument expression can never capture anything.
6145 if (auto *InitWithCleanup
= dyn_cast
<ExprWithCleanups
>(Init
)) {
6146 // Set the "needs cleanups" bit regardless of whether there are
6147 // any explicit objects.
6148 Cleanup
.setExprNeedsCleanups(InitWithCleanup
->cleanupsHaveSideEffects());
6149 // Append all the objects to the cleanup list. Right now, this
6150 // should always be a no-op, because blocks in default argument
6151 // expressions should never be able to capture anything.
6152 assert(!InitWithCleanup
->getNumObjects() &&
6153 "default argument expression has capturing blocks?");
6155 // C++ [expr.const]p15.1:
6156 // An expression or conversion is in an immediate function context if it is
6157 // potentially evaluated and [...] its innermost enclosing non-block scope
6158 // is a function parameter scope of an immediate function.
6159 EnterExpressionEvaluationContext
EvalContext(
6161 FD
->isImmediateFunction()
6162 ? ExpressionEvaluationContext::ImmediateFunctionContext
6163 : ExpressionEvaluationContext::PotentiallyEvaluated
,
6165 ExprEvalContexts
.back().IsCurrentlyCheckingDefaultArgumentOrInitializer
=
6166 SkipImmediateInvocations
;
6167 runWithSufficientStackSpace(CallLoc
, [&] {
6168 MarkDeclarationsReferencedInExpr(Init
, /*SkipLocalVariables=*/true);
6173 struct ImmediateCallVisitor
: public RecursiveASTVisitor
<ImmediateCallVisitor
> {
6174 const ASTContext
&Context
;
6175 ImmediateCallVisitor(const ASTContext
&Ctx
) : Context(Ctx
) {}
6177 bool HasImmediateCalls
= false;
6178 bool shouldVisitImplicitCode() const { return true; }
6180 bool VisitCallExpr(CallExpr
*E
) {
6181 if (const FunctionDecl
*FD
= E
->getDirectCallee())
6182 HasImmediateCalls
|= FD
->isImmediateFunction();
6183 return RecursiveASTVisitor
<ImmediateCallVisitor
>::VisitStmt(E
);
6186 // SourceLocExpr are not immediate invocations
6187 // but CXXDefaultInitExpr/CXXDefaultArgExpr containing a SourceLocExpr
6188 // need to be rebuilt so that they refer to the correct SourceLocation and
6190 bool VisitSourceLocExpr(SourceLocExpr
*E
) {
6191 HasImmediateCalls
= true;
6192 return RecursiveASTVisitor
<ImmediateCallVisitor
>::VisitStmt(E
);
6195 // A nested lambda might have parameters with immediate invocations
6196 // in their default arguments.
6197 // The compound statement is not visited (as it does not constitute a
6199 // FIXME: We should consider visiting and transforming captures
6200 // with init expressions.
6201 bool VisitLambdaExpr(LambdaExpr
*E
) {
6202 return VisitCXXMethodDecl(E
->getCallOperator());
6205 // Blocks don't support default parameters, and, as for lambdas,
6206 // we don't consider their body a subexpression.
6207 bool VisitBlockDecl(BlockDecl
*B
) { return false; }
6209 bool VisitCompoundStmt(CompoundStmt
*B
) { return false; }
6211 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr
*E
) {
6212 return TraverseStmt(E
->getExpr());
6215 bool VisitCXXDefaultInitExpr(CXXDefaultInitExpr
*E
) {
6216 return TraverseStmt(E
->getExpr());
6220 struct EnsureImmediateInvocationInDefaultArgs
6221 : TreeTransform
<EnsureImmediateInvocationInDefaultArgs
> {
6222 EnsureImmediateInvocationInDefaultArgs(Sema
&SemaRef
)
6223 : TreeTransform(SemaRef
) {}
6225 // Lambda can only have immediate invocations in the default
6226 // args of their parameters, which is transformed upon calling the closure.
6227 // The body is not a subexpression, so we have nothing to do.
6228 // FIXME: Immediate calls in capture initializers should be transformed.
6229 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) { return E
; }
6230 ExprResult
TransformBlockExpr(BlockExpr
*E
) { return E
; }
6232 // Make sure we don't rebuild the this pointer as it would
6233 // cause it to incorrectly point it to the outermost class
6234 // in the case of nested struct initialization.
6235 ExprResult
TransformCXXThisExpr(CXXThisExpr
*E
) { return E
; }
6238 ExprResult
Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc
,
6239 FunctionDecl
*FD
, ParmVarDecl
*Param
,
6241 assert(Param
->hasDefaultArg() && "can't build nonexistent default arg");
6243 bool NestedDefaultChecking
= isCheckingDefaultArgumentOrInitializer();
6245 std::optional
<ExpressionEvaluationContextRecord::InitializationContext
>
6246 InitializationContext
=
6247 OutermostDeclarationWithDelayedImmediateInvocations();
6248 if (!InitializationContext
.has_value())
6249 InitializationContext
.emplace(CallLoc
, Param
, CurContext
);
6251 if (!Init
&& !Param
->hasUnparsedDefaultArg()) {
6252 // Mark that we are replacing a default argument first.
6253 // If we are instantiating a template we won't have to
6254 // retransform immediate calls.
6255 // C++ [expr.const]p15.1:
6256 // An expression or conversion is in an immediate function context if it
6257 // is potentially evaluated and [...] its innermost enclosing non-block
6258 // scope is a function parameter scope of an immediate function.
6259 EnterExpressionEvaluationContext
EvalContext(
6261 FD
->isImmediateFunction()
6262 ? ExpressionEvaluationContext::ImmediateFunctionContext
6263 : ExpressionEvaluationContext::PotentiallyEvaluated
,
6266 if (Param
->hasUninstantiatedDefaultArg()) {
6267 if (InstantiateDefaultArgument(CallLoc
, FD
, Param
))
6271 // An immediate invocation that is not evaluated where it appears is
6272 // evaluated and checked for whether it is a constant expression at the
6273 // point where the enclosing initializer is used in a function call.
6274 ImmediateCallVisitor
V(getASTContext());
6275 if (!NestedDefaultChecking
)
6276 V
.TraverseDecl(Param
);
6277 if (V
.HasImmediateCalls
) {
6278 ExprEvalContexts
.back().DelayedDefaultInitializationContext
= {
6279 CallLoc
, Param
, CurContext
};
6280 EnsureImmediateInvocationInDefaultArgs
Immediate(*this);
6282 runWithSufficientStackSpace(CallLoc
, [&] {
6283 Res
= Immediate
.TransformInitializer(Param
->getInit(),
6286 if (Res
.isInvalid())
6288 Res
= ConvertParamDefaultArgument(Param
, Res
.get(),
6289 Res
.get()->getBeginLoc());
6290 if (Res
.isInvalid())
6296 if (CheckCXXDefaultArgExpr(
6297 CallLoc
, FD
, Param
, Init
,
6298 /*SkipImmediateInvocations=*/NestedDefaultChecking
))
6301 return CXXDefaultArgExpr::Create(Context
, InitializationContext
->Loc
, Param
,
6302 Init
, InitializationContext
->Context
);
6305 ExprResult
Sema::BuildCXXDefaultInitExpr(SourceLocation Loc
, FieldDecl
*Field
) {
6306 assert(Field
->hasInClassInitializer());
6308 // If we might have already tried and failed to instantiate, don't try again.
6309 if (Field
->isInvalidDecl())
6312 CXXThisScopeRAII
This(*this, Field
->getParent(), Qualifiers());
6314 auto *ParentRD
= cast
<CXXRecordDecl
>(Field
->getParent());
6316 std::optional
<ExpressionEvaluationContextRecord::InitializationContext
>
6317 InitializationContext
=
6318 OutermostDeclarationWithDelayedImmediateInvocations();
6319 if (!InitializationContext
.has_value())
6320 InitializationContext
.emplace(Loc
, Field
, CurContext
);
6322 Expr
*Init
= nullptr;
6324 bool NestedDefaultChecking
= isCheckingDefaultArgumentOrInitializer();
6326 EnterExpressionEvaluationContext
EvalContext(
6327 *this, ExpressionEvaluationContext::PotentiallyEvaluated
, Field
);
6329 if (!Field
->getInClassInitializer()) {
6330 // Maybe we haven't instantiated the in-class initializer. Go check the
6331 // pattern FieldDecl to see if it has one.
6332 if (isTemplateInstantiation(ParentRD
->getTemplateSpecializationKind())) {
6333 CXXRecordDecl
*ClassPattern
= ParentRD
->getTemplateInstantiationPattern();
6334 DeclContext::lookup_result Lookup
=
6335 ClassPattern
->lookup(Field
->getDeclName());
6337 FieldDecl
*Pattern
= nullptr;
6338 for (auto *L
: Lookup
) {
6339 if ((Pattern
= dyn_cast
<FieldDecl
>(L
)))
6342 assert(Pattern
&& "We must have set the Pattern!");
6343 if (!Pattern
->hasInClassInitializer() ||
6344 InstantiateInClassInitializer(Loc
, Field
, Pattern
,
6345 getTemplateInstantiationArgs(Field
))) {
6346 Field
->setInvalidDecl();
6353 // An immediate invocation that is not evaluated where it appears is
6354 // evaluated and checked for whether it is a constant expression at the
6355 // point where the enclosing initializer is used in a [...] a constructor
6356 // definition, or an aggregate initialization.
6357 ImmediateCallVisitor
V(getASTContext());
6358 if (!NestedDefaultChecking
)
6359 V
.TraverseDecl(Field
);
6360 if (V
.HasImmediateCalls
) {
6361 ExprEvalContexts
.back().DelayedDefaultInitializationContext
= {Loc
, Field
,
6363 ExprEvalContexts
.back().IsCurrentlyCheckingDefaultArgumentOrInitializer
=
6364 NestedDefaultChecking
;
6366 EnsureImmediateInvocationInDefaultArgs
Immediate(*this);
6368 runWithSufficientStackSpace(Loc
, [&] {
6369 Res
= Immediate
.TransformInitializer(Field
->getInClassInitializer(),
6370 /*CXXDirectInit=*/false);
6372 if (!Res
.isInvalid())
6373 Res
= ConvertMemberDefaultInitExpression(Field
, Res
.get(), Loc
);
6374 if (Res
.isInvalid()) {
6375 Field
->setInvalidDecl();
6381 if (Field
->getInClassInitializer()) {
6382 Expr
*E
= Init
? Init
: Field
->getInClassInitializer();
6383 if (!NestedDefaultChecking
)
6384 runWithSufficientStackSpace(Loc
, [&] {
6385 MarkDeclarationsReferencedInExpr(E
, /*SkipLocalVariables=*/false);
6387 // C++11 [class.base.init]p7:
6388 // The initialization of each base and member constitutes a
6390 ExprResult Res
= ActOnFinishFullExpr(E
, /*DiscardedValue=*/false);
6391 if (Res
.isInvalid()) {
6392 Field
->setInvalidDecl();
6397 return CXXDefaultInitExpr::Create(Context
, InitializationContext
->Loc
,
6398 Field
, InitializationContext
->Context
,
6403 // If the brace-or-equal-initializer of a non-static data member
6404 // invokes a defaulted default constructor of its class or of an
6405 // enclosing class in a potentially evaluated subexpression, the
6406 // program is ill-formed.
6408 // This resolution is unworkable: the exception specification of the
6409 // default constructor can be needed in an unevaluated context, in
6410 // particular, in the operand of a noexcept-expression, and we can be
6411 // unable to compute an exception specification for an enclosed class.
6413 // Any attempt to resolve the exception specification of a defaulted default
6414 // constructor before the initializer is lexically complete will ultimately
6415 // come here at which point we can diagnose it.
6416 RecordDecl
*OutermostClass
= ParentRD
->getOuterLexicalRecordContext();
6417 Diag(Loc
, diag::err_default_member_initializer_not_yet_parsed
)
6418 << OutermostClass
<< Field
;
6419 Diag(Field
->getEndLoc(),
6420 diag::note_default_member_initializer_not_yet_parsed
);
6421 // Recover by marking the field invalid, unless we're in a SFINAE context.
6422 if (!isSFINAEContext())
6423 Field
->setInvalidDecl();
6427 Sema::VariadicCallType
6428 Sema::getVariadicCallType(FunctionDecl
*FDecl
, const FunctionProtoType
*Proto
,
6430 if (Proto
&& Proto
->isVariadic()) {
6431 if (isa_and_nonnull
<CXXConstructorDecl
>(FDecl
))
6432 return VariadicConstructor
;
6433 else if (Fn
&& Fn
->getType()->isBlockPointerType())
6434 return VariadicBlock
;
6436 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(FDecl
))
6437 if (Method
->isInstance())
6438 return VariadicMethod
;
6439 } else if (Fn
&& Fn
->getType() == Context
.BoundMemberTy
)
6440 return VariadicMethod
;
6441 return VariadicFunction
;
6443 return VariadicDoesNotApply
;
6447 class FunctionCallCCC final
: public FunctionCallFilterCCC
{
6449 FunctionCallCCC(Sema
&SemaRef
, const IdentifierInfo
*FuncName
,
6450 unsigned NumArgs
, MemberExpr
*ME
)
6451 : FunctionCallFilterCCC(SemaRef
, NumArgs
, false, ME
),
6452 FunctionName(FuncName
) {}
6454 bool ValidateCandidate(const TypoCorrection
&candidate
) override
{
6455 if (!candidate
.getCorrectionSpecifier() ||
6456 candidate
.getCorrectionAsIdentifierInfo() != FunctionName
) {
6460 return FunctionCallFilterCCC::ValidateCandidate(candidate
);
6463 std::unique_ptr
<CorrectionCandidateCallback
> clone() override
{
6464 return std::make_unique
<FunctionCallCCC
>(*this);
6468 const IdentifierInfo
*const FunctionName
;
6472 static TypoCorrection
TryTypoCorrectionForCall(Sema
&S
, Expr
*Fn
,
6473 FunctionDecl
*FDecl
,
6474 ArrayRef
<Expr
*> Args
) {
6475 MemberExpr
*ME
= dyn_cast
<MemberExpr
>(Fn
);
6476 DeclarationName FuncName
= FDecl
->getDeclName();
6477 SourceLocation NameLoc
= ME
? ME
->getMemberLoc() : Fn
->getBeginLoc();
6479 FunctionCallCCC
CCC(S
, FuncName
.getAsIdentifierInfo(), Args
.size(), ME
);
6480 if (TypoCorrection Corrected
= S
.CorrectTypo(
6481 DeclarationNameInfo(FuncName
, NameLoc
), Sema::LookupOrdinaryName
,
6482 S
.getScopeForContext(S
.CurContext
), nullptr, CCC
,
6483 Sema::CTK_ErrorRecovery
)) {
6484 if (NamedDecl
*ND
= Corrected
.getFoundDecl()) {
6485 if (Corrected
.isOverloaded()) {
6486 OverloadCandidateSet
OCS(NameLoc
, OverloadCandidateSet::CSK_Normal
);
6487 OverloadCandidateSet::iterator Best
;
6488 for (NamedDecl
*CD
: Corrected
) {
6489 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(CD
))
6490 S
.AddOverloadCandidate(FD
, DeclAccessPair::make(FD
, AS_none
), Args
,
6493 switch (OCS
.BestViableFunction(S
, NameLoc
, Best
)) {
6495 ND
= Best
->FoundDecl
;
6496 Corrected
.setCorrectionDecl(ND
);
6502 ND
= ND
->getUnderlyingDecl();
6503 if (isa
<ValueDecl
>(ND
) || isa
<FunctionTemplateDecl
>(ND
))
6507 return TypoCorrection();
6510 /// ConvertArgumentsForCall - Converts the arguments specified in
6511 /// Args/NumArgs to the parameter types of the function FDecl with
6512 /// function prototype Proto. Call is the call expression itself, and
6513 /// Fn is the function expression. For a C++ member function, this
6514 /// routine does not attempt to convert the object argument. Returns
6515 /// true if the call is ill-formed.
6517 Sema::ConvertArgumentsForCall(CallExpr
*Call
, Expr
*Fn
,
6518 FunctionDecl
*FDecl
,
6519 const FunctionProtoType
*Proto
,
6520 ArrayRef
<Expr
*> Args
,
6521 SourceLocation RParenLoc
,
6522 bool IsExecConfig
) {
6523 // Bail out early if calling a builtin with custom typechecking.
6525 if (unsigned ID
= FDecl
->getBuiltinID())
6526 if (Context
.BuiltinInfo
.hasCustomTypechecking(ID
))
6529 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
6530 // assignment, to the types of the corresponding parameter, ...
6531 bool HasExplicitObjectParameter
=
6532 FDecl
&& FDecl
->hasCXXExplicitFunctionObjectParameter();
6533 unsigned ExplicitObjectParameterOffset
= HasExplicitObjectParameter
? 1 : 0;
6534 unsigned NumParams
= Proto
->getNumParams();
6535 bool Invalid
= false;
6536 unsigned MinArgs
= FDecl
? FDecl
->getMinRequiredArguments() : NumParams
;
6537 unsigned FnKind
= Fn
->getType()->isBlockPointerType()
6539 : (IsExecConfig
? 3 /* kernel function (exec config) */
6540 : 0 /* function */);
6542 // If too few arguments are available (and we don't have default
6543 // arguments for the remaining parameters), don't make the call.
6544 if (Args
.size() < NumParams
) {
6545 if (Args
.size() < MinArgs
) {
6547 if (FDecl
&& (TC
= TryTypoCorrectionForCall(*this, Fn
, FDecl
, Args
))) {
6549 MinArgs
== NumParams
&& !Proto
->isVariadic()
6550 ? diag::err_typecheck_call_too_few_args_suggest
6551 : diag::err_typecheck_call_too_few_args_at_least_suggest
;
6554 << FnKind
<< MinArgs
- ExplicitObjectParameterOffset
6555 << static_cast<unsigned>(Args
.size()) -
6556 ExplicitObjectParameterOffset
6557 << HasExplicitObjectParameter
<< TC
.getCorrectionRange());
6558 } else if (MinArgs
- ExplicitObjectParameterOffset
== 1 && FDecl
&&
6559 FDecl
->getParamDecl(ExplicitObjectParameterOffset
)
6562 MinArgs
== NumParams
&& !Proto
->isVariadic()
6563 ? diag::err_typecheck_call_too_few_args_one
6564 : diag::err_typecheck_call_too_few_args_at_least_one
)
6565 << FnKind
<< FDecl
->getParamDecl(ExplicitObjectParameterOffset
)
6566 << HasExplicitObjectParameter
<< Fn
->getSourceRange();
6568 Diag(RParenLoc
, MinArgs
== NumParams
&& !Proto
->isVariadic()
6569 ? diag::err_typecheck_call_too_few_args
6570 : diag::err_typecheck_call_too_few_args_at_least
)
6571 << FnKind
<< MinArgs
- ExplicitObjectParameterOffset
6572 << static_cast<unsigned>(Args
.size()) -
6573 ExplicitObjectParameterOffset
6574 << HasExplicitObjectParameter
<< Fn
->getSourceRange();
6576 // Emit the location of the prototype.
6577 if (!TC
&& FDecl
&& !FDecl
->getBuiltinID() && !IsExecConfig
)
6578 Diag(FDecl
->getLocation(), diag::note_callee_decl
)
6579 << FDecl
<< FDecl
->getParametersSourceRange();
6583 // We reserve space for the default arguments when we create
6584 // the call expression, before calling ConvertArgumentsForCall.
6585 assert((Call
->getNumArgs() == NumParams
) &&
6586 "We should have reserved space for the default arguments before!");
6589 // If too many are passed and not variadic, error on the extras and drop
6591 if (Args
.size() > NumParams
) {
6592 if (!Proto
->isVariadic()) {
6594 if (FDecl
&& (TC
= TryTypoCorrectionForCall(*this, Fn
, FDecl
, Args
))) {
6596 MinArgs
== NumParams
&& !Proto
->isVariadic()
6597 ? diag::err_typecheck_call_too_many_args_suggest
6598 : diag::err_typecheck_call_too_many_args_at_most_suggest
;
6601 << FnKind
<< NumParams
- ExplicitObjectParameterOffset
6602 << static_cast<unsigned>(Args
.size()) -
6603 ExplicitObjectParameterOffset
6604 << HasExplicitObjectParameter
<< TC
.getCorrectionRange());
6605 } else if (NumParams
- ExplicitObjectParameterOffset
== 1 && FDecl
&&
6606 FDecl
->getParamDecl(ExplicitObjectParameterOffset
)
6608 Diag(Args
[NumParams
]->getBeginLoc(),
6609 MinArgs
== NumParams
6610 ? diag::err_typecheck_call_too_many_args_one
6611 : diag::err_typecheck_call_too_many_args_at_most_one
)
6612 << FnKind
<< FDecl
->getParamDecl(ExplicitObjectParameterOffset
)
6613 << static_cast<unsigned>(Args
.size()) -
6614 ExplicitObjectParameterOffset
6615 << HasExplicitObjectParameter
<< Fn
->getSourceRange()
6616 << SourceRange(Args
[NumParams
]->getBeginLoc(),
6617 Args
.back()->getEndLoc());
6619 Diag(Args
[NumParams
]->getBeginLoc(),
6620 MinArgs
== NumParams
6621 ? diag::err_typecheck_call_too_many_args
6622 : diag::err_typecheck_call_too_many_args_at_most
)
6623 << FnKind
<< NumParams
- ExplicitObjectParameterOffset
6624 << static_cast<unsigned>(Args
.size()) -
6625 ExplicitObjectParameterOffset
6626 << HasExplicitObjectParameter
<< Fn
->getSourceRange()
6627 << SourceRange(Args
[NumParams
]->getBeginLoc(),
6628 Args
.back()->getEndLoc());
6630 // Emit the location of the prototype.
6631 if (!TC
&& FDecl
&& !FDecl
->getBuiltinID() && !IsExecConfig
)
6632 Diag(FDecl
->getLocation(), diag::note_callee_decl
)
6633 << FDecl
<< FDecl
->getParametersSourceRange();
6635 // This deletes the extra arguments.
6636 Call
->shrinkNumArgs(NumParams
);
6640 SmallVector
<Expr
*, 8> AllArgs
;
6641 VariadicCallType CallType
= getVariadicCallType(FDecl
, Proto
, Fn
);
6643 Invalid
= GatherArgumentsForCall(Call
->getBeginLoc(), FDecl
, Proto
, 0, Args
,
6647 unsigned TotalNumArgs
= AllArgs
.size();
6648 for (unsigned i
= 0; i
< TotalNumArgs
; ++i
)
6649 Call
->setArg(i
, AllArgs
[i
]);
6651 Call
->computeDependence();
6655 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc
, FunctionDecl
*FDecl
,
6656 const FunctionProtoType
*Proto
,
6657 unsigned FirstParam
, ArrayRef
<Expr
*> Args
,
6658 SmallVectorImpl
<Expr
*> &AllArgs
,
6659 VariadicCallType CallType
, bool AllowExplicit
,
6660 bool IsListInitialization
) {
6661 unsigned NumParams
= Proto
->getNumParams();
6662 bool Invalid
= false;
6664 // Continue to check argument types (even if we have too few/many args).
6665 for (unsigned i
= FirstParam
; i
< NumParams
; i
++) {
6666 QualType ProtoArgType
= Proto
->getParamType(i
);
6669 ParmVarDecl
*Param
= FDecl
? FDecl
->getParamDecl(i
) : nullptr;
6670 if (ArgIx
< Args
.size()) {
6671 Arg
= Args
[ArgIx
++];
6673 if (RequireCompleteType(Arg
->getBeginLoc(), ProtoArgType
,
6674 diag::err_call_incomplete_argument
, Arg
))
6677 // Strip the unbridged-cast placeholder expression off, if applicable.
6678 bool CFAudited
= false;
6679 if (Arg
->getType() == Context
.ARCUnbridgedCastTy
&&
6680 FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>() &&
6681 (!Param
|| !Param
->hasAttr
<CFConsumedAttr
>()))
6682 Arg
= stripARCUnbridgedCast(Arg
);
6683 else if (getLangOpts().ObjCAutoRefCount
&&
6684 FDecl
&& FDecl
->hasAttr
<CFAuditedTransferAttr
>() &&
6685 (!Param
|| !Param
->hasAttr
<CFConsumedAttr
>()))
6688 if (Proto
->getExtParameterInfo(i
).isNoEscape() &&
6689 ProtoArgType
->isBlockPointerType())
6690 if (auto *BE
= dyn_cast
<BlockExpr
>(Arg
->IgnoreParenNoopCasts(Context
)))
6691 BE
->getBlockDecl()->setDoesNotEscape();
6693 InitializedEntity Entity
=
6694 Param
? InitializedEntity::InitializeParameter(Context
, Param
,
6696 : InitializedEntity::InitializeParameter(
6697 Context
, ProtoArgType
, Proto
->isParamConsumed(i
));
6699 // Remember that parameter belongs to a CF audited API.
6701 Entity
.setParameterCFAudited();
6703 ExprResult ArgE
= PerformCopyInitialization(
6704 Entity
, SourceLocation(), Arg
, IsListInitialization
, AllowExplicit
);
6705 if (ArgE
.isInvalid())
6708 Arg
= ArgE
.getAs
<Expr
>();
6710 assert(Param
&& "can't use default arguments without a known callee");
6712 ExprResult ArgExpr
= BuildCXXDefaultArgExpr(CallLoc
, FDecl
, Param
);
6713 if (ArgExpr
.isInvalid())
6716 Arg
= ArgExpr
.getAs
<Expr
>();
6719 // Check for array bounds violations for each argument to the call. This
6720 // check only triggers warnings when the argument isn't a more complex Expr
6721 // with its own checking, such as a BinaryOperator.
6722 CheckArrayAccess(Arg
);
6724 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
6725 CheckStaticArrayArgument(CallLoc
, Param
, Arg
);
6727 AllArgs
.push_back(Arg
);
6730 // If this is a variadic call, handle args passed through "...".
6731 if (CallType
!= VariadicDoesNotApply
) {
6732 // Assume that extern "C" functions with variadic arguments that
6733 // return __unknown_anytype aren't *really* variadic.
6734 if (Proto
->getReturnType() == Context
.UnknownAnyTy
&& FDecl
&&
6735 FDecl
->isExternC()) {
6736 for (Expr
*A
: Args
.slice(ArgIx
)) {
6737 QualType paramType
; // ignored
6738 ExprResult arg
= checkUnknownAnyArg(CallLoc
, A
, paramType
);
6739 Invalid
|= arg
.isInvalid();
6740 AllArgs
.push_back(arg
.get());
6743 // Otherwise do argument promotion, (C99 6.5.2.2p7).
6745 for (Expr
*A
: Args
.slice(ArgIx
)) {
6746 ExprResult Arg
= DefaultVariadicArgumentPromotion(A
, CallType
, FDecl
);
6747 Invalid
|= Arg
.isInvalid();
6748 AllArgs
.push_back(Arg
.get());
6752 // Check for array bounds violations.
6753 for (Expr
*A
: Args
.slice(ArgIx
))
6754 CheckArrayAccess(A
);
6759 static void DiagnoseCalleeStaticArrayParam(Sema
&S
, ParmVarDecl
*PVD
) {
6760 TypeLoc TL
= PVD
->getTypeSourceInfo()->getTypeLoc();
6761 if (DecayedTypeLoc DTL
= TL
.getAs
<DecayedTypeLoc
>())
6762 TL
= DTL
.getOriginalLoc();
6763 if (ArrayTypeLoc ATL
= TL
.getAs
<ArrayTypeLoc
>())
6764 S
.Diag(PVD
->getLocation(), diag::note_callee_static_array
)
6765 << ATL
.getLocalSourceRange();
6768 /// CheckStaticArrayArgument - If the given argument corresponds to a static
6769 /// array parameter, check that it is non-null, and that if it is formed by
6770 /// array-to-pointer decay, the underlying array is sufficiently large.
6772 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
6773 /// array type derivation, then for each call to the function, the value of the
6774 /// corresponding actual argument shall provide access to the first element of
6775 /// an array with at least as many elements as specified by the size expression.
6777 Sema::CheckStaticArrayArgument(SourceLocation CallLoc
,
6779 const Expr
*ArgExpr
) {
6780 // Static array parameters are not supported in C++.
6781 if (!Param
|| getLangOpts().CPlusPlus
)
6784 QualType OrigTy
= Param
->getOriginalType();
6786 const ArrayType
*AT
= Context
.getAsArrayType(OrigTy
);
6787 if (!AT
|| AT
->getSizeModifier() != ArraySizeModifier::Static
)
6790 if (ArgExpr
->isNullPointerConstant(Context
,
6791 Expr::NPC_NeverValueDependent
)) {
6792 Diag(CallLoc
, diag::warn_null_arg
) << ArgExpr
->getSourceRange();
6793 DiagnoseCalleeStaticArrayParam(*this, Param
);
6797 const ConstantArrayType
*CAT
= dyn_cast
<ConstantArrayType
>(AT
);
6801 const ConstantArrayType
*ArgCAT
=
6802 Context
.getAsConstantArrayType(ArgExpr
->IgnoreParenCasts()->getType());
6806 if (getASTContext().hasSameUnqualifiedType(CAT
->getElementType(),
6807 ArgCAT
->getElementType())) {
6808 if (ArgCAT
->getSize().ult(CAT
->getSize())) {
6809 Diag(CallLoc
, diag::warn_static_array_too_small
)
6810 << ArgExpr
->getSourceRange()
6811 << (unsigned)ArgCAT
->getSize().getZExtValue()
6812 << (unsigned)CAT
->getSize().getZExtValue() << 0;
6813 DiagnoseCalleeStaticArrayParam(*this, Param
);
6818 std::optional
<CharUnits
> ArgSize
=
6819 getASTContext().getTypeSizeInCharsIfKnown(ArgCAT
);
6820 std::optional
<CharUnits
> ParmSize
=
6821 getASTContext().getTypeSizeInCharsIfKnown(CAT
);
6822 if (ArgSize
&& ParmSize
&& *ArgSize
< *ParmSize
) {
6823 Diag(CallLoc
, diag::warn_static_array_too_small
)
6824 << ArgExpr
->getSourceRange() << (unsigned)ArgSize
->getQuantity()
6825 << (unsigned)ParmSize
->getQuantity() << 1;
6826 DiagnoseCalleeStaticArrayParam(*this, Param
);
6830 /// Given a function expression of unknown-any type, try to rebuild it
6831 /// to have a function type.
6832 static ExprResult
rebuildUnknownAnyFunction(Sema
&S
, Expr
*fn
);
6834 /// Is the given type a placeholder that we need to lower out
6835 /// immediately during argument processing?
6836 static bool isPlaceholderToRemoveAsArg(QualType type
) {
6837 // Placeholders are never sugared.
6838 const BuiltinType
*placeholder
= dyn_cast
<BuiltinType
>(type
);
6839 if (!placeholder
) return false;
6841 switch (placeholder
->getKind()) {
6842 // Ignore all the non-placeholder types.
6843 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6844 case BuiltinType::Id:
6845 #include "clang/Basic/OpenCLImageTypes.def"
6846 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6847 case BuiltinType::Id:
6848 #include "clang/Basic/OpenCLExtensionTypes.def"
6849 // In practice we'll never use this, since all SVE types are sugared
6850 // via TypedefTypes rather than exposed directly as BuiltinTypes.
6851 #define SVE_TYPE(Name, Id, SingletonId) \
6852 case BuiltinType::Id:
6853 #include "clang/Basic/AArch64SVEACLETypes.def"
6854 #define PPC_VECTOR_TYPE(Name, Id, Size) \
6855 case BuiltinType::Id:
6856 #include "clang/Basic/PPCTypes.def"
6857 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6858 #include "clang/Basic/RISCVVTypes.def"
6859 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
6860 #include "clang/Basic/WebAssemblyReferenceTypes.def"
6861 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
6862 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
6863 #include "clang/AST/BuiltinTypes.def"
6866 // We cannot lower out overload sets; they might validly be resolved
6867 // by the call machinery.
6868 case BuiltinType::Overload
:
6871 // Unbridged casts in ARC can be handled in some call positions and
6872 // should be left in place.
6873 case BuiltinType::ARCUnbridgedCast
:
6876 // Pseudo-objects should be converted as soon as possible.
6877 case BuiltinType::PseudoObject
:
6880 // The debugger mode could theoretically but currently does not try
6881 // to resolve unknown-typed arguments based on known parameter types.
6882 case BuiltinType::UnknownAny
:
6885 // These are always invalid as call arguments and should be reported.
6886 case BuiltinType::BoundMember
:
6887 case BuiltinType::BuiltinFn
:
6888 case BuiltinType::IncompleteMatrixIdx
:
6889 case BuiltinType::OMPArraySection
:
6890 case BuiltinType::OMPArrayShaping
:
6891 case BuiltinType::OMPIterator
:
6895 llvm_unreachable("bad builtin type kind");
6898 /// Check an argument list for placeholders that we won't try to
6900 static bool checkArgsForPlaceholders(Sema
&S
, MultiExprArg args
) {
6901 // Apply this processing to all the arguments at once instead of
6902 // dying at the first failure.
6903 bool hasInvalid
= false;
6904 for (size_t i
= 0, e
= args
.size(); i
!= e
; i
++) {
6905 if (isPlaceholderToRemoveAsArg(args
[i
]->getType())) {
6906 ExprResult result
= S
.CheckPlaceholderExpr(args
[i
]);
6907 if (result
.isInvalid()) hasInvalid
= true;
6908 else args
[i
] = result
.get();
6914 /// If a builtin function has a pointer argument with no explicit address
6915 /// space, then it should be able to accept a pointer to any address
6916 /// space as input. In order to do this, we need to replace the
6917 /// standard builtin declaration with one that uses the same address space
6920 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
6921 /// it does not contain any pointer arguments without
6922 /// an address space qualifer. Otherwise the rewritten
6923 /// FunctionDecl is returned.
6924 /// TODO: Handle pointer return types.
6925 static FunctionDecl
*rewriteBuiltinFunctionDecl(Sema
*Sema
, ASTContext
&Context
,
6926 FunctionDecl
*FDecl
,
6927 MultiExprArg ArgExprs
) {
6929 QualType DeclType
= FDecl
->getType();
6930 const FunctionProtoType
*FT
= dyn_cast
<FunctionProtoType
>(DeclType
);
6932 if (!Context
.BuiltinInfo
.hasPtrArgsOrResult(FDecl
->getBuiltinID()) || !FT
||
6933 ArgExprs
.size() < FT
->getNumParams())
6936 bool NeedsNewDecl
= false;
6938 SmallVector
<QualType
, 8> OverloadParams
;
6940 for (QualType ParamType
: FT
->param_types()) {
6942 // Convert array arguments to pointer to simplify type lookup.
6944 Sema
->DefaultFunctionArrayLvalueConversion(ArgExprs
[i
++]);
6945 if (ArgRes
.isInvalid())
6947 Expr
*Arg
= ArgRes
.get();
6948 QualType ArgType
= Arg
->getType();
6949 if (!ParamType
->isPointerType() || ParamType
.hasAddressSpace() ||
6950 !ArgType
->isPointerType() ||
6951 !ArgType
->getPointeeType().hasAddressSpace() ||
6952 isPtrSizeAddressSpace(ArgType
->getPointeeType().getAddressSpace())) {
6953 OverloadParams
.push_back(ParamType
);
6957 QualType PointeeType
= ParamType
->getPointeeType();
6958 if (PointeeType
.hasAddressSpace())
6961 NeedsNewDecl
= true;
6962 LangAS AS
= ArgType
->getPointeeType().getAddressSpace();
6964 PointeeType
= Context
.getAddrSpaceQualType(PointeeType
, AS
);
6965 OverloadParams
.push_back(Context
.getPointerType(PointeeType
));
6971 FunctionProtoType::ExtProtoInfo EPI
;
6972 EPI
.Variadic
= FT
->isVariadic();
6973 QualType OverloadTy
= Context
.getFunctionType(FT
->getReturnType(),
6974 OverloadParams
, EPI
);
6975 DeclContext
*Parent
= FDecl
->getParent();
6976 FunctionDecl
*OverloadDecl
= FunctionDecl::Create(
6977 Context
, Parent
, FDecl
->getLocation(), FDecl
->getLocation(),
6978 FDecl
->getIdentifier(), OverloadTy
,
6979 /*TInfo=*/nullptr, SC_Extern
, Sema
->getCurFPFeatures().isFPConstrained(),
6981 /*hasPrototype=*/true);
6982 SmallVector
<ParmVarDecl
*, 16> Params
;
6983 FT
= cast
<FunctionProtoType
>(OverloadTy
);
6984 for (unsigned i
= 0, e
= FT
->getNumParams(); i
!= e
; ++i
) {
6985 QualType ParamType
= FT
->getParamType(i
);
6987 ParmVarDecl::Create(Context
, OverloadDecl
, SourceLocation(),
6988 SourceLocation(), nullptr, ParamType
,
6989 /*TInfo=*/nullptr, SC_None
, nullptr);
6990 Parm
->setScopeInfo(0, i
);
6991 Params
.push_back(Parm
);
6993 OverloadDecl
->setParams(Params
);
6994 Sema
->mergeDeclAttributes(OverloadDecl
, FDecl
);
6995 return OverloadDecl
;
6998 static void checkDirectCallValidity(Sema
&S
, const Expr
*Fn
,
6999 FunctionDecl
*Callee
,
7000 MultiExprArg ArgExprs
) {
7001 // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
7002 // similar attributes) really don't like it when functions are called with an
7003 // invalid number of args.
7004 if (S
.TooManyArguments(Callee
->getNumParams(), ArgExprs
.size(),
7005 /*PartialOverloading=*/false) &&
7006 !Callee
->isVariadic())
7008 if (Callee
->getMinRequiredArguments() > ArgExprs
.size())
7011 if (const EnableIfAttr
*Attr
=
7012 S
.CheckEnableIf(Callee
, Fn
->getBeginLoc(), ArgExprs
, true)) {
7013 S
.Diag(Fn
->getBeginLoc(),
7014 isa
<CXXMethodDecl
>(Callee
)
7015 ? diag::err_ovl_no_viable_member_function_in_call
7016 : diag::err_ovl_no_viable_function_in_call
)
7017 << Callee
<< Callee
->getSourceRange();
7018 S
.Diag(Callee
->getLocation(),
7019 diag::note_ovl_candidate_disabled_by_function_cond_attr
)
7020 << Attr
->getCond()->getSourceRange() << Attr
->getMessage();
7025 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
7026 const UnresolvedMemberExpr
*const UME
, Sema
&S
) {
7028 const auto GetFunctionLevelDCIfCXXClass
=
7029 [](Sema
&S
) -> const CXXRecordDecl
* {
7030 const DeclContext
*const DC
= S
.getFunctionLevelDeclContext();
7031 if (!DC
|| !DC
->getParent())
7034 // If the call to some member function was made from within a member
7035 // function body 'M' return return 'M's parent.
7036 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(DC
))
7037 return MD
->getParent()->getCanonicalDecl();
7038 // else the call was made from within a default member initializer of a
7039 // class, so return the class.
7040 if (const auto *RD
= dyn_cast
<CXXRecordDecl
>(DC
))
7041 return RD
->getCanonicalDecl();
7044 // If our DeclContext is neither a member function nor a class (in the
7045 // case of a lambda in a default member initializer), we can't have an
7046 // enclosing 'this'.
7048 const CXXRecordDecl
*const CurParentClass
= GetFunctionLevelDCIfCXXClass(S
);
7049 if (!CurParentClass
)
7052 // The naming class for implicit member functions call is the class in which
7053 // name lookup starts.
7054 const CXXRecordDecl
*const NamingClass
=
7055 UME
->getNamingClass()->getCanonicalDecl();
7056 assert(NamingClass
&& "Must have naming class even for implicit access");
7058 // If the unresolved member functions were found in a 'naming class' that is
7059 // related (either the same or derived from) to the class that contains the
7060 // member function that itself contained the implicit member access.
7062 return CurParentClass
== NamingClass
||
7063 CurParentClass
->isDerivedFrom(NamingClass
);
7067 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7068 Sema
&S
, const UnresolvedMemberExpr
*const UME
, SourceLocation CallLoc
) {
7073 LambdaScopeInfo
*const CurLSI
= S
.getCurLambda();
7074 // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
7075 // already been captured, or if this is an implicit member function call (if
7076 // it isn't, an attempt to capture 'this' should already have been made).
7077 if (!CurLSI
|| CurLSI
->ImpCaptureStyle
== CurLSI
->ImpCap_None
||
7078 !UME
->isImplicitAccess() || CurLSI
->isCXXThisCaptured())
7081 // Check if the naming class in which the unresolved members were found is
7082 // related (same as or is a base of) to the enclosing class.
7084 if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME
, S
))
7088 DeclContext
*EnclosingFunctionCtx
= S
.CurContext
->getParent()->getParent();
7089 // If the enclosing function is not dependent, then this lambda is
7090 // capture ready, so if we can capture this, do so.
7091 if (!EnclosingFunctionCtx
->isDependentContext()) {
7092 // If the current lambda and all enclosing lambdas can capture 'this' -
7093 // then go ahead and capture 'this' (since our unresolved overload set
7094 // contains at least one non-static member function).
7095 if (!S
.CheckCXXThisCapture(CallLoc
, /*Explcit*/ false, /*Diagnose*/ false))
7096 S
.CheckCXXThisCapture(CallLoc
);
7097 } else if (S
.CurContext
->isDependentContext()) {
7098 // ... since this is an implicit member reference, that might potentially
7099 // involve a 'this' capture, mark 'this' for potential capture in
7100 // enclosing lambdas.
7101 if (CurLSI
->ImpCaptureStyle
!= CurLSI
->ImpCap_None
)
7102 CurLSI
->addPotentialThisCapture(CallLoc
);
7106 // Once a call is fully resolved, warn for unqualified calls to specific
7107 // C++ standard functions, like move and forward.
7108 static void DiagnosedUnqualifiedCallsToStdFunctions(Sema
&S
,
7109 const CallExpr
*Call
) {
7110 // We are only checking unary move and forward so exit early here.
7111 if (Call
->getNumArgs() != 1)
7114 const Expr
*E
= Call
->getCallee()->IgnoreParenImpCasts();
7115 if (!E
|| isa
<UnresolvedLookupExpr
>(E
))
7117 const DeclRefExpr
*DRE
= dyn_cast_if_present
<DeclRefExpr
>(E
);
7118 if (!DRE
|| !DRE
->getLocation().isValid())
7121 if (DRE
->getQualifier())
7124 const FunctionDecl
*FD
= Call
->getDirectCallee();
7128 // Only warn for some functions deemed more frequent or problematic.
7129 unsigned BuiltinID
= FD
->getBuiltinID();
7130 if (BuiltinID
!= Builtin::BImove
&& BuiltinID
!= Builtin::BIforward
)
7133 S
.Diag(DRE
->getLocation(), diag::warn_unqualified_call_to_std_cast_function
)
7134 << FD
->getQualifiedNameAsString()
7135 << FixItHint::CreateInsertion(DRE
->getLocation(), "std::");
7138 ExprResult
Sema::ActOnCallExpr(Scope
*Scope
, Expr
*Fn
, SourceLocation LParenLoc
,
7139 MultiExprArg ArgExprs
, SourceLocation RParenLoc
,
7142 BuildCallExpr(Scope
, Fn
, LParenLoc
, ArgExprs
, RParenLoc
, ExecConfig
,
7143 /*IsExecConfig=*/false, /*AllowRecovery=*/true);
7144 if (Call
.isInvalid())
7147 // Diagnose uses of the C++20 "ADL-only template-id call" feature in earlier
7149 if (const auto *ULE
= dyn_cast
<UnresolvedLookupExpr
>(Fn
);
7150 ULE
&& ULE
->hasExplicitTemplateArgs() &&
7151 ULE
->decls_begin() == ULE
->decls_end()) {
7152 Diag(Fn
->getExprLoc(), getLangOpts().CPlusPlus20
7153 ? diag::warn_cxx17_compat_adl_only_template_id
7154 : diag::ext_adl_only_template_id
)
7158 if (LangOpts
.OpenMP
)
7159 Call
= ActOnOpenMPCall(Call
, Scope
, LParenLoc
, ArgExprs
, RParenLoc
,
7161 if (LangOpts
.CPlusPlus
) {
7162 if (const auto *CE
= dyn_cast
<CallExpr
>(Call
.get()))
7163 DiagnosedUnqualifiedCallsToStdFunctions(*this, CE
);
7168 /// BuildCallExpr - Handle a call to Fn with the specified array of arguments.
7169 /// This provides the location of the left/right parens and a list of comma
7171 ExprResult
Sema::BuildCallExpr(Scope
*Scope
, Expr
*Fn
, SourceLocation LParenLoc
,
7172 MultiExprArg ArgExprs
, SourceLocation RParenLoc
,
7173 Expr
*ExecConfig
, bool IsExecConfig
,
7174 bool AllowRecovery
) {
7175 // Since this might be a postfix expression, get rid of ParenListExprs.
7176 ExprResult Result
= MaybeConvertParenListExprToParenExpr(Scope
, Fn
);
7177 if (Result
.isInvalid()) return ExprError();
7180 if (checkArgsForPlaceholders(*this, ArgExprs
))
7183 if (getLangOpts().CPlusPlus
) {
7184 // If this is a pseudo-destructor expression, build the call immediately.
7185 if (isa
<CXXPseudoDestructorExpr
>(Fn
)) {
7186 if (!ArgExprs
.empty()) {
7187 // Pseudo-destructor calls should not have any arguments.
7188 Diag(Fn
->getBeginLoc(), diag::err_pseudo_dtor_call_with_args
)
7189 << FixItHint::CreateRemoval(
7190 SourceRange(ArgExprs
.front()->getBeginLoc(),
7191 ArgExprs
.back()->getEndLoc()));
7194 return CallExpr::Create(Context
, Fn
, /*Args=*/{}, Context
.VoidTy
,
7195 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
7197 if (Fn
->getType() == Context
.PseudoObjectTy
) {
7198 ExprResult result
= CheckPlaceholderExpr(Fn
);
7199 if (result
.isInvalid()) return ExprError();
7203 // Determine whether this is a dependent call inside a C++ template,
7204 // in which case we won't do any semantic analysis now.
7205 if (Fn
->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs
)) {
7207 return CUDAKernelCallExpr::Create(Context
, Fn
,
7208 cast
<CallExpr
>(ExecConfig
), ArgExprs
,
7209 Context
.DependentTy
, VK_PRValue
,
7210 RParenLoc
, CurFPFeatureOverrides());
7213 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
7214 *this, dyn_cast
<UnresolvedMemberExpr
>(Fn
->IgnoreParens()),
7217 return CallExpr::Create(Context
, Fn
, ArgExprs
, Context
.DependentTy
,
7218 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
7222 // Determine whether this is a call to an object (C++ [over.call.object]).
7223 if (Fn
->getType()->isRecordType())
7224 return BuildCallToObjectOfClassType(Scope
, Fn
, LParenLoc
, ArgExprs
,
7227 if (Fn
->getType() == Context
.UnknownAnyTy
) {
7228 ExprResult result
= rebuildUnknownAnyFunction(*this, Fn
);
7229 if (result
.isInvalid()) return ExprError();
7233 if (Fn
->getType() == Context
.BoundMemberTy
) {
7234 return BuildCallToMemberFunction(Scope
, Fn
, LParenLoc
, ArgExprs
,
7235 RParenLoc
, ExecConfig
, IsExecConfig
,
7240 // Check for overloaded calls. This can happen even in C due to extensions.
7241 if (Fn
->getType() == Context
.OverloadTy
) {
7242 OverloadExpr::FindResult find
= OverloadExpr::find(Fn
);
7244 // We aren't supposed to apply this logic if there's an '&' involved.
7245 if (!find
.HasFormOfMemberPointer
) {
7246 if (Expr::hasAnyTypeDependentArguments(ArgExprs
))
7247 return CallExpr::Create(Context
, Fn
, ArgExprs
, Context
.DependentTy
,
7248 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
7249 OverloadExpr
*ovl
= find
.Expression
;
7250 if (UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(ovl
))
7251 return BuildOverloadedCallExpr(
7252 Scope
, Fn
, ULE
, LParenLoc
, ArgExprs
, RParenLoc
, ExecConfig
,
7253 /*AllowTypoCorrection=*/true, find
.IsAddressOfOperand
);
7254 return BuildCallToMemberFunction(Scope
, Fn
, LParenLoc
, ArgExprs
,
7255 RParenLoc
, ExecConfig
, IsExecConfig
,
7260 // If we're directly calling a function, get the appropriate declaration.
7261 if (Fn
->getType() == Context
.UnknownAnyTy
) {
7262 ExprResult result
= rebuildUnknownAnyFunction(*this, Fn
);
7263 if (result
.isInvalid()) return ExprError();
7267 Expr
*NakedFn
= Fn
->IgnoreParens();
7269 bool CallingNDeclIndirectly
= false;
7270 NamedDecl
*NDecl
= nullptr;
7271 if (UnaryOperator
*UnOp
= dyn_cast
<UnaryOperator
>(NakedFn
)) {
7272 if (UnOp
->getOpcode() == UO_AddrOf
) {
7273 CallingNDeclIndirectly
= true;
7274 NakedFn
= UnOp
->getSubExpr()->IgnoreParens();
7278 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(NakedFn
)) {
7279 NDecl
= DRE
->getDecl();
7281 FunctionDecl
*FDecl
= dyn_cast
<FunctionDecl
>(NDecl
);
7282 if (FDecl
&& FDecl
->getBuiltinID()) {
7283 // Rewrite the function decl for this builtin by replacing parameters
7284 // with no explicit address space with the address space of the arguments
7287 rewriteBuiltinFunctionDecl(this, Context
, FDecl
, ArgExprs
))) {
7289 Fn
= DeclRefExpr::Create(
7290 Context
, FDecl
->getQualifierLoc(), SourceLocation(), FDecl
, false,
7291 SourceLocation(), FDecl
->getType(), Fn
->getValueKind(), FDecl
,
7292 nullptr, DRE
->isNonOdrUse());
7295 } else if (auto *ME
= dyn_cast
<MemberExpr
>(NakedFn
))
7296 NDecl
= ME
->getMemberDecl();
7298 if (FunctionDecl
*FD
= dyn_cast_or_null
<FunctionDecl
>(NDecl
)) {
7299 if (CallingNDeclIndirectly
&& !checkAddressOfFunctionIsAvailable(
7300 FD
, /*Complain=*/true, Fn
->getBeginLoc()))
7303 checkDirectCallValidity(*this, Fn
, FD
, ArgExprs
);
7305 // If this expression is a call to a builtin function in HIP device
7306 // compilation, allow a pointer-type argument to default address space to be
7307 // passed as a pointer-type parameter to a non-default address space.
7308 // If Arg is declared in the default address space and Param is declared
7309 // in a non-default address space, perform an implicit address space cast to
7310 // the parameter type.
7311 if (getLangOpts().HIP
&& getLangOpts().CUDAIsDevice
&& FD
&&
7312 FD
->getBuiltinID()) {
7313 for (unsigned Idx
= 0; Idx
< FD
->param_size(); ++Idx
) {
7314 ParmVarDecl
*Param
= FD
->getParamDecl(Idx
);
7315 if (!ArgExprs
[Idx
] || !Param
|| !Param
->getType()->isPointerType() ||
7316 !ArgExprs
[Idx
]->getType()->isPointerType())
7319 auto ParamAS
= Param
->getType()->getPointeeType().getAddressSpace();
7320 auto ArgTy
= ArgExprs
[Idx
]->getType();
7321 auto ArgPtTy
= ArgTy
->getPointeeType();
7322 auto ArgAS
= ArgPtTy
.getAddressSpace();
7324 // Add address space cast if target address spaces are different
7325 bool NeedImplicitASC
=
7326 ParamAS
!= LangAS::Default
&& // Pointer params in generic AS don't need special handling.
7327 ( ArgAS
== LangAS::Default
|| // We do allow implicit conversion from generic AS
7328 // or from specific AS which has target AS matching that of Param.
7329 getASTContext().getTargetAddressSpace(ArgAS
) == getASTContext().getTargetAddressSpace(ParamAS
));
7330 if (!NeedImplicitASC
)
7333 // First, ensure that the Arg is an RValue.
7334 if (ArgExprs
[Idx
]->isGLValue()) {
7335 ArgExprs
[Idx
] = ImplicitCastExpr::Create(
7336 Context
, ArgExprs
[Idx
]->getType(), CK_NoOp
, ArgExprs
[Idx
],
7337 nullptr, VK_PRValue
, FPOptionsOverride());
7340 // Construct a new arg type with address space of Param
7341 Qualifiers ArgPtQuals
= ArgPtTy
.getQualifiers();
7342 ArgPtQuals
.setAddressSpace(ParamAS
);
7344 Context
.getQualifiedType(ArgPtTy
.getUnqualifiedType(), ArgPtQuals
);
7346 Context
.getQualifiedType(Context
.getPointerType(NewArgPtTy
),
7347 ArgTy
.getQualifiers());
7349 // Finally perform an implicit address space cast
7350 ArgExprs
[Idx
] = ImpCastExprToType(ArgExprs
[Idx
], NewArgTy
,
7351 CK_AddressSpaceConversion
)
7357 if (Context
.isDependenceAllowed() &&
7358 (Fn
->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs
))) {
7359 assert(!getLangOpts().CPlusPlus
);
7360 assert((Fn
->containsErrors() ||
7361 llvm::any_of(ArgExprs
,
7362 [](clang::Expr
*E
) { return E
->containsErrors(); })) &&
7363 "should only occur in error-recovery path.");
7364 return CallExpr::Create(Context
, Fn
, ArgExprs
, Context
.DependentTy
,
7365 VK_PRValue
, RParenLoc
, CurFPFeatureOverrides());
7367 return BuildResolvedCallExpr(Fn
, NDecl
, LParenLoc
, ArgExprs
, RParenLoc
,
7368 ExecConfig
, IsExecConfig
);
7371 /// BuildBuiltinCallExpr - Create a call to a builtin function specified by Id
7372 // with the specified CallArgs
7373 Expr
*Sema::BuildBuiltinCallExpr(SourceLocation Loc
, Builtin::ID Id
,
7374 MultiExprArg CallArgs
) {
7375 StringRef Name
= Context
.BuiltinInfo
.getName(Id
);
7376 LookupResult
R(*this, &Context
.Idents
.get(Name
), Loc
,
7377 Sema::LookupOrdinaryName
);
7378 LookupName(R
, TUScope
, /*AllowBuiltinCreation=*/true);
7380 auto *BuiltInDecl
= R
.getAsSingle
<FunctionDecl
>();
7381 assert(BuiltInDecl
&& "failed to find builtin declaration");
7383 ExprResult DeclRef
=
7384 BuildDeclRefExpr(BuiltInDecl
, BuiltInDecl
->getType(), VK_LValue
, Loc
);
7385 assert(DeclRef
.isUsable() && "Builtin reference cannot fail");
7388 BuildCallExpr(/*Scope=*/nullptr, DeclRef
.get(), Loc
, CallArgs
, Loc
);
7390 assert(!Call
.isInvalid() && "Call to builtin cannot fail!");
7394 /// Parse a __builtin_astype expression.
7396 /// __builtin_astype( value, dst type )
7398 ExprResult
Sema::ActOnAsTypeExpr(Expr
*E
, ParsedType ParsedDestTy
,
7399 SourceLocation BuiltinLoc
,
7400 SourceLocation RParenLoc
) {
7401 QualType DstTy
= GetTypeFromParser(ParsedDestTy
);
7402 return BuildAsTypeExpr(E
, DstTy
, BuiltinLoc
, RParenLoc
);
7405 /// Create a new AsTypeExpr node (bitcast) from the arguments.
7406 ExprResult
Sema::BuildAsTypeExpr(Expr
*E
, QualType DestTy
,
7407 SourceLocation BuiltinLoc
,
7408 SourceLocation RParenLoc
) {
7409 ExprValueKind VK
= VK_PRValue
;
7410 ExprObjectKind OK
= OK_Ordinary
;
7411 QualType SrcTy
= E
->getType();
7412 if (!SrcTy
->isDependentType() &&
7413 Context
.getTypeSize(DestTy
) != Context
.getTypeSize(SrcTy
))
7415 Diag(BuiltinLoc
, diag::err_invalid_astype_of_different_size
)
7416 << DestTy
<< SrcTy
<< E
->getSourceRange());
7417 return new (Context
) AsTypeExpr(E
, DestTy
, VK
, OK
, BuiltinLoc
, RParenLoc
);
7420 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
7421 /// provided arguments.
7423 /// __builtin_convertvector( value, dst type )
7425 ExprResult
Sema::ActOnConvertVectorExpr(Expr
*E
, ParsedType ParsedDestTy
,
7426 SourceLocation BuiltinLoc
,
7427 SourceLocation RParenLoc
) {
7428 TypeSourceInfo
*TInfo
;
7429 GetTypeFromParser(ParsedDestTy
, &TInfo
);
7430 return SemaConvertVectorExpr(E
, TInfo
, BuiltinLoc
, RParenLoc
);
7433 /// BuildResolvedCallExpr - Build a call to a resolved expression,
7434 /// i.e. an expression not of \p OverloadTy. The expression should
7435 /// unary-convert to an expression of function-pointer or
7436 /// block-pointer type.
7438 /// \param NDecl the declaration being called, if available
7439 ExprResult
Sema::BuildResolvedCallExpr(Expr
*Fn
, NamedDecl
*NDecl
,
7440 SourceLocation LParenLoc
,
7441 ArrayRef
<Expr
*> Args
,
7442 SourceLocation RParenLoc
, Expr
*Config
,
7443 bool IsExecConfig
, ADLCallKind UsesADL
) {
7444 FunctionDecl
*FDecl
= dyn_cast_or_null
<FunctionDecl
>(NDecl
);
7445 unsigned BuiltinID
= (FDecl
? FDecl
->getBuiltinID() : 0);
7447 // Functions with 'interrupt' attribute cannot be called directly.
7448 if (FDecl
&& FDecl
->hasAttr
<AnyX86InterruptAttr
>()) {
7449 Diag(Fn
->getExprLoc(), diag::err_anyx86_interrupt_called
);
7453 // Interrupt handlers don't save off the VFP regs automatically on ARM,
7454 // so there's some risk when calling out to non-interrupt handler functions
7455 // that the callee might not preserve them. This is easy to diagnose here,
7456 // but can be very challenging to debug.
7457 // Likewise, X86 interrupt handlers may only call routines with attribute
7458 // no_caller_saved_registers since there is no efficient way to
7459 // save and restore the non-GPR state.
7460 if (auto *Caller
= getCurFunctionDecl()) {
7461 if (Caller
->hasAttr
<ARMInterruptAttr
>()) {
7462 bool VFP
= Context
.getTargetInfo().hasFeature("vfp");
7463 if (VFP
&& (!FDecl
|| !FDecl
->hasAttr
<ARMInterruptAttr
>())) {
7464 Diag(Fn
->getExprLoc(), diag::warn_arm_interrupt_calling_convention
);
7466 Diag(FDecl
->getLocation(), diag::note_callee_decl
) << FDecl
;
7469 if (Caller
->hasAttr
<AnyX86InterruptAttr
>() ||
7470 Caller
->hasAttr
<AnyX86NoCallerSavedRegistersAttr
>()) {
7471 const TargetInfo
&TI
= Context
.getTargetInfo();
7472 bool HasNonGPRRegisters
=
7473 TI
.hasFeature("sse") || TI
.hasFeature("x87") || TI
.hasFeature("mmx");
7474 if (HasNonGPRRegisters
&&
7475 (!FDecl
|| !FDecl
->hasAttr
<AnyX86NoCallerSavedRegistersAttr
>())) {
7476 Diag(Fn
->getExprLoc(), diag::warn_anyx86_excessive_regsave
)
7477 << (Caller
->hasAttr
<AnyX86InterruptAttr
>() ? 0 : 1);
7479 Diag(FDecl
->getLocation(), diag::note_callee_decl
) << FDecl
;
7484 // Promote the function operand.
7485 // We special-case function promotion here because we only allow promoting
7486 // builtin functions to function pointers in the callee of a call.
7490 Fn
->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn
)) {
7491 // Extract the return type from the (builtin) function pointer type.
7492 // FIXME Several builtins still have setType in
7493 // Sema::CheckBuiltinFunctionCall. One should review their definitions in
7494 // Builtins.def to ensure they are correct before removing setType calls.
7495 QualType FnPtrTy
= Context
.getPointerType(FDecl
->getType());
7496 Result
= ImpCastExprToType(Fn
, FnPtrTy
, CK_BuiltinFnToFnPtr
).get();
7497 ResultTy
= FDecl
->getCallResultType();
7499 Result
= CallExprUnaryConversions(Fn
);
7500 ResultTy
= Context
.BoolTy
;
7502 if (Result
.isInvalid())
7506 // Check for a valid function type, but only if it is not a builtin which
7507 // requires custom type checking. These will be handled by
7508 // CheckBuiltinFunctionCall below just after creation of the call expression.
7509 const FunctionType
*FuncT
= nullptr;
7510 if (!BuiltinID
|| !Context
.BuiltinInfo
.hasCustomTypechecking(BuiltinID
)) {
7512 if (const PointerType
*PT
= Fn
->getType()->getAs
<PointerType
>()) {
7513 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
7514 // have type pointer to function".
7515 FuncT
= PT
->getPointeeType()->getAs
<FunctionType
>();
7517 return ExprError(Diag(LParenLoc
, diag::err_typecheck_call_not_function
)
7518 << Fn
->getType() << Fn
->getSourceRange());
7519 } else if (const BlockPointerType
*BPT
=
7520 Fn
->getType()->getAs
<BlockPointerType
>()) {
7521 FuncT
= BPT
->getPointeeType()->castAs
<FunctionType
>();
7523 // Handle calls to expressions of unknown-any type.
7524 if (Fn
->getType() == Context
.UnknownAnyTy
) {
7525 ExprResult rewrite
= rebuildUnknownAnyFunction(*this, Fn
);
7526 if (rewrite
.isInvalid())
7532 return ExprError(Diag(LParenLoc
, diag::err_typecheck_call_not_function
)
7533 << Fn
->getType() << Fn
->getSourceRange());
7537 // Get the number of parameters in the function prototype, if any.
7538 // We will allocate space for max(Args.size(), NumParams) arguments
7539 // in the call expression.
7540 const auto *Proto
= dyn_cast_or_null
<FunctionProtoType
>(FuncT
);
7541 unsigned NumParams
= Proto
? Proto
->getNumParams() : 0;
7545 assert(UsesADL
== ADLCallKind::NotADL
&&
7546 "CUDAKernelCallExpr should not use ADL");
7547 TheCall
= CUDAKernelCallExpr::Create(Context
, Fn
, cast
<CallExpr
>(Config
),
7548 Args
, ResultTy
, VK_PRValue
, RParenLoc
,
7549 CurFPFeatureOverrides(), NumParams
);
7552 CallExpr::Create(Context
, Fn
, Args
, ResultTy
, VK_PRValue
, RParenLoc
,
7553 CurFPFeatureOverrides(), NumParams
, UsesADL
);
7556 if (!Context
.isDependenceAllowed()) {
7557 // Forget about the nulled arguments since typo correction
7558 // do not handle them well.
7559 TheCall
->shrinkNumArgs(Args
.size());
7560 // C cannot always handle TypoExpr nodes in builtin calls and direct
7561 // function calls as their argument checking don't necessarily handle
7562 // dependent types properly, so make sure any TypoExprs have been
7564 ExprResult Result
= CorrectDelayedTyposInExpr(TheCall
);
7565 if (!Result
.isUsable()) return ExprError();
7566 CallExpr
*TheOldCall
= TheCall
;
7567 TheCall
= dyn_cast
<CallExpr
>(Result
.get());
7568 bool CorrectedTypos
= TheCall
!= TheOldCall
;
7569 if (!TheCall
) return Result
;
7570 Args
= llvm::ArrayRef(TheCall
->getArgs(), TheCall
->getNumArgs());
7572 // A new call expression node was created if some typos were corrected.
7573 // However it may not have been constructed with enough storage. In this
7574 // case, rebuild the node with enough storage. The waste of space is
7575 // immaterial since this only happens when some typos were corrected.
7576 if (CorrectedTypos
&& Args
.size() < NumParams
) {
7578 TheCall
= CUDAKernelCallExpr::Create(
7579 Context
, Fn
, cast
<CallExpr
>(Config
), Args
, ResultTy
, VK_PRValue
,
7580 RParenLoc
, CurFPFeatureOverrides(), NumParams
);
7583 CallExpr::Create(Context
, Fn
, Args
, ResultTy
, VK_PRValue
, RParenLoc
,
7584 CurFPFeatureOverrides(), NumParams
, UsesADL
);
7586 // We can now handle the nulled arguments for the default arguments.
7587 TheCall
->setNumArgsUnsafe(std::max
<unsigned>(Args
.size(), NumParams
));
7590 // Bail out early if calling a builtin with custom type checking.
7591 if (BuiltinID
&& Context
.BuiltinInfo
.hasCustomTypechecking(BuiltinID
))
7592 return CheckBuiltinFunctionCall(FDecl
, BuiltinID
, TheCall
);
7594 if (getLangOpts().CUDA
) {
7596 // CUDA: Kernel calls must be to global functions
7597 if (FDecl
&& !FDecl
->hasAttr
<CUDAGlobalAttr
>())
7598 return ExprError(Diag(LParenLoc
,diag::err_kern_call_not_global_function
)
7599 << FDecl
<< Fn
->getSourceRange());
7601 // CUDA: Kernel function must have 'void' return type
7602 if (!FuncT
->getReturnType()->isVoidType() &&
7603 !FuncT
->getReturnType()->getAs
<AutoType
>() &&
7604 !FuncT
->getReturnType()->isInstantiationDependentType())
7605 return ExprError(Diag(LParenLoc
, diag::err_kern_type_not_void_return
)
7606 << Fn
->getType() << Fn
->getSourceRange());
7608 // CUDA: Calls to global functions must be configured
7609 if (FDecl
&& FDecl
->hasAttr
<CUDAGlobalAttr
>())
7610 return ExprError(Diag(LParenLoc
, diag::err_global_call_not_config
)
7611 << FDecl
<< Fn
->getSourceRange());
7615 // Check for a valid return type
7616 if (CheckCallReturnType(FuncT
->getReturnType(), Fn
->getBeginLoc(), TheCall
,
7620 // We know the result type of the call, set it.
7621 TheCall
->setType(FuncT
->getCallResultType(Context
));
7622 TheCall
->setValueKind(Expr::getValueKindForType(FuncT
->getReturnType()));
7624 // WebAssembly tables can't be used as arguments.
7625 if (Context
.getTargetInfo().getTriple().isWasm()) {
7626 for (const Expr
*Arg
: Args
) {
7627 if (Arg
&& Arg
->getType()->isWebAssemblyTableType()) {
7628 return ExprError(Diag(Arg
->getExprLoc(),
7629 diag::err_wasm_table_as_function_parameter
));
7635 if (ConvertArgumentsForCall(TheCall
, Fn
, FDecl
, Proto
, Args
, RParenLoc
,
7639 assert(isa
<FunctionNoProtoType
>(FuncT
) && "Unknown FunctionType!");
7642 // Check if we have too few/too many template arguments, based
7643 // on our knowledge of the function definition.
7644 const FunctionDecl
*Def
= nullptr;
7645 if (FDecl
->hasBody(Def
) && Args
.size() != Def
->param_size()) {
7646 Proto
= Def
->getType()->getAs
<FunctionProtoType
>();
7647 if (!Proto
|| !(Proto
->isVariadic() && Args
.size() >= Def
->param_size()))
7648 Diag(RParenLoc
, diag::warn_call_wrong_number_of_arguments
)
7649 << (Args
.size() > Def
->param_size()) << FDecl
<< Fn
->getSourceRange();
7652 // If the function we're calling isn't a function prototype, but we have
7653 // a function prototype from a prior declaratiom, use that prototype.
7654 if (!FDecl
->hasPrototype())
7655 Proto
= FDecl
->getType()->getAs
<FunctionProtoType
>();
7658 // If we still haven't found a prototype to use but there are arguments to
7659 // the call, diagnose this as calling a function without a prototype.
7660 // However, if we found a function declaration, check to see if
7661 // -Wdeprecated-non-prototype was disabled where the function was declared.
7662 // If so, we will silence the diagnostic here on the assumption that this
7663 // interface is intentional and the user knows what they're doing. We will
7664 // also silence the diagnostic if there is a function declaration but it
7665 // was implicitly defined (the user already gets diagnostics about the
7666 // creation of the implicit function declaration, so the additional warning
7668 if (!Proto
&& !Args
.empty() &&
7669 (!FDecl
|| (!FDecl
->isImplicit() &&
7670 !Diags
.isIgnored(diag::warn_strict_uses_without_prototype
,
7671 FDecl
->getLocation()))))
7672 Diag(LParenLoc
, diag::warn_strict_uses_without_prototype
)
7673 << (FDecl
!= nullptr) << FDecl
;
7675 // Promote the arguments (C99 6.5.2.2p6).
7676 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++) {
7677 Expr
*Arg
= Args
[i
];
7679 if (Proto
&& i
< Proto
->getNumParams()) {
7680 InitializedEntity Entity
= InitializedEntity::InitializeParameter(
7681 Context
, Proto
->getParamType(i
), Proto
->isParamConsumed(i
));
7683 PerformCopyInitialization(Entity
, SourceLocation(), Arg
);
7684 if (ArgE
.isInvalid())
7687 Arg
= ArgE
.getAs
<Expr
>();
7690 ExprResult ArgE
= DefaultArgumentPromotion(Arg
);
7692 if (ArgE
.isInvalid())
7695 Arg
= ArgE
.getAs
<Expr
>();
7698 if (RequireCompleteType(Arg
->getBeginLoc(), Arg
->getType(),
7699 diag::err_call_incomplete_argument
, Arg
))
7702 TheCall
->setArg(i
, Arg
);
7704 TheCall
->computeDependence();
7707 if (CXXMethodDecl
*Method
= dyn_cast_or_null
<CXXMethodDecl
>(FDecl
))
7708 if (Method
->isImplicitObjectMemberFunction())
7709 return ExprError(Diag(LParenLoc
, diag::err_member_call_without_object
)
7710 << Fn
->getSourceRange() << 0);
7712 // Check for sentinels
7714 DiagnoseSentinelCalls(NDecl
, LParenLoc
, Args
);
7716 // Warn for unions passing across security boundary (CMSE).
7717 if (FuncT
!= nullptr && FuncT
->getCmseNSCallAttr()) {
7718 for (unsigned i
= 0, e
= Args
.size(); i
!= e
; i
++) {
7719 if (const auto *RT
=
7720 dyn_cast
<RecordType
>(Args
[i
]->getType().getCanonicalType())) {
7721 if (RT
->getDecl()->isOrContainsUnion())
7722 Diag(Args
[i
]->getBeginLoc(), diag::warn_cmse_nonsecure_union
)
7728 // Do special checking on direct calls to functions.
7730 if (CheckFunctionCall(FDecl
, TheCall
, Proto
))
7733 checkFortifiedBuiltinMemoryFunction(FDecl
, TheCall
);
7736 return CheckBuiltinFunctionCall(FDecl
, BuiltinID
, TheCall
);
7738 if (CheckPointerCall(NDecl
, TheCall
, Proto
))
7741 if (CheckOtherCall(TheCall
, Proto
))
7745 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall
), FDecl
);
7749 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc
, ParsedType Ty
,
7750 SourceLocation RParenLoc
, Expr
*InitExpr
) {
7751 assert(Ty
&& "ActOnCompoundLiteral(): missing type");
7752 assert(InitExpr
&& "ActOnCompoundLiteral(): missing expression");
7754 TypeSourceInfo
*TInfo
;
7755 QualType literalType
= GetTypeFromParser(Ty
, &TInfo
);
7757 TInfo
= Context
.getTrivialTypeSourceInfo(literalType
);
7759 return BuildCompoundLiteralExpr(LParenLoc
, TInfo
, RParenLoc
, InitExpr
);
7763 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc
, TypeSourceInfo
*TInfo
,
7764 SourceLocation RParenLoc
, Expr
*LiteralExpr
) {
7765 QualType literalType
= TInfo
->getType();
7767 if (literalType
->isArrayType()) {
7768 if (RequireCompleteSizedType(
7769 LParenLoc
, Context
.getBaseElementType(literalType
),
7770 diag::err_array_incomplete_or_sizeless_type
,
7771 SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd())))
7773 if (literalType
->isVariableArrayType()) {
7774 // C23 6.7.10p4: An entity of variable length array type shall not be
7775 // initialized except by an empty initializer.
7777 // The C extension warnings are issued from ParseBraceInitializer() and
7778 // do not need to be issued here. However, we continue to issue an error
7779 // in the case there are initializers or we are compiling C++. We allow
7780 // use of VLAs in C++, but it's not clear we want to allow {} to zero
7781 // init a VLA in C++ in all cases (such as with non-trivial constructors).
7782 // FIXME: should we allow this construct in C++ when it makes sense to do
7784 std::optional
<unsigned> NumInits
;
7785 if (const auto *ILE
= dyn_cast
<InitListExpr
>(LiteralExpr
))
7786 NumInits
= ILE
->getNumInits();
7787 if ((LangOpts
.CPlusPlus
|| NumInits
.value_or(0)) &&
7788 !tryToFixVariablyModifiedVarType(TInfo
, literalType
, LParenLoc
,
7789 diag::err_variable_object_no_init
))
7792 } else if (!literalType
->isDependentType() &&
7793 RequireCompleteType(LParenLoc
, literalType
,
7794 diag::err_typecheck_decl_incomplete_type
,
7795 SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd())))
7798 InitializedEntity Entity
7799 = InitializedEntity::InitializeCompoundLiteralInit(TInfo
);
7800 InitializationKind Kind
7801 = InitializationKind::CreateCStyleCast(LParenLoc
,
7802 SourceRange(LParenLoc
, RParenLoc
),
7804 InitializationSequence
InitSeq(*this, Entity
, Kind
, LiteralExpr
);
7805 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, LiteralExpr
,
7807 if (Result
.isInvalid())
7809 LiteralExpr
= Result
.get();
7811 bool isFileScope
= !CurContext
->isFunctionOrMethod();
7813 // In C, compound literals are l-values for some reason.
7814 // For GCC compatibility, in C++, file-scope array compound literals with
7815 // constant initializers are also l-values, and compound literals are
7816 // otherwise prvalues.
7818 // (GCC also treats C++ list-initialized file-scope array prvalues with
7819 // constant initializers as l-values, but that's non-conforming, so we don't
7820 // follow it there.)
7822 // FIXME: It would be better to handle the lvalue cases as materializing and
7823 // lifetime-extending a temporary object, but our materialized temporaries
7824 // representation only supports lifetime extension from a variable, not "out
7826 // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
7827 // is bound to the result of applying array-to-pointer decay to the compound
7829 // FIXME: GCC supports compound literals of reference type, which should
7830 // obviously have a value kind derived from the kind of reference involved.
7832 (getLangOpts().CPlusPlus
&& !(isFileScope
&& literalType
->isArrayType()))
7837 if (auto ILE
= dyn_cast
<InitListExpr
>(LiteralExpr
))
7838 for (unsigned i
= 0, j
= ILE
->getNumInits(); i
!= j
; i
++) {
7839 Expr
*Init
= ILE
->getInit(i
);
7840 ILE
->setInit(i
, ConstantExpr::Create(Context
, Init
));
7843 auto *E
= new (Context
) CompoundLiteralExpr(LParenLoc
, TInfo
, literalType
,
7844 VK
, LiteralExpr
, isFileScope
);
7846 if (!LiteralExpr
->isTypeDependent() &&
7847 !LiteralExpr
->isValueDependent() &&
7848 !literalType
->isDependentType()) // C99 6.5.2.5p3
7849 if (CheckForConstantInitializer(LiteralExpr
, literalType
))
7851 } else if (literalType
.getAddressSpace() != LangAS::opencl_private
&&
7852 literalType
.getAddressSpace() != LangAS::Default
) {
7853 // Embedded-C extensions to C99 6.5.2.5:
7854 // "If the compound literal occurs inside the body of a function, the
7855 // type name shall not be qualified by an address-space qualifier."
7856 Diag(LParenLoc
, diag::err_compound_literal_with_address_space
)
7857 << SourceRange(LParenLoc
, LiteralExpr
->getSourceRange().getEnd());
7861 if (!isFileScope
&& !getLangOpts().CPlusPlus
) {
7862 // Compound literals that have automatic storage duration are destroyed at
7863 // the end of the scope in C; in C++, they're just temporaries.
7865 // Emit diagnostics if it is or contains a C union type that is non-trivial
7867 if (E
->getType().hasNonTrivialToPrimitiveDestructCUnion())
7868 checkNonTrivialCUnion(E
->getType(), E
->getExprLoc(),
7869 NTCUC_CompoundLiteral
, NTCUK_Destruct
);
7871 // Diagnose jumps that enter or exit the lifetime of the compound literal.
7872 if (literalType
.isDestructedType()) {
7873 Cleanup
.setExprNeedsCleanups(true);
7874 ExprCleanupObjects
.push_back(E
);
7875 getCurFunction()->setHasBranchProtectedScope();
7879 if (E
->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
7880 E
->getType().hasNonTrivialToPrimitiveCopyCUnion())
7881 checkNonTrivialCUnionInInitializer(E
->getInitializer(),
7882 E
->getInitializer()->getExprLoc());
7884 return MaybeBindToTemporary(E
);
7888 Sema::ActOnInitList(SourceLocation LBraceLoc
, MultiExprArg InitArgList
,
7889 SourceLocation RBraceLoc
) {
7890 // Only produce each kind of designated initialization diagnostic once.
7891 SourceLocation FirstDesignator
;
7892 bool DiagnosedArrayDesignator
= false;
7893 bool DiagnosedNestedDesignator
= false;
7894 bool DiagnosedMixedDesignator
= false;
7896 // Check that any designated initializers are syntactically valid in the
7897 // current language mode.
7898 for (unsigned I
= 0, E
= InitArgList
.size(); I
!= E
; ++I
) {
7899 if (auto *DIE
= dyn_cast
<DesignatedInitExpr
>(InitArgList
[I
])) {
7900 if (FirstDesignator
.isInvalid())
7901 FirstDesignator
= DIE
->getBeginLoc();
7903 if (!getLangOpts().CPlusPlus
)
7906 if (!DiagnosedNestedDesignator
&& DIE
->size() > 1) {
7907 DiagnosedNestedDesignator
= true;
7908 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_nested
)
7909 << DIE
->getDesignatorsSourceRange();
7912 for (auto &Desig
: DIE
->designators()) {
7913 if (!Desig
.isFieldDesignator() && !DiagnosedArrayDesignator
) {
7914 DiagnosedArrayDesignator
= true;
7915 Diag(Desig
.getBeginLoc(), diag::ext_designated_init_array
)
7916 << Desig
.getSourceRange();
7920 if (!DiagnosedMixedDesignator
&&
7921 !isa
<DesignatedInitExpr
>(InitArgList
[0])) {
7922 DiagnosedMixedDesignator
= true;
7923 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_mixed
)
7924 << DIE
->getSourceRange();
7925 Diag(InitArgList
[0]->getBeginLoc(), diag::note_designated_init_mixed
)
7926 << InitArgList
[0]->getSourceRange();
7928 } else if (getLangOpts().CPlusPlus
&& !DiagnosedMixedDesignator
&&
7929 isa
<DesignatedInitExpr
>(InitArgList
[0])) {
7930 DiagnosedMixedDesignator
= true;
7931 auto *DIE
= cast
<DesignatedInitExpr
>(InitArgList
[0]);
7932 Diag(DIE
->getBeginLoc(), diag::ext_designated_init_mixed
)
7933 << DIE
->getSourceRange();
7934 Diag(InitArgList
[I
]->getBeginLoc(), diag::note_designated_init_mixed
)
7935 << InitArgList
[I
]->getSourceRange();
7939 if (FirstDesignator
.isValid()) {
7940 // Only diagnose designated initiaization as a C++20 extension if we didn't
7941 // already diagnose use of (non-C++20) C99 designator syntax.
7942 if (getLangOpts().CPlusPlus
&& !DiagnosedArrayDesignator
&&
7943 !DiagnosedNestedDesignator
&& !DiagnosedMixedDesignator
) {
7944 Diag(FirstDesignator
, getLangOpts().CPlusPlus20
7945 ? diag::warn_cxx17_compat_designated_init
7946 : diag::ext_cxx_designated_init
);
7947 } else if (!getLangOpts().CPlusPlus
&& !getLangOpts().C99
) {
7948 Diag(FirstDesignator
, diag::ext_designated_init
);
7952 return BuildInitList(LBraceLoc
, InitArgList
, RBraceLoc
);
7956 Sema::BuildInitList(SourceLocation LBraceLoc
, MultiExprArg InitArgList
,
7957 SourceLocation RBraceLoc
) {
7958 // Semantic analysis for initializers is done by ActOnDeclarator() and
7959 // CheckInitializer() - it requires knowledge of the object being initialized.
7961 // Immediately handle non-overload placeholders. Overloads can be
7962 // resolved contextually, but everything else here can't.
7963 for (unsigned I
= 0, E
= InitArgList
.size(); I
!= E
; ++I
) {
7964 if (InitArgList
[I
]->getType()->isNonOverloadPlaceholderType()) {
7965 ExprResult result
= CheckPlaceholderExpr(InitArgList
[I
]);
7967 // Ignore failures; dropping the entire initializer list because
7968 // of one failure would be terrible for indexing/etc.
7969 if (result
.isInvalid()) continue;
7971 InitArgList
[I
] = result
.get();
7975 InitListExpr
*E
= new (Context
) InitListExpr(Context
, LBraceLoc
, InitArgList
,
7977 E
->setType(Context
.VoidTy
); // FIXME: just a place holder for now.
7981 /// Do an explicit extend of the given block pointer if we're in ARC.
7982 void Sema::maybeExtendBlockObject(ExprResult
&E
) {
7983 assert(E
.get()->getType()->isBlockPointerType());
7984 assert(E
.get()->isPRValue());
7986 // Only do this in an r-value context.
7987 if (!getLangOpts().ObjCAutoRefCount
) return;
7989 E
= ImplicitCastExpr::Create(
7990 Context
, E
.get()->getType(), CK_ARCExtendBlockObject
, E
.get(),
7991 /*base path*/ nullptr, VK_PRValue
, FPOptionsOverride());
7992 Cleanup
.setExprNeedsCleanups(true);
7995 /// Prepare a conversion of the given expression to an ObjC object
7997 CastKind
Sema::PrepareCastToObjCObjectPointer(ExprResult
&E
) {
7998 QualType type
= E
.get()->getType();
7999 if (type
->isObjCObjectPointerType()) {
8001 } else if (type
->isBlockPointerType()) {
8002 maybeExtendBlockObject(E
);
8003 return CK_BlockPointerToObjCPointerCast
;
8005 assert(type
->isPointerType());
8006 return CK_CPointerToObjCPointerCast
;
8010 /// Prepares for a scalar cast, performing all the necessary stages
8011 /// except the final cast and returning the kind required.
8012 CastKind
Sema::PrepareScalarCast(ExprResult
&Src
, QualType DestTy
) {
8013 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
8014 // Also, callers should have filtered out the invalid cases with
8015 // pointers. Everything else should be possible.
8017 QualType SrcTy
= Src
.get()->getType();
8018 if (Context
.hasSameUnqualifiedType(SrcTy
, DestTy
))
8021 switch (Type::ScalarTypeKind SrcKind
= SrcTy
->getScalarTypeKind()) {
8022 case Type::STK_MemberPointer
:
8023 llvm_unreachable("member pointer type in C");
8025 case Type::STK_CPointer
:
8026 case Type::STK_BlockPointer
:
8027 case Type::STK_ObjCObjectPointer
:
8028 switch (DestTy
->getScalarTypeKind()) {
8029 case Type::STK_CPointer
: {
8030 LangAS SrcAS
= SrcTy
->getPointeeType().getAddressSpace();
8031 LangAS DestAS
= DestTy
->getPointeeType().getAddressSpace();
8032 if (SrcAS
!= DestAS
)
8033 return CK_AddressSpaceConversion
;
8034 if (Context
.hasCvrSimilarType(SrcTy
, DestTy
))
8038 case Type::STK_BlockPointer
:
8039 return (SrcKind
== Type::STK_BlockPointer
8040 ? CK_BitCast
: CK_AnyPointerToBlockPointerCast
);
8041 case Type::STK_ObjCObjectPointer
:
8042 if (SrcKind
== Type::STK_ObjCObjectPointer
)
8044 if (SrcKind
== Type::STK_CPointer
)
8045 return CK_CPointerToObjCPointerCast
;
8046 maybeExtendBlockObject(Src
);
8047 return CK_BlockPointerToObjCPointerCast
;
8048 case Type::STK_Bool
:
8049 return CK_PointerToBoolean
;
8050 case Type::STK_Integral
:
8051 return CK_PointerToIntegral
;
8052 case Type::STK_Floating
:
8053 case Type::STK_FloatingComplex
:
8054 case Type::STK_IntegralComplex
:
8055 case Type::STK_MemberPointer
:
8056 case Type::STK_FixedPoint
:
8057 llvm_unreachable("illegal cast from pointer");
8059 llvm_unreachable("Should have returned before this");
8061 case Type::STK_FixedPoint
:
8062 switch (DestTy
->getScalarTypeKind()) {
8063 case Type::STK_FixedPoint
:
8064 return CK_FixedPointCast
;
8065 case Type::STK_Bool
:
8066 return CK_FixedPointToBoolean
;
8067 case Type::STK_Integral
:
8068 return CK_FixedPointToIntegral
;
8069 case Type::STK_Floating
:
8070 return CK_FixedPointToFloating
;
8071 case Type::STK_IntegralComplex
:
8072 case Type::STK_FloatingComplex
:
8073 Diag(Src
.get()->getExprLoc(),
8074 diag::err_unimplemented_conversion_with_fixed_point_type
)
8076 return CK_IntegralCast
;
8077 case Type::STK_CPointer
:
8078 case Type::STK_ObjCObjectPointer
:
8079 case Type::STK_BlockPointer
:
8080 case Type::STK_MemberPointer
:
8081 llvm_unreachable("illegal cast to pointer type");
8083 llvm_unreachable("Should have returned before this");
8085 case Type::STK_Bool
: // casting from bool is like casting from an integer
8086 case Type::STK_Integral
:
8087 switch (DestTy
->getScalarTypeKind()) {
8088 case Type::STK_CPointer
:
8089 case Type::STK_ObjCObjectPointer
:
8090 case Type::STK_BlockPointer
:
8091 if (Src
.get()->isNullPointerConstant(Context
,
8092 Expr::NPC_ValueDependentIsNull
))
8093 return CK_NullToPointer
;
8094 return CK_IntegralToPointer
;
8095 case Type::STK_Bool
:
8096 return CK_IntegralToBoolean
;
8097 case Type::STK_Integral
:
8098 return CK_IntegralCast
;
8099 case Type::STK_Floating
:
8100 return CK_IntegralToFloating
;
8101 case Type::STK_IntegralComplex
:
8102 Src
= ImpCastExprToType(Src
.get(),
8103 DestTy
->castAs
<ComplexType
>()->getElementType(),
8105 return CK_IntegralRealToComplex
;
8106 case Type::STK_FloatingComplex
:
8107 Src
= ImpCastExprToType(Src
.get(),
8108 DestTy
->castAs
<ComplexType
>()->getElementType(),
8109 CK_IntegralToFloating
);
8110 return CK_FloatingRealToComplex
;
8111 case Type::STK_MemberPointer
:
8112 llvm_unreachable("member pointer type in C");
8113 case Type::STK_FixedPoint
:
8114 return CK_IntegralToFixedPoint
;
8116 llvm_unreachable("Should have returned before this");
8118 case Type::STK_Floating
:
8119 switch (DestTy
->getScalarTypeKind()) {
8120 case Type::STK_Floating
:
8121 return CK_FloatingCast
;
8122 case Type::STK_Bool
:
8123 return CK_FloatingToBoolean
;
8124 case Type::STK_Integral
:
8125 return CK_FloatingToIntegral
;
8126 case Type::STK_FloatingComplex
:
8127 Src
= ImpCastExprToType(Src
.get(),
8128 DestTy
->castAs
<ComplexType
>()->getElementType(),
8130 return CK_FloatingRealToComplex
;
8131 case Type::STK_IntegralComplex
:
8132 Src
= ImpCastExprToType(Src
.get(),
8133 DestTy
->castAs
<ComplexType
>()->getElementType(),
8134 CK_FloatingToIntegral
);
8135 return CK_IntegralRealToComplex
;
8136 case Type::STK_CPointer
:
8137 case Type::STK_ObjCObjectPointer
:
8138 case Type::STK_BlockPointer
:
8139 llvm_unreachable("valid float->pointer cast?");
8140 case Type::STK_MemberPointer
:
8141 llvm_unreachable("member pointer type in C");
8142 case Type::STK_FixedPoint
:
8143 return CK_FloatingToFixedPoint
;
8145 llvm_unreachable("Should have returned before this");
8147 case Type::STK_FloatingComplex
:
8148 switch (DestTy
->getScalarTypeKind()) {
8149 case Type::STK_FloatingComplex
:
8150 return CK_FloatingComplexCast
;
8151 case Type::STK_IntegralComplex
:
8152 return CK_FloatingComplexToIntegralComplex
;
8153 case Type::STK_Floating
: {
8154 QualType ET
= SrcTy
->castAs
<ComplexType
>()->getElementType();
8155 if (Context
.hasSameType(ET
, DestTy
))
8156 return CK_FloatingComplexToReal
;
8157 Src
= ImpCastExprToType(Src
.get(), ET
, CK_FloatingComplexToReal
);
8158 return CK_FloatingCast
;
8160 case Type::STK_Bool
:
8161 return CK_FloatingComplexToBoolean
;
8162 case Type::STK_Integral
:
8163 Src
= ImpCastExprToType(Src
.get(),
8164 SrcTy
->castAs
<ComplexType
>()->getElementType(),
8165 CK_FloatingComplexToReal
);
8166 return CK_FloatingToIntegral
;
8167 case Type::STK_CPointer
:
8168 case Type::STK_ObjCObjectPointer
:
8169 case Type::STK_BlockPointer
:
8170 llvm_unreachable("valid complex float->pointer cast?");
8171 case Type::STK_MemberPointer
:
8172 llvm_unreachable("member pointer type in C");
8173 case Type::STK_FixedPoint
:
8174 Diag(Src
.get()->getExprLoc(),
8175 diag::err_unimplemented_conversion_with_fixed_point_type
)
8177 return CK_IntegralCast
;
8179 llvm_unreachable("Should have returned before this");
8181 case Type::STK_IntegralComplex
:
8182 switch (DestTy
->getScalarTypeKind()) {
8183 case Type::STK_FloatingComplex
:
8184 return CK_IntegralComplexToFloatingComplex
;
8185 case Type::STK_IntegralComplex
:
8186 return CK_IntegralComplexCast
;
8187 case Type::STK_Integral
: {
8188 QualType ET
= SrcTy
->castAs
<ComplexType
>()->getElementType();
8189 if (Context
.hasSameType(ET
, DestTy
))
8190 return CK_IntegralComplexToReal
;
8191 Src
= ImpCastExprToType(Src
.get(), ET
, CK_IntegralComplexToReal
);
8192 return CK_IntegralCast
;
8194 case Type::STK_Bool
:
8195 return CK_IntegralComplexToBoolean
;
8196 case Type::STK_Floating
:
8197 Src
= ImpCastExprToType(Src
.get(),
8198 SrcTy
->castAs
<ComplexType
>()->getElementType(),
8199 CK_IntegralComplexToReal
);
8200 return CK_IntegralToFloating
;
8201 case Type::STK_CPointer
:
8202 case Type::STK_ObjCObjectPointer
:
8203 case Type::STK_BlockPointer
:
8204 llvm_unreachable("valid complex int->pointer cast?");
8205 case Type::STK_MemberPointer
:
8206 llvm_unreachable("member pointer type in C");
8207 case Type::STK_FixedPoint
:
8208 Diag(Src
.get()->getExprLoc(),
8209 diag::err_unimplemented_conversion_with_fixed_point_type
)
8211 return CK_IntegralCast
;
8213 llvm_unreachable("Should have returned before this");
8216 llvm_unreachable("Unhandled scalar cast");
8219 static bool breakDownVectorType(QualType type
, uint64_t &len
,
8220 QualType
&eltType
) {
8221 // Vectors are simple.
8222 if (const VectorType
*vecType
= type
->getAs
<VectorType
>()) {
8223 len
= vecType
->getNumElements();
8224 eltType
= vecType
->getElementType();
8225 assert(eltType
->isScalarType());
8229 // We allow lax conversion to and from non-vector types, but only if
8230 // they're real types (i.e. non-complex, non-pointer scalar types).
8231 if (!type
->isRealType()) return false;
8238 /// Are the two types SVE-bitcast-compatible types? I.e. is bitcasting from the
8239 /// first SVE type (e.g. an SVE VLAT) to the second type (e.g. an SVE VLST)
8242 /// This will also return false if the two given types do not make sense from
8243 /// the perspective of SVE bitcasts.
8244 bool Sema::isValidSveBitcast(QualType srcTy
, QualType destTy
) {
8245 assert(srcTy
->isVectorType() || destTy
->isVectorType());
8247 auto ValidScalableConversion
= [](QualType FirstType
, QualType SecondType
) {
8248 if (!FirstType
->isSVESizelessBuiltinType())
8251 const auto *VecTy
= SecondType
->getAs
<VectorType
>();
8252 return VecTy
&& VecTy
->getVectorKind() == VectorKind::SveFixedLengthData
;
8255 return ValidScalableConversion(srcTy
, destTy
) ||
8256 ValidScalableConversion(destTy
, srcTy
);
8259 /// Are the two types RVV-bitcast-compatible types? I.e. is bitcasting from the
8260 /// first RVV type (e.g. an RVV scalable type) to the second type (e.g. an RVV
8261 /// VLS type) allowed?
8263 /// This will also return false if the two given types do not make sense from
8264 /// the perspective of RVV bitcasts.
8265 bool Sema::isValidRVVBitcast(QualType srcTy
, QualType destTy
) {
8266 assert(srcTy
->isVectorType() || destTy
->isVectorType());
8268 auto ValidScalableConversion
= [](QualType FirstType
, QualType SecondType
) {
8269 if (!FirstType
->isRVVSizelessBuiltinType())
8272 const auto *VecTy
= SecondType
->getAs
<VectorType
>();
8273 return VecTy
&& VecTy
->getVectorKind() == VectorKind::RVVFixedLengthData
;
8276 return ValidScalableConversion(srcTy
, destTy
) ||
8277 ValidScalableConversion(destTy
, srcTy
);
8280 /// Are the two types matrix types and do they have the same dimensions i.e.
8281 /// do they have the same number of rows and the same number of columns?
8282 bool Sema::areMatrixTypesOfTheSameDimension(QualType srcTy
, QualType destTy
) {
8283 if (!destTy
->isMatrixType() || !srcTy
->isMatrixType())
8286 const ConstantMatrixType
*matSrcType
= srcTy
->getAs
<ConstantMatrixType
>();
8287 const ConstantMatrixType
*matDestType
= destTy
->getAs
<ConstantMatrixType
>();
8289 return matSrcType
->getNumRows() == matDestType
->getNumRows() &&
8290 matSrcType
->getNumColumns() == matDestType
->getNumColumns();
8293 bool Sema::areVectorTypesSameSize(QualType SrcTy
, QualType DestTy
) {
8294 assert(DestTy
->isVectorType() || SrcTy
->isVectorType());
8296 uint64_t SrcLen
, DestLen
;
8297 QualType SrcEltTy
, DestEltTy
;
8298 if (!breakDownVectorType(SrcTy
, SrcLen
, SrcEltTy
))
8300 if (!breakDownVectorType(DestTy
, DestLen
, DestEltTy
))
8303 // ASTContext::getTypeSize will return the size rounded up to a
8304 // power of 2, so instead of using that, we need to use the raw
8305 // element size multiplied by the element count.
8306 uint64_t SrcEltSize
= Context
.getTypeSize(SrcEltTy
);
8307 uint64_t DestEltSize
= Context
.getTypeSize(DestEltTy
);
8309 return (SrcLen
* SrcEltSize
== DestLen
* DestEltSize
);
8312 // This returns true if at least one of the types is an altivec vector.
8313 bool Sema::anyAltivecTypes(QualType SrcTy
, QualType DestTy
) {
8314 assert((DestTy
->isVectorType() || SrcTy
->isVectorType()) &&
8315 "expected at least one type to be a vector here");
8317 bool IsSrcTyAltivec
=
8318 SrcTy
->isVectorType() && ((SrcTy
->castAs
<VectorType
>()->getVectorKind() ==
8319 VectorKind::AltiVecVector
) ||
8320 (SrcTy
->castAs
<VectorType
>()->getVectorKind() ==
8321 VectorKind::AltiVecBool
) ||
8322 (SrcTy
->castAs
<VectorType
>()->getVectorKind() ==
8323 VectorKind::AltiVecPixel
));
8325 bool IsDestTyAltivec
= DestTy
->isVectorType() &&
8326 ((DestTy
->castAs
<VectorType
>()->getVectorKind() ==
8327 VectorKind::AltiVecVector
) ||
8328 (DestTy
->castAs
<VectorType
>()->getVectorKind() ==
8329 VectorKind::AltiVecBool
) ||
8330 (DestTy
->castAs
<VectorType
>()->getVectorKind() ==
8331 VectorKind::AltiVecPixel
));
8333 return (IsSrcTyAltivec
|| IsDestTyAltivec
);
8336 /// Are the two types lax-compatible vector types? That is, given
8337 /// that one of them is a vector, do they have equal storage sizes,
8338 /// where the storage size is the number of elements times the element
8341 /// This will also return false if either of the types is neither a
8342 /// vector nor a real type.
8343 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy
, QualType destTy
) {
8344 assert(destTy
->isVectorType() || srcTy
->isVectorType());
8346 // Disallow lax conversions between scalars and ExtVectors (these
8347 // conversions are allowed for other vector types because common headers
8348 // depend on them). Most scalar OP ExtVector cases are handled by the
8349 // splat path anyway, which does what we want (convert, not bitcast).
8350 // What this rules out for ExtVectors is crazy things like char4*float.
8351 if (srcTy
->isScalarType() && destTy
->isExtVectorType()) return false;
8352 if (destTy
->isScalarType() && srcTy
->isExtVectorType()) return false;
8354 return areVectorTypesSameSize(srcTy
, destTy
);
8357 /// Is this a legal conversion between two types, one of which is
8358 /// known to be a vector type?
8359 bool Sema::isLaxVectorConversion(QualType srcTy
, QualType destTy
) {
8360 assert(destTy
->isVectorType() || srcTy
->isVectorType());
8362 switch (Context
.getLangOpts().getLaxVectorConversions()) {
8363 case LangOptions::LaxVectorConversionKind::None
:
8366 case LangOptions::LaxVectorConversionKind::Integer
:
8367 if (!srcTy
->isIntegralOrEnumerationType()) {
8368 auto *Vec
= srcTy
->getAs
<VectorType
>();
8369 if (!Vec
|| !Vec
->getElementType()->isIntegralOrEnumerationType())
8372 if (!destTy
->isIntegralOrEnumerationType()) {
8373 auto *Vec
= destTy
->getAs
<VectorType
>();
8374 if (!Vec
|| !Vec
->getElementType()->isIntegralOrEnumerationType())
8377 // OK, integer (vector) -> integer (vector) bitcast.
8380 case LangOptions::LaxVectorConversionKind::All
:
8384 return areLaxCompatibleVectorTypes(srcTy
, destTy
);
8387 bool Sema::CheckMatrixCast(SourceRange R
, QualType DestTy
, QualType SrcTy
,
8389 if (SrcTy
->isMatrixType() && DestTy
->isMatrixType()) {
8390 if (!areMatrixTypesOfTheSameDimension(SrcTy
, DestTy
)) {
8391 return Diag(R
.getBegin(), diag::err_invalid_conversion_between_matrixes
)
8392 << DestTy
<< SrcTy
<< R
;
8394 } else if (SrcTy
->isMatrixType()) {
8395 return Diag(R
.getBegin(),
8396 diag::err_invalid_conversion_between_matrix_and_type
)
8397 << SrcTy
<< DestTy
<< R
;
8398 } else if (DestTy
->isMatrixType()) {
8399 return Diag(R
.getBegin(),
8400 diag::err_invalid_conversion_between_matrix_and_type
)
8401 << DestTy
<< SrcTy
<< R
;
8404 Kind
= CK_MatrixCast
;
8408 bool Sema::CheckVectorCast(SourceRange R
, QualType VectorTy
, QualType Ty
,
8410 assert(VectorTy
->isVectorType() && "Not a vector type!");
8412 if (Ty
->isVectorType() || Ty
->isIntegralType(Context
)) {
8413 if (!areLaxCompatibleVectorTypes(Ty
, VectorTy
))
8414 return Diag(R
.getBegin(),
8415 Ty
->isVectorType() ?
8416 diag::err_invalid_conversion_between_vectors
:
8417 diag::err_invalid_conversion_between_vector_and_integer
)
8418 << VectorTy
<< Ty
<< R
;
8420 return Diag(R
.getBegin(),
8421 diag::err_invalid_conversion_between_vector_and_scalar
)
8422 << VectorTy
<< Ty
<< R
;
8428 ExprResult
Sema::prepareVectorSplat(QualType VectorTy
, Expr
*SplattedExpr
) {
8429 QualType DestElemTy
= VectorTy
->castAs
<VectorType
>()->getElementType();
8431 if (DestElemTy
== SplattedExpr
->getType())
8432 return SplattedExpr
;
8434 assert(DestElemTy
->isFloatingType() ||
8435 DestElemTy
->isIntegralOrEnumerationType());
8438 if (VectorTy
->isExtVectorType() && SplattedExpr
->getType()->isBooleanType()) {
8439 // OpenCL requires that we convert `true` boolean expressions to -1, but
8440 // only when splatting vectors.
8441 if (DestElemTy
->isFloatingType()) {
8442 // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
8443 // in two steps: boolean to signed integral, then to floating.
8444 ExprResult CastExprRes
= ImpCastExprToType(SplattedExpr
, Context
.IntTy
,
8445 CK_BooleanToSignedIntegral
);
8446 SplattedExpr
= CastExprRes
.get();
8447 CK
= CK_IntegralToFloating
;
8449 CK
= CK_BooleanToSignedIntegral
;
8452 ExprResult CastExprRes
= SplattedExpr
;
8453 CK
= PrepareScalarCast(CastExprRes
, DestElemTy
);
8454 if (CastExprRes
.isInvalid())
8456 SplattedExpr
= CastExprRes
.get();
8458 return ImpCastExprToType(SplattedExpr
, DestElemTy
, CK
);
8461 ExprResult
Sema::CheckExtVectorCast(SourceRange R
, QualType DestTy
,
8462 Expr
*CastExpr
, CastKind
&Kind
) {
8463 assert(DestTy
->isExtVectorType() && "Not an extended vector type!");
8465 QualType SrcTy
= CastExpr
->getType();
8467 // If SrcTy is a VectorType, the total size must match to explicitly cast to
8468 // an ExtVectorType.
8469 // In OpenCL, casts between vectors of different types are not allowed.
8470 // (See OpenCL 6.2).
8471 if (SrcTy
->isVectorType()) {
8472 if (!areLaxCompatibleVectorTypes(SrcTy
, DestTy
) ||
8473 (getLangOpts().OpenCL
&&
8474 !Context
.hasSameUnqualifiedType(DestTy
, SrcTy
))) {
8475 Diag(R
.getBegin(),diag::err_invalid_conversion_between_ext_vectors
)
8476 << DestTy
<< SrcTy
<< R
;
8483 // All non-pointer scalars can be cast to ExtVector type. The appropriate
8484 // conversion will take place first from scalar to elt type, and then
8485 // splat from elt type to vector.
8486 if (SrcTy
->isPointerType())
8487 return Diag(R
.getBegin(),
8488 diag::err_invalid_conversion_between_vector_and_scalar
)
8489 << DestTy
<< SrcTy
<< R
;
8491 Kind
= CK_VectorSplat
;
8492 return prepareVectorSplat(DestTy
, CastExpr
);
8496 Sema::ActOnCastExpr(Scope
*S
, SourceLocation LParenLoc
,
8497 Declarator
&D
, ParsedType
&Ty
,
8498 SourceLocation RParenLoc
, Expr
*CastExpr
) {
8499 assert(!D
.isInvalidType() && (CastExpr
!= nullptr) &&
8500 "ActOnCastExpr(): missing type or expr");
8502 TypeSourceInfo
*castTInfo
= GetTypeForDeclaratorCast(D
, CastExpr
->getType());
8503 if (D
.isInvalidType())
8506 if (getLangOpts().CPlusPlus
) {
8507 // Check that there are no default arguments (C++ only).
8508 CheckExtraCXXDefaultArguments(D
);
8510 // Make sure any TypoExprs have been dealt with.
8511 ExprResult Res
= CorrectDelayedTyposInExpr(CastExpr
);
8512 if (!Res
.isUsable())
8514 CastExpr
= Res
.get();
8517 checkUnusedDeclAttributes(D
);
8519 QualType castType
= castTInfo
->getType();
8520 Ty
= CreateParsedType(castType
, castTInfo
);
8522 bool isVectorLiteral
= false;
8524 // Check for an altivec or OpenCL literal,
8525 // i.e. all the elements are integer constants.
8526 ParenExpr
*PE
= dyn_cast
<ParenExpr
>(CastExpr
);
8527 ParenListExpr
*PLE
= dyn_cast
<ParenListExpr
>(CastExpr
);
8528 if ((getLangOpts().AltiVec
|| getLangOpts().ZVector
|| getLangOpts().OpenCL
)
8529 && castType
->isVectorType() && (PE
|| PLE
)) {
8530 if (PLE
&& PLE
->getNumExprs() == 0) {
8531 Diag(PLE
->getExprLoc(), diag::err_altivec_empty_initializer
);
8534 if (PE
|| PLE
->getNumExprs() == 1) {
8535 Expr
*E
= (PE
? PE
->getSubExpr() : PLE
->getExpr(0));
8536 if (!E
->isTypeDependent() && !E
->getType()->isVectorType())
8537 isVectorLiteral
= true;
8540 isVectorLiteral
= true;
8543 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
8544 // then handle it as such.
8545 if (isVectorLiteral
)
8546 return BuildVectorLiteral(LParenLoc
, RParenLoc
, CastExpr
, castTInfo
);
8548 // If the Expr being casted is a ParenListExpr, handle it specially.
8549 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
8550 // sequence of BinOp comma operators.
8551 if (isa
<ParenListExpr
>(CastExpr
)) {
8552 ExprResult Result
= MaybeConvertParenListExprToParenExpr(S
, CastExpr
);
8553 if (Result
.isInvalid()) return ExprError();
8554 CastExpr
= Result
.get();
8557 if (getLangOpts().CPlusPlus
&& !castType
->isVoidType())
8558 Diag(LParenLoc
, diag::warn_old_style_cast
) << CastExpr
->getSourceRange();
8560 CheckTollFreeBridgeCast(castType
, CastExpr
);
8562 CheckObjCBridgeRelatedCast(castType
, CastExpr
);
8564 DiscardMisalignedMemberAddress(castType
.getTypePtr(), CastExpr
);
8566 return BuildCStyleCastExpr(LParenLoc
, castTInfo
, RParenLoc
, CastExpr
);
8569 ExprResult
Sema::BuildVectorLiteral(SourceLocation LParenLoc
,
8570 SourceLocation RParenLoc
, Expr
*E
,
8571 TypeSourceInfo
*TInfo
) {
8572 assert((isa
<ParenListExpr
>(E
) || isa
<ParenExpr
>(E
)) &&
8573 "Expected paren or paren list expression");
8578 SourceLocation LiteralLParenLoc
, LiteralRParenLoc
;
8579 if (ParenListExpr
*PE
= dyn_cast
<ParenListExpr
>(E
)) {
8580 LiteralLParenLoc
= PE
->getLParenLoc();
8581 LiteralRParenLoc
= PE
->getRParenLoc();
8582 exprs
= PE
->getExprs();
8583 numExprs
= PE
->getNumExprs();
8584 } else { // isa<ParenExpr> by assertion at function entrance
8585 LiteralLParenLoc
= cast
<ParenExpr
>(E
)->getLParen();
8586 LiteralRParenLoc
= cast
<ParenExpr
>(E
)->getRParen();
8587 subExpr
= cast
<ParenExpr
>(E
)->getSubExpr();
8592 QualType Ty
= TInfo
->getType();
8593 assert(Ty
->isVectorType() && "Expected vector type");
8595 SmallVector
<Expr
*, 8> initExprs
;
8596 const VectorType
*VTy
= Ty
->castAs
<VectorType
>();
8597 unsigned numElems
= VTy
->getNumElements();
8599 // '(...)' form of vector initialization in AltiVec: the number of
8600 // initializers must be one or must match the size of the vector.
8601 // If a single value is specified in the initializer then it will be
8602 // replicated to all the components of the vector
8603 if (CheckAltivecInitFromScalar(E
->getSourceRange(), Ty
,
8604 VTy
->getElementType()))
8606 if (ShouldSplatAltivecScalarInCast(VTy
)) {
8607 // The number of initializers must be one or must match the size of the
8608 // vector. If a single value is specified in the initializer then it will
8609 // be replicated to all the components of the vector
8610 if (numExprs
== 1) {
8611 QualType ElemTy
= VTy
->getElementType();
8612 ExprResult Literal
= DefaultLvalueConversion(exprs
[0]);
8613 if (Literal
.isInvalid())
8615 Literal
= ImpCastExprToType(Literal
.get(), ElemTy
,
8616 PrepareScalarCast(Literal
, ElemTy
));
8617 return BuildCStyleCastExpr(LParenLoc
, TInfo
, RParenLoc
, Literal
.get());
8619 else if (numExprs
< numElems
) {
8620 Diag(E
->getExprLoc(),
8621 diag::err_incorrect_number_of_vector_initializers
);
8625 initExprs
.append(exprs
, exprs
+ numExprs
);
8628 // For OpenCL, when the number of initializers is a single value,
8629 // it will be replicated to all components of the vector.
8630 if (getLangOpts().OpenCL
&& VTy
->getVectorKind() == VectorKind::Generic
&&
8632 QualType ElemTy
= VTy
->getElementType();
8633 ExprResult Literal
= DefaultLvalueConversion(exprs
[0]);
8634 if (Literal
.isInvalid())
8636 Literal
= ImpCastExprToType(Literal
.get(), ElemTy
,
8637 PrepareScalarCast(Literal
, ElemTy
));
8638 return BuildCStyleCastExpr(LParenLoc
, TInfo
, RParenLoc
, Literal
.get());
8641 initExprs
.append(exprs
, exprs
+ numExprs
);
8643 // FIXME: This means that pretty-printing the final AST will produce curly
8644 // braces instead of the original commas.
8645 InitListExpr
*initE
= new (Context
) InitListExpr(Context
, LiteralLParenLoc
,
8646 initExprs
, LiteralRParenLoc
);
8648 return BuildCompoundLiteralExpr(LParenLoc
, TInfo
, RParenLoc
, initE
);
8651 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
8652 /// the ParenListExpr into a sequence of comma binary operators.
8654 Sema::MaybeConvertParenListExprToParenExpr(Scope
*S
, Expr
*OrigExpr
) {
8655 ParenListExpr
*E
= dyn_cast
<ParenListExpr
>(OrigExpr
);
8659 ExprResult
Result(E
->getExpr(0));
8661 for (unsigned i
= 1, e
= E
->getNumExprs(); i
!= e
&& !Result
.isInvalid(); ++i
)
8662 Result
= ActOnBinOp(S
, E
->getExprLoc(), tok::comma
, Result
.get(),
8665 if (Result
.isInvalid()) return ExprError();
8667 return ActOnParenExpr(E
->getLParenLoc(), E
->getRParenLoc(), Result
.get());
8670 ExprResult
Sema::ActOnParenListExpr(SourceLocation L
,
8673 return ParenListExpr::Create(Context
, L
, Val
, R
);
8676 /// Emit a specialized diagnostic when one expression is a null pointer
8677 /// constant and the other is not a pointer. Returns true if a diagnostic is
8679 bool Sema::DiagnoseConditionalForNull(Expr
*LHSExpr
, Expr
*RHSExpr
,
8680 SourceLocation QuestionLoc
) {
8681 Expr
*NullExpr
= LHSExpr
;
8682 Expr
*NonPointerExpr
= RHSExpr
;
8683 Expr::NullPointerConstantKind NullKind
=
8684 NullExpr
->isNullPointerConstant(Context
,
8685 Expr::NPC_ValueDependentIsNotNull
);
8687 if (NullKind
== Expr::NPCK_NotNull
) {
8689 NonPointerExpr
= LHSExpr
;
8691 NullExpr
->isNullPointerConstant(Context
,
8692 Expr::NPC_ValueDependentIsNotNull
);
8695 if (NullKind
== Expr::NPCK_NotNull
)
8698 if (NullKind
== Expr::NPCK_ZeroExpression
)
8701 if (NullKind
== Expr::NPCK_ZeroLiteral
) {
8702 // In this case, check to make sure that we got here from a "NULL"
8703 // string in the source code.
8704 NullExpr
= NullExpr
->IgnoreParenImpCasts();
8705 SourceLocation loc
= NullExpr
->getExprLoc();
8706 if (!findMacroSpelling(loc
, "NULL"))
8710 int DiagType
= (NullKind
== Expr::NPCK_CXX11_nullptr
);
8711 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands_null
)
8712 << NonPointerExpr
->getType() << DiagType
8713 << NonPointerExpr
->getSourceRange();
8717 /// Return false if the condition expression is valid, true otherwise.
8718 static bool checkCondition(Sema
&S
, Expr
*Cond
, SourceLocation QuestionLoc
) {
8719 QualType CondTy
= Cond
->getType();
8721 // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
8722 if (S
.getLangOpts().OpenCL
&& CondTy
->isFloatingType()) {
8723 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_nonfloat
)
8724 << CondTy
<< Cond
->getSourceRange();
8729 if (CondTy
->isScalarType()) return false;
8731 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_scalar
)
8732 << CondTy
<< Cond
->getSourceRange();
8736 /// Return false if the NullExpr can be promoted to PointerTy,
8738 static bool checkConditionalNullPointer(Sema
&S
, ExprResult
&NullExpr
,
8739 QualType PointerTy
) {
8740 if ((!PointerTy
->isAnyPointerType() && !PointerTy
->isBlockPointerType()) ||
8741 !NullExpr
.get()->isNullPointerConstant(S
.Context
,
8742 Expr::NPC_ValueDependentIsNull
))
8745 NullExpr
= S
.ImpCastExprToType(NullExpr
.get(), PointerTy
, CK_NullToPointer
);
8749 /// Checks compatibility between two pointers and return the resulting
8751 static QualType
checkConditionalPointerCompatibility(Sema
&S
, ExprResult
&LHS
,
8753 SourceLocation Loc
) {
8754 QualType LHSTy
= LHS
.get()->getType();
8755 QualType RHSTy
= RHS
.get()->getType();
8757 if (S
.Context
.hasSameType(LHSTy
, RHSTy
)) {
8758 // Two identical pointers types are always compatible.
8759 return S
.Context
.getCommonSugaredType(LHSTy
, RHSTy
);
8762 QualType lhptee
, rhptee
;
8764 // Get the pointee types.
8765 bool IsBlockPointer
= false;
8766 if (const BlockPointerType
*LHSBTy
= LHSTy
->getAs
<BlockPointerType
>()) {
8767 lhptee
= LHSBTy
->getPointeeType();
8768 rhptee
= RHSTy
->castAs
<BlockPointerType
>()->getPointeeType();
8769 IsBlockPointer
= true;
8771 lhptee
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
8772 rhptee
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
8775 // C99 6.5.15p6: If both operands are pointers to compatible types or to
8776 // differently qualified versions of compatible types, the result type is
8777 // a pointer to an appropriately qualified version of the composite
8780 // Only CVR-qualifiers exist in the standard, and the differently-qualified
8781 // clause doesn't make sense for our extensions. E.g. address space 2 should
8782 // be incompatible with address space 3: they may live on different devices or
8784 Qualifiers lhQual
= lhptee
.getQualifiers();
8785 Qualifiers rhQual
= rhptee
.getQualifiers();
8787 LangAS ResultAddrSpace
= LangAS::Default
;
8788 LangAS LAddrSpace
= lhQual
.getAddressSpace();
8789 LangAS RAddrSpace
= rhQual
.getAddressSpace();
8791 // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
8792 // spaces is disallowed.
8793 if (lhQual
.isAddressSpaceSupersetOf(rhQual
))
8794 ResultAddrSpace
= LAddrSpace
;
8795 else if (rhQual
.isAddressSpaceSupersetOf(lhQual
))
8796 ResultAddrSpace
= RAddrSpace
;
8798 S
.Diag(Loc
, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
8799 << LHSTy
<< RHSTy
<< 2 << LHS
.get()->getSourceRange()
8800 << RHS
.get()->getSourceRange();
8804 unsigned MergedCVRQual
= lhQual
.getCVRQualifiers() | rhQual
.getCVRQualifiers();
8805 auto LHSCastKind
= CK_BitCast
, RHSCastKind
= CK_BitCast
;
8806 lhQual
.removeCVRQualifiers();
8807 rhQual
.removeCVRQualifiers();
8809 // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
8810 // (C99 6.7.3) for address spaces. We assume that the check should behave in
8811 // the same manner as it's defined for CVR qualifiers, so for OpenCL two
8812 // qual types are compatible iff
8813 // * corresponded types are compatible
8814 // * CVR qualifiers are equal
8815 // * address spaces are equal
8816 // Thus for conditional operator we merge CVR and address space unqualified
8817 // pointees and if there is a composite type we return a pointer to it with
8818 // merged qualifiers.
8820 LAddrSpace
== ResultAddrSpace
? CK_BitCast
: CK_AddressSpaceConversion
;
8822 RAddrSpace
== ResultAddrSpace
? CK_BitCast
: CK_AddressSpaceConversion
;
8823 lhQual
.removeAddressSpace();
8824 rhQual
.removeAddressSpace();
8826 lhptee
= S
.Context
.getQualifiedType(lhptee
.getUnqualifiedType(), lhQual
);
8827 rhptee
= S
.Context
.getQualifiedType(rhptee
.getUnqualifiedType(), rhQual
);
8829 QualType CompositeTy
= S
.Context
.mergeTypes(
8830 lhptee
, rhptee
, /*OfBlockPointer=*/false, /*Unqualified=*/false,
8831 /*BlockReturnType=*/false, /*IsConditionalOperator=*/true);
8833 if (CompositeTy
.isNull()) {
8834 // In this situation, we assume void* type. No especially good
8835 // reason, but this is what gcc does, and we do have to pick
8836 // to get a consistent AST.
8837 QualType incompatTy
;
8838 incompatTy
= S
.Context
.getPointerType(
8839 S
.Context
.getAddrSpaceQualType(S
.Context
.VoidTy
, ResultAddrSpace
));
8840 LHS
= S
.ImpCastExprToType(LHS
.get(), incompatTy
, LHSCastKind
);
8841 RHS
= S
.ImpCastExprToType(RHS
.get(), incompatTy
, RHSCastKind
);
8843 // FIXME: For OpenCL the warning emission and cast to void* leaves a room
8844 // for casts between types with incompatible address space qualifiers.
8845 // For the following code the compiler produces casts between global and
8846 // local address spaces of the corresponded innermost pointees:
8847 // local int *global *a;
8848 // global int *global *b;
8849 // a = (0 ? a : b); // see C99 6.5.16.1.p1.
8850 S
.Diag(Loc
, diag::ext_typecheck_cond_incompatible_pointers
)
8851 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8852 << RHS
.get()->getSourceRange();
8857 // The pointer types are compatible.
8858 // In case of OpenCL ResultTy should have the address space qualifier
8859 // which is a superset of address spaces of both the 2nd and the 3rd
8860 // operands of the conditional operator.
8861 QualType ResultTy
= [&, ResultAddrSpace
]() {
8862 if (S
.getLangOpts().OpenCL
) {
8863 Qualifiers CompositeQuals
= CompositeTy
.getQualifiers();
8864 CompositeQuals
.setAddressSpace(ResultAddrSpace
);
8866 .getQualifiedType(CompositeTy
.getUnqualifiedType(), CompositeQuals
)
8867 .withCVRQualifiers(MergedCVRQual
);
8869 return CompositeTy
.withCVRQualifiers(MergedCVRQual
);
8872 ResultTy
= S
.Context
.getBlockPointerType(ResultTy
);
8874 ResultTy
= S
.Context
.getPointerType(ResultTy
);
8876 LHS
= S
.ImpCastExprToType(LHS
.get(), ResultTy
, LHSCastKind
);
8877 RHS
= S
.ImpCastExprToType(RHS
.get(), ResultTy
, RHSCastKind
);
8881 /// Return the resulting type when the operands are both block pointers.
8882 static QualType
checkConditionalBlockPointerCompatibility(Sema
&S
,
8885 SourceLocation Loc
) {
8886 QualType LHSTy
= LHS
.get()->getType();
8887 QualType RHSTy
= RHS
.get()->getType();
8889 if (!LHSTy
->isBlockPointerType() || !RHSTy
->isBlockPointerType()) {
8890 if (LHSTy
->isVoidPointerType() || RHSTy
->isVoidPointerType()) {
8891 QualType destType
= S
.Context
.getPointerType(S
.Context
.VoidTy
);
8892 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_BitCast
);
8893 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_BitCast
);
8896 S
.Diag(Loc
, diag::err_typecheck_cond_incompatible_operands
)
8897 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
8898 << RHS
.get()->getSourceRange();
8902 // We have 2 block pointer types.
8903 return checkConditionalPointerCompatibility(S
, LHS
, RHS
, Loc
);
8906 /// Return the resulting type when the operands are both pointers.
8908 checkConditionalObjectPointersCompatibility(Sema
&S
, ExprResult
&LHS
,
8910 SourceLocation Loc
) {
8911 // get the pointer types
8912 QualType LHSTy
= LHS
.get()->getType();
8913 QualType RHSTy
= RHS
.get()->getType();
8915 // get the "pointed to" types
8916 QualType lhptee
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
8917 QualType rhptee
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
8919 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
8920 if (lhptee
->isVoidType() && rhptee
->isIncompleteOrObjectType()) {
8921 // Figure out necessary qualifiers (C99 6.5.15p6)
8922 QualType destPointee
8923 = S
.Context
.getQualifiedType(lhptee
, rhptee
.getQualifiers());
8924 QualType destType
= S
.Context
.getPointerType(destPointee
);
8925 // Add qualifiers if necessary.
8926 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_NoOp
);
8927 // Promote to void*.
8928 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_BitCast
);
8931 if (rhptee
->isVoidType() && lhptee
->isIncompleteOrObjectType()) {
8932 QualType destPointee
8933 = S
.Context
.getQualifiedType(rhptee
, lhptee
.getQualifiers());
8934 QualType destType
= S
.Context
.getPointerType(destPointee
);
8935 // Add qualifiers if necessary.
8936 RHS
= S
.ImpCastExprToType(RHS
.get(), destType
, CK_NoOp
);
8937 // Promote to void*.
8938 LHS
= S
.ImpCastExprToType(LHS
.get(), destType
, CK_BitCast
);
8942 return checkConditionalPointerCompatibility(S
, LHS
, RHS
, Loc
);
8945 /// Return false if the first expression is not an integer and the second
8946 /// expression is not a pointer, true otherwise.
8947 static bool checkPointerIntegerMismatch(Sema
&S
, ExprResult
&Int
,
8948 Expr
* PointerExpr
, SourceLocation Loc
,
8949 bool IsIntFirstExpr
) {
8950 if (!PointerExpr
->getType()->isPointerType() ||
8951 !Int
.get()->getType()->isIntegerType())
8954 Expr
*Expr1
= IsIntFirstExpr
? Int
.get() : PointerExpr
;
8955 Expr
*Expr2
= IsIntFirstExpr
? PointerExpr
: Int
.get();
8957 S
.Diag(Loc
, diag::ext_typecheck_cond_pointer_integer_mismatch
)
8958 << Expr1
->getType() << Expr2
->getType()
8959 << Expr1
->getSourceRange() << Expr2
->getSourceRange();
8960 Int
= S
.ImpCastExprToType(Int
.get(), PointerExpr
->getType(),
8961 CK_IntegralToPointer
);
8965 /// Simple conversion between integer and floating point types.
8967 /// Used when handling the OpenCL conditional operator where the
8968 /// condition is a vector while the other operands are scalar.
8970 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
8971 /// types are either integer or floating type. Between the two
8972 /// operands, the type with the higher rank is defined as the "result
8973 /// type". The other operand needs to be promoted to the same type. No
8974 /// other type promotion is allowed. We cannot use
8975 /// UsualArithmeticConversions() for this purpose, since it always
8976 /// promotes promotable types.
8977 static QualType
OpenCLArithmeticConversions(Sema
&S
, ExprResult
&LHS
,
8979 SourceLocation QuestionLoc
) {
8980 LHS
= S
.DefaultFunctionArrayLvalueConversion(LHS
.get());
8981 if (LHS
.isInvalid())
8983 RHS
= S
.DefaultFunctionArrayLvalueConversion(RHS
.get());
8984 if (RHS
.isInvalid())
8987 // For conversion purposes, we ignore any qualifiers.
8988 // For example, "const float" and "float" are equivalent.
8990 S
.Context
.getCanonicalType(LHS
.get()->getType()).getUnqualifiedType();
8992 S
.Context
.getCanonicalType(RHS
.get()->getType()).getUnqualifiedType();
8994 if (!LHSType
->isIntegerType() && !LHSType
->isRealFloatingType()) {
8995 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_int_float
)
8996 << LHSType
<< LHS
.get()->getSourceRange();
9000 if (!RHSType
->isIntegerType() && !RHSType
->isRealFloatingType()) {
9001 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_int_float
)
9002 << RHSType
<< RHS
.get()->getSourceRange();
9006 // If both types are identical, no conversion is needed.
9007 if (LHSType
== RHSType
)
9010 // Now handle "real" floating types (i.e. float, double, long double).
9011 if (LHSType
->isRealFloatingType() || RHSType
->isRealFloatingType())
9012 return handleFloatConversion(S
, LHS
, RHS
, LHSType
, RHSType
,
9013 /*IsCompAssign = */ false);
9015 // Finally, we have two differing integer types.
9016 return handleIntegerConversion
<doIntegralCast
, doIntegralCast
>
9017 (S
, LHS
, RHS
, LHSType
, RHSType
, /*IsCompAssign = */ false);
9020 /// Convert scalar operands to a vector that matches the
9021 /// condition in length.
9023 /// Used when handling the OpenCL conditional operator where the
9024 /// condition is a vector while the other operands are scalar.
9026 /// We first compute the "result type" for the scalar operands
9027 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
9028 /// into a vector of that type where the length matches the condition
9029 /// vector type. s6.11.6 requires that the element types of the result
9030 /// and the condition must have the same number of bits.
9032 OpenCLConvertScalarsToVectors(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
9033 QualType CondTy
, SourceLocation QuestionLoc
) {
9034 QualType ResTy
= OpenCLArithmeticConversions(S
, LHS
, RHS
, QuestionLoc
);
9035 if (ResTy
.isNull()) return QualType();
9037 const VectorType
*CV
= CondTy
->getAs
<VectorType
>();
9040 // Determine the vector result type
9041 unsigned NumElements
= CV
->getNumElements();
9042 QualType VectorTy
= S
.Context
.getExtVectorType(ResTy
, NumElements
);
9044 // Ensure that all types have the same number of bits
9045 if (S
.Context
.getTypeSize(CV
->getElementType())
9046 != S
.Context
.getTypeSize(ResTy
)) {
9047 // Since VectorTy is created internally, it does not pretty print
9048 // with an OpenCL name. Instead, we just print a description.
9049 std::string EleTyName
= ResTy
.getUnqualifiedType().getAsString();
9050 SmallString
<64> Str
;
9051 llvm::raw_svector_ostream
OS(Str
);
9052 OS
<< "(vector of " << NumElements
<< " '" << EleTyName
<< "' values)";
9053 S
.Diag(QuestionLoc
, diag::err_conditional_vector_element_size
)
9054 << CondTy
<< OS
.str();
9058 // Convert operands to the vector result type
9059 LHS
= S
.ImpCastExprToType(LHS
.get(), VectorTy
, CK_VectorSplat
);
9060 RHS
= S
.ImpCastExprToType(RHS
.get(), VectorTy
, CK_VectorSplat
);
9065 /// Return false if this is a valid OpenCL condition vector
9066 static bool checkOpenCLConditionVector(Sema
&S
, Expr
*Cond
,
9067 SourceLocation QuestionLoc
) {
9068 // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
9070 const VectorType
*CondTy
= Cond
->getType()->getAs
<VectorType
>();
9072 QualType EleTy
= CondTy
->getElementType();
9073 if (EleTy
->isIntegerType()) return false;
9075 S
.Diag(QuestionLoc
, diag::err_typecheck_cond_expect_nonfloat
)
9076 << Cond
->getType() << Cond
->getSourceRange();
9080 /// Return false if the vector condition type and the vector
9081 /// result type are compatible.
9083 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
9084 /// number of elements, and their element types have the same number
9086 static bool checkVectorResult(Sema
&S
, QualType CondTy
, QualType VecResTy
,
9087 SourceLocation QuestionLoc
) {
9088 const VectorType
*CV
= CondTy
->getAs
<VectorType
>();
9089 const VectorType
*RV
= VecResTy
->getAs
<VectorType
>();
9092 if (CV
->getNumElements() != RV
->getNumElements()) {
9093 S
.Diag(QuestionLoc
, diag::err_conditional_vector_size
)
9094 << CondTy
<< VecResTy
;
9098 QualType CVE
= CV
->getElementType();
9099 QualType RVE
= RV
->getElementType();
9101 if (S
.Context
.getTypeSize(CVE
) != S
.Context
.getTypeSize(RVE
)) {
9102 S
.Diag(QuestionLoc
, diag::err_conditional_vector_element_size
)
9103 << CondTy
<< VecResTy
;
9110 /// Return the resulting type for the conditional operator in
9111 /// OpenCL (aka "ternary selection operator", OpenCL v1.1
9112 /// s6.3.i) when the condition is a vector type.
9114 OpenCLCheckVectorConditional(Sema
&S
, ExprResult
&Cond
,
9115 ExprResult
&LHS
, ExprResult
&RHS
,
9116 SourceLocation QuestionLoc
) {
9117 Cond
= S
.DefaultFunctionArrayLvalueConversion(Cond
.get());
9118 if (Cond
.isInvalid())
9120 QualType CondTy
= Cond
.get()->getType();
9122 if (checkOpenCLConditionVector(S
, Cond
.get(), QuestionLoc
))
9125 // If either operand is a vector then find the vector type of the
9126 // result as specified in OpenCL v1.1 s6.3.i.
9127 if (LHS
.get()->getType()->isVectorType() ||
9128 RHS
.get()->getType()->isVectorType()) {
9129 bool IsBoolVecLang
=
9130 !S
.getLangOpts().OpenCL
&& !S
.getLangOpts().OpenCLCPlusPlus
;
9132 S
.CheckVectorOperands(LHS
, RHS
, QuestionLoc
,
9133 /*isCompAssign*/ false,
9134 /*AllowBothBool*/ true,
9135 /*AllowBoolConversions*/ false,
9136 /*AllowBooleanOperation*/ IsBoolVecLang
,
9137 /*ReportInvalid*/ true);
9138 if (VecResTy
.isNull())
9140 // The result type must match the condition type as specified in
9141 // OpenCL v1.1 s6.11.6.
9142 if (checkVectorResult(S
, CondTy
, VecResTy
, QuestionLoc
))
9147 // Both operands are scalar.
9148 return OpenCLConvertScalarsToVectors(S
, LHS
, RHS
, CondTy
, QuestionLoc
);
9151 /// Return true if the Expr is block type
9152 static bool checkBlockType(Sema
&S
, const Expr
*E
) {
9153 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
9154 QualType Ty
= CE
->getCallee()->getType();
9155 if (Ty
->isBlockPointerType()) {
9156 S
.Diag(E
->getExprLoc(), diag::err_opencl_ternary_with_block
);
9163 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
9164 /// In that case, LHS = cond.
9166 QualType
Sema::CheckConditionalOperands(ExprResult
&Cond
, ExprResult
&LHS
,
9167 ExprResult
&RHS
, ExprValueKind
&VK
,
9169 SourceLocation QuestionLoc
) {
9171 ExprResult LHSResult
= CheckPlaceholderExpr(LHS
.get());
9172 if (!LHSResult
.isUsable()) return QualType();
9175 ExprResult RHSResult
= CheckPlaceholderExpr(RHS
.get());
9176 if (!RHSResult
.isUsable()) return QualType();
9179 // C++ is sufficiently different to merit its own checker.
9180 if (getLangOpts().CPlusPlus
)
9181 return CXXCheckConditionalOperands(Cond
, LHS
, RHS
, VK
, OK
, QuestionLoc
);
9186 if (Context
.isDependenceAllowed() &&
9187 (Cond
.get()->isTypeDependent() || LHS
.get()->isTypeDependent() ||
9188 RHS
.get()->isTypeDependent())) {
9189 assert(!getLangOpts().CPlusPlus
);
9190 assert((Cond
.get()->containsErrors() || LHS
.get()->containsErrors() ||
9191 RHS
.get()->containsErrors()) &&
9192 "should only occur in error-recovery path.");
9193 return Context
.DependentTy
;
9196 // The OpenCL operator with a vector condition is sufficiently
9197 // different to merit its own checker.
9198 if ((getLangOpts().OpenCL
&& Cond
.get()->getType()->isVectorType()) ||
9199 Cond
.get()->getType()->isExtVectorType())
9200 return OpenCLCheckVectorConditional(*this, Cond
, LHS
, RHS
, QuestionLoc
);
9202 // First, check the condition.
9203 Cond
= UsualUnaryConversions(Cond
.get());
9204 if (Cond
.isInvalid())
9206 if (checkCondition(*this, Cond
.get(), QuestionLoc
))
9210 if (LHS
.get()->getType()->isVectorType() ||
9211 RHS
.get()->getType()->isVectorType())
9212 return CheckVectorOperands(LHS
, RHS
, QuestionLoc
, /*isCompAssign*/ false,
9213 /*AllowBothBool*/ true,
9214 /*AllowBoolConversions*/ false,
9215 /*AllowBooleanOperation*/ false,
9216 /*ReportInvalid*/ true);
9219 UsualArithmeticConversions(LHS
, RHS
, QuestionLoc
, ACK_Conditional
);
9220 if (LHS
.isInvalid() || RHS
.isInvalid())
9223 // WebAssembly tables are not allowed as conditional LHS or RHS.
9224 QualType LHSTy
= LHS
.get()->getType();
9225 QualType RHSTy
= RHS
.get()->getType();
9226 if (LHSTy
->isWebAssemblyTableType() || RHSTy
->isWebAssemblyTableType()) {
9227 Diag(QuestionLoc
, diag::err_wasm_table_conditional_expression
)
9228 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9232 // Diagnose attempts to convert between __ibm128, __float128 and long double
9233 // where such conversions currently can't be handled.
9234 if (unsupportedTypeConversion(*this, LHSTy
, RHSTy
)) {
9236 diag::err_typecheck_cond_incompatible_operands
) << LHSTy
<< RHSTy
9237 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9241 // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
9242 // selection operator (?:).
9243 if (getLangOpts().OpenCL
&&
9244 ((int)checkBlockType(*this, LHS
.get()) | (int)checkBlockType(*this, RHS
.get()))) {
9248 // If both operands have arithmetic type, do the usual arithmetic conversions
9249 // to find a common type: C99 6.5.15p3,5.
9250 if (LHSTy
->isArithmeticType() && RHSTy
->isArithmeticType()) {
9251 // Disallow invalid arithmetic conversions, such as those between bit-
9252 // precise integers types of different sizes, or between a bit-precise
9253 // integer and another type.
9254 if (ResTy
.isNull() && (LHSTy
->isBitIntType() || RHSTy
->isBitIntType())) {
9255 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
9256 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
9257 << RHS
.get()->getSourceRange();
9261 LHS
= ImpCastExprToType(LHS
.get(), ResTy
, PrepareScalarCast(LHS
, ResTy
));
9262 RHS
= ImpCastExprToType(RHS
.get(), ResTy
, PrepareScalarCast(RHS
, ResTy
));
9267 // If both operands are the same structure or union type, the result is that
9269 if (const RecordType
*LHSRT
= LHSTy
->getAs
<RecordType
>()) { // C99 6.5.15p3
9270 if (const RecordType
*RHSRT
= RHSTy
->getAs
<RecordType
>())
9271 if (LHSRT
->getDecl() == RHSRT
->getDecl())
9272 // "If both the operands have structure or union type, the result has
9273 // that type." This implies that CV qualifiers are dropped.
9274 return Context
.getCommonSugaredType(LHSTy
.getUnqualifiedType(),
9275 RHSTy
.getUnqualifiedType());
9276 // FIXME: Type of conditional expression must be complete in C mode.
9279 // C99 6.5.15p5: "If both operands have void type, the result has void type."
9280 // The following || allows only one side to be void (a GCC-ism).
9281 if (LHSTy
->isVoidType() || RHSTy
->isVoidType()) {
9283 if (LHSTy
->isVoidType() && RHSTy
->isVoidType()) {
9284 ResTy
= Context
.getCommonSugaredType(LHSTy
, RHSTy
);
9285 } else if (RHSTy
->isVoidType()) {
9287 Diag(RHS
.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void
)
9288 << RHS
.get()->getSourceRange();
9291 Diag(LHS
.get()->getBeginLoc(), diag::ext_typecheck_cond_one_void
)
9292 << LHS
.get()->getSourceRange();
9294 LHS
= ImpCastExprToType(LHS
.get(), ResTy
, CK_ToVoid
);
9295 RHS
= ImpCastExprToType(RHS
.get(), ResTy
, CK_ToVoid
);
9300 // ... if both the second and third operands have nullptr_t type, the
9301 // result also has that type.
9302 if (LHSTy
->isNullPtrType() && Context
.hasSameType(LHSTy
, RHSTy
))
9305 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
9306 // the type of the other operand."
9307 if (!checkConditionalNullPointer(*this, RHS
, LHSTy
)) return LHSTy
;
9308 if (!checkConditionalNullPointer(*this, LHS
, RHSTy
)) return RHSTy
;
9310 // All objective-c pointer type analysis is done here.
9311 QualType compositeType
= FindCompositeObjCPointerType(LHS
, RHS
,
9313 if (LHS
.isInvalid() || RHS
.isInvalid())
9315 if (!compositeType
.isNull())
9316 return compositeType
;
9319 // Handle block pointer types.
9320 if (LHSTy
->isBlockPointerType() || RHSTy
->isBlockPointerType())
9321 return checkConditionalBlockPointerCompatibility(*this, LHS
, RHS
,
9324 // Check constraints for C object pointers types (C99 6.5.15p3,6).
9325 if (LHSTy
->isPointerType() && RHSTy
->isPointerType())
9326 return checkConditionalObjectPointersCompatibility(*this, LHS
, RHS
,
9329 // GCC compatibility: soften pointer/integer mismatch. Note that
9330 // null pointers have been filtered out by this point.
9331 if (checkPointerIntegerMismatch(*this, LHS
, RHS
.get(), QuestionLoc
,
9332 /*IsIntFirstExpr=*/true))
9334 if (checkPointerIntegerMismatch(*this, RHS
, LHS
.get(), QuestionLoc
,
9335 /*IsIntFirstExpr=*/false))
9338 // Emit a better diagnostic if one of the expressions is a null pointer
9339 // constant and the other is not a pointer type. In this case, the user most
9340 // likely forgot to take the address of the other expression.
9341 if (DiagnoseConditionalForNull(LHS
.get(), RHS
.get(), QuestionLoc
))
9344 // Finally, if the LHS and RHS types are canonically the same type, we can
9345 // use the common sugared type.
9346 if (Context
.hasSameType(LHSTy
, RHSTy
))
9347 return Context
.getCommonSugaredType(LHSTy
, RHSTy
);
9349 // Otherwise, the operands are not compatible.
9350 Diag(QuestionLoc
, diag::err_typecheck_cond_incompatible_operands
)
9351 << LHSTy
<< RHSTy
<< LHS
.get()->getSourceRange()
9352 << RHS
.get()->getSourceRange();
9356 /// FindCompositeObjCPointerType - Helper method to find composite type of
9357 /// two objective-c pointer types of the two input expressions.
9358 QualType
Sema::FindCompositeObjCPointerType(ExprResult
&LHS
, ExprResult
&RHS
,
9359 SourceLocation QuestionLoc
) {
9360 QualType LHSTy
= LHS
.get()->getType();
9361 QualType RHSTy
= RHS
.get()->getType();
9363 // Handle things like Class and struct objc_class*. Here we case the result
9364 // to the pseudo-builtin, because that will be implicitly cast back to the
9365 // redefinition type if an attempt is made to access its fields.
9366 if (LHSTy
->isObjCClassType() &&
9367 (Context
.hasSameType(RHSTy
, Context
.getObjCClassRedefinitionType()))) {
9368 RHS
= ImpCastExprToType(RHS
.get(), LHSTy
, CK_CPointerToObjCPointerCast
);
9371 if (RHSTy
->isObjCClassType() &&
9372 (Context
.hasSameType(LHSTy
, Context
.getObjCClassRedefinitionType()))) {
9373 LHS
= ImpCastExprToType(LHS
.get(), RHSTy
, CK_CPointerToObjCPointerCast
);
9376 // And the same for struct objc_object* / id
9377 if (LHSTy
->isObjCIdType() &&
9378 (Context
.hasSameType(RHSTy
, Context
.getObjCIdRedefinitionType()))) {
9379 RHS
= ImpCastExprToType(RHS
.get(), LHSTy
, CK_CPointerToObjCPointerCast
);
9382 if (RHSTy
->isObjCIdType() &&
9383 (Context
.hasSameType(LHSTy
, Context
.getObjCIdRedefinitionType()))) {
9384 LHS
= ImpCastExprToType(LHS
.get(), RHSTy
, CK_CPointerToObjCPointerCast
);
9387 // And the same for struct objc_selector* / SEL
9388 if (Context
.isObjCSelType(LHSTy
) &&
9389 (Context
.hasSameType(RHSTy
, Context
.getObjCSelRedefinitionType()))) {
9390 RHS
= ImpCastExprToType(RHS
.get(), LHSTy
, CK_BitCast
);
9393 if (Context
.isObjCSelType(RHSTy
) &&
9394 (Context
.hasSameType(LHSTy
, Context
.getObjCSelRedefinitionType()))) {
9395 LHS
= ImpCastExprToType(LHS
.get(), RHSTy
, CK_BitCast
);
9398 // Check constraints for Objective-C object pointers types.
9399 if (LHSTy
->isObjCObjectPointerType() && RHSTy
->isObjCObjectPointerType()) {
9401 if (Context
.getCanonicalType(LHSTy
) == Context
.getCanonicalType(RHSTy
)) {
9402 // Two identical object pointer types are always compatible.
9405 const ObjCObjectPointerType
*LHSOPT
= LHSTy
->castAs
<ObjCObjectPointerType
>();
9406 const ObjCObjectPointerType
*RHSOPT
= RHSTy
->castAs
<ObjCObjectPointerType
>();
9407 QualType compositeType
= LHSTy
;
9409 // If both operands are interfaces and either operand can be
9410 // assigned to the other, use that type as the composite
9411 // type. This allows
9412 // xxx ? (A*) a : (B*) b
9413 // where B is a subclass of A.
9415 // Additionally, as for assignment, if either type is 'id'
9416 // allow silent coercion. Finally, if the types are
9417 // incompatible then make sure to use 'id' as the composite
9418 // type so the result is acceptable for sending messages to.
9420 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
9421 // It could return the composite type.
9422 if (!(compositeType
=
9423 Context
.areCommonBaseCompatible(LHSOPT
, RHSOPT
)).isNull()) {
9424 // Nothing more to do.
9425 } else if (Context
.canAssignObjCInterfaces(LHSOPT
, RHSOPT
)) {
9426 compositeType
= RHSOPT
->isObjCBuiltinType() ? RHSTy
: LHSTy
;
9427 } else if (Context
.canAssignObjCInterfaces(RHSOPT
, LHSOPT
)) {
9428 compositeType
= LHSOPT
->isObjCBuiltinType() ? LHSTy
: RHSTy
;
9429 } else if ((LHSOPT
->isObjCQualifiedIdType() ||
9430 RHSOPT
->isObjCQualifiedIdType()) &&
9431 Context
.ObjCQualifiedIdTypesAreCompatible(LHSOPT
, RHSOPT
,
9433 // Need to handle "id<xx>" explicitly.
9434 // GCC allows qualified id and any Objective-C type to devolve to
9435 // id. Currently localizing to here until clear this should be
9436 // part of ObjCQualifiedIdTypesAreCompatible.
9437 compositeType
= Context
.getObjCIdType();
9438 } else if (LHSTy
->isObjCIdType() || RHSTy
->isObjCIdType()) {
9439 compositeType
= Context
.getObjCIdType();
9441 Diag(QuestionLoc
, diag::ext_typecheck_cond_incompatible_operands
)
9443 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9444 QualType incompatTy
= Context
.getObjCIdType();
9445 LHS
= ImpCastExprToType(LHS
.get(), incompatTy
, CK_BitCast
);
9446 RHS
= ImpCastExprToType(RHS
.get(), incompatTy
, CK_BitCast
);
9449 // The object pointer types are compatible.
9450 LHS
= ImpCastExprToType(LHS
.get(), compositeType
, CK_BitCast
);
9451 RHS
= ImpCastExprToType(RHS
.get(), compositeType
, CK_BitCast
);
9452 return compositeType
;
9454 // Check Objective-C object pointer types and 'void *'
9455 if (LHSTy
->isVoidPointerType() && RHSTy
->isObjCObjectPointerType()) {
9456 if (getLangOpts().ObjCAutoRefCount
) {
9457 // ARC forbids the implicit conversion of object pointers to 'void *',
9458 // so these types are not compatible.
9459 Diag(QuestionLoc
, diag::err_cond_voidptr_arc
) << LHSTy
<< RHSTy
9460 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9464 QualType lhptee
= LHSTy
->castAs
<PointerType
>()->getPointeeType();
9465 QualType rhptee
= RHSTy
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
9466 QualType destPointee
9467 = Context
.getQualifiedType(lhptee
, rhptee
.getQualifiers());
9468 QualType destType
= Context
.getPointerType(destPointee
);
9469 // Add qualifiers if necessary.
9470 LHS
= ImpCastExprToType(LHS
.get(), destType
, CK_NoOp
);
9471 // Promote to void*.
9472 RHS
= ImpCastExprToType(RHS
.get(), destType
, CK_BitCast
);
9475 if (LHSTy
->isObjCObjectPointerType() && RHSTy
->isVoidPointerType()) {
9476 if (getLangOpts().ObjCAutoRefCount
) {
9477 // ARC forbids the implicit conversion of object pointers to 'void *',
9478 // so these types are not compatible.
9479 Diag(QuestionLoc
, diag::err_cond_voidptr_arc
) << LHSTy
<< RHSTy
9480 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
9484 QualType lhptee
= LHSTy
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
9485 QualType rhptee
= RHSTy
->castAs
<PointerType
>()->getPointeeType();
9486 QualType destPointee
9487 = Context
.getQualifiedType(rhptee
, lhptee
.getQualifiers());
9488 QualType destType
= Context
.getPointerType(destPointee
);
9489 // Add qualifiers if necessary.
9490 RHS
= ImpCastExprToType(RHS
.get(), destType
, CK_NoOp
);
9491 // Promote to void*.
9492 LHS
= ImpCastExprToType(LHS
.get(), destType
, CK_BitCast
);
9498 /// SuggestParentheses - Emit a note with a fixit hint that wraps
9499 /// ParenRange in parentheses.
9500 static void SuggestParentheses(Sema
&Self
, SourceLocation Loc
,
9501 const PartialDiagnostic
&Note
,
9502 SourceRange ParenRange
) {
9503 SourceLocation EndLoc
= Self
.getLocForEndOfToken(ParenRange
.getEnd());
9504 if (ParenRange
.getBegin().isFileID() && ParenRange
.getEnd().isFileID() &&
9506 Self
.Diag(Loc
, Note
)
9507 << FixItHint::CreateInsertion(ParenRange
.getBegin(), "(")
9508 << FixItHint::CreateInsertion(EndLoc
, ")");
9510 // We can't display the parentheses, so just show the bare note.
9511 Self
.Diag(Loc
, Note
) << ParenRange
;
9515 static bool IsArithmeticOp(BinaryOperatorKind Opc
) {
9516 return BinaryOperator::isAdditiveOp(Opc
) ||
9517 BinaryOperator::isMultiplicativeOp(Opc
) ||
9518 BinaryOperator::isShiftOp(Opc
) || Opc
== BO_And
|| Opc
== BO_Or
;
9519 // This only checks for bitwise-or and bitwise-and, but not bitwise-xor and
9520 // not any of the logical operators. Bitwise-xor is commonly used as a
9521 // logical-xor because there is no logical-xor operator. The logical
9522 // operators, including uses of xor, have a high false positive rate for
9523 // precedence warnings.
9526 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
9527 /// expression, either using a built-in or overloaded operator,
9528 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
9530 static bool IsArithmeticBinaryExpr(Expr
*E
, BinaryOperatorKind
*Opcode
,
9532 // Don't strip parenthesis: we should not warn if E is in parenthesis.
9533 E
= E
->IgnoreImpCasts();
9534 E
= E
->IgnoreConversionOperatorSingleStep();
9535 E
= E
->IgnoreImpCasts();
9536 if (auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(E
)) {
9537 E
= MTE
->getSubExpr();
9538 E
= E
->IgnoreImpCasts();
9541 // Built-in binary operator.
9542 if (BinaryOperator
*OP
= dyn_cast
<BinaryOperator
>(E
)) {
9543 if (IsArithmeticOp(OP
->getOpcode())) {
9544 *Opcode
= OP
->getOpcode();
9545 *RHSExprs
= OP
->getRHS();
9550 // Overloaded operator.
9551 if (CXXOperatorCallExpr
*Call
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
9552 if (Call
->getNumArgs() != 2)
9555 // Make sure this is really a binary operator that is safe to pass into
9556 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
9557 OverloadedOperatorKind OO
= Call
->getOperator();
9558 if (OO
< OO_Plus
|| OO
> OO_Arrow
||
9559 OO
== OO_PlusPlus
|| OO
== OO_MinusMinus
)
9562 BinaryOperatorKind OpKind
= BinaryOperator::getOverloadedOpcode(OO
);
9563 if (IsArithmeticOp(OpKind
)) {
9565 *RHSExprs
= Call
->getArg(1);
9573 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
9574 /// or is a logical expression such as (x==y) which has int type, but is
9575 /// commonly interpreted as boolean.
9576 static bool ExprLooksBoolean(Expr
*E
) {
9577 E
= E
->IgnoreParenImpCasts();
9579 if (E
->getType()->isBooleanType())
9581 if (BinaryOperator
*OP
= dyn_cast
<BinaryOperator
>(E
))
9582 return OP
->isComparisonOp() || OP
->isLogicalOp();
9583 if (UnaryOperator
*OP
= dyn_cast
<UnaryOperator
>(E
))
9584 return OP
->getOpcode() == UO_LNot
;
9585 if (E
->getType()->isPointerType())
9587 // FIXME: What about overloaded operator calls returning "unspecified boolean
9588 // type"s (commonly pointer-to-members)?
9593 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
9594 /// and binary operator are mixed in a way that suggests the programmer assumed
9595 /// the conditional operator has higher precedence, for example:
9596 /// "int x = a + someBinaryCondition ? 1 : 2".
9597 static void DiagnoseConditionalPrecedence(Sema
&Self
,
9598 SourceLocation OpLoc
,
9602 BinaryOperatorKind CondOpcode
;
9605 if (!IsArithmeticBinaryExpr(Condition
, &CondOpcode
, &CondRHS
))
9607 if (!ExprLooksBoolean(CondRHS
))
9610 // The condition is an arithmetic binary expression, with a right-
9611 // hand side that looks boolean, so warn.
9613 unsigned DiagID
= BinaryOperator::isBitwiseOp(CondOpcode
)
9614 ? diag::warn_precedence_bitwise_conditional
9615 : diag::warn_precedence_conditional
;
9617 Self
.Diag(OpLoc
, DiagID
)
9618 << Condition
->getSourceRange()
9619 << BinaryOperator::getOpcodeStr(CondOpcode
);
9623 Self
.PDiag(diag::note_precedence_silence
)
9624 << BinaryOperator::getOpcodeStr(CondOpcode
),
9625 SourceRange(Condition
->getBeginLoc(), Condition
->getEndLoc()));
9627 SuggestParentheses(Self
, OpLoc
,
9628 Self
.PDiag(diag::note_precedence_conditional_first
),
9629 SourceRange(CondRHS
->getBeginLoc(), RHSExpr
->getEndLoc()));
9632 /// Compute the nullability of a conditional expression.
9633 static QualType
computeConditionalNullability(QualType ResTy
, bool IsBin
,
9634 QualType LHSTy
, QualType RHSTy
,
9636 if (!ResTy
->isAnyPointerType())
9639 auto GetNullability
= [](QualType Ty
) {
9640 std::optional
<NullabilityKind
> Kind
= Ty
->getNullability();
9642 // For our purposes, treat _Nullable_result as _Nullable.
9643 if (*Kind
== NullabilityKind::NullableResult
)
9644 return NullabilityKind::Nullable
;
9647 return NullabilityKind::Unspecified
;
9650 auto LHSKind
= GetNullability(LHSTy
), RHSKind
= GetNullability(RHSTy
);
9651 NullabilityKind MergedKind
;
9653 // Compute nullability of a binary conditional expression.
9655 if (LHSKind
== NullabilityKind::NonNull
)
9656 MergedKind
= NullabilityKind::NonNull
;
9658 MergedKind
= RHSKind
;
9659 // Compute nullability of a normal conditional expression.
9661 if (LHSKind
== NullabilityKind::Nullable
||
9662 RHSKind
== NullabilityKind::Nullable
)
9663 MergedKind
= NullabilityKind::Nullable
;
9664 else if (LHSKind
== NullabilityKind::NonNull
)
9665 MergedKind
= RHSKind
;
9666 else if (RHSKind
== NullabilityKind::NonNull
)
9667 MergedKind
= LHSKind
;
9669 MergedKind
= NullabilityKind::Unspecified
;
9672 // Return if ResTy already has the correct nullability.
9673 if (GetNullability(ResTy
) == MergedKind
)
9676 // Strip all nullability from ResTy.
9677 while (ResTy
->getNullability())
9678 ResTy
= ResTy
.getSingleStepDesugaredType(Ctx
);
9680 // Create a new AttributedType with the new nullability kind.
9681 auto NewAttr
= AttributedType::getNullabilityAttrKind(MergedKind
);
9682 return Ctx
.getAttributedType(NewAttr
, ResTy
, ResTy
);
9685 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
9686 /// in the case of a the GNU conditional expr extension.
9687 ExprResult
Sema::ActOnConditionalOp(SourceLocation QuestionLoc
,
9688 SourceLocation ColonLoc
,
9689 Expr
*CondExpr
, Expr
*LHSExpr
,
9691 if (!Context
.isDependenceAllowed()) {
9692 // C cannot handle TypoExpr nodes in the condition because it
9693 // doesn't handle dependent types properly, so make sure any TypoExprs have
9694 // been dealt with before checking the operands.
9695 ExprResult CondResult
= CorrectDelayedTyposInExpr(CondExpr
);
9696 ExprResult LHSResult
= CorrectDelayedTyposInExpr(LHSExpr
);
9697 ExprResult RHSResult
= CorrectDelayedTyposInExpr(RHSExpr
);
9699 if (!CondResult
.isUsable())
9703 if (!LHSResult
.isUsable())
9707 if (!RHSResult
.isUsable())
9710 CondExpr
= CondResult
.get();
9711 LHSExpr
= LHSResult
.get();
9712 RHSExpr
= RHSResult
.get();
9715 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
9716 // was the condition.
9717 OpaqueValueExpr
*opaqueValue
= nullptr;
9718 Expr
*commonExpr
= nullptr;
9720 commonExpr
= CondExpr
;
9721 // Lower out placeholder types first. This is important so that we don't
9722 // try to capture a placeholder. This happens in few cases in C++; such
9723 // as Objective-C++'s dictionary subscripting syntax.
9724 if (commonExpr
->hasPlaceholderType()) {
9725 ExprResult result
= CheckPlaceholderExpr(commonExpr
);
9726 if (!result
.isUsable()) return ExprError();
9727 commonExpr
= result
.get();
9729 // We usually want to apply unary conversions *before* saving, except
9730 // in the special case of a C++ l-value conditional.
9731 if (!(getLangOpts().CPlusPlus
9732 && !commonExpr
->isTypeDependent()
9733 && commonExpr
->getValueKind() == RHSExpr
->getValueKind()
9734 && commonExpr
->isGLValue()
9735 && commonExpr
->isOrdinaryOrBitFieldObject()
9736 && RHSExpr
->isOrdinaryOrBitFieldObject()
9737 && Context
.hasSameType(commonExpr
->getType(), RHSExpr
->getType()))) {
9738 ExprResult commonRes
= UsualUnaryConversions(commonExpr
);
9739 if (commonRes
.isInvalid())
9741 commonExpr
= commonRes
.get();
9744 // If the common expression is a class or array prvalue, materialize it
9745 // so that we can safely refer to it multiple times.
9746 if (commonExpr
->isPRValue() && (commonExpr
->getType()->isRecordType() ||
9747 commonExpr
->getType()->isArrayType())) {
9748 ExprResult MatExpr
= TemporaryMaterializationConversion(commonExpr
);
9749 if (MatExpr
.isInvalid())
9751 commonExpr
= MatExpr
.get();
9754 opaqueValue
= new (Context
) OpaqueValueExpr(commonExpr
->getExprLoc(),
9755 commonExpr
->getType(),
9756 commonExpr
->getValueKind(),
9757 commonExpr
->getObjectKind(),
9759 LHSExpr
= CondExpr
= opaqueValue
;
9762 QualType LHSTy
= LHSExpr
->getType(), RHSTy
= RHSExpr
->getType();
9763 ExprValueKind VK
= VK_PRValue
;
9764 ExprObjectKind OK
= OK_Ordinary
;
9765 ExprResult Cond
= CondExpr
, LHS
= LHSExpr
, RHS
= RHSExpr
;
9766 QualType result
= CheckConditionalOperands(Cond
, LHS
, RHS
,
9767 VK
, OK
, QuestionLoc
);
9768 if (result
.isNull() || Cond
.isInvalid() || LHS
.isInvalid() ||
9772 DiagnoseConditionalPrecedence(*this, QuestionLoc
, Cond
.get(), LHS
.get(),
9775 CheckBoolLikeConversion(Cond
.get(), QuestionLoc
);
9777 result
= computeConditionalNullability(result
, commonExpr
, LHSTy
, RHSTy
,
9781 return new (Context
)
9782 ConditionalOperator(Cond
.get(), QuestionLoc
, LHS
.get(), ColonLoc
,
9783 RHS
.get(), result
, VK
, OK
);
9785 return new (Context
) BinaryConditionalOperator(
9786 commonExpr
, opaqueValue
, Cond
.get(), LHS
.get(), RHS
.get(), QuestionLoc
,
9787 ColonLoc
, result
, VK
, OK
);
9790 // Check that the SME attributes for PSTATE.ZA and PSTATE.SM are compatible.
9791 bool Sema::IsInvalidSMECallConversion(QualType FromType
, QualType ToType
,
9792 AArch64SMECallConversionKind C
) {
9793 unsigned FromAttributes
= 0, ToAttributes
= 0;
9794 if (const auto *FromFn
=
9795 dyn_cast
<FunctionProtoType
>(Context
.getCanonicalType(FromType
)))
9797 FromFn
->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask
;
9798 if (const auto *ToFn
=
9799 dyn_cast
<FunctionProtoType
>(Context
.getCanonicalType(ToType
)))
9801 ToFn
->getAArch64SMEAttributes() & FunctionType::SME_AttributeMask
;
9803 if (FromAttributes
== ToAttributes
)
9806 // If the '__arm_preserves_za' is the only difference between the types,
9807 // check whether we're allowed to add or remove it.
9808 if ((FromAttributes
^ ToAttributes
) ==
9809 FunctionType::SME_PStateZAPreservedMask
) {
9811 case AArch64SMECallConversionKind::MatchExactly
:
9813 case AArch64SMECallConversionKind::MayAddPreservesZA
:
9814 return !(ToAttributes
& FunctionType::SME_PStateZAPreservedMask
);
9815 case AArch64SMECallConversionKind::MayDropPreservesZA
:
9816 return !(FromAttributes
& FunctionType::SME_PStateZAPreservedMask
);
9820 // There has been a mismatch of attributes
9824 // Check if we have a conversion between incompatible cmse function pointer
9825 // types, that is, a conversion between a function pointer with the
9826 // cmse_nonsecure_call attribute and one without.
9827 static bool IsInvalidCmseNSCallConversion(Sema
&S
, QualType FromType
,
9829 if (const auto *ToFn
=
9830 dyn_cast
<FunctionType
>(S
.Context
.getCanonicalType(ToType
))) {
9831 if (const auto *FromFn
=
9832 dyn_cast
<FunctionType
>(S
.Context
.getCanonicalType(FromType
))) {
9833 FunctionType::ExtInfo ToEInfo
= ToFn
->getExtInfo();
9834 FunctionType::ExtInfo FromEInfo
= FromFn
->getExtInfo();
9836 return ToEInfo
.getCmseNSCall() != FromEInfo
.getCmseNSCall();
9842 // checkPointerTypesForAssignment - This is a very tricky routine (despite
9843 // being closely modeled after the C99 spec:-). The odd characteristic of this
9844 // routine is it effectively iqnores the qualifiers on the top level pointee.
9845 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
9846 // FIXME: add a couple examples in this comment.
9847 static Sema::AssignConvertType
9848 checkPointerTypesForAssignment(Sema
&S
, QualType LHSType
, QualType RHSType
,
9849 SourceLocation Loc
) {
9850 assert(LHSType
.isCanonical() && "LHS not canonicalized!");
9851 assert(RHSType
.isCanonical() && "RHS not canonicalized!");
9853 // get the "pointed to" type (ignoring qualifiers at the top level)
9854 const Type
*lhptee
, *rhptee
;
9855 Qualifiers lhq
, rhq
;
9856 std::tie(lhptee
, lhq
) =
9857 cast
<PointerType
>(LHSType
)->getPointeeType().split().asPair();
9858 std::tie(rhptee
, rhq
) =
9859 cast
<PointerType
>(RHSType
)->getPointeeType().split().asPair();
9861 Sema::AssignConvertType ConvTy
= Sema::Compatible
;
9863 // C99 6.5.16.1p1: This following citation is common to constraints
9864 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
9865 // qualifiers of the type *pointed to* by the right;
9867 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
9868 if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime() &&
9869 lhq
.compatiblyIncludesObjCLifetime(rhq
)) {
9870 // Ignore lifetime for further calculation.
9871 lhq
.removeObjCLifetime();
9872 rhq
.removeObjCLifetime();
9875 if (!lhq
.compatiblyIncludes(rhq
)) {
9876 // Treat address-space mismatches as fatal.
9877 if (!lhq
.isAddressSpaceSupersetOf(rhq
))
9878 return Sema::IncompatiblePointerDiscardsQualifiers
;
9880 // It's okay to add or remove GC or lifetime qualifiers when converting to
9882 else if (lhq
.withoutObjCGCAttr().withoutObjCLifetime()
9883 .compatiblyIncludes(
9884 rhq
.withoutObjCGCAttr().withoutObjCLifetime())
9885 && (lhptee
->isVoidType() || rhptee
->isVoidType()))
9888 // Treat lifetime mismatches as fatal.
9889 else if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime())
9890 ConvTy
= Sema::IncompatiblePointerDiscardsQualifiers
;
9892 // For GCC/MS compatibility, other qualifier mismatches are treated
9893 // as still compatible in C.
9894 else ConvTy
= Sema::CompatiblePointerDiscardsQualifiers
;
9897 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
9898 // incomplete type and the other is a pointer to a qualified or unqualified
9899 // version of void...
9900 if (lhptee
->isVoidType()) {
9901 if (rhptee
->isIncompleteOrObjectType())
9904 // As an extension, we allow cast to/from void* to function pointer.
9905 assert(rhptee
->isFunctionType());
9906 return Sema::FunctionVoidPointer
;
9909 if (rhptee
->isVoidType()) {
9910 if (lhptee
->isIncompleteOrObjectType())
9913 // As an extension, we allow cast to/from void* to function pointer.
9914 assert(lhptee
->isFunctionType());
9915 return Sema::FunctionVoidPointer
;
9918 if (!S
.Diags
.isIgnored(
9919 diag::warn_typecheck_convert_incompatible_function_pointer_strict
,
9921 RHSType
->isFunctionPointerType() && LHSType
->isFunctionPointerType() &&
9922 !S
.IsFunctionConversion(RHSType
, LHSType
, RHSType
))
9923 return Sema::IncompatibleFunctionPointerStrict
;
9925 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
9926 // unqualified versions of compatible types, ...
9927 QualType ltrans
= QualType(lhptee
, 0), rtrans
= QualType(rhptee
, 0);
9928 if (!S
.Context
.typesAreCompatible(ltrans
, rtrans
)) {
9929 // Check if the pointee types are compatible ignoring the sign.
9930 // We explicitly check for char so that we catch "char" vs
9931 // "unsigned char" on systems where "char" is unsigned.
9932 if (lhptee
->isCharType())
9933 ltrans
= S
.Context
.UnsignedCharTy
;
9934 else if (lhptee
->hasSignedIntegerRepresentation())
9935 ltrans
= S
.Context
.getCorrespondingUnsignedType(ltrans
);
9937 if (rhptee
->isCharType())
9938 rtrans
= S
.Context
.UnsignedCharTy
;
9939 else if (rhptee
->hasSignedIntegerRepresentation())
9940 rtrans
= S
.Context
.getCorrespondingUnsignedType(rtrans
);
9942 if (ltrans
== rtrans
) {
9943 // Types are compatible ignoring the sign. Qualifier incompatibility
9944 // takes priority over sign incompatibility because the sign
9945 // warning can be disabled.
9946 if (ConvTy
!= Sema::Compatible
)
9949 return Sema::IncompatiblePointerSign
;
9952 // If we are a multi-level pointer, it's possible that our issue is simply
9953 // one of qualification - e.g. char ** -> const char ** is not allowed. If
9954 // the eventual target type is the same and the pointers have the same
9955 // level of indirection, this must be the issue.
9956 if (isa
<PointerType
>(lhptee
) && isa
<PointerType
>(rhptee
)) {
9958 std::tie(lhptee
, lhq
) =
9959 cast
<PointerType
>(lhptee
)->getPointeeType().split().asPair();
9960 std::tie(rhptee
, rhq
) =
9961 cast
<PointerType
>(rhptee
)->getPointeeType().split().asPair();
9963 // Inconsistent address spaces at this point is invalid, even if the
9964 // address spaces would be compatible.
9965 // FIXME: This doesn't catch address space mismatches for pointers of
9966 // different nesting levels, like:
9967 // __local int *** a;
9969 // It's not clear how to actually determine when such pointers are
9970 // invalidly incompatible.
9971 if (lhq
.getAddressSpace() != rhq
.getAddressSpace())
9972 return Sema::IncompatibleNestedPointerAddressSpaceMismatch
;
9974 } while (isa
<PointerType
>(lhptee
) && isa
<PointerType
>(rhptee
));
9976 if (lhptee
== rhptee
)
9977 return Sema::IncompatibleNestedPointerQualifiers
;
9980 // General pointer incompatibility takes priority over qualifiers.
9981 if (RHSType
->isFunctionPointerType() && LHSType
->isFunctionPointerType())
9982 return Sema::IncompatibleFunctionPointer
;
9983 return Sema::IncompatiblePointer
;
9985 if (!S
.getLangOpts().CPlusPlus
&&
9986 S
.IsFunctionConversion(ltrans
, rtrans
, ltrans
))
9987 return Sema::IncompatibleFunctionPointer
;
9988 if (IsInvalidCmseNSCallConversion(S
, ltrans
, rtrans
))
9989 return Sema::IncompatibleFunctionPointer
;
9990 if (S
.IsInvalidSMECallConversion(
9992 Sema::AArch64SMECallConversionKind::MayDropPreservesZA
))
9993 return Sema::IncompatibleFunctionPointer
;
9997 /// checkBlockPointerTypesForAssignment - This routine determines whether two
9998 /// block pointer types are compatible or whether a block and normal pointer
9999 /// are compatible. It is more restrict than comparing two function pointer
10001 static Sema::AssignConvertType
10002 checkBlockPointerTypesForAssignment(Sema
&S
, QualType LHSType
,
10003 QualType RHSType
) {
10004 assert(LHSType
.isCanonical() && "LHS not canonicalized!");
10005 assert(RHSType
.isCanonical() && "RHS not canonicalized!");
10007 QualType lhptee
, rhptee
;
10009 // get the "pointed to" type (ignoring qualifiers at the top level)
10010 lhptee
= cast
<BlockPointerType
>(LHSType
)->getPointeeType();
10011 rhptee
= cast
<BlockPointerType
>(RHSType
)->getPointeeType();
10013 // In C++, the types have to match exactly.
10014 if (S
.getLangOpts().CPlusPlus
)
10015 return Sema::IncompatibleBlockPointer
;
10017 Sema::AssignConvertType ConvTy
= Sema::Compatible
;
10019 // For blocks we enforce that qualifiers are identical.
10020 Qualifiers LQuals
= lhptee
.getLocalQualifiers();
10021 Qualifiers RQuals
= rhptee
.getLocalQualifiers();
10022 if (S
.getLangOpts().OpenCL
) {
10023 LQuals
.removeAddressSpace();
10024 RQuals
.removeAddressSpace();
10026 if (LQuals
!= RQuals
)
10027 ConvTy
= Sema::CompatiblePointerDiscardsQualifiers
;
10029 // FIXME: OpenCL doesn't define the exact compile time semantics for a block
10031 // The current behavior is similar to C++ lambdas. A block might be
10032 // assigned to a variable iff its return type and parameters are compatible
10033 // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
10034 // an assignment. Presumably it should behave in way that a function pointer
10035 // assignment does in C, so for each parameter and return type:
10036 // * CVR and address space of LHS should be a superset of CVR and address
10038 // * unqualified types should be compatible.
10039 if (S
.getLangOpts().OpenCL
) {
10040 if (!S
.Context
.typesAreBlockPointerCompatible(
10041 S
.Context
.getQualifiedType(LHSType
.getUnqualifiedType(), LQuals
),
10042 S
.Context
.getQualifiedType(RHSType
.getUnqualifiedType(), RQuals
)))
10043 return Sema::IncompatibleBlockPointer
;
10044 } else if (!S
.Context
.typesAreBlockPointerCompatible(LHSType
, RHSType
))
10045 return Sema::IncompatibleBlockPointer
;
10050 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
10051 /// for assignment compatibility.
10052 static Sema::AssignConvertType
10053 checkObjCPointerTypesForAssignment(Sema
&S
, QualType LHSType
,
10054 QualType RHSType
) {
10055 assert(LHSType
.isCanonical() && "LHS was not canonicalized!");
10056 assert(RHSType
.isCanonical() && "RHS was not canonicalized!");
10058 if (LHSType
->isObjCBuiltinType()) {
10059 // Class is not compatible with ObjC object pointers.
10060 if (LHSType
->isObjCClassType() && !RHSType
->isObjCBuiltinType() &&
10061 !RHSType
->isObjCQualifiedClassType())
10062 return Sema::IncompatiblePointer
;
10063 return Sema::Compatible
;
10065 if (RHSType
->isObjCBuiltinType()) {
10066 if (RHSType
->isObjCClassType() && !LHSType
->isObjCBuiltinType() &&
10067 !LHSType
->isObjCQualifiedClassType())
10068 return Sema::IncompatiblePointer
;
10069 return Sema::Compatible
;
10071 QualType lhptee
= LHSType
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
10072 QualType rhptee
= RHSType
->castAs
<ObjCObjectPointerType
>()->getPointeeType();
10074 if (!lhptee
.isAtLeastAsQualifiedAs(rhptee
) &&
10075 // make an exception for id<P>
10076 !LHSType
->isObjCQualifiedIdType())
10077 return Sema::CompatiblePointerDiscardsQualifiers
;
10079 if (S
.Context
.typesAreCompatible(LHSType
, RHSType
))
10080 return Sema::Compatible
;
10081 if (LHSType
->isObjCQualifiedIdType() || RHSType
->isObjCQualifiedIdType())
10082 return Sema::IncompatibleObjCQualifiedId
;
10083 return Sema::IncompatiblePointer
;
10086 Sema::AssignConvertType
10087 Sema::CheckAssignmentConstraints(SourceLocation Loc
,
10088 QualType LHSType
, QualType RHSType
) {
10089 // Fake up an opaque expression. We don't actually care about what
10090 // cast operations are required, so if CheckAssignmentConstraints
10091 // adds casts to this they'll be wasted, but fortunately that doesn't
10092 // usually happen on valid code.
10093 OpaqueValueExpr
RHSExpr(Loc
, RHSType
, VK_PRValue
);
10094 ExprResult RHSPtr
= &RHSExpr
;
10097 return CheckAssignmentConstraints(LHSType
, RHSPtr
, K
, /*ConvertRHS=*/false);
10100 /// This helper function returns true if QT is a vector type that has element
10101 /// type ElementType.
10102 static bool isVector(QualType QT
, QualType ElementType
) {
10103 if (const VectorType
*VT
= QT
->getAs
<VectorType
>())
10104 return VT
->getElementType().getCanonicalType() == ElementType
;
10108 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
10109 /// has code to accommodate several GCC extensions when type checking
10110 /// pointers. Here are some objectionable examples that GCC considers warnings:
10114 /// struct foo *pfoo;
10116 /// pint = pshort; // warning: assignment from incompatible pointer type
10117 /// a = pint; // warning: assignment makes integer from pointer without a cast
10118 /// pint = a; // warning: assignment makes pointer from integer without a cast
10119 /// pint = pfoo; // warning: assignment from incompatible pointer type
10121 /// As a result, the code for dealing with pointers is more complex than the
10122 /// C99 spec dictates.
10124 /// Sets 'Kind' for any result kind except Incompatible.
10125 Sema::AssignConvertType
10126 Sema::CheckAssignmentConstraints(QualType LHSType
, ExprResult
&RHS
,
10127 CastKind
&Kind
, bool ConvertRHS
) {
10128 QualType RHSType
= RHS
.get()->getType();
10129 QualType OrigLHSType
= LHSType
;
10131 // Get canonical types. We're not formatting these types, just comparing
10133 LHSType
= Context
.getCanonicalType(LHSType
).getUnqualifiedType();
10134 RHSType
= Context
.getCanonicalType(RHSType
).getUnqualifiedType();
10136 // Common case: no conversion required.
10137 if (LHSType
== RHSType
) {
10142 // If the LHS has an __auto_type, there are no additional type constraints
10143 // to be worried about.
10144 if (const auto *AT
= dyn_cast
<AutoType
>(LHSType
)) {
10145 if (AT
->isGNUAutoType()) {
10151 // If we have an atomic type, try a non-atomic assignment, then just add an
10152 // atomic qualification step.
10153 if (const AtomicType
*AtomicTy
= dyn_cast
<AtomicType
>(LHSType
)) {
10154 Sema::AssignConvertType result
=
10155 CheckAssignmentConstraints(AtomicTy
->getValueType(), RHS
, Kind
);
10156 if (result
!= Compatible
)
10158 if (Kind
!= CK_NoOp
&& ConvertRHS
)
10159 RHS
= ImpCastExprToType(RHS
.get(), AtomicTy
->getValueType(), Kind
);
10160 Kind
= CK_NonAtomicToAtomic
;
10164 // If the left-hand side is a reference type, then we are in a
10165 // (rare!) case where we've allowed the use of references in C,
10166 // e.g., as a parameter type in a built-in function. In this case,
10167 // just make sure that the type referenced is compatible with the
10168 // right-hand side type. The caller is responsible for adjusting
10169 // LHSType so that the resulting expression does not have reference
10171 if (const ReferenceType
*LHSTypeRef
= LHSType
->getAs
<ReferenceType
>()) {
10172 if (Context
.typesAreCompatible(LHSTypeRef
->getPointeeType(), RHSType
)) {
10173 Kind
= CK_LValueBitCast
;
10176 return Incompatible
;
10179 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
10180 // to the same ExtVector type.
10181 if (LHSType
->isExtVectorType()) {
10182 if (RHSType
->isExtVectorType())
10183 return Incompatible
;
10184 if (RHSType
->isArithmeticType()) {
10185 // CK_VectorSplat does T -> vector T, so first cast to the element type.
10187 RHS
= prepareVectorSplat(LHSType
, RHS
.get());
10188 Kind
= CK_VectorSplat
;
10193 // Conversions to or from vector type.
10194 if (LHSType
->isVectorType() || RHSType
->isVectorType()) {
10195 if (LHSType
->isVectorType() && RHSType
->isVectorType()) {
10196 // Allow assignments of an AltiVec vector type to an equivalent GCC
10197 // vector type and vice versa
10198 if (Context
.areCompatibleVectorTypes(LHSType
, RHSType
)) {
10203 // If we are allowing lax vector conversions, and LHS and RHS are both
10204 // vectors, the total size only needs to be the same. This is a bitcast;
10205 // no bits are changed but the result type is different.
10206 if (isLaxVectorConversion(RHSType
, LHSType
)) {
10207 // The default for lax vector conversions with Altivec vectors will
10208 // change, so if we are converting between vector types where
10209 // at least one is an Altivec vector, emit a warning.
10210 if (Context
.getTargetInfo().getTriple().isPPC() &&
10211 anyAltivecTypes(RHSType
, LHSType
) &&
10212 !Context
.areCompatibleVectorTypes(RHSType
, LHSType
))
10213 Diag(RHS
.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all
)
10214 << RHSType
<< LHSType
;
10216 return IncompatibleVectors
;
10220 // When the RHS comes from another lax conversion (e.g. binops between
10221 // scalars and vectors) the result is canonicalized as a vector. When the
10222 // LHS is also a vector, the lax is allowed by the condition above. Handle
10223 // the case where LHS is a scalar.
10224 if (LHSType
->isScalarType()) {
10225 const VectorType
*VecType
= RHSType
->getAs
<VectorType
>();
10226 if (VecType
&& VecType
->getNumElements() == 1 &&
10227 isLaxVectorConversion(RHSType
, LHSType
)) {
10228 if (Context
.getTargetInfo().getTriple().isPPC() &&
10229 (VecType
->getVectorKind() == VectorKind::AltiVecVector
||
10230 VecType
->getVectorKind() == VectorKind::AltiVecBool
||
10231 VecType
->getVectorKind() == VectorKind::AltiVecPixel
))
10232 Diag(RHS
.get()->getExprLoc(), diag::warn_deprecated_lax_vec_conv_all
)
10233 << RHSType
<< LHSType
;
10234 ExprResult
*VecExpr
= &RHS
;
10235 *VecExpr
= ImpCastExprToType(VecExpr
->get(), LHSType
, CK_BitCast
);
10241 // Allow assignments between fixed-length and sizeless SVE vectors.
10242 if ((LHSType
->isSVESizelessBuiltinType() && RHSType
->isVectorType()) ||
10243 (LHSType
->isVectorType() && RHSType
->isSVESizelessBuiltinType()))
10244 if (Context
.areCompatibleSveTypes(LHSType
, RHSType
) ||
10245 Context
.areLaxCompatibleSveTypes(LHSType
, RHSType
)) {
10250 // Allow assignments between fixed-length and sizeless RVV vectors.
10251 if ((LHSType
->isRVVSizelessBuiltinType() && RHSType
->isVectorType()) ||
10252 (LHSType
->isVectorType() && RHSType
->isRVVSizelessBuiltinType())) {
10253 if (Context
.areCompatibleRVVTypes(LHSType
, RHSType
) ||
10254 Context
.areLaxCompatibleRVVTypes(LHSType
, RHSType
)) {
10260 return Incompatible
;
10263 // Diagnose attempts to convert between __ibm128, __float128 and long double
10264 // where such conversions currently can't be handled.
10265 if (unsupportedTypeConversion(*this, LHSType
, RHSType
))
10266 return Incompatible
;
10268 // Disallow assigning a _Complex to a real type in C++ mode since it simply
10269 // discards the imaginary part.
10270 if (getLangOpts().CPlusPlus
&& RHSType
->getAs
<ComplexType
>() &&
10271 !LHSType
->getAs
<ComplexType
>())
10272 return Incompatible
;
10274 // Arithmetic conversions.
10275 if (LHSType
->isArithmeticType() && RHSType
->isArithmeticType() &&
10276 !(getLangOpts().CPlusPlus
&& LHSType
->isEnumeralType())) {
10278 Kind
= PrepareScalarCast(RHS
, LHSType
);
10282 // Conversions to normal pointers.
10283 if (const PointerType
*LHSPointer
= dyn_cast
<PointerType
>(LHSType
)) {
10285 if (isa
<PointerType
>(RHSType
)) {
10286 LangAS AddrSpaceL
= LHSPointer
->getPointeeType().getAddressSpace();
10287 LangAS AddrSpaceR
= RHSType
->getPointeeType().getAddressSpace();
10288 if (AddrSpaceL
!= AddrSpaceR
)
10289 Kind
= CK_AddressSpaceConversion
;
10290 else if (Context
.hasCvrSimilarType(RHSType
, LHSType
))
10294 return checkPointerTypesForAssignment(*this, LHSType
, RHSType
,
10295 RHS
.get()->getBeginLoc());
10299 if (RHSType
->isIntegerType()) {
10300 Kind
= CK_IntegralToPointer
; // FIXME: null?
10301 return IntToPointer
;
10304 // C pointers are not compatible with ObjC object pointers,
10305 // with two exceptions:
10306 if (isa
<ObjCObjectPointerType
>(RHSType
)) {
10307 // - conversions to void*
10308 if (LHSPointer
->getPointeeType()->isVoidType()) {
10313 // - conversions from 'Class' to the redefinition type
10314 if (RHSType
->isObjCClassType() &&
10315 Context
.hasSameType(LHSType
,
10316 Context
.getObjCClassRedefinitionType())) {
10322 return IncompatiblePointer
;
10326 if (RHSType
->getAs
<BlockPointerType
>()) {
10327 if (LHSPointer
->getPointeeType()->isVoidType()) {
10328 LangAS AddrSpaceL
= LHSPointer
->getPointeeType().getAddressSpace();
10329 LangAS AddrSpaceR
= RHSType
->getAs
<BlockPointerType
>()
10331 .getAddressSpace();
10333 AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
: CK_BitCast
;
10338 return Incompatible
;
10341 // Conversions to block pointers.
10342 if (isa
<BlockPointerType
>(LHSType
)) {
10344 if (RHSType
->isBlockPointerType()) {
10345 LangAS AddrSpaceL
= LHSType
->getAs
<BlockPointerType
>()
10347 .getAddressSpace();
10348 LangAS AddrSpaceR
= RHSType
->getAs
<BlockPointerType
>()
10350 .getAddressSpace();
10351 Kind
= AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
: CK_BitCast
;
10352 return checkBlockPointerTypesForAssignment(*this, LHSType
, RHSType
);
10355 // int or null -> T^
10356 if (RHSType
->isIntegerType()) {
10357 Kind
= CK_IntegralToPointer
; // FIXME: null
10358 return IntToBlockPointer
;
10362 if (getLangOpts().ObjC
&& RHSType
->isObjCIdType()) {
10363 Kind
= CK_AnyPointerToBlockPointerCast
;
10368 if (const PointerType
*RHSPT
= RHSType
->getAs
<PointerType
>())
10369 if (RHSPT
->getPointeeType()->isVoidType()) {
10370 Kind
= CK_AnyPointerToBlockPointerCast
;
10374 return Incompatible
;
10377 // Conversions to Objective-C pointers.
10378 if (isa
<ObjCObjectPointerType
>(LHSType
)) {
10380 if (RHSType
->isObjCObjectPointerType()) {
10382 Sema::AssignConvertType result
=
10383 checkObjCPointerTypesForAssignment(*this, LHSType
, RHSType
);
10384 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10385 result
== Compatible
&&
10386 !CheckObjCARCUnavailableWeakConversion(OrigLHSType
, RHSType
))
10387 result
= IncompatibleObjCWeakRef
;
10391 // int or null -> A*
10392 if (RHSType
->isIntegerType()) {
10393 Kind
= CK_IntegralToPointer
; // FIXME: null
10394 return IntToPointer
;
10397 // In general, C pointers are not compatible with ObjC object pointers,
10398 // with two exceptions:
10399 if (isa
<PointerType
>(RHSType
)) {
10400 Kind
= CK_CPointerToObjCPointerCast
;
10402 // - conversions from 'void*'
10403 if (RHSType
->isVoidPointerType()) {
10407 // - conversions to 'Class' from its redefinition type
10408 if (LHSType
->isObjCClassType() &&
10409 Context
.hasSameType(RHSType
,
10410 Context
.getObjCClassRedefinitionType())) {
10414 return IncompatiblePointer
;
10417 // Only under strict condition T^ is compatible with an Objective-C pointer.
10418 if (RHSType
->isBlockPointerType() &&
10419 LHSType
->isBlockCompatibleObjCPointerType(Context
)) {
10421 maybeExtendBlockObject(RHS
);
10422 Kind
= CK_BlockPointerToObjCPointerCast
;
10426 return Incompatible
;
10429 // Conversion to nullptr_t (C23 only)
10430 if (getLangOpts().C23
&& LHSType
->isNullPtrType() &&
10431 RHS
.get()->isNullPointerConstant(Context
,
10432 Expr::NPC_ValueDependentIsNull
)) {
10433 // null -> nullptr_t
10434 Kind
= CK_NullToPointer
;
10438 // Conversions from pointers that are not covered by the above.
10439 if (isa
<PointerType
>(RHSType
)) {
10441 if (LHSType
== Context
.BoolTy
) {
10442 Kind
= CK_PointerToBoolean
;
10447 if (LHSType
->isIntegerType()) {
10448 Kind
= CK_PointerToIntegral
;
10449 return PointerToInt
;
10452 return Incompatible
;
10455 // Conversions from Objective-C pointers that are not covered by the above.
10456 if (isa
<ObjCObjectPointerType
>(RHSType
)) {
10458 if (LHSType
== Context
.BoolTy
) {
10459 Kind
= CK_PointerToBoolean
;
10464 if (LHSType
->isIntegerType()) {
10465 Kind
= CK_PointerToIntegral
;
10466 return PointerToInt
;
10469 return Incompatible
;
10472 // struct A -> struct B
10473 if (isa
<TagType
>(LHSType
) && isa
<TagType
>(RHSType
)) {
10474 if (Context
.typesAreCompatible(LHSType
, RHSType
)) {
10480 if (LHSType
->isSamplerT() && RHSType
->isIntegerType()) {
10481 Kind
= CK_IntToOCLSampler
;
10485 return Incompatible
;
10488 /// Constructs a transparent union from an expression that is
10489 /// used to initialize the transparent union.
10490 static void ConstructTransparentUnion(Sema
&S
, ASTContext
&C
,
10491 ExprResult
&EResult
, QualType UnionType
,
10492 FieldDecl
*Field
) {
10493 // Build an initializer list that designates the appropriate member
10494 // of the transparent union.
10495 Expr
*E
= EResult
.get();
10496 InitListExpr
*Initializer
= new (C
) InitListExpr(C
, SourceLocation(),
10497 E
, SourceLocation());
10498 Initializer
->setType(UnionType
);
10499 Initializer
->setInitializedFieldInUnion(Field
);
10501 // Build a compound literal constructing a value of the transparent
10502 // union type from this initializer list.
10503 TypeSourceInfo
*unionTInfo
= C
.getTrivialTypeSourceInfo(UnionType
);
10504 EResult
= new (C
) CompoundLiteralExpr(SourceLocation(), unionTInfo
, UnionType
,
10505 VK_PRValue
, Initializer
, false);
10508 Sema::AssignConvertType
10509 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType
,
10511 QualType RHSType
= RHS
.get()->getType();
10513 // If the ArgType is a Union type, we want to handle a potential
10514 // transparent_union GCC extension.
10515 const RecordType
*UT
= ArgType
->getAsUnionType();
10516 if (!UT
|| !UT
->getDecl()->hasAttr
<TransparentUnionAttr
>())
10517 return Incompatible
;
10519 // The field to initialize within the transparent union.
10520 RecordDecl
*UD
= UT
->getDecl();
10521 FieldDecl
*InitField
= nullptr;
10522 // It's compatible if the expression matches any of the fields.
10523 for (auto *it
: UD
->fields()) {
10524 if (it
->getType()->isPointerType()) {
10525 // If the transparent union contains a pointer type, we allow:
10527 // 2) null pointer constant
10528 if (RHSType
->isPointerType())
10529 if (RHSType
->castAs
<PointerType
>()->getPointeeType()->isVoidType()) {
10530 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(), CK_BitCast
);
10535 if (RHS
.get()->isNullPointerConstant(Context
,
10536 Expr::NPC_ValueDependentIsNull
)) {
10537 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(),
10545 if (CheckAssignmentConstraints(it
->getType(), RHS
, Kind
)
10547 RHS
= ImpCastExprToType(RHS
.get(), it
->getType(), Kind
);
10554 return Incompatible
;
10556 ConstructTransparentUnion(*this, Context
, RHS
, ArgType
, InitField
);
10560 Sema::AssignConvertType
10561 Sema::CheckSingleAssignmentConstraints(QualType LHSType
, ExprResult
&CallerRHS
,
10563 bool DiagnoseCFAudited
,
10565 // We need to be able to tell the caller whether we diagnosed a problem, if
10566 // they ask us to issue diagnostics.
10567 assert((ConvertRHS
|| !Diagnose
) && "can't indicate whether we diagnosed");
10569 // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
10570 // we can't avoid *all* modifications at the moment, so we need some somewhere
10571 // to put the updated value.
10572 ExprResult LocalRHS
= CallerRHS
;
10573 ExprResult
&RHS
= ConvertRHS
? CallerRHS
: LocalRHS
;
10575 if (const auto *LHSPtrType
= LHSType
->getAs
<PointerType
>()) {
10576 if (const auto *RHSPtrType
= RHS
.get()->getType()->getAs
<PointerType
>()) {
10577 if (RHSPtrType
->getPointeeType()->hasAttr(attr::NoDeref
) &&
10578 !LHSPtrType
->getPointeeType()->hasAttr(attr::NoDeref
)) {
10579 Diag(RHS
.get()->getExprLoc(),
10580 diag::warn_noderef_to_dereferenceable_pointer
)
10581 << RHS
.get()->getSourceRange();
10586 if (getLangOpts().CPlusPlus
) {
10587 if (!LHSType
->isRecordType() && !LHSType
->isAtomicType()) {
10588 // C++ 5.17p3: If the left operand is not of class type, the
10589 // expression is implicitly converted (C++ 4) to the
10590 // cv-unqualified type of the left operand.
10591 QualType RHSType
= RHS
.get()->getType();
10593 RHS
= PerformImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
10596 ImplicitConversionSequence ICS
=
10597 TryImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
10598 /*SuppressUserConversions=*/false,
10599 AllowedExplicit::None
,
10600 /*InOverloadResolution=*/false,
10602 /*AllowObjCWritebackConversion=*/false);
10603 if (ICS
.isFailure())
10604 return Incompatible
;
10605 RHS
= PerformImplicitConversion(RHS
.get(), LHSType
.getUnqualifiedType(),
10606 ICS
, AA_Assigning
);
10608 if (RHS
.isInvalid())
10609 return Incompatible
;
10610 Sema::AssignConvertType result
= Compatible
;
10611 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10612 !CheckObjCARCUnavailableWeakConversion(LHSType
, RHSType
))
10613 result
= IncompatibleObjCWeakRef
;
10617 // FIXME: Currently, we fall through and treat C++ classes like C
10619 // FIXME: We also fall through for atomics; not sure what should
10620 // happen there, though.
10621 } else if (RHS
.get()->getType() == Context
.OverloadTy
) {
10622 // As a set of extensions to C, we support overloading on functions. These
10623 // functions need to be resolved here.
10624 DeclAccessPair DAP
;
10625 if (FunctionDecl
*FD
= ResolveAddressOfOverloadedFunction(
10626 RHS
.get(), LHSType
, /*Complain=*/false, DAP
))
10627 RHS
= FixOverloadedFunctionReference(RHS
.get(), DAP
, FD
);
10629 return Incompatible
;
10632 // This check seems unnatural, however it is necessary to ensure the proper
10633 // conversion of functions/arrays. If the conversion were done for all
10634 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
10635 // expressions that suppress this implicit conversion (&, sizeof). This needs
10636 // to happen before we check for null pointer conversions because C does not
10637 // undergo the same implicit conversions as C++ does above (by the calls to
10638 // TryImplicitConversion() and PerformImplicitConversion()) which insert the
10639 // lvalue to rvalue cast before checking for null pointer constraints. This
10640 // addresses code like: nullptr_t val; int *ptr; ptr = val;
10642 // Suppress this for references: C++ 8.5.3p5.
10643 if (!LHSType
->isReferenceType()) {
10644 // FIXME: We potentially allocate here even if ConvertRHS is false.
10645 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get(), Diagnose
);
10646 if (RHS
.isInvalid())
10647 return Incompatible
;
10650 // The constraints are expressed in terms of the atomic, qualified, or
10651 // unqualified type of the LHS.
10652 QualType LHSTypeAfterConversion
= LHSType
.getAtomicUnqualifiedType();
10654 // C99 6.5.16.1p1: the left operand is a pointer and the right is
10655 // a null pointer constant <C23>or its type is nullptr_t;</C23>.
10656 if ((LHSTypeAfterConversion
->isPointerType() ||
10657 LHSTypeAfterConversion
->isObjCObjectPointerType() ||
10658 LHSTypeAfterConversion
->isBlockPointerType()) &&
10659 ((getLangOpts().C23
&& RHS
.get()->getType()->isNullPtrType()) ||
10660 RHS
.get()->isNullPointerConstant(Context
,
10661 Expr::NPC_ValueDependentIsNull
))) {
10662 if (Diagnose
|| ConvertRHS
) {
10665 CheckPointerConversion(RHS
.get(), LHSType
, Kind
, Path
,
10666 /*IgnoreBaseAccess=*/false, Diagnose
);
10668 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, Kind
, VK_PRValue
, &Path
);
10672 // C23 6.5.16.1p1: the left operand has type atomic, qualified, or
10673 // unqualified bool, and the right operand is a pointer or its type is
10675 if (getLangOpts().C23
&& LHSType
->isBooleanType() &&
10676 RHS
.get()->getType()->isNullPtrType()) {
10677 // NB: T* -> _Bool is handled in CheckAssignmentConstraints, this only
10678 // only handles nullptr -> _Bool due to needing an extra conversion
10680 // We model this by converting from nullptr -> void * and then let the
10681 // conversion from void * -> _Bool happen naturally.
10682 if (Diagnose
|| ConvertRHS
) {
10685 CheckPointerConversion(RHS
.get(), Context
.VoidPtrTy
, Kind
, Path
,
10686 /*IgnoreBaseAccess=*/false, Diagnose
);
10688 RHS
= ImpCastExprToType(RHS
.get(), Context
.VoidPtrTy
, Kind
, VK_PRValue
,
10693 // OpenCL queue_t type assignment.
10694 if (LHSType
->isQueueT() && RHS
.get()->isNullPointerConstant(
10695 Context
, Expr::NPC_ValueDependentIsNull
)) {
10696 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
10701 Sema::AssignConvertType result
=
10702 CheckAssignmentConstraints(LHSType
, RHS
, Kind
, ConvertRHS
);
10704 // C99 6.5.16.1p2: The value of the right operand is converted to the
10705 // type of the assignment expression.
10706 // CheckAssignmentConstraints allows the left-hand side to be a reference,
10707 // so that we can use references in built-in functions even in C.
10708 // The getNonReferenceType() call makes sure that the resulting expression
10709 // does not have reference type.
10710 if (result
!= Incompatible
&& RHS
.get()->getType() != LHSType
) {
10711 QualType Ty
= LHSType
.getNonLValueExprType(Context
);
10712 Expr
*E
= RHS
.get();
10714 // Check for various Objective-C errors. If we are not reporting
10715 // diagnostics and just checking for errors, e.g., during overload
10716 // resolution, return Incompatible to indicate the failure.
10717 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
10718 CheckObjCConversion(SourceRange(), Ty
, E
, CCK_ImplicitConversion
,
10719 Diagnose
, DiagnoseCFAudited
) != ACR_okay
) {
10721 return Incompatible
;
10723 if (getLangOpts().ObjC
&&
10724 (CheckObjCBridgeRelatedConversions(E
->getBeginLoc(), LHSType
,
10725 E
->getType(), E
, Diagnose
) ||
10726 CheckConversionToObjCLiteral(LHSType
, E
, Diagnose
))) {
10728 return Incompatible
;
10729 // Replace the expression with a corrected version and continue so we
10730 // can find further errors.
10736 RHS
= ImpCastExprToType(E
, Ty
, Kind
);
10743 /// The original operand to an operator, prior to the application of the usual
10744 /// arithmetic conversions and converting the arguments of a builtin operator
10746 struct OriginalOperand
{
10747 explicit OriginalOperand(Expr
*Op
) : Orig(Op
), Conversion(nullptr) {
10748 if (auto *MTE
= dyn_cast
<MaterializeTemporaryExpr
>(Op
))
10749 Op
= MTE
->getSubExpr();
10750 if (auto *BTE
= dyn_cast
<CXXBindTemporaryExpr
>(Op
))
10751 Op
= BTE
->getSubExpr();
10752 if (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(Op
)) {
10753 Orig
= ICE
->getSubExprAsWritten();
10754 Conversion
= ICE
->getConversionFunction();
10758 QualType
getType() const { return Orig
->getType(); }
10761 NamedDecl
*Conversion
;
10765 QualType
Sema::InvalidOperands(SourceLocation Loc
, ExprResult
&LHS
,
10767 OriginalOperand
OrigLHS(LHS
.get()), OrigRHS(RHS
.get());
10769 Diag(Loc
, diag::err_typecheck_invalid_operands
)
10770 << OrigLHS
.getType() << OrigRHS
.getType()
10771 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
10773 // If a user-defined conversion was applied to either of the operands prior
10774 // to applying the built-in operator rules, tell the user about it.
10775 if (OrigLHS
.Conversion
) {
10776 Diag(OrigLHS
.Conversion
->getLocation(),
10777 diag::note_typecheck_invalid_operands_converted
)
10778 << 0 << LHS
.get()->getType();
10780 if (OrigRHS
.Conversion
) {
10781 Diag(OrigRHS
.Conversion
->getLocation(),
10782 diag::note_typecheck_invalid_operands_converted
)
10783 << 1 << RHS
.get()->getType();
10789 // Diagnose cases where a scalar was implicitly converted to a vector and
10790 // diagnose the underlying types. Otherwise, diagnose the error
10791 // as invalid vector logical operands for non-C++ cases.
10792 QualType
Sema::InvalidLogicalVectorOperands(SourceLocation Loc
, ExprResult
&LHS
,
10794 QualType LHSType
= LHS
.get()->IgnoreImpCasts()->getType();
10795 QualType RHSType
= RHS
.get()->IgnoreImpCasts()->getType();
10797 bool LHSNatVec
= LHSType
->isVectorType();
10798 bool RHSNatVec
= RHSType
->isVectorType();
10800 if (!(LHSNatVec
&& RHSNatVec
)) {
10801 Expr
*Vector
= LHSNatVec
? LHS
.get() : RHS
.get();
10802 Expr
*NonVector
= !LHSNatVec
? LHS
.get() : RHS
.get();
10803 Diag(Loc
, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict
)
10804 << 0 << Vector
->getType() << NonVector
->IgnoreImpCasts()->getType()
10805 << Vector
->getSourceRange();
10809 Diag(Loc
, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict
)
10810 << 1 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
10811 << RHS
.get()->getSourceRange();
10816 /// Try to convert a value of non-vector type to a vector type by converting
10817 /// the type to the element type of the vector and then performing a splat.
10818 /// If the language is OpenCL, we only use conversions that promote scalar
10819 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
10820 /// for float->int.
10822 /// OpenCL V2.0 6.2.6.p2:
10823 /// An error shall occur if any scalar operand type has greater rank
10824 /// than the type of the vector element.
10826 /// \param scalar - if non-null, actually perform the conversions
10827 /// \return true if the operation fails (but without diagnosing the failure)
10828 static bool tryVectorConvertAndSplat(Sema
&S
, ExprResult
*scalar
,
10830 QualType vectorEltTy
,
10832 unsigned &DiagID
) {
10833 // The conversion to apply to the scalar before splatting it,
10835 CastKind scalarCast
= CK_NoOp
;
10837 if (vectorEltTy
->isIntegralType(S
.Context
)) {
10838 if (S
.getLangOpts().OpenCL
&& (scalarTy
->isRealFloatingType() ||
10839 (scalarTy
->isIntegerType() &&
10840 S
.Context
.getIntegerTypeOrder(vectorEltTy
, scalarTy
) < 0))) {
10841 DiagID
= diag::err_opencl_scalar_type_rank_greater_than_vector_type
;
10844 if (!scalarTy
->isIntegralType(S
.Context
))
10846 scalarCast
= CK_IntegralCast
;
10847 } else if (vectorEltTy
->isRealFloatingType()) {
10848 if (scalarTy
->isRealFloatingType()) {
10849 if (S
.getLangOpts().OpenCL
&&
10850 S
.Context
.getFloatingTypeOrder(vectorEltTy
, scalarTy
) < 0) {
10851 DiagID
= diag::err_opencl_scalar_type_rank_greater_than_vector_type
;
10854 scalarCast
= CK_FloatingCast
;
10856 else if (scalarTy
->isIntegralType(S
.Context
))
10857 scalarCast
= CK_IntegralToFloating
;
10864 // Adjust scalar if desired.
10866 if (scalarCast
!= CK_NoOp
)
10867 *scalar
= S
.ImpCastExprToType(scalar
->get(), vectorEltTy
, scalarCast
);
10868 *scalar
= S
.ImpCastExprToType(scalar
->get(), vectorTy
, CK_VectorSplat
);
10873 /// Convert vector E to a vector with the same number of elements but different
10875 static ExprResult
convertVector(Expr
*E
, QualType ElementType
, Sema
&S
) {
10876 const auto *VecTy
= E
->getType()->getAs
<VectorType
>();
10877 assert(VecTy
&& "Expression E must be a vector");
10878 QualType NewVecTy
=
10879 VecTy
->isExtVectorType()
10880 ? S
.Context
.getExtVectorType(ElementType
, VecTy
->getNumElements())
10881 : S
.Context
.getVectorType(ElementType
, VecTy
->getNumElements(),
10882 VecTy
->getVectorKind());
10884 // Look through the implicit cast. Return the subexpression if its type is
10886 if (auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
10887 if (ICE
->getSubExpr()->getType() == NewVecTy
)
10888 return ICE
->getSubExpr();
10890 auto Cast
= ElementType
->isIntegerType() ? CK_IntegralCast
: CK_FloatingCast
;
10891 return S
.ImpCastExprToType(E
, NewVecTy
, Cast
);
10894 /// Test if a (constant) integer Int can be casted to another integer type
10895 /// IntTy without losing precision.
10896 static bool canConvertIntToOtherIntTy(Sema
&S
, ExprResult
*Int
,
10897 QualType OtherIntTy
) {
10898 QualType IntTy
= Int
->get()->getType().getUnqualifiedType();
10900 // Reject cases where the value of the Int is unknown as that would
10901 // possibly cause truncation, but accept cases where the scalar can be
10902 // demoted without loss of precision.
10903 Expr::EvalResult EVResult
;
10904 bool CstInt
= Int
->get()->EvaluateAsInt(EVResult
, S
.Context
);
10905 int Order
= S
.Context
.getIntegerTypeOrder(OtherIntTy
, IntTy
);
10906 bool IntSigned
= IntTy
->hasSignedIntegerRepresentation();
10907 bool OtherIntSigned
= OtherIntTy
->hasSignedIntegerRepresentation();
10910 // If the scalar is constant and is of a higher order and has more active
10911 // bits that the vector element type, reject it.
10912 llvm::APSInt Result
= EVResult
.Val
.getInt();
10913 unsigned NumBits
= IntSigned
10914 ? (Result
.isNegative() ? Result
.getSignificantBits()
10915 : Result
.getActiveBits())
10916 : Result
.getActiveBits();
10917 if (Order
< 0 && S
.Context
.getIntWidth(OtherIntTy
) < NumBits
)
10920 // If the signedness of the scalar type and the vector element type
10921 // differs and the number of bits is greater than that of the vector
10922 // element reject it.
10923 return (IntSigned
!= OtherIntSigned
&&
10924 NumBits
> S
.Context
.getIntWidth(OtherIntTy
));
10927 // Reject cases where the value of the scalar is not constant and it's
10928 // order is greater than that of the vector element type.
10929 return (Order
< 0);
10932 /// Test if a (constant) integer Int can be casted to floating point type
10933 /// FloatTy without losing precision.
10934 static bool canConvertIntTyToFloatTy(Sema
&S
, ExprResult
*Int
,
10935 QualType FloatTy
) {
10936 QualType IntTy
= Int
->get()->getType().getUnqualifiedType();
10938 // Determine if the integer constant can be expressed as a floating point
10939 // number of the appropriate type.
10940 Expr::EvalResult EVResult
;
10941 bool CstInt
= Int
->get()->EvaluateAsInt(EVResult
, S
.Context
);
10945 // Reject constants that would be truncated if they were converted to
10946 // the floating point type. Test by simple to/from conversion.
10947 // FIXME: Ideally the conversion to an APFloat and from an APFloat
10948 // could be avoided if there was a convertFromAPInt method
10949 // which could signal back if implicit truncation occurred.
10950 llvm::APSInt Result
= EVResult
.Val
.getInt();
10951 llvm::APFloat
Float(S
.Context
.getFloatTypeSemantics(FloatTy
));
10952 Float
.convertFromAPInt(Result
, IntTy
->hasSignedIntegerRepresentation(),
10953 llvm::APFloat::rmTowardZero
);
10954 llvm::APSInt
ConvertBack(S
.Context
.getIntWidth(IntTy
),
10955 !IntTy
->hasSignedIntegerRepresentation());
10956 bool Ignored
= false;
10957 Float
.convertToInteger(ConvertBack
, llvm::APFloat::rmNearestTiesToEven
,
10959 if (Result
!= ConvertBack
)
10962 // Reject types that cannot be fully encoded into the mantissa of
10964 Bits
= S
.Context
.getTypeSize(IntTy
);
10965 unsigned FloatPrec
= llvm::APFloat::semanticsPrecision(
10966 S
.Context
.getFloatTypeSemantics(FloatTy
));
10967 if (Bits
> FloatPrec
)
10974 /// Attempt to convert and splat Scalar into a vector whose types matches
10975 /// Vector following GCC conversion rules. The rule is that implicit
10976 /// conversion can occur when Scalar can be casted to match Vector's element
10977 /// type without causing truncation of Scalar.
10978 static bool tryGCCVectorConvertAndSplat(Sema
&S
, ExprResult
*Scalar
,
10979 ExprResult
*Vector
) {
10980 QualType ScalarTy
= Scalar
->get()->getType().getUnqualifiedType();
10981 QualType VectorTy
= Vector
->get()->getType().getUnqualifiedType();
10982 QualType VectorEltTy
;
10984 if (const auto *VT
= VectorTy
->getAs
<VectorType
>()) {
10985 assert(!isa
<ExtVectorType
>(VT
) &&
10986 "ExtVectorTypes should not be handled here!");
10987 VectorEltTy
= VT
->getElementType();
10988 } else if (VectorTy
->isSveVLSBuiltinType()) {
10990 VectorTy
->castAs
<BuiltinType
>()->getSveEltType(S
.getASTContext());
10992 llvm_unreachable("Only Fixed-Length and SVE Vector types are handled here");
10995 // Reject cases where the vector element type or the scalar element type are
10996 // not integral or floating point types.
10997 if (!VectorEltTy
->isArithmeticType() || !ScalarTy
->isArithmeticType())
11000 // The conversion to apply to the scalar before splatting it,
11002 CastKind ScalarCast
= CK_NoOp
;
11004 // Accept cases where the vector elements are integers and the scalar is
11006 // FIXME: Notionally if the scalar was a floating point value with a precise
11007 // integral representation, we could cast it to an appropriate integer
11008 // type and then perform the rest of the checks here. GCC will perform
11009 // this conversion in some cases as determined by the input language.
11010 // We should accept it on a language independent basis.
11011 if (VectorEltTy
->isIntegralType(S
.Context
) &&
11012 ScalarTy
->isIntegralType(S
.Context
) &&
11013 S
.Context
.getIntegerTypeOrder(VectorEltTy
, ScalarTy
)) {
11015 if (canConvertIntToOtherIntTy(S
, Scalar
, VectorEltTy
))
11018 ScalarCast
= CK_IntegralCast
;
11019 } else if (VectorEltTy
->isIntegralType(S
.Context
) &&
11020 ScalarTy
->isRealFloatingType()) {
11021 if (S
.Context
.getTypeSize(VectorEltTy
) == S
.Context
.getTypeSize(ScalarTy
))
11022 ScalarCast
= CK_FloatingToIntegral
;
11025 } else if (VectorEltTy
->isRealFloatingType()) {
11026 if (ScalarTy
->isRealFloatingType()) {
11028 // Reject cases where the scalar type is not a constant and has a higher
11029 // Order than the vector element type.
11030 llvm::APFloat
Result(0.0);
11032 // Determine whether this is a constant scalar. In the event that the
11033 // value is dependent (and thus cannot be evaluated by the constant
11034 // evaluator), skip the evaluation. This will then diagnose once the
11035 // expression is instantiated.
11036 bool CstScalar
= Scalar
->get()->isValueDependent() ||
11037 Scalar
->get()->EvaluateAsFloat(Result
, S
.Context
);
11038 int Order
= S
.Context
.getFloatingTypeOrder(VectorEltTy
, ScalarTy
);
11039 if (!CstScalar
&& Order
< 0)
11042 // If the scalar cannot be safely casted to the vector element type,
11045 bool Truncated
= false;
11046 Result
.convert(S
.Context
.getFloatTypeSemantics(VectorEltTy
),
11047 llvm::APFloat::rmNearestTiesToEven
, &Truncated
);
11052 ScalarCast
= CK_FloatingCast
;
11053 } else if (ScalarTy
->isIntegralType(S
.Context
)) {
11054 if (canConvertIntTyToFloatTy(S
, Scalar
, VectorEltTy
))
11057 ScalarCast
= CK_IntegralToFloating
;
11060 } else if (ScalarTy
->isEnumeralType())
11063 // Adjust scalar if desired.
11064 if (ScalarCast
!= CK_NoOp
)
11065 *Scalar
= S
.ImpCastExprToType(Scalar
->get(), VectorEltTy
, ScalarCast
);
11066 *Scalar
= S
.ImpCastExprToType(Scalar
->get(), VectorTy
, CK_VectorSplat
);
11070 QualType
Sema::CheckVectorOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11071 SourceLocation Loc
, bool IsCompAssign
,
11072 bool AllowBothBool
,
11073 bool AllowBoolConversions
,
11074 bool AllowBoolOperation
,
11075 bool ReportInvalid
) {
11076 if (!IsCompAssign
) {
11077 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
11078 if (LHS
.isInvalid())
11081 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
11082 if (RHS
.isInvalid())
11085 // For conversion purposes, we ignore any qualifiers.
11086 // For example, "const float" and "float" are equivalent.
11087 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
11088 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
11090 const VectorType
*LHSVecType
= LHSType
->getAs
<VectorType
>();
11091 const VectorType
*RHSVecType
= RHSType
->getAs
<VectorType
>();
11092 assert(LHSVecType
|| RHSVecType
);
11094 // AltiVec-style "vector bool op vector bool" combinations are allowed
11095 // for some operators but not others.
11096 if (!AllowBothBool
&& LHSVecType
&&
11097 LHSVecType
->getVectorKind() == VectorKind::AltiVecBool
&& RHSVecType
&&
11098 RHSVecType
->getVectorKind() == VectorKind::AltiVecBool
)
11099 return ReportInvalid
? InvalidOperands(Loc
, LHS
, RHS
) : QualType();
11101 // This operation may not be performed on boolean vectors.
11102 if (!AllowBoolOperation
&&
11103 (LHSType
->isExtVectorBoolType() || RHSType
->isExtVectorBoolType()))
11104 return ReportInvalid
? InvalidOperands(Loc
, LHS
, RHS
) : QualType();
11106 // If the vector types are identical, return.
11107 if (Context
.hasSameType(LHSType
, RHSType
))
11108 return Context
.getCommonSugaredType(LHSType
, RHSType
);
11110 // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
11111 if (LHSVecType
&& RHSVecType
&&
11112 Context
.areCompatibleVectorTypes(LHSType
, RHSType
)) {
11113 if (isa
<ExtVectorType
>(LHSVecType
)) {
11114 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
11119 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
11123 // AllowBoolConversions says that bool and non-bool AltiVec vectors
11124 // can be mixed, with the result being the non-bool type. The non-bool
11125 // operand must have integer element type.
11126 if (AllowBoolConversions
&& LHSVecType
&& RHSVecType
&&
11127 LHSVecType
->getNumElements() == RHSVecType
->getNumElements() &&
11128 (Context
.getTypeSize(LHSVecType
->getElementType()) ==
11129 Context
.getTypeSize(RHSVecType
->getElementType()))) {
11130 if (LHSVecType
->getVectorKind() == VectorKind::AltiVecVector
&&
11131 LHSVecType
->getElementType()->isIntegerType() &&
11132 RHSVecType
->getVectorKind() == VectorKind::AltiVecBool
) {
11133 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
11136 if (!IsCompAssign
&&
11137 LHSVecType
->getVectorKind() == VectorKind::AltiVecBool
&&
11138 RHSVecType
->getVectorKind() == VectorKind::AltiVecVector
&&
11139 RHSVecType
->getElementType()->isIntegerType()) {
11140 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
11145 // Expressions containing fixed-length and sizeless SVE/RVV vectors are
11146 // invalid since the ambiguity can affect the ABI.
11147 auto IsSveRVVConversion
= [](QualType FirstType
, QualType SecondType
,
11148 unsigned &SVEorRVV
) {
11149 const VectorType
*VecType
= SecondType
->getAs
<VectorType
>();
11151 if (FirstType
->isSizelessBuiltinType() && VecType
) {
11152 if (VecType
->getVectorKind() == VectorKind::SveFixedLengthData
||
11153 VecType
->getVectorKind() == VectorKind::SveFixedLengthPredicate
)
11155 if (VecType
->getVectorKind() == VectorKind::RVVFixedLengthData
) {
11165 if (IsSveRVVConversion(LHSType
, RHSType
, SVEorRVV
) ||
11166 IsSveRVVConversion(RHSType
, LHSType
, SVEorRVV
)) {
11167 Diag(Loc
, diag::err_typecheck_sve_rvv_ambiguous
)
11168 << SVEorRVV
<< LHSType
<< RHSType
;
11172 // Expressions containing GNU and SVE or RVV (fixed or sizeless) vectors are
11173 // invalid since the ambiguity can affect the ABI.
11174 auto IsSveRVVGnuConversion
= [](QualType FirstType
, QualType SecondType
,
11175 unsigned &SVEorRVV
) {
11176 const VectorType
*FirstVecType
= FirstType
->getAs
<VectorType
>();
11177 const VectorType
*SecondVecType
= SecondType
->getAs
<VectorType
>();
11180 if (FirstVecType
&& SecondVecType
) {
11181 if (FirstVecType
->getVectorKind() == VectorKind::Generic
) {
11182 if (SecondVecType
->getVectorKind() == VectorKind::SveFixedLengthData
||
11183 SecondVecType
->getVectorKind() ==
11184 VectorKind::SveFixedLengthPredicate
)
11186 if (SecondVecType
->getVectorKind() == VectorKind::RVVFixedLengthData
) {
11194 if (SecondVecType
&&
11195 SecondVecType
->getVectorKind() == VectorKind::Generic
) {
11196 if (FirstType
->isSVESizelessBuiltinType())
11198 if (FirstType
->isRVVSizelessBuiltinType()) {
11207 if (IsSveRVVGnuConversion(LHSType
, RHSType
, SVEorRVV
) ||
11208 IsSveRVVGnuConversion(RHSType
, LHSType
, SVEorRVV
)) {
11209 Diag(Loc
, diag::err_typecheck_sve_rvv_gnu_ambiguous
)
11210 << SVEorRVV
<< LHSType
<< RHSType
;
11214 // If there's a vector type and a scalar, try to convert the scalar to
11215 // the vector element type and splat.
11216 unsigned DiagID
= diag::err_typecheck_vector_not_convertable
;
11218 if (isa
<ExtVectorType
>(LHSVecType
)) {
11219 if (!tryVectorConvertAndSplat(*this, &RHS
, RHSType
,
11220 LHSVecType
->getElementType(), LHSType
,
11224 if (!tryGCCVectorConvertAndSplat(*this, &RHS
, &LHS
))
11229 if (isa
<ExtVectorType
>(RHSVecType
)) {
11230 if (!tryVectorConvertAndSplat(*this, (IsCompAssign
? nullptr : &LHS
),
11231 LHSType
, RHSVecType
->getElementType(),
11235 if (LHS
.get()->isLValue() ||
11236 !tryGCCVectorConvertAndSplat(*this, &LHS
, &RHS
))
11241 // FIXME: The code below also handles conversion between vectors and
11242 // non-scalars, we should break this down into fine grained specific checks
11243 // and emit proper diagnostics.
11244 QualType VecType
= LHSVecType
? LHSType
: RHSType
;
11245 const VectorType
*VT
= LHSVecType
? LHSVecType
: RHSVecType
;
11246 QualType OtherType
= LHSVecType
? RHSType
: LHSType
;
11247 ExprResult
*OtherExpr
= LHSVecType
? &RHS
: &LHS
;
11248 if (isLaxVectorConversion(OtherType
, VecType
)) {
11249 if (Context
.getTargetInfo().getTriple().isPPC() &&
11250 anyAltivecTypes(RHSType
, LHSType
) &&
11251 !Context
.areCompatibleVectorTypes(RHSType
, LHSType
))
11252 Diag(Loc
, diag::warn_deprecated_lax_vec_conv_all
) << RHSType
<< LHSType
;
11253 // If we're allowing lax vector conversions, only the total (data) size
11254 // needs to be the same. For non compound assignment, if one of the types is
11255 // scalar, the result is always the vector type.
11256 if (!IsCompAssign
) {
11257 *OtherExpr
= ImpCastExprToType(OtherExpr
->get(), VecType
, CK_BitCast
);
11259 // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
11260 // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
11261 // type. Note that this is already done by non-compound assignments in
11262 // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
11263 // <1 x T> -> T. The result is also a vector type.
11264 } else if (OtherType
->isExtVectorType() || OtherType
->isVectorType() ||
11265 (OtherType
->isScalarType() && VT
->getNumElements() == 1)) {
11266 ExprResult
*RHSExpr
= &RHS
;
11267 *RHSExpr
= ImpCastExprToType(RHSExpr
->get(), LHSType
, CK_BitCast
);
11272 // Okay, the expression is invalid.
11274 // If there's a non-vector, non-real operand, diagnose that.
11275 if ((!RHSVecType
&& !RHSType
->isRealType()) ||
11276 (!LHSVecType
&& !LHSType
->isRealType())) {
11277 Diag(Loc
, diag::err_typecheck_vector_not_convertable_non_scalar
)
11278 << LHSType
<< RHSType
11279 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11283 // OpenCL V1.1 6.2.6.p1:
11284 // If the operands are of more than one vector type, then an error shall
11285 // occur. Implicit conversions between vector types are not permitted, per
11287 if (getLangOpts().OpenCL
&&
11288 RHSVecType
&& isa
<ExtVectorType
>(RHSVecType
) &&
11289 LHSVecType
&& isa
<ExtVectorType
>(LHSVecType
)) {
11290 Diag(Loc
, diag::err_opencl_implicit_vector_conversion
) << LHSType
11296 // If there is a vector type that is not a ExtVector and a scalar, we reach
11297 // this point if scalar could not be converted to the vector's element type
11298 // without truncation.
11299 if ((RHSVecType
&& !isa
<ExtVectorType
>(RHSVecType
)) ||
11300 (LHSVecType
&& !isa
<ExtVectorType
>(LHSVecType
))) {
11301 QualType Scalar
= LHSVecType
? RHSType
: LHSType
;
11302 QualType Vector
= LHSVecType
? LHSType
: RHSType
;
11303 unsigned ScalarOrVector
= LHSVecType
&& RHSVecType
? 1 : 0;
11305 diag::err_typecheck_vector_not_convertable_implict_truncation
)
11306 << ScalarOrVector
<< Scalar
<< Vector
;
11311 // Otherwise, use the generic diagnostic.
11313 << LHSType
<< RHSType
11314 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11318 QualType
Sema::CheckSizelessVectorOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11319 SourceLocation Loc
,
11321 ArithConvKind OperationKind
) {
11322 if (!IsCompAssign
) {
11323 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
11324 if (LHS
.isInvalid())
11327 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
11328 if (RHS
.isInvalid())
11331 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
11332 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
11334 const BuiltinType
*LHSBuiltinTy
= LHSType
->getAs
<BuiltinType
>();
11335 const BuiltinType
*RHSBuiltinTy
= RHSType
->getAs
<BuiltinType
>();
11337 unsigned DiagID
= diag::err_typecheck_invalid_operands
;
11338 if ((OperationKind
== ACK_Arithmetic
) &&
11339 ((LHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool()) ||
11340 (RHSBuiltinTy
&& RHSBuiltinTy
->isSVEBool()))) {
11341 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
11342 << RHS
.get()->getSourceRange();
11346 if (Context
.hasSameType(LHSType
, RHSType
))
11349 if (LHSType
->isSveVLSBuiltinType() && !RHSType
->isSveVLSBuiltinType()) {
11350 if (!tryGCCVectorConvertAndSplat(*this, &RHS
, &LHS
))
11353 if (RHSType
->isSveVLSBuiltinType() && !LHSType
->isSveVLSBuiltinType()) {
11354 if (LHS
.get()->isLValue() ||
11355 !tryGCCVectorConvertAndSplat(*this, &LHS
, &RHS
))
11359 if ((!LHSType
->isSveVLSBuiltinType() && !LHSType
->isRealType()) ||
11360 (!RHSType
->isSveVLSBuiltinType() && !RHSType
->isRealType())) {
11361 Diag(Loc
, diag::err_typecheck_vector_not_convertable_non_scalar
)
11362 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
11363 << RHS
.get()->getSourceRange();
11367 if (LHSType
->isSveVLSBuiltinType() && RHSType
->isSveVLSBuiltinType() &&
11368 Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
!=
11369 Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
) {
11370 Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
11371 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
11372 << RHS
.get()->getSourceRange();
11376 if (LHSType
->isSveVLSBuiltinType() || RHSType
->isSveVLSBuiltinType()) {
11377 QualType Scalar
= LHSType
->isSveVLSBuiltinType() ? RHSType
: LHSType
;
11378 QualType Vector
= LHSType
->isSveVLSBuiltinType() ? LHSType
: RHSType
;
11379 bool ScalarOrVector
=
11380 LHSType
->isSveVLSBuiltinType() && RHSType
->isSveVLSBuiltinType();
11382 Diag(Loc
, diag::err_typecheck_vector_not_convertable_implict_truncation
)
11383 << ScalarOrVector
<< Scalar
<< Vector
;
11388 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
11389 << RHS
.get()->getSourceRange();
11393 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
11394 // expression. These are mainly cases where the null pointer is used as an
11395 // integer instead of a pointer.
11396 static void checkArithmeticNull(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
11397 SourceLocation Loc
, bool IsCompare
) {
11398 // The canonical way to check for a GNU null is with isNullPointerConstant,
11399 // but we use a bit of a hack here for speed; this is a relatively
11400 // hot path, and isNullPointerConstant is slow.
11401 bool LHSNull
= isa
<GNUNullExpr
>(LHS
.get()->IgnoreParenImpCasts());
11402 bool RHSNull
= isa
<GNUNullExpr
>(RHS
.get()->IgnoreParenImpCasts());
11404 QualType NonNullType
= LHSNull
? RHS
.get()->getType() : LHS
.get()->getType();
11406 // Avoid analyzing cases where the result will either be invalid (and
11407 // diagnosed as such) or entirely valid and not something to warn about.
11408 if ((!LHSNull
&& !RHSNull
) || NonNullType
->isBlockPointerType() ||
11409 NonNullType
->isMemberPointerType() || NonNullType
->isFunctionType())
11412 // Comparison operations would not make sense with a null pointer no matter
11413 // what the other expression is.
11415 S
.Diag(Loc
, diag::warn_null_in_arithmetic_operation
)
11416 << (LHSNull
? LHS
.get()->getSourceRange() : SourceRange())
11417 << (RHSNull
? RHS
.get()->getSourceRange() : SourceRange());
11421 // The rest of the operations only make sense with a null pointer
11422 // if the other expression is a pointer.
11423 if (LHSNull
== RHSNull
|| NonNullType
->isAnyPointerType() ||
11424 NonNullType
->canDecayToPointerType())
11427 S
.Diag(Loc
, diag::warn_null_in_comparison_operation
)
11428 << LHSNull
/* LHS is NULL */ << NonNullType
11429 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
11432 static void DiagnoseDivisionSizeofPointerOrArray(Sema
&S
, Expr
*LHS
, Expr
*RHS
,
11433 SourceLocation Loc
) {
11434 const auto *LUE
= dyn_cast
<UnaryExprOrTypeTraitExpr
>(LHS
);
11435 const auto *RUE
= dyn_cast
<UnaryExprOrTypeTraitExpr
>(RHS
);
11438 if (LUE
->getKind() != UETT_SizeOf
|| LUE
->isArgumentType() ||
11439 RUE
->getKind() != UETT_SizeOf
)
11442 const Expr
*LHSArg
= LUE
->getArgumentExpr()->IgnoreParens();
11443 QualType LHSTy
= LHSArg
->getType();
11446 if (RUE
->isArgumentType())
11447 RHSTy
= RUE
->getArgumentType().getNonReferenceType();
11449 RHSTy
= RUE
->getArgumentExpr()->IgnoreParens()->getType();
11451 if (LHSTy
->isPointerType() && !RHSTy
->isPointerType()) {
11452 if (!S
.Context
.hasSameUnqualifiedType(LHSTy
->getPointeeType(), RHSTy
))
11455 S
.Diag(Loc
, diag::warn_division_sizeof_ptr
) << LHS
<< LHS
->getSourceRange();
11456 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(LHSArg
)) {
11457 if (const ValueDecl
*LHSArgDecl
= DRE
->getDecl())
11458 S
.Diag(LHSArgDecl
->getLocation(), diag::note_pointer_declared_here
)
11461 } else if (const auto *ArrayTy
= S
.Context
.getAsArrayType(LHSTy
)) {
11462 QualType ArrayElemTy
= ArrayTy
->getElementType();
11463 if (ArrayElemTy
!= S
.Context
.getBaseElementType(ArrayTy
) ||
11464 ArrayElemTy
->isDependentType() || RHSTy
->isDependentType() ||
11465 RHSTy
->isReferenceType() || ArrayElemTy
->isCharType() ||
11466 S
.Context
.getTypeSize(ArrayElemTy
) == S
.Context
.getTypeSize(RHSTy
))
11468 S
.Diag(Loc
, diag::warn_division_sizeof_array
)
11469 << LHSArg
->getSourceRange() << ArrayElemTy
<< RHSTy
;
11470 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(LHSArg
)) {
11471 if (const ValueDecl
*LHSArgDecl
= DRE
->getDecl())
11472 S
.Diag(LHSArgDecl
->getLocation(), diag::note_array_declared_here
)
11476 S
.Diag(Loc
, diag::note_precedence_silence
) << RHS
;
11480 static void DiagnoseBadDivideOrRemainderValues(Sema
& S
, ExprResult
&LHS
,
11482 SourceLocation Loc
, bool IsDiv
) {
11483 // Check for division/remainder by zero.
11484 Expr::EvalResult RHSValue
;
11485 if (!RHS
.get()->isValueDependent() &&
11486 RHS
.get()->EvaluateAsInt(RHSValue
, S
.Context
) &&
11487 RHSValue
.Val
.getInt() == 0)
11488 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
11489 S
.PDiag(diag::warn_remainder_division_by_zero
)
11490 << IsDiv
<< RHS
.get()->getSourceRange());
11493 QualType
Sema::CheckMultiplyDivideOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11494 SourceLocation Loc
,
11495 bool IsCompAssign
, bool IsDiv
) {
11496 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11498 QualType LHSTy
= LHS
.get()->getType();
11499 QualType RHSTy
= RHS
.get()->getType();
11500 if (LHSTy
->isVectorType() || RHSTy
->isVectorType())
11501 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
11502 /*AllowBothBool*/ getLangOpts().AltiVec
,
11503 /*AllowBoolConversions*/ false,
11504 /*AllowBooleanOperation*/ false,
11505 /*ReportInvalid*/ true);
11506 if (LHSTy
->isSveVLSBuiltinType() || RHSTy
->isSveVLSBuiltinType())
11507 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
11510 (LHSTy
->isConstantMatrixType() || RHSTy
->isConstantMatrixType()))
11511 return CheckMatrixMultiplyOperands(LHS
, RHS
, Loc
, IsCompAssign
);
11512 // For division, only matrix-by-scalar is supported. Other combinations with
11513 // matrix types are invalid.
11514 if (IsDiv
&& LHSTy
->isConstantMatrixType() && RHSTy
->isArithmeticType())
11515 return CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, IsCompAssign
);
11517 QualType compType
= UsualArithmeticConversions(
11518 LHS
, RHS
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_Arithmetic
);
11519 if (LHS
.isInvalid() || RHS
.isInvalid())
11523 if (compType
.isNull() || !compType
->isArithmeticType())
11524 return InvalidOperands(Loc
, LHS
, RHS
);
11526 DiagnoseBadDivideOrRemainderValues(*this, LHS
, RHS
, Loc
, IsDiv
);
11527 DiagnoseDivisionSizeofPointerOrArray(*this, LHS
.get(), RHS
.get(), Loc
);
11532 QualType
Sema::CheckRemainderOperands(
11533 ExprResult
&LHS
, ExprResult
&RHS
, SourceLocation Loc
, bool IsCompAssign
) {
11534 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11536 if (LHS
.get()->getType()->isVectorType() ||
11537 RHS
.get()->getType()->isVectorType()) {
11538 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
11539 RHS
.get()->getType()->hasIntegerRepresentation())
11540 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
11541 /*AllowBothBool*/ getLangOpts().AltiVec
,
11542 /*AllowBoolConversions*/ false,
11543 /*AllowBooleanOperation*/ false,
11544 /*ReportInvalid*/ true);
11545 return InvalidOperands(Loc
, LHS
, RHS
);
11548 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
11549 RHS
.get()->getType()->isSveVLSBuiltinType()) {
11550 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
11551 RHS
.get()->getType()->hasIntegerRepresentation())
11552 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
11555 return InvalidOperands(Loc
, LHS
, RHS
);
11558 QualType compType
= UsualArithmeticConversions(
11559 LHS
, RHS
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_Arithmetic
);
11560 if (LHS
.isInvalid() || RHS
.isInvalid())
11563 if (compType
.isNull() || !compType
->isIntegerType())
11564 return InvalidOperands(Loc
, LHS
, RHS
);
11565 DiagnoseBadDivideOrRemainderValues(*this, LHS
, RHS
, Loc
, false /* IsDiv */);
11569 /// Diagnose invalid arithmetic on two void pointers.
11570 static void diagnoseArithmeticOnTwoVoidPointers(Sema
&S
, SourceLocation Loc
,
11571 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11572 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
11573 ? diag::err_typecheck_pointer_arith_void_type
11574 : diag::ext_gnu_void_ptr
)
11575 << 1 /* two pointers */ << LHSExpr
->getSourceRange()
11576 << RHSExpr
->getSourceRange();
11579 /// Diagnose invalid arithmetic on a void pointer.
11580 static void diagnoseArithmeticOnVoidPointer(Sema
&S
, SourceLocation Loc
,
11582 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
11583 ? diag::err_typecheck_pointer_arith_void_type
11584 : diag::ext_gnu_void_ptr
)
11585 << 0 /* one pointer */ << Pointer
->getSourceRange();
11588 /// Diagnose invalid arithmetic on a null pointer.
11590 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
11591 /// idiom, which we recognize as a GNU extension.
11593 static void diagnoseArithmeticOnNullPointer(Sema
&S
, SourceLocation Loc
,
11594 Expr
*Pointer
, bool IsGNUIdiom
) {
11596 S
.Diag(Loc
, diag::warn_gnu_null_ptr_arith
)
11597 << Pointer
->getSourceRange();
11599 S
.Diag(Loc
, diag::warn_pointer_arith_null_ptr
)
11600 << S
.getLangOpts().CPlusPlus
<< Pointer
->getSourceRange();
11603 /// Diagnose invalid subraction on a null pointer.
11605 static void diagnoseSubtractionOnNullPointer(Sema
&S
, SourceLocation Loc
,
11606 Expr
*Pointer
, bool BothNull
) {
11607 // Null - null is valid in C++ [expr.add]p7
11608 if (BothNull
&& S
.getLangOpts().CPlusPlus
)
11611 // Is this s a macro from a system header?
11612 if (S
.Diags
.getSuppressSystemWarnings() && S
.SourceMgr
.isInSystemMacro(Loc
))
11615 S
.DiagRuntimeBehavior(Loc
, Pointer
,
11616 S
.PDiag(diag::warn_pointer_sub_null_ptr
)
11617 << S
.getLangOpts().CPlusPlus
11618 << Pointer
->getSourceRange());
11621 /// Diagnose invalid arithmetic on two function pointers.
11622 static void diagnoseArithmeticOnTwoFunctionPointers(Sema
&S
, SourceLocation Loc
,
11623 Expr
*LHS
, Expr
*RHS
) {
11624 assert(LHS
->getType()->isAnyPointerType());
11625 assert(RHS
->getType()->isAnyPointerType());
11626 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
11627 ? diag::err_typecheck_pointer_arith_function_type
11628 : diag::ext_gnu_ptr_func_arith
)
11629 << 1 /* two pointers */ << LHS
->getType()->getPointeeType()
11630 // We only show the second type if it differs from the first.
11631 << (unsigned)!S
.Context
.hasSameUnqualifiedType(LHS
->getType(),
11633 << RHS
->getType()->getPointeeType()
11634 << LHS
->getSourceRange() << RHS
->getSourceRange();
11637 /// Diagnose invalid arithmetic on a function pointer.
11638 static void diagnoseArithmeticOnFunctionPointer(Sema
&S
, SourceLocation Loc
,
11640 assert(Pointer
->getType()->isAnyPointerType());
11641 S
.Diag(Loc
, S
.getLangOpts().CPlusPlus
11642 ? diag::err_typecheck_pointer_arith_function_type
11643 : diag::ext_gnu_ptr_func_arith
)
11644 << 0 /* one pointer */ << Pointer
->getType()->getPointeeType()
11645 << 0 /* one pointer, so only one type */
11646 << Pointer
->getSourceRange();
11649 /// Emit error if Operand is incomplete pointer type
11651 /// \returns True if pointer has incomplete type
11652 static bool checkArithmeticIncompletePointerType(Sema
&S
, SourceLocation Loc
,
11654 QualType ResType
= Operand
->getType();
11655 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
11656 ResType
= ResAtomicType
->getValueType();
11658 assert(ResType
->isAnyPointerType() && !ResType
->isDependentType());
11659 QualType PointeeTy
= ResType
->getPointeeType();
11660 return S
.RequireCompleteSizedType(
11662 diag::err_typecheck_arithmetic_incomplete_or_sizeless_type
,
11663 Operand
->getSourceRange());
11666 /// Check the validity of an arithmetic pointer operand.
11668 /// If the operand has pointer type, this code will check for pointer types
11669 /// which are invalid in arithmetic operations. These will be diagnosed
11670 /// appropriately, including whether or not the use is supported as an
11673 /// \returns True when the operand is valid to use (even if as an extension).
11674 static bool checkArithmeticOpPointerOperand(Sema
&S
, SourceLocation Loc
,
11676 QualType ResType
= Operand
->getType();
11677 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
11678 ResType
= ResAtomicType
->getValueType();
11680 if (!ResType
->isAnyPointerType()) return true;
11682 QualType PointeeTy
= ResType
->getPointeeType();
11683 if (PointeeTy
->isVoidType()) {
11684 diagnoseArithmeticOnVoidPointer(S
, Loc
, Operand
);
11685 return !S
.getLangOpts().CPlusPlus
;
11687 if (PointeeTy
->isFunctionType()) {
11688 diagnoseArithmeticOnFunctionPointer(S
, Loc
, Operand
);
11689 return !S
.getLangOpts().CPlusPlus
;
11692 if (checkArithmeticIncompletePointerType(S
, Loc
, Operand
)) return false;
11697 /// Check the validity of a binary arithmetic operation w.r.t. pointer
11700 /// This routine will diagnose any invalid arithmetic on pointer operands much
11701 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
11702 /// for emitting a single diagnostic even for operations where both LHS and RHS
11703 /// are (potentially problematic) pointers.
11705 /// \returns True when the operand is valid to use (even if as an extension).
11706 static bool checkArithmeticBinOpPointerOperands(Sema
&S
, SourceLocation Loc
,
11707 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11708 bool isLHSPointer
= LHSExpr
->getType()->isAnyPointerType();
11709 bool isRHSPointer
= RHSExpr
->getType()->isAnyPointerType();
11710 if (!isLHSPointer
&& !isRHSPointer
) return true;
11712 QualType LHSPointeeTy
, RHSPointeeTy
;
11713 if (isLHSPointer
) LHSPointeeTy
= LHSExpr
->getType()->getPointeeType();
11714 if (isRHSPointer
) RHSPointeeTy
= RHSExpr
->getType()->getPointeeType();
11716 // if both are pointers check if operation is valid wrt address spaces
11717 if (isLHSPointer
&& isRHSPointer
) {
11718 if (!LHSPointeeTy
.isAddressSpaceOverlapping(RHSPointeeTy
)) {
11720 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
11721 << LHSExpr
->getType() << RHSExpr
->getType() << 1 /*arithmetic op*/
11722 << LHSExpr
->getSourceRange() << RHSExpr
->getSourceRange();
11727 // Check for arithmetic on pointers to incomplete types.
11728 bool isLHSVoidPtr
= isLHSPointer
&& LHSPointeeTy
->isVoidType();
11729 bool isRHSVoidPtr
= isRHSPointer
&& RHSPointeeTy
->isVoidType();
11730 if (isLHSVoidPtr
|| isRHSVoidPtr
) {
11731 if (!isRHSVoidPtr
) diagnoseArithmeticOnVoidPointer(S
, Loc
, LHSExpr
);
11732 else if (!isLHSVoidPtr
) diagnoseArithmeticOnVoidPointer(S
, Loc
, RHSExpr
);
11733 else diagnoseArithmeticOnTwoVoidPointers(S
, Loc
, LHSExpr
, RHSExpr
);
11735 return !S
.getLangOpts().CPlusPlus
;
11738 bool isLHSFuncPtr
= isLHSPointer
&& LHSPointeeTy
->isFunctionType();
11739 bool isRHSFuncPtr
= isRHSPointer
&& RHSPointeeTy
->isFunctionType();
11740 if (isLHSFuncPtr
|| isRHSFuncPtr
) {
11741 if (!isRHSFuncPtr
) diagnoseArithmeticOnFunctionPointer(S
, Loc
, LHSExpr
);
11742 else if (!isLHSFuncPtr
) diagnoseArithmeticOnFunctionPointer(S
, Loc
,
11744 else diagnoseArithmeticOnTwoFunctionPointers(S
, Loc
, LHSExpr
, RHSExpr
);
11746 return !S
.getLangOpts().CPlusPlus
;
11749 if (isLHSPointer
&& checkArithmeticIncompletePointerType(S
, Loc
, LHSExpr
))
11751 if (isRHSPointer
&& checkArithmeticIncompletePointerType(S
, Loc
, RHSExpr
))
11757 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
11759 static void diagnoseStringPlusInt(Sema
&Self
, SourceLocation OpLoc
,
11760 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11761 StringLiteral
* StrExpr
= dyn_cast
<StringLiteral
>(LHSExpr
->IgnoreImpCasts());
11762 Expr
* IndexExpr
= RHSExpr
;
11764 StrExpr
= dyn_cast
<StringLiteral
>(RHSExpr
->IgnoreImpCasts());
11765 IndexExpr
= LHSExpr
;
11768 bool IsStringPlusInt
= StrExpr
&&
11769 IndexExpr
->getType()->isIntegralOrUnscopedEnumerationType();
11770 if (!IsStringPlusInt
|| IndexExpr
->isValueDependent())
11773 SourceRange
DiagRange(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
11774 Self
.Diag(OpLoc
, diag::warn_string_plus_int
)
11775 << DiagRange
<< IndexExpr
->IgnoreImpCasts()->getType();
11777 // Only print a fixit for "str" + int, not for int + "str".
11778 if (IndexExpr
== RHSExpr
) {
11779 SourceLocation EndLoc
= Self
.getLocForEndOfToken(RHSExpr
->getEndLoc());
11780 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
)
11781 << FixItHint::CreateInsertion(LHSExpr
->getBeginLoc(), "&")
11782 << FixItHint::CreateReplacement(SourceRange(OpLoc
), "[")
11783 << FixItHint::CreateInsertion(EndLoc
, "]");
11785 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
);
11788 /// Emit a warning when adding a char literal to a string.
11789 static void diagnoseStringPlusChar(Sema
&Self
, SourceLocation OpLoc
,
11790 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11791 const Expr
*StringRefExpr
= LHSExpr
;
11792 const CharacterLiteral
*CharExpr
=
11793 dyn_cast
<CharacterLiteral
>(RHSExpr
->IgnoreImpCasts());
11796 CharExpr
= dyn_cast
<CharacterLiteral
>(LHSExpr
->IgnoreImpCasts());
11797 StringRefExpr
= RHSExpr
;
11800 if (!CharExpr
|| !StringRefExpr
)
11803 const QualType StringType
= StringRefExpr
->getType();
11805 // Return if not a PointerType.
11806 if (!StringType
->isAnyPointerType())
11809 // Return if not a CharacterType.
11810 if (!StringType
->getPointeeType()->isAnyCharacterType())
11813 ASTContext
&Ctx
= Self
.getASTContext();
11814 SourceRange
DiagRange(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
11816 const QualType CharType
= CharExpr
->getType();
11817 if (!CharType
->isAnyCharacterType() &&
11818 CharType
->isIntegerType() &&
11819 llvm::isUIntN(Ctx
.getCharWidth(), CharExpr
->getValue())) {
11820 Self
.Diag(OpLoc
, diag::warn_string_plus_char
)
11821 << DiagRange
<< Ctx
.CharTy
;
11823 Self
.Diag(OpLoc
, diag::warn_string_plus_char
)
11824 << DiagRange
<< CharExpr
->getType();
11827 // Only print a fixit for str + char, not for char + str.
11828 if (isa
<CharacterLiteral
>(RHSExpr
->IgnoreImpCasts())) {
11829 SourceLocation EndLoc
= Self
.getLocForEndOfToken(RHSExpr
->getEndLoc());
11830 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
)
11831 << FixItHint::CreateInsertion(LHSExpr
->getBeginLoc(), "&")
11832 << FixItHint::CreateReplacement(SourceRange(OpLoc
), "[")
11833 << FixItHint::CreateInsertion(EndLoc
, "]");
11835 Self
.Diag(OpLoc
, diag::note_string_plus_scalar_silence
);
11839 /// Emit error when two pointers are incompatible.
11840 static void diagnosePointerIncompatibility(Sema
&S
, SourceLocation Loc
,
11841 Expr
*LHSExpr
, Expr
*RHSExpr
) {
11842 assert(LHSExpr
->getType()->isAnyPointerType());
11843 assert(RHSExpr
->getType()->isAnyPointerType());
11844 S
.Diag(Loc
, diag::err_typecheck_sub_ptr_compatible
)
11845 << LHSExpr
->getType() << RHSExpr
->getType() << LHSExpr
->getSourceRange()
11846 << RHSExpr
->getSourceRange();
11850 QualType
Sema::CheckAdditionOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11851 SourceLocation Loc
, BinaryOperatorKind Opc
,
11852 QualType
* CompLHSTy
) {
11853 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11855 if (LHS
.get()->getType()->isVectorType() ||
11856 RHS
.get()->getType()->isVectorType()) {
11857 QualType compType
=
11858 CheckVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
,
11859 /*AllowBothBool*/ getLangOpts().AltiVec
,
11860 /*AllowBoolConversions*/ getLangOpts().ZVector
,
11861 /*AllowBooleanOperation*/ false,
11862 /*ReportInvalid*/ true);
11863 if (CompLHSTy
) *CompLHSTy
= compType
;
11867 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
11868 RHS
.get()->getType()->isSveVLSBuiltinType()) {
11869 QualType compType
=
11870 CheckSizelessVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
, ACK_Arithmetic
);
11872 *CompLHSTy
= compType
;
11876 if (LHS
.get()->getType()->isConstantMatrixType() ||
11877 RHS
.get()->getType()->isConstantMatrixType()) {
11878 QualType compType
=
11879 CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, CompLHSTy
);
11881 *CompLHSTy
= compType
;
11885 QualType compType
= UsualArithmeticConversions(
11886 LHS
, RHS
, Loc
, CompLHSTy
? ACK_CompAssign
: ACK_Arithmetic
);
11887 if (LHS
.isInvalid() || RHS
.isInvalid())
11890 // Diagnose "string literal" '+' int and string '+' "char literal".
11891 if (Opc
== BO_Add
) {
11892 diagnoseStringPlusInt(*this, Loc
, LHS
.get(), RHS
.get());
11893 diagnoseStringPlusChar(*this, Loc
, LHS
.get(), RHS
.get());
11896 // handle the common case first (both operands are arithmetic).
11897 if (!compType
.isNull() && compType
->isArithmeticType()) {
11898 if (CompLHSTy
) *CompLHSTy
= compType
;
11902 // Type-checking. Ultimately the pointer's going to be in PExp;
11903 // note that we bias towards the LHS being the pointer.
11904 Expr
*PExp
= LHS
.get(), *IExp
= RHS
.get();
11906 bool isObjCPointer
;
11907 if (PExp
->getType()->isPointerType()) {
11908 isObjCPointer
= false;
11909 } else if (PExp
->getType()->isObjCObjectPointerType()) {
11910 isObjCPointer
= true;
11912 std::swap(PExp
, IExp
);
11913 if (PExp
->getType()->isPointerType()) {
11914 isObjCPointer
= false;
11915 } else if (PExp
->getType()->isObjCObjectPointerType()) {
11916 isObjCPointer
= true;
11918 return InvalidOperands(Loc
, LHS
, RHS
);
11921 assert(PExp
->getType()->isAnyPointerType());
11923 if (!IExp
->getType()->isIntegerType())
11924 return InvalidOperands(Loc
, LHS
, RHS
);
11926 // Adding to a null pointer results in undefined behavior.
11927 if (PExp
->IgnoreParenCasts()->isNullPointerConstant(
11928 Context
, Expr::NPC_ValueDependentIsNotNull
)) {
11929 // In C++ adding zero to a null pointer is defined.
11930 Expr::EvalResult KnownVal
;
11931 if (!getLangOpts().CPlusPlus
||
11932 (!IExp
->isValueDependent() &&
11933 (!IExp
->EvaluateAsInt(KnownVal
, Context
) ||
11934 KnownVal
.Val
.getInt() != 0))) {
11935 // Check the conditions to see if this is the 'p = nullptr + n' idiom.
11936 bool IsGNUIdiom
= BinaryOperator::isNullPointerArithmeticExtension(
11937 Context
, BO_Add
, PExp
, IExp
);
11938 diagnoseArithmeticOnNullPointer(*this, Loc
, PExp
, IsGNUIdiom
);
11942 if (!checkArithmeticOpPointerOperand(*this, Loc
, PExp
))
11945 if (isObjCPointer
&& checkArithmeticOnObjCPointer(*this, Loc
, PExp
))
11948 // Check array bounds for pointer arithemtic
11949 CheckArrayAccess(PExp
, IExp
);
11952 QualType LHSTy
= Context
.isPromotableBitField(LHS
.get());
11953 if (LHSTy
.isNull()) {
11954 LHSTy
= LHS
.get()->getType();
11955 if (Context
.isPromotableIntegerType(LHSTy
))
11956 LHSTy
= Context
.getPromotedIntegerType(LHSTy
);
11958 *CompLHSTy
= LHSTy
;
11961 return PExp
->getType();
11965 QualType
Sema::CheckSubtractionOperands(ExprResult
&LHS
, ExprResult
&RHS
,
11966 SourceLocation Loc
,
11967 QualType
* CompLHSTy
) {
11968 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
11970 if (LHS
.get()->getType()->isVectorType() ||
11971 RHS
.get()->getType()->isVectorType()) {
11972 QualType compType
=
11973 CheckVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
,
11974 /*AllowBothBool*/ getLangOpts().AltiVec
,
11975 /*AllowBoolConversions*/ getLangOpts().ZVector
,
11976 /*AllowBooleanOperation*/ false,
11977 /*ReportInvalid*/ true);
11978 if (CompLHSTy
) *CompLHSTy
= compType
;
11982 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
11983 RHS
.get()->getType()->isSveVLSBuiltinType()) {
11984 QualType compType
=
11985 CheckSizelessVectorOperands(LHS
, RHS
, Loc
, CompLHSTy
, ACK_Arithmetic
);
11987 *CompLHSTy
= compType
;
11991 if (LHS
.get()->getType()->isConstantMatrixType() ||
11992 RHS
.get()->getType()->isConstantMatrixType()) {
11993 QualType compType
=
11994 CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, CompLHSTy
);
11996 *CompLHSTy
= compType
;
12000 QualType compType
= UsualArithmeticConversions(
12001 LHS
, RHS
, Loc
, CompLHSTy
? ACK_CompAssign
: ACK_Arithmetic
);
12002 if (LHS
.isInvalid() || RHS
.isInvalid())
12005 // Enforce type constraints: C99 6.5.6p3.
12007 // Handle the common case first (both operands are arithmetic).
12008 if (!compType
.isNull() && compType
->isArithmeticType()) {
12009 if (CompLHSTy
) *CompLHSTy
= compType
;
12013 // Either ptr - int or ptr - ptr.
12014 if (LHS
.get()->getType()->isAnyPointerType()) {
12015 QualType lpointee
= LHS
.get()->getType()->getPointeeType();
12017 // Diagnose bad cases where we step over interface counts.
12018 if (LHS
.get()->getType()->isObjCObjectPointerType() &&
12019 checkArithmeticOnObjCPointer(*this, Loc
, LHS
.get()))
12022 // The result type of a pointer-int computation is the pointer type.
12023 if (RHS
.get()->getType()->isIntegerType()) {
12024 // Subtracting from a null pointer should produce a warning.
12025 // The last argument to the diagnose call says this doesn't match the
12026 // GNU int-to-pointer idiom.
12027 if (LHS
.get()->IgnoreParenCasts()->isNullPointerConstant(Context
,
12028 Expr::NPC_ValueDependentIsNotNull
)) {
12029 // In C++ adding zero to a null pointer is defined.
12030 Expr::EvalResult KnownVal
;
12031 if (!getLangOpts().CPlusPlus
||
12032 (!RHS
.get()->isValueDependent() &&
12033 (!RHS
.get()->EvaluateAsInt(KnownVal
, Context
) ||
12034 KnownVal
.Val
.getInt() != 0))) {
12035 diagnoseArithmeticOnNullPointer(*this, Loc
, LHS
.get(), false);
12039 if (!checkArithmeticOpPointerOperand(*this, Loc
, LHS
.get()))
12042 // Check array bounds for pointer arithemtic
12043 CheckArrayAccess(LHS
.get(), RHS
.get(), /*ArraySubscriptExpr*/nullptr,
12044 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
12046 if (CompLHSTy
) *CompLHSTy
= LHS
.get()->getType();
12047 return LHS
.get()->getType();
12050 // Handle pointer-pointer subtractions.
12051 if (const PointerType
*RHSPTy
12052 = RHS
.get()->getType()->getAs
<PointerType
>()) {
12053 QualType rpointee
= RHSPTy
->getPointeeType();
12055 if (getLangOpts().CPlusPlus
) {
12056 // Pointee types must be the same: C++ [expr.add]
12057 if (!Context
.hasSameUnqualifiedType(lpointee
, rpointee
)) {
12058 diagnosePointerIncompatibility(*this, Loc
, LHS
.get(), RHS
.get());
12061 // Pointee types must be compatible C99 6.5.6p3
12062 if (!Context
.typesAreCompatible(
12063 Context
.getCanonicalType(lpointee
).getUnqualifiedType(),
12064 Context
.getCanonicalType(rpointee
).getUnqualifiedType())) {
12065 diagnosePointerIncompatibility(*this, Loc
, LHS
.get(), RHS
.get());
12070 if (!checkArithmeticBinOpPointerOperands(*this, Loc
,
12071 LHS
.get(), RHS
.get()))
12074 bool LHSIsNullPtr
= LHS
.get()->IgnoreParenCasts()->isNullPointerConstant(
12075 Context
, Expr::NPC_ValueDependentIsNotNull
);
12076 bool RHSIsNullPtr
= RHS
.get()->IgnoreParenCasts()->isNullPointerConstant(
12077 Context
, Expr::NPC_ValueDependentIsNotNull
);
12079 // Subtracting nullptr or from nullptr is suspect
12081 diagnoseSubtractionOnNullPointer(*this, Loc
, LHS
.get(), RHSIsNullPtr
);
12083 diagnoseSubtractionOnNullPointer(*this, Loc
, RHS
.get(), LHSIsNullPtr
);
12085 // The pointee type may have zero size. As an extension, a structure or
12086 // union may have zero size or an array may have zero length. In this
12087 // case subtraction does not make sense.
12088 if (!rpointee
->isVoidType() && !rpointee
->isFunctionType()) {
12089 CharUnits ElementSize
= Context
.getTypeSizeInChars(rpointee
);
12090 if (ElementSize
.isZero()) {
12091 Diag(Loc
,diag::warn_sub_ptr_zero_size_types
)
12092 << rpointee
.getUnqualifiedType()
12093 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12097 if (CompLHSTy
) *CompLHSTy
= LHS
.get()->getType();
12098 return Context
.getPointerDiffType();
12102 return InvalidOperands(Loc
, LHS
, RHS
);
12105 static bool isScopedEnumerationType(QualType T
) {
12106 if (const EnumType
*ET
= T
->getAs
<EnumType
>())
12107 return ET
->getDecl()->isScoped();
12111 static void DiagnoseBadShiftValues(Sema
& S
, ExprResult
&LHS
, ExprResult
&RHS
,
12112 SourceLocation Loc
, BinaryOperatorKind Opc
,
12113 QualType LHSType
) {
12114 // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
12115 // so skip remaining warnings as we don't want to modify values within Sema.
12116 if (S
.getLangOpts().OpenCL
)
12119 // Check right/shifter operand
12120 Expr::EvalResult RHSResult
;
12121 if (RHS
.get()->isValueDependent() ||
12122 !RHS
.get()->EvaluateAsInt(RHSResult
, S
.Context
))
12124 llvm::APSInt Right
= RHSResult
.Val
.getInt();
12126 if (Right
.isNegative()) {
12127 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
12128 S
.PDiag(diag::warn_shift_negative
)
12129 << RHS
.get()->getSourceRange());
12133 QualType LHSExprType
= LHS
.get()->getType();
12134 uint64_t LeftSize
= S
.Context
.getTypeSize(LHSExprType
);
12135 if (LHSExprType
->isBitIntType())
12136 LeftSize
= S
.Context
.getIntWidth(LHSExprType
);
12137 else if (LHSExprType
->isFixedPointType()) {
12138 auto FXSema
= S
.Context
.getFixedPointSemantics(LHSExprType
);
12139 LeftSize
= FXSema
.getWidth() - (unsigned)FXSema
.hasUnsignedPadding();
12141 if (Right
.uge(LeftSize
)) {
12142 S
.DiagRuntimeBehavior(Loc
, RHS
.get(),
12143 S
.PDiag(diag::warn_shift_gt_typewidth
)
12144 << RHS
.get()->getSourceRange());
12148 // FIXME: We probably need to handle fixed point types specially here.
12149 if (Opc
!= BO_Shl
|| LHSExprType
->isFixedPointType())
12152 // When left shifting an ICE which is signed, we can check for overflow which
12153 // according to C++ standards prior to C++2a has undefined behavior
12154 // ([expr.shift] 5.8/2). Unsigned integers have defined behavior modulo one
12155 // more than the maximum value representable in the result type, so never
12156 // warn for those. (FIXME: Unsigned left-shift overflow in a constant
12157 // expression is still probably a bug.)
12158 Expr::EvalResult LHSResult
;
12159 if (LHS
.get()->isValueDependent() ||
12160 LHSType
->hasUnsignedIntegerRepresentation() ||
12161 !LHS
.get()->EvaluateAsInt(LHSResult
, S
.Context
))
12163 llvm::APSInt Left
= LHSResult
.Val
.getInt();
12165 // Don't warn if signed overflow is defined, then all the rest of the
12166 // diagnostics will not be triggered because the behavior is defined.
12167 // Also don't warn in C++20 mode (and newer), as signed left shifts
12168 // always wrap and never overflow.
12169 if (S
.getLangOpts().isSignedOverflowDefined() || S
.getLangOpts().CPlusPlus20
)
12172 // If LHS does not have a non-negative value then, the
12173 // behavior is undefined before C++2a. Warn about it.
12174 if (Left
.isNegative()) {
12175 S
.DiagRuntimeBehavior(Loc
, LHS
.get(),
12176 S
.PDiag(diag::warn_shift_lhs_negative
)
12177 << LHS
.get()->getSourceRange());
12181 llvm::APInt ResultBits
=
12182 static_cast<llvm::APInt
&>(Right
) + Left
.getSignificantBits();
12183 if (ResultBits
.ule(LeftSize
))
12185 llvm::APSInt Result
= Left
.extend(ResultBits
.getLimitedValue());
12186 Result
= Result
.shl(Right
);
12188 // Print the bit representation of the signed integer as an unsigned
12189 // hexadecimal number.
12190 SmallString
<40> HexResult
;
12191 Result
.toString(HexResult
, 16, /*Signed =*/false, /*Literal =*/true);
12193 // If we are only missing a sign bit, this is less likely to result in actual
12194 // bugs -- if the result is cast back to an unsigned type, it will have the
12195 // expected value. Thus we place this behind a different warning that can be
12196 // turned off separately if needed.
12197 if (ResultBits
- 1 == LeftSize
) {
12198 S
.Diag(Loc
, diag::warn_shift_result_sets_sign_bit
)
12199 << HexResult
<< LHSType
12200 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12204 S
.Diag(Loc
, diag::warn_shift_result_gt_typewidth
)
12205 << HexResult
.str() << Result
.getSignificantBits() << LHSType
12206 << Left
.getBitWidth() << LHS
.get()->getSourceRange()
12207 << RHS
.get()->getSourceRange();
12210 /// Return the resulting type when a vector is shifted
12211 /// by a scalar or vector shift amount.
12212 static QualType
checkVectorShift(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
12213 SourceLocation Loc
, bool IsCompAssign
) {
12214 // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
12215 if ((S
.LangOpts
.OpenCL
|| S
.LangOpts
.ZVector
) &&
12216 !LHS
.get()->getType()->isVectorType()) {
12217 S
.Diag(Loc
, diag::err_shift_rhs_only_vector
)
12218 << RHS
.get()->getType() << LHS
.get()->getType()
12219 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12223 if (!IsCompAssign
) {
12224 LHS
= S
.UsualUnaryConversions(LHS
.get());
12225 if (LHS
.isInvalid()) return QualType();
12228 RHS
= S
.UsualUnaryConversions(RHS
.get());
12229 if (RHS
.isInvalid()) return QualType();
12231 QualType LHSType
= LHS
.get()->getType();
12232 // Note that LHS might be a scalar because the routine calls not only in
12234 const VectorType
*LHSVecTy
= LHSType
->getAs
<VectorType
>();
12235 QualType LHSEleType
= LHSVecTy
? LHSVecTy
->getElementType() : LHSType
;
12237 // Note that RHS might not be a vector.
12238 QualType RHSType
= RHS
.get()->getType();
12239 const VectorType
*RHSVecTy
= RHSType
->getAs
<VectorType
>();
12240 QualType RHSEleType
= RHSVecTy
? RHSVecTy
->getElementType() : RHSType
;
12242 // Do not allow shifts for boolean vectors.
12243 if ((LHSVecTy
&& LHSVecTy
->isExtVectorBoolType()) ||
12244 (RHSVecTy
&& RHSVecTy
->isExtVectorBoolType())) {
12245 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
12246 << LHS
.get()->getType() << RHS
.get()->getType()
12247 << LHS
.get()->getSourceRange();
12251 // The operands need to be integers.
12252 if (!LHSEleType
->isIntegerType()) {
12253 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
12254 << LHS
.get()->getType() << LHS
.get()->getSourceRange();
12258 if (!RHSEleType
->isIntegerType()) {
12259 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
12260 << RHS
.get()->getType() << RHS
.get()->getSourceRange();
12268 if (LHSEleType
!= RHSEleType
) {
12269 LHS
= S
.ImpCastExprToType(LHS
.get(),RHSEleType
, CK_IntegralCast
);
12270 LHSEleType
= RHSEleType
;
12273 S
.Context
.getExtVectorType(LHSEleType
, RHSVecTy
->getNumElements());
12274 LHS
= S
.ImpCastExprToType(LHS
.get(), VecTy
, CK_VectorSplat
);
12276 } else if (RHSVecTy
) {
12277 // OpenCL v1.1 s6.3.j says that for vector types, the operators
12278 // are applied component-wise. So if RHS is a vector, then ensure
12279 // that the number of elements is the same as LHS...
12280 if (RHSVecTy
->getNumElements() != LHSVecTy
->getNumElements()) {
12281 S
.Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
12282 << LHS
.get()->getType() << RHS
.get()->getType()
12283 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12286 if (!S
.LangOpts
.OpenCL
&& !S
.LangOpts
.ZVector
) {
12287 const BuiltinType
*LHSBT
= LHSEleType
->getAs
<clang::BuiltinType
>();
12288 const BuiltinType
*RHSBT
= RHSEleType
->getAs
<clang::BuiltinType
>();
12289 if (LHSBT
!= RHSBT
&&
12290 S
.Context
.getTypeSize(LHSBT
) != S
.Context
.getTypeSize(RHSBT
)) {
12291 S
.Diag(Loc
, diag::warn_typecheck_vector_element_sizes_not_equal
)
12292 << LHS
.get()->getType() << RHS
.get()->getType()
12293 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12297 // ...else expand RHS to match the number of elements in LHS.
12299 S
.Context
.getExtVectorType(RHSEleType
, LHSVecTy
->getNumElements());
12300 RHS
= S
.ImpCastExprToType(RHS
.get(), VecTy
, CK_VectorSplat
);
12306 static QualType
checkSizelessVectorShift(Sema
&S
, ExprResult
&LHS
,
12307 ExprResult
&RHS
, SourceLocation Loc
,
12308 bool IsCompAssign
) {
12309 if (!IsCompAssign
) {
12310 LHS
= S
.UsualUnaryConversions(LHS
.get());
12311 if (LHS
.isInvalid())
12315 RHS
= S
.UsualUnaryConversions(RHS
.get());
12316 if (RHS
.isInvalid())
12319 QualType LHSType
= LHS
.get()->getType();
12320 const BuiltinType
*LHSBuiltinTy
= LHSType
->castAs
<BuiltinType
>();
12321 QualType LHSEleType
= LHSType
->isSveVLSBuiltinType()
12322 ? LHSBuiltinTy
->getSveEltType(S
.getASTContext())
12325 // Note that RHS might not be a vector
12326 QualType RHSType
= RHS
.get()->getType();
12327 const BuiltinType
*RHSBuiltinTy
= RHSType
->castAs
<BuiltinType
>();
12328 QualType RHSEleType
= RHSType
->isSveVLSBuiltinType()
12329 ? RHSBuiltinTy
->getSveEltType(S
.getASTContext())
12332 if ((LHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool()) ||
12333 (RHSBuiltinTy
&& RHSBuiltinTy
->isSVEBool())) {
12334 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
12335 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange();
12339 if (!LHSEleType
->isIntegerType()) {
12340 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
12341 << LHS
.get()->getType() << LHS
.get()->getSourceRange();
12345 if (!RHSEleType
->isIntegerType()) {
12346 S
.Diag(Loc
, diag::err_typecheck_expect_int
)
12347 << RHS
.get()->getType() << RHS
.get()->getSourceRange();
12351 if (LHSType
->isSveVLSBuiltinType() && RHSType
->isSveVLSBuiltinType() &&
12352 (S
.Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
!=
12353 S
.Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
)) {
12354 S
.Diag(Loc
, diag::err_typecheck_invalid_operands
)
12355 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12356 << RHS
.get()->getSourceRange();
12360 if (!LHSType
->isSveVLSBuiltinType()) {
12361 assert(RHSType
->isSveVLSBuiltinType());
12364 if (LHSEleType
!= RHSEleType
) {
12365 LHS
= S
.ImpCastExprToType(LHS
.get(), RHSEleType
, clang::CK_IntegralCast
);
12366 LHSEleType
= RHSEleType
;
12368 const llvm::ElementCount VecSize
=
12369 S
.Context
.getBuiltinVectorTypeInfo(RHSBuiltinTy
).EC
;
12371 S
.Context
.getScalableVectorType(LHSEleType
, VecSize
.getKnownMinValue());
12372 LHS
= S
.ImpCastExprToType(LHS
.get(), VecTy
, clang::CK_VectorSplat
);
12374 } else if (RHSBuiltinTy
&& RHSBuiltinTy
->isSveVLSBuiltinType()) {
12375 if (S
.Context
.getTypeSize(RHSBuiltinTy
) !=
12376 S
.Context
.getTypeSize(LHSBuiltinTy
)) {
12377 S
.Diag(Loc
, diag::err_typecheck_vector_lengths_not_equal
)
12378 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
12379 << RHS
.get()->getSourceRange();
12383 const llvm::ElementCount VecSize
=
12384 S
.Context
.getBuiltinVectorTypeInfo(LHSBuiltinTy
).EC
;
12385 if (LHSEleType
!= RHSEleType
) {
12386 RHS
= S
.ImpCastExprToType(RHS
.get(), LHSEleType
, clang::CK_IntegralCast
);
12387 RHSEleType
= LHSEleType
;
12390 S
.Context
.getScalableVectorType(RHSEleType
, VecSize
.getKnownMinValue());
12391 RHS
= S
.ImpCastExprToType(RHS
.get(), VecTy
, CK_VectorSplat
);
12398 QualType
Sema::CheckShiftOperands(ExprResult
&LHS
, ExprResult
&RHS
,
12399 SourceLocation Loc
, BinaryOperatorKind Opc
,
12400 bool IsCompAssign
) {
12401 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
12403 // Vector shifts promote their scalar inputs to vector type.
12404 if (LHS
.get()->getType()->isVectorType() ||
12405 RHS
.get()->getType()->isVectorType()) {
12406 if (LangOpts
.ZVector
) {
12407 // The shift operators for the z vector extensions work basically
12408 // like general shifts, except that neither the LHS nor the RHS is
12409 // allowed to be a "vector bool".
12410 if (auto LHSVecType
= LHS
.get()->getType()->getAs
<VectorType
>())
12411 if (LHSVecType
->getVectorKind() == VectorKind::AltiVecBool
)
12412 return InvalidOperands(Loc
, LHS
, RHS
);
12413 if (auto RHSVecType
= RHS
.get()->getType()->getAs
<VectorType
>())
12414 if (RHSVecType
->getVectorKind() == VectorKind::AltiVecBool
)
12415 return InvalidOperands(Loc
, LHS
, RHS
);
12417 return checkVectorShift(*this, LHS
, RHS
, Loc
, IsCompAssign
);
12420 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
12421 RHS
.get()->getType()->isSveVLSBuiltinType())
12422 return checkSizelessVectorShift(*this, LHS
, RHS
, Loc
, IsCompAssign
);
12424 // Shifts don't perform usual arithmetic conversions, they just do integer
12425 // promotions on each operand. C99 6.5.7p3
12427 // For the LHS, do usual unary conversions, but then reset them away
12428 // if this is a compound assignment.
12429 ExprResult OldLHS
= LHS
;
12430 LHS
= UsualUnaryConversions(LHS
.get());
12431 if (LHS
.isInvalid())
12433 QualType LHSType
= LHS
.get()->getType();
12434 if (IsCompAssign
) LHS
= OldLHS
;
12436 // The RHS is simpler.
12437 RHS
= UsualUnaryConversions(RHS
.get());
12438 if (RHS
.isInvalid())
12440 QualType RHSType
= RHS
.get()->getType();
12442 // C99 6.5.7p2: Each of the operands shall have integer type.
12443 // Embedded-C 4.1.6.2.2: The LHS may also be fixed-point.
12444 if ((!LHSType
->isFixedPointOrIntegerType() &&
12445 !LHSType
->hasIntegerRepresentation()) ||
12446 !RHSType
->hasIntegerRepresentation())
12447 return InvalidOperands(Loc
, LHS
, RHS
);
12449 // C++0x: Don't allow scoped enums. FIXME: Use something better than
12450 // hasIntegerRepresentation() above instead of this.
12451 if (isScopedEnumerationType(LHSType
) ||
12452 isScopedEnumerationType(RHSType
)) {
12453 return InvalidOperands(Loc
, LHS
, RHS
);
12455 DiagnoseBadShiftValues(*this, LHS
, RHS
, Loc
, Opc
, LHSType
);
12457 // "The type of the result is that of the promoted left operand."
12461 /// Diagnose bad pointer comparisons.
12462 static void diagnoseDistinctPointerComparison(Sema
&S
, SourceLocation Loc
,
12463 ExprResult
&LHS
, ExprResult
&RHS
,
12465 S
.Diag(Loc
, IsError
? diag::err_typecheck_comparison_of_distinct_pointers
12466 : diag::ext_typecheck_comparison_of_distinct_pointers
)
12467 << LHS
.get()->getType() << RHS
.get()->getType()
12468 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12471 /// Returns false if the pointers are converted to a composite type,
12472 /// true otherwise.
12473 static bool convertPointersToCompositeType(Sema
&S
, SourceLocation Loc
,
12474 ExprResult
&LHS
, ExprResult
&RHS
) {
12475 // C++ [expr.rel]p2:
12476 // [...] Pointer conversions (4.10) and qualification
12477 // conversions (4.4) are performed on pointer operands (or on
12478 // a pointer operand and a null pointer constant) to bring
12479 // them to their composite pointer type. [...]
12481 // C++ [expr.eq]p1 uses the same notion for (in)equality
12482 // comparisons of pointers.
12484 QualType LHSType
= LHS
.get()->getType();
12485 QualType RHSType
= RHS
.get()->getType();
12486 assert(LHSType
->isPointerType() || RHSType
->isPointerType() ||
12487 LHSType
->isMemberPointerType() || RHSType
->isMemberPointerType());
12489 QualType T
= S
.FindCompositePointerType(Loc
, LHS
, RHS
);
12491 if ((LHSType
->isAnyPointerType() || LHSType
->isMemberPointerType()) &&
12492 (RHSType
->isAnyPointerType() || RHSType
->isMemberPointerType()))
12493 diagnoseDistinctPointerComparison(S
, Loc
, LHS
, RHS
, /*isError*/true);
12495 S
.InvalidOperands(Loc
, LHS
, RHS
);
12502 static void diagnoseFunctionPointerToVoidComparison(Sema
&S
, SourceLocation Loc
,
12506 S
.Diag(Loc
, IsError
? diag::err_typecheck_comparison_of_fptr_to_void
12507 : diag::ext_typecheck_comparison_of_fptr_to_void
)
12508 << LHS
.get()->getType() << RHS
.get()->getType()
12509 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
12512 static bool isObjCObjectLiteral(ExprResult
&E
) {
12513 switch (E
.get()->IgnoreParenImpCasts()->getStmtClass()) {
12514 case Stmt::ObjCArrayLiteralClass
:
12515 case Stmt::ObjCDictionaryLiteralClass
:
12516 case Stmt::ObjCStringLiteralClass
:
12517 case Stmt::ObjCBoxedExprClass
:
12520 // Note that ObjCBoolLiteral is NOT an object literal!
12525 static bool hasIsEqualMethod(Sema
&S
, const Expr
*LHS
, const Expr
*RHS
) {
12526 const ObjCObjectPointerType
*Type
=
12527 LHS
->getType()->getAs
<ObjCObjectPointerType
>();
12529 // If this is not actually an Objective-C object, bail out.
12533 // Get the LHS object's interface type.
12534 QualType InterfaceType
= Type
->getPointeeType();
12536 // If the RHS isn't an Objective-C object, bail out.
12537 if (!RHS
->getType()->isObjCObjectPointerType())
12540 // Try to find the -isEqual: method.
12541 Selector IsEqualSel
= S
.NSAPIObj
->getIsEqualSelector();
12542 ObjCMethodDecl
*Method
= S
.LookupMethodInObjectType(IsEqualSel
,
12544 /*IsInstance=*/true);
12546 if (Type
->isObjCIdType()) {
12547 // For 'id', just check the global pool.
12548 Method
= S
.LookupInstanceMethodInGlobalPool(IsEqualSel
, SourceRange(),
12549 /*receiverId=*/true);
12551 // Check protocols.
12552 Method
= S
.LookupMethodInQualifiedType(IsEqualSel
, Type
,
12553 /*IsInstance=*/true);
12560 QualType T
= Method
->parameters()[0]->getType();
12561 if (!T
->isObjCObjectPointerType())
12564 QualType R
= Method
->getReturnType();
12565 if (!R
->isScalarType())
12571 Sema::ObjCLiteralKind
Sema::CheckLiteralKind(Expr
*FromE
) {
12572 FromE
= FromE
->IgnoreParenImpCasts();
12573 switch (FromE
->getStmtClass()) {
12576 case Stmt::ObjCStringLiteralClass
:
12577 // "string literal"
12579 case Stmt::ObjCArrayLiteralClass
:
12582 case Stmt::ObjCDictionaryLiteralClass
:
12583 // "dictionary literal"
12584 return LK_Dictionary
;
12585 case Stmt::BlockExprClass
:
12587 case Stmt::ObjCBoxedExprClass
: {
12588 Expr
*Inner
= cast
<ObjCBoxedExpr
>(FromE
)->getSubExpr()->IgnoreParens();
12589 switch (Inner
->getStmtClass()) {
12590 case Stmt::IntegerLiteralClass
:
12591 case Stmt::FloatingLiteralClass
:
12592 case Stmt::CharacterLiteralClass
:
12593 case Stmt::ObjCBoolLiteralExprClass
:
12594 case Stmt::CXXBoolLiteralExprClass
:
12595 // "numeric literal"
12597 case Stmt::ImplicitCastExprClass
: {
12598 CastKind CK
= cast
<CastExpr
>(Inner
)->getCastKind();
12599 // Boolean literals can be represented by implicit casts.
12600 if (CK
== CK_IntegralToBoolean
|| CK
== CK_IntegralCast
)
12613 static void diagnoseObjCLiteralComparison(Sema
&S
, SourceLocation Loc
,
12614 ExprResult
&LHS
, ExprResult
&RHS
,
12615 BinaryOperator::Opcode Opc
){
12618 if (isObjCObjectLiteral(LHS
)) {
12619 Literal
= LHS
.get();
12622 Literal
= RHS
.get();
12626 // Don't warn on comparisons against nil.
12627 Other
= Other
->IgnoreParenCasts();
12628 if (Other
->isNullPointerConstant(S
.getASTContext(),
12629 Expr::NPC_ValueDependentIsNotNull
))
12632 // This should be kept in sync with warn_objc_literal_comparison.
12633 // LK_String should always be after the other literals, since it has its own
12635 Sema::ObjCLiteralKind LiteralKind
= S
.CheckLiteralKind(Literal
);
12636 assert(LiteralKind
!= Sema::LK_Block
);
12637 if (LiteralKind
== Sema::LK_None
) {
12638 llvm_unreachable("Unknown Objective-C object literal kind");
12641 if (LiteralKind
== Sema::LK_String
)
12642 S
.Diag(Loc
, diag::warn_objc_string_literal_comparison
)
12643 << Literal
->getSourceRange();
12645 S
.Diag(Loc
, diag::warn_objc_literal_comparison
)
12646 << LiteralKind
<< Literal
->getSourceRange();
12648 if (BinaryOperator::isEqualityOp(Opc
) &&
12649 hasIsEqualMethod(S
, LHS
.get(), RHS
.get())) {
12650 SourceLocation Start
= LHS
.get()->getBeginLoc();
12651 SourceLocation End
= S
.getLocForEndOfToken(RHS
.get()->getEndLoc());
12652 CharSourceRange OpRange
=
12653 CharSourceRange::getCharRange(Loc
, S
.getLocForEndOfToken(Loc
));
12655 S
.Diag(Loc
, diag::note_objc_literal_comparison_isequal
)
12656 << FixItHint::CreateInsertion(Start
, Opc
== BO_EQ
? "[" : "![")
12657 << FixItHint::CreateReplacement(OpRange
, " isEqual:")
12658 << FixItHint::CreateInsertion(End
, "]");
12662 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
12663 static void diagnoseLogicalNotOnLHSofCheck(Sema
&S
, ExprResult
&LHS
,
12664 ExprResult
&RHS
, SourceLocation Loc
,
12665 BinaryOperatorKind Opc
) {
12666 // Check that left hand side is !something.
12667 UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(LHS
.get()->IgnoreImpCasts());
12668 if (!UO
|| UO
->getOpcode() != UO_LNot
) return;
12670 // Only check if the right hand side is non-bool arithmetic type.
12671 if (RHS
.get()->isKnownToHaveBooleanValue()) return;
12673 // Make sure that the something in !something is not bool.
12674 Expr
*SubExpr
= UO
->getSubExpr()->IgnoreImpCasts();
12675 if (SubExpr
->isKnownToHaveBooleanValue()) return;
12678 bool IsBitwiseOp
= Opc
== BO_And
|| Opc
== BO_Or
|| Opc
== BO_Xor
;
12679 S
.Diag(UO
->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check
)
12680 << Loc
<< IsBitwiseOp
;
12682 // First note suggest !(x < y)
12683 SourceLocation FirstOpen
= SubExpr
->getBeginLoc();
12684 SourceLocation FirstClose
= RHS
.get()->getEndLoc();
12685 FirstClose
= S
.getLocForEndOfToken(FirstClose
);
12686 if (FirstClose
.isInvalid())
12687 FirstOpen
= SourceLocation();
12688 S
.Diag(UO
->getOperatorLoc(), diag::note_logical_not_fix
)
12690 << FixItHint::CreateInsertion(FirstOpen
, "(")
12691 << FixItHint::CreateInsertion(FirstClose
, ")");
12693 // Second note suggests (!x) < y
12694 SourceLocation SecondOpen
= LHS
.get()->getBeginLoc();
12695 SourceLocation SecondClose
= LHS
.get()->getEndLoc();
12696 SecondClose
= S
.getLocForEndOfToken(SecondClose
);
12697 if (SecondClose
.isInvalid())
12698 SecondOpen
= SourceLocation();
12699 S
.Diag(UO
->getOperatorLoc(), diag::note_logical_not_silence_with_parens
)
12700 << FixItHint::CreateInsertion(SecondOpen
, "(")
12701 << FixItHint::CreateInsertion(SecondClose
, ")");
12704 // Returns true if E refers to a non-weak array.
12705 static bool checkForArray(const Expr
*E
) {
12706 const ValueDecl
*D
= nullptr;
12707 if (const DeclRefExpr
*DR
= dyn_cast
<DeclRefExpr
>(E
)) {
12709 } else if (const MemberExpr
*Mem
= dyn_cast
<MemberExpr
>(E
)) {
12710 if (Mem
->isImplicitAccess())
12711 D
= Mem
->getMemberDecl();
12715 return D
->getType()->isArrayType() && !D
->isWeak();
12718 /// Diagnose some forms of syntactically-obvious tautological comparison.
12719 static void diagnoseTautologicalComparison(Sema
&S
, SourceLocation Loc
,
12720 Expr
*LHS
, Expr
*RHS
,
12721 BinaryOperatorKind Opc
) {
12722 Expr
*LHSStripped
= LHS
->IgnoreParenImpCasts();
12723 Expr
*RHSStripped
= RHS
->IgnoreParenImpCasts();
12725 QualType LHSType
= LHS
->getType();
12726 QualType RHSType
= RHS
->getType();
12727 if (LHSType
->hasFloatingRepresentation() ||
12728 (LHSType
->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc
)) ||
12729 S
.inTemplateInstantiation())
12732 // WebAssembly Tables cannot be compared, therefore shouldn't emit
12733 // Tautological diagnostics.
12734 if (LHSType
->isWebAssemblyTableType() || RHSType
->isWebAssemblyTableType())
12737 // Comparisons between two array types are ill-formed for operator<=>, so
12738 // we shouldn't emit any additional warnings about it.
12739 if (Opc
== BO_Cmp
&& LHSType
->isArrayType() && RHSType
->isArrayType())
12742 // For non-floating point types, check for self-comparisons of the form
12743 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
12744 // often indicate logic errors in the program.
12746 // NOTE: Don't warn about comparison expressions resulting from macro
12747 // expansion. Also don't warn about comparisons which are only self
12748 // comparisons within a template instantiation. The warnings should catch
12749 // obvious cases in the definition of the template anyways. The idea is to
12750 // warn when the typed comparison operator will always evaluate to the same
12753 // Used for indexing into %select in warn_comparison_always
12758 AlwaysEqual
, // std::strong_ordering::equal from operator<=>
12761 // C++2a [depr.array.comp]:
12762 // Equality and relational comparisons ([expr.eq], [expr.rel]) between two
12763 // operands of array type are deprecated.
12764 if (S
.getLangOpts().CPlusPlus20
&& LHSStripped
->getType()->isArrayType() &&
12765 RHSStripped
->getType()->isArrayType()) {
12766 S
.Diag(Loc
, diag::warn_depr_array_comparison
)
12767 << LHS
->getSourceRange() << RHS
->getSourceRange()
12768 << LHSStripped
->getType() << RHSStripped
->getType();
12769 // Carry on to produce the tautological comparison warning, if this
12770 // expression is potentially-evaluated, we can resolve the array to a
12771 // non-weak declaration, and so on.
12774 if (!LHS
->getBeginLoc().isMacroID() && !RHS
->getBeginLoc().isMacroID()) {
12775 if (Expr::isSameComparisonOperand(LHS
, RHS
)) {
12781 Result
= AlwaysTrue
;
12786 Result
= AlwaysFalse
;
12789 Result
= AlwaysEqual
;
12792 Result
= AlwaysConstant
;
12795 S
.DiagRuntimeBehavior(Loc
, nullptr,
12796 S
.PDiag(diag::warn_comparison_always
)
12797 << 0 /*self-comparison*/
12799 } else if (checkForArray(LHSStripped
) && checkForArray(RHSStripped
)) {
12800 // What is it always going to evaluate to?
12803 case BO_EQ
: // e.g. array1 == array2
12804 Result
= AlwaysFalse
;
12806 case BO_NE
: // e.g. array1 != array2
12807 Result
= AlwaysTrue
;
12809 default: // e.g. array1 <= array2
12810 // The best we can say is 'a constant'
12811 Result
= AlwaysConstant
;
12814 S
.DiagRuntimeBehavior(Loc
, nullptr,
12815 S
.PDiag(diag::warn_comparison_always
)
12816 << 1 /*array comparison*/
12821 if (isa
<CastExpr
>(LHSStripped
))
12822 LHSStripped
= LHSStripped
->IgnoreParenCasts();
12823 if (isa
<CastExpr
>(RHSStripped
))
12824 RHSStripped
= RHSStripped
->IgnoreParenCasts();
12826 // Warn about comparisons against a string constant (unless the other
12827 // operand is null); the user probably wants string comparison function.
12828 Expr
*LiteralString
= nullptr;
12829 Expr
*LiteralStringStripped
= nullptr;
12830 if ((isa
<StringLiteral
>(LHSStripped
) || isa
<ObjCEncodeExpr
>(LHSStripped
)) &&
12831 !RHSStripped
->isNullPointerConstant(S
.Context
,
12832 Expr::NPC_ValueDependentIsNull
)) {
12833 LiteralString
= LHS
;
12834 LiteralStringStripped
= LHSStripped
;
12835 } else if ((isa
<StringLiteral
>(RHSStripped
) ||
12836 isa
<ObjCEncodeExpr
>(RHSStripped
)) &&
12837 !LHSStripped
->isNullPointerConstant(S
.Context
,
12838 Expr::NPC_ValueDependentIsNull
)) {
12839 LiteralString
= RHS
;
12840 LiteralStringStripped
= RHSStripped
;
12843 if (LiteralString
) {
12844 S
.DiagRuntimeBehavior(Loc
, nullptr,
12845 S
.PDiag(diag::warn_stringcompare
)
12846 << isa
<ObjCEncodeExpr
>(LiteralStringStripped
)
12847 << LiteralString
->getSourceRange());
12851 static ImplicitConversionKind
castKindToImplicitConversionKind(CastKind CK
) {
12855 llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK
)
12858 llvm_unreachable("unhandled cast kind");
12860 case CK_UserDefinedConversion
:
12861 return ICK_Identity
;
12862 case CK_LValueToRValue
:
12863 return ICK_Lvalue_To_Rvalue
;
12864 case CK_ArrayToPointerDecay
:
12865 return ICK_Array_To_Pointer
;
12866 case CK_FunctionToPointerDecay
:
12867 return ICK_Function_To_Pointer
;
12868 case CK_IntegralCast
:
12869 return ICK_Integral_Conversion
;
12870 case CK_FloatingCast
:
12871 return ICK_Floating_Conversion
;
12872 case CK_IntegralToFloating
:
12873 case CK_FloatingToIntegral
:
12874 return ICK_Floating_Integral
;
12875 case CK_IntegralComplexCast
:
12876 case CK_FloatingComplexCast
:
12877 case CK_FloatingComplexToIntegralComplex
:
12878 case CK_IntegralComplexToFloatingComplex
:
12879 return ICK_Complex_Conversion
;
12880 case CK_FloatingComplexToReal
:
12881 case CK_FloatingRealToComplex
:
12882 case CK_IntegralComplexToReal
:
12883 case CK_IntegralRealToComplex
:
12884 return ICK_Complex_Real
;
12888 static bool checkThreeWayNarrowingConversion(Sema
&S
, QualType ToType
, Expr
*E
,
12890 SourceLocation Loc
) {
12891 // Check for a narrowing implicit conversion.
12892 StandardConversionSequence SCS
;
12893 SCS
.setAsIdentityConversion();
12894 SCS
.setToType(0, FromType
);
12895 SCS
.setToType(1, ToType
);
12896 if (const auto *ICE
= dyn_cast
<ImplicitCastExpr
>(E
))
12897 SCS
.Second
= castKindToImplicitConversionKind(ICE
->getCastKind());
12899 APValue PreNarrowingValue
;
12900 QualType PreNarrowingType
;
12901 switch (SCS
.getNarrowingKind(S
.Context
, E
, PreNarrowingValue
,
12903 /*IgnoreFloatToIntegralConversion*/ true)) {
12904 case NK_Dependent_Narrowing
:
12905 // Implicit conversion to a narrower type, but the expression is
12906 // value-dependent so we can't tell whether it's actually narrowing.
12907 case NK_Not_Narrowing
:
12910 case NK_Constant_Narrowing
:
12911 // Implicit conversion to a narrower type, and the value is not a constant
12913 S
.Diag(E
->getBeginLoc(), diag::err_spaceship_argument_narrowing
)
12915 << PreNarrowingValue
.getAsString(S
.Context
, PreNarrowingType
) << ToType
;
12918 case NK_Variable_Narrowing
:
12919 // Implicit conversion to a narrower type, and the value is not a constant
12921 case NK_Type_Narrowing
:
12922 S
.Diag(E
->getBeginLoc(), diag::err_spaceship_argument_narrowing
)
12923 << /*Constant*/ 0 << FromType
<< ToType
;
12924 // TODO: It's not a constant expression, but what if the user intended it
12925 // to be? Can we produce notes to help them figure out why it isn't?
12928 llvm_unreachable("unhandled case in switch");
12931 static QualType
checkArithmeticOrEnumeralThreeWayCompare(Sema
&S
,
12934 SourceLocation Loc
) {
12935 QualType LHSType
= LHS
.get()->getType();
12936 QualType RHSType
= RHS
.get()->getType();
12937 // Dig out the original argument type and expression before implicit casts
12938 // were applied. These are the types/expressions we need to check the
12939 // [expr.spaceship] requirements against.
12940 ExprResult LHSStripped
= LHS
.get()->IgnoreParenImpCasts();
12941 ExprResult RHSStripped
= RHS
.get()->IgnoreParenImpCasts();
12942 QualType LHSStrippedType
= LHSStripped
.get()->getType();
12943 QualType RHSStrippedType
= RHSStripped
.get()->getType();
12945 // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
12946 // other is not, the program is ill-formed.
12947 if (LHSStrippedType
->isBooleanType() != RHSStrippedType
->isBooleanType()) {
12948 S
.InvalidOperands(Loc
, LHSStripped
, RHSStripped
);
12952 // FIXME: Consider combining this with checkEnumArithmeticConversions.
12953 int NumEnumArgs
= (int)LHSStrippedType
->isEnumeralType() +
12954 RHSStrippedType
->isEnumeralType();
12955 if (NumEnumArgs
== 1) {
12956 bool LHSIsEnum
= LHSStrippedType
->isEnumeralType();
12957 QualType OtherTy
= LHSIsEnum
? RHSStrippedType
: LHSStrippedType
;
12958 if (OtherTy
->hasFloatingRepresentation()) {
12959 S
.InvalidOperands(Loc
, LHSStripped
, RHSStripped
);
12963 if (NumEnumArgs
== 2) {
12964 // C++2a [expr.spaceship]p5: If both operands have the same enumeration
12965 // type E, the operator yields the result of converting the operands
12966 // to the underlying type of E and applying <=> to the converted operands.
12967 if (!S
.Context
.hasSameUnqualifiedType(LHSStrippedType
, RHSStrippedType
)) {
12968 S
.InvalidOperands(Loc
, LHS
, RHS
);
12972 LHSStrippedType
->castAs
<EnumType
>()->getDecl()->getIntegerType();
12973 assert(IntType
->isArithmeticType());
12975 // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
12976 // promote the boolean type, and all other promotable integer types, to
12978 if (S
.Context
.isPromotableIntegerType(IntType
))
12979 IntType
= S
.Context
.getPromotedIntegerType(IntType
);
12981 LHS
= S
.ImpCastExprToType(LHS
.get(), IntType
, CK_IntegralCast
);
12982 RHS
= S
.ImpCastExprToType(RHS
.get(), IntType
, CK_IntegralCast
);
12983 LHSType
= RHSType
= IntType
;
12986 // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
12987 // usual arithmetic conversions are applied to the operands.
12989 S
.UsualArithmeticConversions(LHS
, RHS
, Loc
, Sema::ACK_Comparison
);
12990 if (LHS
.isInvalid() || RHS
.isInvalid())
12993 return S
.InvalidOperands(Loc
, LHS
, RHS
);
12995 std::optional
<ComparisonCategoryType
> CCT
=
12996 getComparisonCategoryForBuiltinCmp(Type
);
12998 return S
.InvalidOperands(Loc
, LHS
, RHS
);
13000 bool HasNarrowing
= checkThreeWayNarrowingConversion(
13001 S
, Type
, LHS
.get(), LHSType
, LHS
.get()->getBeginLoc());
13002 HasNarrowing
|= checkThreeWayNarrowingConversion(S
, Type
, RHS
.get(), RHSType
,
13003 RHS
.get()->getBeginLoc());
13007 assert(!Type
.isNull() && "composite type for <=> has not been set");
13009 return S
.CheckComparisonCategoryType(
13010 *CCT
, Loc
, Sema::ComparisonCategoryUsage::OperatorInExpression
);
13013 static QualType
checkArithmeticOrEnumeralCompare(Sema
&S
, ExprResult
&LHS
,
13015 SourceLocation Loc
,
13016 BinaryOperatorKind Opc
) {
13018 return checkArithmeticOrEnumeralThreeWayCompare(S
, LHS
, RHS
, Loc
);
13020 // C99 6.5.8p3 / C99 6.5.9p4
13022 S
.UsualArithmeticConversions(LHS
, RHS
, Loc
, Sema::ACK_Comparison
);
13023 if (LHS
.isInvalid() || RHS
.isInvalid())
13026 return S
.InvalidOperands(Loc
, LHS
, RHS
);
13027 assert(Type
->isArithmeticType() || Type
->isEnumeralType());
13029 if (Type
->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc
))
13030 return S
.InvalidOperands(Loc
, LHS
, RHS
);
13032 // Check for comparisons of floating point operands using != and ==.
13033 if (Type
->hasFloatingRepresentation())
13034 S
.CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
13036 // The result of comparisons is 'bool' in C++, 'int' in C.
13037 return S
.Context
.getLogicalOperationType();
13040 void Sema::CheckPtrComparisonWithNullChar(ExprResult
&E
, ExprResult
&NullE
) {
13041 if (!NullE
.get()->getType()->isAnyPointerType())
13043 int NullValue
= PP
.isMacroDefined("NULL") ? 0 : 1;
13044 if (!E
.get()->getType()->isAnyPointerType() &&
13045 E
.get()->isNullPointerConstant(Context
,
13046 Expr::NPC_ValueDependentIsNotNull
) ==
13047 Expr::NPCK_ZeroExpression
) {
13048 if (const auto *CL
= dyn_cast
<CharacterLiteral
>(E
.get())) {
13049 if (CL
->getValue() == 0)
13050 Diag(E
.get()->getExprLoc(), diag::warn_pointer_compare
)
13052 << FixItHint::CreateReplacement(E
.get()->getExprLoc(),
13053 NullValue
? "NULL" : "(void *)0");
13054 } else if (const auto *CE
= dyn_cast
<CStyleCastExpr
>(E
.get())) {
13055 TypeSourceInfo
*TI
= CE
->getTypeInfoAsWritten();
13056 QualType T
= Context
.getCanonicalType(TI
->getType()).getUnqualifiedType();
13057 if (T
== Context
.CharTy
)
13058 Diag(E
.get()->getExprLoc(), diag::warn_pointer_compare
)
13060 << FixItHint::CreateReplacement(E
.get()->getExprLoc(),
13061 NullValue
? "NULL" : "(void *)0");
13066 // C99 6.5.8, C++ [expr.rel]
13067 QualType
Sema::CheckCompareOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13068 SourceLocation Loc
,
13069 BinaryOperatorKind Opc
) {
13070 bool IsRelational
= BinaryOperator::isRelationalOp(Opc
);
13071 bool IsThreeWay
= Opc
== BO_Cmp
;
13072 bool IsOrdered
= IsRelational
|| IsThreeWay
;
13073 auto IsAnyPointerType
= [](ExprResult E
) {
13074 QualType Ty
= E
.get()->getType();
13075 return Ty
->isPointerType() || Ty
->isMemberPointerType();
13078 // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
13079 // type, array-to-pointer, ..., conversions are performed on both operands to
13080 // bring them to their composite type.
13081 // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
13082 // any type-related checks.
13083 if (!IsThreeWay
|| IsAnyPointerType(LHS
) || IsAnyPointerType(RHS
)) {
13084 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
13085 if (LHS
.isInvalid())
13087 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
13088 if (RHS
.isInvalid())
13091 LHS
= DefaultLvalueConversion(LHS
.get());
13092 if (LHS
.isInvalid())
13094 RHS
= DefaultLvalueConversion(RHS
.get());
13095 if (RHS
.isInvalid())
13099 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/true);
13100 if (!getLangOpts().CPlusPlus
&& BinaryOperator::isEqualityOp(Opc
)) {
13101 CheckPtrComparisonWithNullChar(LHS
, RHS
);
13102 CheckPtrComparisonWithNullChar(RHS
, LHS
);
13105 // Handle vector comparisons separately.
13106 if (LHS
.get()->getType()->isVectorType() ||
13107 RHS
.get()->getType()->isVectorType())
13108 return CheckVectorCompareOperands(LHS
, RHS
, Loc
, Opc
);
13110 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
13111 RHS
.get()->getType()->isSveVLSBuiltinType())
13112 return CheckSizelessVectorCompareOperands(LHS
, RHS
, Loc
, Opc
);
13114 diagnoseLogicalNotOnLHSofCheck(*this, LHS
, RHS
, Loc
, Opc
);
13115 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
13117 QualType LHSType
= LHS
.get()->getType();
13118 QualType RHSType
= RHS
.get()->getType();
13119 if ((LHSType
->isArithmeticType() || LHSType
->isEnumeralType()) &&
13120 (RHSType
->isArithmeticType() || RHSType
->isEnumeralType()))
13121 return checkArithmeticOrEnumeralCompare(*this, LHS
, RHS
, Loc
, Opc
);
13123 if ((LHSType
->isPointerType() &&
13124 LHSType
->getPointeeType().isWebAssemblyReferenceType()) ||
13125 (RHSType
->isPointerType() &&
13126 RHSType
->getPointeeType().isWebAssemblyReferenceType()))
13127 return InvalidOperands(Loc
, LHS
, RHS
);
13129 const Expr::NullPointerConstantKind LHSNullKind
=
13130 LHS
.get()->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
);
13131 const Expr::NullPointerConstantKind RHSNullKind
=
13132 RHS
.get()->isNullPointerConstant(Context
, Expr::NPC_ValueDependentIsNull
);
13133 bool LHSIsNull
= LHSNullKind
!= Expr::NPCK_NotNull
;
13134 bool RHSIsNull
= RHSNullKind
!= Expr::NPCK_NotNull
;
13136 auto computeResultTy
= [&]() {
13138 return Context
.getLogicalOperationType();
13139 assert(getLangOpts().CPlusPlus
);
13140 assert(Context
.hasSameType(LHS
.get()->getType(), RHS
.get()->getType()));
13142 QualType CompositeTy
= LHS
.get()->getType();
13143 assert(!CompositeTy
->isReferenceType());
13145 std::optional
<ComparisonCategoryType
> CCT
=
13146 getComparisonCategoryForBuiltinCmp(CompositeTy
);
13148 return InvalidOperands(Loc
, LHS
, RHS
);
13150 if (CompositeTy
->isPointerType() && LHSIsNull
!= RHSIsNull
) {
13151 // P0946R0: Comparisons between a null pointer constant and an object
13152 // pointer result in std::strong_equality, which is ill-formed under
13154 Diag(Loc
, diag::err_typecheck_three_way_comparison_of_pointer_and_zero
)
13155 << (LHSIsNull
? LHS
.get()->getSourceRange()
13156 : RHS
.get()->getSourceRange());
13160 return CheckComparisonCategoryType(
13161 *CCT
, Loc
, ComparisonCategoryUsage::OperatorInExpression
);
13164 if (!IsOrdered
&& LHSIsNull
!= RHSIsNull
) {
13165 bool IsEquality
= Opc
== BO_EQ
;
13167 DiagnoseAlwaysNonNullPointer(LHS
.get(), RHSNullKind
, IsEquality
,
13168 RHS
.get()->getSourceRange());
13170 DiagnoseAlwaysNonNullPointer(RHS
.get(), LHSNullKind
, IsEquality
,
13171 LHS
.get()->getSourceRange());
13174 if (IsOrdered
&& LHSType
->isFunctionPointerType() &&
13175 RHSType
->isFunctionPointerType()) {
13176 // Valid unless a relational comparison of function pointers
13177 bool IsError
= Opc
== BO_Cmp
;
13179 IsError
? diag::err_typecheck_ordered_comparison_of_function_pointers
13180 : getLangOpts().CPlusPlus
13181 ? diag::warn_typecheck_ordered_comparison_of_function_pointers
13182 : diag::ext_typecheck_ordered_comparison_of_function_pointers
;
13183 Diag(Loc
, DiagID
) << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
13184 << RHS
.get()->getSourceRange();
13189 if ((LHSType
->isIntegerType() && !LHSIsNull
) ||
13190 (RHSType
->isIntegerType() && !RHSIsNull
)) {
13191 // Skip normal pointer conversion checks in this case; we have better
13192 // diagnostics for this below.
13193 } else if (getLangOpts().CPlusPlus
) {
13194 // Equality comparison of a function pointer to a void pointer is invalid,
13195 // but we allow it as an extension.
13196 // FIXME: If we really want to allow this, should it be part of composite
13197 // pointer type computation so it works in conditionals too?
13199 ((LHSType
->isFunctionPointerType() && RHSType
->isVoidPointerType()) ||
13200 (RHSType
->isFunctionPointerType() && LHSType
->isVoidPointerType()))) {
13201 // This is a gcc extension compatibility comparison.
13202 // In a SFINAE context, we treat this as a hard error to maintain
13203 // conformance with the C++ standard.
13204 diagnoseFunctionPointerToVoidComparison(
13205 *this, Loc
, LHS
, RHS
, /*isError*/ (bool)isSFINAEContext());
13207 if (isSFINAEContext())
13210 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
13211 return computeResultTy();
13214 // C++ [expr.eq]p2:
13215 // If at least one operand is a pointer [...] bring them to their
13216 // composite pointer type.
13217 // C++ [expr.spaceship]p6
13218 // If at least one of the operands is of pointer type, [...] bring them
13219 // to their composite pointer type.
13220 // C++ [expr.rel]p2:
13221 // If both operands are pointers, [...] bring them to their composite
13223 // For <=>, the only valid non-pointer types are arrays and functions, and
13224 // we already decayed those, so this is really the same as the relational
13225 // comparison rule.
13226 if ((int)LHSType
->isPointerType() + (int)RHSType
->isPointerType() >=
13227 (IsOrdered
? 2 : 1) &&
13228 (!LangOpts
.ObjCAutoRefCount
|| !(LHSType
->isObjCObjectPointerType() ||
13229 RHSType
->isObjCObjectPointerType()))) {
13230 if (convertPointersToCompositeType(*this, Loc
, LHS
, RHS
))
13232 return computeResultTy();
13234 } else if (LHSType
->isPointerType() &&
13235 RHSType
->isPointerType()) { // C99 6.5.8p2
13236 // All of the following pointer-related warnings are GCC extensions, except
13237 // when handling null pointer constants.
13238 QualType LCanPointeeTy
=
13239 LHSType
->castAs
<PointerType
>()->getPointeeType().getCanonicalType();
13240 QualType RCanPointeeTy
=
13241 RHSType
->castAs
<PointerType
>()->getPointeeType().getCanonicalType();
13243 // C99 6.5.9p2 and C99 6.5.8p2
13244 if (Context
.typesAreCompatible(LCanPointeeTy
.getUnqualifiedType(),
13245 RCanPointeeTy
.getUnqualifiedType())) {
13246 if (IsRelational
) {
13247 // Pointers both need to point to complete or incomplete types
13248 if ((LCanPointeeTy
->isIncompleteType() !=
13249 RCanPointeeTy
->isIncompleteType()) &&
13250 !getLangOpts().C11
) {
13251 Diag(Loc
, diag::ext_typecheck_compare_complete_incomplete_pointers
)
13252 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange()
13253 << LHSType
<< RHSType
<< LCanPointeeTy
->isIncompleteType()
13254 << RCanPointeeTy
->isIncompleteType();
13257 } else if (!IsRelational
&&
13258 (LCanPointeeTy
->isVoidType() || RCanPointeeTy
->isVoidType())) {
13259 // Valid unless comparison between non-null pointer and function pointer
13260 if ((LCanPointeeTy
->isFunctionType() || RCanPointeeTy
->isFunctionType())
13261 && !LHSIsNull
&& !RHSIsNull
)
13262 diagnoseFunctionPointerToVoidComparison(*this, Loc
, LHS
, RHS
,
13266 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
, /*isError*/false);
13268 if (LCanPointeeTy
!= RCanPointeeTy
) {
13269 // Treat NULL constant as a special case in OpenCL.
13270 if (getLangOpts().OpenCL
&& !LHSIsNull
&& !RHSIsNull
) {
13271 if (!LCanPointeeTy
.isAddressSpaceOverlapping(RCanPointeeTy
)) {
13273 diag::err_typecheck_op_on_nonoverlapping_address_space_pointers
)
13274 << LHSType
<< RHSType
<< 0 /* comparison */
13275 << LHS
.get()->getSourceRange() << RHS
.get()->getSourceRange();
13278 LangAS AddrSpaceL
= LCanPointeeTy
.getAddressSpace();
13279 LangAS AddrSpaceR
= RCanPointeeTy
.getAddressSpace();
13280 CastKind Kind
= AddrSpaceL
!= AddrSpaceR
? CK_AddressSpaceConversion
13282 if (LHSIsNull
&& !RHSIsNull
)
13283 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, Kind
);
13285 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, Kind
);
13287 return computeResultTy();
13291 // C++ [expr.eq]p4:
13292 // Two operands of type std::nullptr_t or one operand of type
13293 // std::nullptr_t and the other a null pointer constant compare
13296 // If both operands have type nullptr_t or one operand has type nullptr_t
13297 // and the other is a null pointer constant, they compare equal if the
13298 // former is a null pointer.
13299 if (!IsOrdered
&& LHSIsNull
&& RHSIsNull
) {
13300 if (LHSType
->isNullPtrType()) {
13301 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
13302 return computeResultTy();
13304 if (RHSType
->isNullPtrType()) {
13305 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
13306 return computeResultTy();
13310 if (!getLangOpts().CPlusPlus
&& !IsOrdered
&& (LHSIsNull
|| RHSIsNull
)) {
13312 // Otherwise, at least one operand is a pointer. If one is a pointer and
13313 // the other is a null pointer constant or has type nullptr_t, they
13315 if (LHSIsNull
&& RHSType
->isPointerType()) {
13316 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
13317 return computeResultTy();
13319 if (RHSIsNull
&& LHSType
->isPointerType()) {
13320 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
13321 return computeResultTy();
13325 // Comparison of Objective-C pointers and block pointers against nullptr_t.
13326 // These aren't covered by the composite pointer type rules.
13327 if (!IsOrdered
&& RHSType
->isNullPtrType() &&
13328 (LHSType
->isObjCObjectPointerType() || LHSType
->isBlockPointerType())) {
13329 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
13330 return computeResultTy();
13332 if (!IsOrdered
&& LHSType
->isNullPtrType() &&
13333 (RHSType
->isObjCObjectPointerType() || RHSType
->isBlockPointerType())) {
13334 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
13335 return computeResultTy();
13338 if (getLangOpts().CPlusPlus
) {
13339 if (IsRelational
&&
13340 ((LHSType
->isNullPtrType() && RHSType
->isPointerType()) ||
13341 (RHSType
->isNullPtrType() && LHSType
->isPointerType()))) {
13342 // HACK: Relational comparison of nullptr_t against a pointer type is
13343 // invalid per DR583, but we allow it within std::less<> and friends,
13344 // since otherwise common uses of it break.
13345 // FIXME: Consider removing this hack once LWG fixes std::less<> and
13346 // friends to have std::nullptr_t overload candidates.
13347 DeclContext
*DC
= CurContext
;
13348 if (isa
<FunctionDecl
>(DC
))
13349 DC
= DC
->getParent();
13350 if (auto *CTSD
= dyn_cast
<ClassTemplateSpecializationDecl
>(DC
)) {
13351 if (CTSD
->isInStdNamespace() &&
13352 llvm::StringSwitch
<bool>(CTSD
->getName())
13353 .Cases("less", "less_equal", "greater", "greater_equal", true)
13355 if (RHSType
->isNullPtrType())
13356 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
13358 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
13359 return computeResultTy();
13364 // C++ [expr.eq]p2:
13365 // If at least one operand is a pointer to member, [...] bring them to
13366 // their composite pointer type.
13368 (LHSType
->isMemberPointerType() || RHSType
->isMemberPointerType())) {
13369 if (convertPointersToCompositeType(*this, Loc
, LHS
, RHS
))
13372 return computeResultTy();
13376 // Handle block pointer types.
13377 if (!IsOrdered
&& LHSType
->isBlockPointerType() &&
13378 RHSType
->isBlockPointerType()) {
13379 QualType lpointee
= LHSType
->castAs
<BlockPointerType
>()->getPointeeType();
13380 QualType rpointee
= RHSType
->castAs
<BlockPointerType
>()->getPointeeType();
13382 if (!LHSIsNull
&& !RHSIsNull
&&
13383 !Context
.typesAreCompatible(lpointee
, rpointee
)) {
13384 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_blocks
)
13385 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
13386 << RHS
.get()->getSourceRange();
13388 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
13389 return computeResultTy();
13392 // Allow block pointers to be compared with null pointer constants.
13394 && ((LHSType
->isBlockPointerType() && RHSType
->isPointerType())
13395 || (LHSType
->isPointerType() && RHSType
->isBlockPointerType()))) {
13396 if (!LHSIsNull
&& !RHSIsNull
) {
13397 if (!((RHSType
->isPointerType() && RHSType
->castAs
<PointerType
>()
13398 ->getPointeeType()->isVoidType())
13399 || (LHSType
->isPointerType() && LHSType
->castAs
<PointerType
>()
13400 ->getPointeeType()->isVoidType())))
13401 Diag(Loc
, diag::err_typecheck_comparison_of_distinct_blocks
)
13402 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
13403 << RHS
.get()->getSourceRange();
13405 if (LHSIsNull
&& !RHSIsNull
)
13406 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
13407 RHSType
->isPointerType() ? CK_BitCast
13408 : CK_AnyPointerToBlockPointerCast
);
13410 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
13411 LHSType
->isPointerType() ? CK_BitCast
13412 : CK_AnyPointerToBlockPointerCast
);
13413 return computeResultTy();
13416 if (LHSType
->isObjCObjectPointerType() ||
13417 RHSType
->isObjCObjectPointerType()) {
13418 const PointerType
*LPT
= LHSType
->getAs
<PointerType
>();
13419 const PointerType
*RPT
= RHSType
->getAs
<PointerType
>();
13421 bool LPtrToVoid
= LPT
? LPT
->getPointeeType()->isVoidType() : false;
13422 bool RPtrToVoid
= RPT
? RPT
->getPointeeType()->isVoidType() : false;
13424 if (!LPtrToVoid
&& !RPtrToVoid
&&
13425 !Context
.typesAreCompatible(LHSType
, RHSType
)) {
13426 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
,
13429 // FIXME: If LPtrToVoid, we should presumably convert the LHS rather than
13430 // the RHS, but we have test coverage for this behavior.
13431 // FIXME: Consider using convertPointersToCompositeType in C++.
13432 if (LHSIsNull
&& !RHSIsNull
) {
13433 Expr
*E
= LHS
.get();
13434 if (getLangOpts().ObjCAutoRefCount
)
13435 CheckObjCConversion(SourceRange(), RHSType
, E
,
13436 CCK_ImplicitConversion
);
13437 LHS
= ImpCastExprToType(E
, RHSType
,
13438 RPT
? CK_BitCast
:CK_CPointerToObjCPointerCast
);
13441 Expr
*E
= RHS
.get();
13442 if (getLangOpts().ObjCAutoRefCount
)
13443 CheckObjCConversion(SourceRange(), LHSType
, E
, CCK_ImplicitConversion
,
13445 /*DiagnoseCFAudited=*/false, Opc
);
13446 RHS
= ImpCastExprToType(E
, LHSType
,
13447 LPT
? CK_BitCast
:CK_CPointerToObjCPointerCast
);
13449 return computeResultTy();
13451 if (LHSType
->isObjCObjectPointerType() &&
13452 RHSType
->isObjCObjectPointerType()) {
13453 if (!Context
.areComparableObjCPointerTypes(LHSType
, RHSType
))
13454 diagnoseDistinctPointerComparison(*this, Loc
, LHS
, RHS
,
13456 if (isObjCObjectLiteral(LHS
) || isObjCObjectLiteral(RHS
))
13457 diagnoseObjCLiteralComparison(*this, Loc
, LHS
, RHS
, Opc
);
13459 if (LHSIsNull
&& !RHSIsNull
)
13460 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_BitCast
);
13462 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_BitCast
);
13463 return computeResultTy();
13466 if (!IsOrdered
&& LHSType
->isBlockPointerType() &&
13467 RHSType
->isBlockCompatibleObjCPointerType(Context
)) {
13468 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
13469 CK_BlockPointerToObjCPointerCast
);
13470 return computeResultTy();
13471 } else if (!IsOrdered
&&
13472 LHSType
->isBlockCompatibleObjCPointerType(Context
) &&
13473 RHSType
->isBlockPointerType()) {
13474 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
13475 CK_BlockPointerToObjCPointerCast
);
13476 return computeResultTy();
13479 if ((LHSType
->isAnyPointerType() && RHSType
->isIntegerType()) ||
13480 (LHSType
->isIntegerType() && RHSType
->isAnyPointerType())) {
13481 unsigned DiagID
= 0;
13482 bool isError
= false;
13483 if (LangOpts
.DebuggerSupport
) {
13484 // Under a debugger, allow the comparison of pointers to integers,
13485 // since users tend to want to compare addresses.
13486 } else if ((LHSIsNull
&& LHSType
->isIntegerType()) ||
13487 (RHSIsNull
&& RHSType
->isIntegerType())) {
13489 isError
= getLangOpts().CPlusPlus
;
13491 isError
? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
13492 : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero
;
13494 } else if (getLangOpts().CPlusPlus
) {
13495 DiagID
= diag::err_typecheck_comparison_of_pointer_integer
;
13497 } else if (IsOrdered
)
13498 DiagID
= diag::ext_typecheck_ordered_comparison_of_pointer_integer
;
13500 DiagID
= diag::ext_typecheck_comparison_of_pointer_integer
;
13504 << LHSType
<< RHSType
<< LHS
.get()->getSourceRange()
13505 << RHS
.get()->getSourceRange();
13510 if (LHSType
->isIntegerType())
13511 LHS
= ImpCastExprToType(LHS
.get(), RHSType
,
13512 LHSIsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
13514 RHS
= ImpCastExprToType(RHS
.get(), LHSType
,
13515 RHSIsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
13516 return computeResultTy();
13519 // Handle block pointers.
13520 if (!IsOrdered
&& RHSIsNull
13521 && LHSType
->isBlockPointerType() && RHSType
->isIntegerType()) {
13522 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
13523 return computeResultTy();
13525 if (!IsOrdered
&& LHSIsNull
13526 && LHSType
->isIntegerType() && RHSType
->isBlockPointerType()) {
13527 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
13528 return computeResultTy();
13531 if (getLangOpts().getOpenCLCompatibleVersion() >= 200) {
13532 if (LHSType
->isClkEventT() && RHSType
->isClkEventT()) {
13533 return computeResultTy();
13536 if (LHSType
->isQueueT() && RHSType
->isQueueT()) {
13537 return computeResultTy();
13540 if (LHSIsNull
&& RHSType
->isQueueT()) {
13541 LHS
= ImpCastExprToType(LHS
.get(), RHSType
, CK_NullToPointer
);
13542 return computeResultTy();
13545 if (LHSType
->isQueueT() && RHSIsNull
) {
13546 RHS
= ImpCastExprToType(RHS
.get(), LHSType
, CK_NullToPointer
);
13547 return computeResultTy();
13551 return InvalidOperands(Loc
, LHS
, RHS
);
13554 // Return a signed ext_vector_type that is of identical size and number of
13555 // elements. For floating point vectors, return an integer type of identical
13556 // size and number of elements. In the non ext_vector_type case, search from
13557 // the largest type to the smallest type to avoid cases where long long == long,
13558 // where long gets picked over long long.
13559 QualType
Sema::GetSignedVectorType(QualType V
) {
13560 const VectorType
*VTy
= V
->castAs
<VectorType
>();
13561 unsigned TypeSize
= Context
.getTypeSize(VTy
->getElementType());
13563 if (isa
<ExtVectorType
>(VTy
)) {
13564 if (VTy
->isExtVectorBoolType())
13565 return Context
.getExtVectorType(Context
.BoolTy
, VTy
->getNumElements());
13566 if (TypeSize
== Context
.getTypeSize(Context
.CharTy
))
13567 return Context
.getExtVectorType(Context
.CharTy
, VTy
->getNumElements());
13568 if (TypeSize
== Context
.getTypeSize(Context
.ShortTy
))
13569 return Context
.getExtVectorType(Context
.ShortTy
, VTy
->getNumElements());
13570 if (TypeSize
== Context
.getTypeSize(Context
.IntTy
))
13571 return Context
.getExtVectorType(Context
.IntTy
, VTy
->getNumElements());
13572 if (TypeSize
== Context
.getTypeSize(Context
.Int128Ty
))
13573 return Context
.getExtVectorType(Context
.Int128Ty
, VTy
->getNumElements());
13574 if (TypeSize
== Context
.getTypeSize(Context
.LongTy
))
13575 return Context
.getExtVectorType(Context
.LongTy
, VTy
->getNumElements());
13576 assert(TypeSize
== Context
.getTypeSize(Context
.LongLongTy
) &&
13577 "Unhandled vector element size in vector compare");
13578 return Context
.getExtVectorType(Context
.LongLongTy
, VTy
->getNumElements());
13581 if (TypeSize
== Context
.getTypeSize(Context
.Int128Ty
))
13582 return Context
.getVectorType(Context
.Int128Ty
, VTy
->getNumElements(),
13583 VectorKind::Generic
);
13584 if (TypeSize
== Context
.getTypeSize(Context
.LongLongTy
))
13585 return Context
.getVectorType(Context
.LongLongTy
, VTy
->getNumElements(),
13586 VectorKind::Generic
);
13587 if (TypeSize
== Context
.getTypeSize(Context
.LongTy
))
13588 return Context
.getVectorType(Context
.LongTy
, VTy
->getNumElements(),
13589 VectorKind::Generic
);
13590 if (TypeSize
== Context
.getTypeSize(Context
.IntTy
))
13591 return Context
.getVectorType(Context
.IntTy
, VTy
->getNumElements(),
13592 VectorKind::Generic
);
13593 if (TypeSize
== Context
.getTypeSize(Context
.ShortTy
))
13594 return Context
.getVectorType(Context
.ShortTy
, VTy
->getNumElements(),
13595 VectorKind::Generic
);
13596 assert(TypeSize
== Context
.getTypeSize(Context
.CharTy
) &&
13597 "Unhandled vector element size in vector compare");
13598 return Context
.getVectorType(Context
.CharTy
, VTy
->getNumElements(),
13599 VectorKind::Generic
);
13602 QualType
Sema::GetSignedSizelessVectorType(QualType V
) {
13603 const BuiltinType
*VTy
= V
->castAs
<BuiltinType
>();
13604 assert(VTy
->isSizelessBuiltinType() && "expected sizeless type");
13606 const QualType ETy
= V
->getSveEltType(Context
);
13607 const auto TypeSize
= Context
.getTypeSize(ETy
);
13609 const QualType IntTy
= Context
.getIntTypeForBitwidth(TypeSize
, true);
13610 const llvm::ElementCount VecSize
= Context
.getBuiltinVectorTypeInfo(VTy
).EC
;
13611 return Context
.getScalableVectorType(IntTy
, VecSize
.getKnownMinValue());
13614 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
13615 /// operates on extended vector types. Instead of producing an IntTy result,
13616 /// like a scalar comparison, a vector comparison produces a vector of integer
13618 QualType
Sema::CheckVectorCompareOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13619 SourceLocation Loc
,
13620 BinaryOperatorKind Opc
) {
13621 if (Opc
== BO_Cmp
) {
13622 Diag(Loc
, diag::err_three_way_vector_comparison
);
13626 // Check to make sure we're operating on vectors of the same type and width,
13627 // Allowing one side to be a scalar of element type.
13629 CheckVectorOperands(LHS
, RHS
, Loc
, /*isCompAssign*/ false,
13630 /*AllowBothBool*/ true,
13631 /*AllowBoolConversions*/ getLangOpts().ZVector
,
13632 /*AllowBooleanOperation*/ true,
13633 /*ReportInvalid*/ true);
13634 if (vType
.isNull())
13637 QualType LHSType
= LHS
.get()->getType();
13639 // Determine the return type of a vector compare. By default clang will return
13640 // a scalar for all vector compares except vector bool and vector pixel.
13641 // With the gcc compiler we will always return a vector type and with the xl
13642 // compiler we will always return a scalar type. This switch allows choosing
13643 // which behavior is prefered.
13644 if (getLangOpts().AltiVec
) {
13645 switch (getLangOpts().getAltivecSrcCompat()) {
13646 case LangOptions::AltivecSrcCompatKind::Mixed
:
13647 // If AltiVec, the comparison results in a numeric type, i.e.
13648 // bool for C++, int for C
13649 if (vType
->castAs
<VectorType
>()->getVectorKind() ==
13650 VectorKind::AltiVecVector
)
13651 return Context
.getLogicalOperationType();
13653 Diag(Loc
, diag::warn_deprecated_altivec_src_compat
);
13655 case LangOptions::AltivecSrcCompatKind::GCC
:
13656 // For GCC we always return the vector type.
13658 case LangOptions::AltivecSrcCompatKind::XL
:
13659 return Context
.getLogicalOperationType();
13664 // For non-floating point types, check for self-comparisons of the form
13665 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13666 // often indicate logic errors in the program.
13667 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
13669 // Check for comparisons of floating point operands using != and ==.
13670 if (LHSType
->hasFloatingRepresentation()) {
13671 assert(RHS
.get()->getType()->hasFloatingRepresentation());
13672 CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
13675 // Return a signed type for the vector.
13676 return GetSignedVectorType(vType
);
13679 QualType
Sema::CheckSizelessVectorCompareOperands(ExprResult
&LHS
,
13681 SourceLocation Loc
,
13682 BinaryOperatorKind Opc
) {
13683 if (Opc
== BO_Cmp
) {
13684 Diag(Loc
, diag::err_three_way_vector_comparison
);
13688 // Check to make sure we're operating on vectors of the same type and width,
13689 // Allowing one side to be a scalar of element type.
13690 QualType vType
= CheckSizelessVectorOperands(
13691 LHS
, RHS
, Loc
, /*isCompAssign*/ false, ACK_Comparison
);
13693 if (vType
.isNull())
13696 QualType LHSType
= LHS
.get()->getType();
13698 // For non-floating point types, check for self-comparisons of the form
13699 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
13700 // often indicate logic errors in the program.
13701 diagnoseTautologicalComparison(*this, Loc
, LHS
.get(), RHS
.get(), Opc
);
13703 // Check for comparisons of floating point operands using != and ==.
13704 if (LHSType
->hasFloatingRepresentation()) {
13705 assert(RHS
.get()->getType()->hasFloatingRepresentation());
13706 CheckFloatComparison(Loc
, LHS
.get(), RHS
.get(), Opc
);
13709 const BuiltinType
*LHSBuiltinTy
= LHSType
->getAs
<BuiltinType
>();
13710 const BuiltinType
*RHSBuiltinTy
= RHS
.get()->getType()->getAs
<BuiltinType
>();
13712 if (LHSBuiltinTy
&& RHSBuiltinTy
&& LHSBuiltinTy
->isSVEBool() &&
13713 RHSBuiltinTy
->isSVEBool())
13716 // Return a signed type for the vector.
13717 return GetSignedSizelessVectorType(vType
);
13720 static void diagnoseXorMisusedAsPow(Sema
&S
, const ExprResult
&XorLHS
,
13721 const ExprResult
&XorRHS
,
13722 const SourceLocation Loc
) {
13723 // Do not diagnose macros.
13724 if (Loc
.isMacroID())
13727 // Do not diagnose if both LHS and RHS are macros.
13728 if (XorLHS
.get()->getExprLoc().isMacroID() &&
13729 XorRHS
.get()->getExprLoc().isMacroID())
13732 bool Negative
= false;
13733 bool ExplicitPlus
= false;
13734 const auto *LHSInt
= dyn_cast
<IntegerLiteral
>(XorLHS
.get());
13735 const auto *RHSInt
= dyn_cast
<IntegerLiteral
>(XorRHS
.get());
13740 // Check negative literals.
13741 if (const auto *UO
= dyn_cast
<UnaryOperator
>(XorRHS
.get())) {
13742 UnaryOperatorKind Opc
= UO
->getOpcode();
13743 if (Opc
!= UO_Minus
&& Opc
!= UO_Plus
)
13745 RHSInt
= dyn_cast
<IntegerLiteral
>(UO
->getSubExpr());
13748 Negative
= (Opc
== UO_Minus
);
13749 ExplicitPlus
= !Negative
;
13755 const llvm::APInt
&LeftSideValue
= LHSInt
->getValue();
13756 llvm::APInt RightSideValue
= RHSInt
->getValue();
13757 if (LeftSideValue
!= 2 && LeftSideValue
!= 10)
13760 if (LeftSideValue
.getBitWidth() != RightSideValue
.getBitWidth())
13763 CharSourceRange ExprRange
= CharSourceRange::getCharRange(
13764 LHSInt
->getBeginLoc(), S
.getLocForEndOfToken(RHSInt
->getLocation()));
13765 llvm::StringRef ExprStr
=
13766 Lexer::getSourceText(ExprRange
, S
.getSourceManager(), S
.getLangOpts());
13768 CharSourceRange XorRange
=
13769 CharSourceRange::getCharRange(Loc
, S
.getLocForEndOfToken(Loc
));
13770 llvm::StringRef XorStr
=
13771 Lexer::getSourceText(XorRange
, S
.getSourceManager(), S
.getLangOpts());
13772 // Do not diagnose if xor keyword/macro is used.
13773 if (XorStr
== "xor")
13776 std::string LHSStr
= std::string(Lexer::getSourceText(
13777 CharSourceRange::getTokenRange(LHSInt
->getSourceRange()),
13778 S
.getSourceManager(), S
.getLangOpts()));
13779 std::string RHSStr
= std::string(Lexer::getSourceText(
13780 CharSourceRange::getTokenRange(RHSInt
->getSourceRange()),
13781 S
.getSourceManager(), S
.getLangOpts()));
13784 RightSideValue
= -RightSideValue
;
13785 RHSStr
= "-" + RHSStr
;
13786 } else if (ExplicitPlus
) {
13787 RHSStr
= "+" + RHSStr
;
13790 StringRef LHSStrRef
= LHSStr
;
13791 StringRef RHSStrRef
= RHSStr
;
13792 // Do not diagnose literals with digit separators, binary, hexadecimal, octal
13794 if (LHSStrRef
.startswith("0b") || LHSStrRef
.startswith("0B") ||
13795 RHSStrRef
.startswith("0b") || RHSStrRef
.startswith("0B") ||
13796 LHSStrRef
.startswith("0x") || LHSStrRef
.startswith("0X") ||
13797 RHSStrRef
.startswith("0x") || RHSStrRef
.startswith("0X") ||
13798 (LHSStrRef
.size() > 1 && LHSStrRef
.startswith("0")) ||
13799 (RHSStrRef
.size() > 1 && RHSStrRef
.startswith("0")) ||
13800 LHSStrRef
.contains('\'') || RHSStrRef
.contains('\''))
13804 S
.getLangOpts().CPlusPlus
|| S
.getPreprocessor().isMacroDefined("xor");
13805 const llvm::APInt XorValue
= LeftSideValue
^ RightSideValue
;
13806 int64_t RightSideIntValue
= RightSideValue
.getSExtValue();
13807 if (LeftSideValue
== 2 && RightSideIntValue
>= 0) {
13808 std::string SuggestedExpr
= "1 << " + RHSStr
;
13809 bool Overflow
= false;
13810 llvm::APInt One
= (LeftSideValue
- 1);
13811 llvm::APInt PowValue
= One
.sshl_ov(RightSideValue
, Overflow
);
13813 if (RightSideIntValue
< 64)
13814 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base
)
13815 << ExprStr
<< toString(XorValue
, 10, true) << ("1LL << " + RHSStr
)
13816 << FixItHint::CreateReplacement(ExprRange
, "1LL << " + RHSStr
);
13817 else if (RightSideIntValue
== 64)
13818 S
.Diag(Loc
, diag::warn_xor_used_as_pow
)
13819 << ExprStr
<< toString(XorValue
, 10, true);
13823 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base_extra
)
13824 << ExprStr
<< toString(XorValue
, 10, true) << SuggestedExpr
13825 << toString(PowValue
, 10, true)
13826 << FixItHint::CreateReplacement(
13827 ExprRange
, (RightSideIntValue
== 0) ? "1" : SuggestedExpr
);
13830 S
.Diag(Loc
, diag::note_xor_used_as_pow_silence
)
13831 << ("0x2 ^ " + RHSStr
) << SuggestXor
;
13832 } else if (LeftSideValue
== 10) {
13833 std::string SuggestedValue
= "1e" + std::to_string(RightSideIntValue
);
13834 S
.Diag(Loc
, diag::warn_xor_used_as_pow_base
)
13835 << ExprStr
<< toString(XorValue
, 10, true) << SuggestedValue
13836 << FixItHint::CreateReplacement(ExprRange
, SuggestedValue
);
13837 S
.Diag(Loc
, diag::note_xor_used_as_pow_silence
)
13838 << ("0xA ^ " + RHSStr
) << SuggestXor
;
13842 QualType
Sema::CheckVectorLogicalOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13843 SourceLocation Loc
) {
13844 // Ensure that either both operands are of the same vector type, or
13845 // one operand is of a vector type and the other is of its element type.
13846 QualType vType
= CheckVectorOperands(LHS
, RHS
, Loc
, false,
13847 /*AllowBothBool*/ true,
13848 /*AllowBoolConversions*/ false,
13849 /*AllowBooleanOperation*/ false,
13850 /*ReportInvalid*/ false);
13851 if (vType
.isNull())
13852 return InvalidOperands(Loc
, LHS
, RHS
);
13853 if (getLangOpts().OpenCL
&&
13854 getLangOpts().getOpenCLCompatibleVersion() < 120 &&
13855 vType
->hasFloatingRepresentation())
13856 return InvalidOperands(Loc
, LHS
, RHS
);
13857 // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
13858 // usage of the logical operators && and || with vectors in C. This
13859 // check could be notionally dropped.
13860 if (!getLangOpts().CPlusPlus
&&
13861 !(isa
<ExtVectorType
>(vType
->getAs
<VectorType
>())))
13862 return InvalidLogicalVectorOperands(Loc
, LHS
, RHS
);
13864 return GetSignedVectorType(LHS
.get()->getType());
13867 QualType
Sema::CheckMatrixElementwiseOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13868 SourceLocation Loc
,
13869 bool IsCompAssign
) {
13870 if (!IsCompAssign
) {
13871 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
13872 if (LHS
.isInvalid())
13875 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
13876 if (RHS
.isInvalid())
13879 // For conversion purposes, we ignore any qualifiers.
13880 // For example, "const float" and "float" are equivalent.
13881 QualType LHSType
= LHS
.get()->getType().getUnqualifiedType();
13882 QualType RHSType
= RHS
.get()->getType().getUnqualifiedType();
13884 const MatrixType
*LHSMatType
= LHSType
->getAs
<MatrixType
>();
13885 const MatrixType
*RHSMatType
= RHSType
->getAs
<MatrixType
>();
13886 assert((LHSMatType
|| RHSMatType
) && "At least one operand must be a matrix");
13888 if (Context
.hasSameType(LHSType
, RHSType
))
13889 return Context
.getCommonSugaredType(LHSType
, RHSType
);
13891 // Type conversion may change LHS/RHS. Keep copies to the original results, in
13892 // case we have to return InvalidOperands.
13893 ExprResult OriginalLHS
= LHS
;
13894 ExprResult OriginalRHS
= RHS
;
13895 if (LHSMatType
&& !RHSMatType
) {
13896 RHS
= tryConvertExprToType(RHS
.get(), LHSMatType
->getElementType());
13897 if (!RHS
.isInvalid())
13900 return InvalidOperands(Loc
, OriginalLHS
, OriginalRHS
);
13903 if (!LHSMatType
&& RHSMatType
) {
13904 LHS
= tryConvertExprToType(LHS
.get(), RHSMatType
->getElementType());
13905 if (!LHS
.isInvalid())
13907 return InvalidOperands(Loc
, OriginalLHS
, OriginalRHS
);
13910 return InvalidOperands(Loc
, LHS
, RHS
);
13913 QualType
Sema::CheckMatrixMultiplyOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13914 SourceLocation Loc
,
13915 bool IsCompAssign
) {
13916 if (!IsCompAssign
) {
13917 LHS
= DefaultFunctionArrayLvalueConversion(LHS
.get());
13918 if (LHS
.isInvalid())
13921 RHS
= DefaultFunctionArrayLvalueConversion(RHS
.get());
13922 if (RHS
.isInvalid())
13925 auto *LHSMatType
= LHS
.get()->getType()->getAs
<ConstantMatrixType
>();
13926 auto *RHSMatType
= RHS
.get()->getType()->getAs
<ConstantMatrixType
>();
13927 assert((LHSMatType
|| RHSMatType
) && "At least one operand must be a matrix");
13929 if (LHSMatType
&& RHSMatType
) {
13930 if (LHSMatType
->getNumColumns() != RHSMatType
->getNumRows())
13931 return InvalidOperands(Loc
, LHS
, RHS
);
13933 if (Context
.hasSameType(LHSMatType
, RHSMatType
))
13934 return Context
.getCommonSugaredType(
13935 LHS
.get()->getType().getUnqualifiedType(),
13936 RHS
.get()->getType().getUnqualifiedType());
13938 QualType LHSELTy
= LHSMatType
->getElementType(),
13939 RHSELTy
= RHSMatType
->getElementType();
13940 if (!Context
.hasSameType(LHSELTy
, RHSELTy
))
13941 return InvalidOperands(Loc
, LHS
, RHS
);
13943 return Context
.getConstantMatrixType(
13944 Context
.getCommonSugaredType(LHSELTy
, RHSELTy
),
13945 LHSMatType
->getNumRows(), RHSMatType
->getNumColumns());
13947 return CheckMatrixElementwiseOperands(LHS
, RHS
, Loc
, IsCompAssign
);
13950 static bool isLegalBoolVectorBinaryOp(BinaryOperatorKind Opc
) {
13964 inline QualType
Sema::CheckBitwiseOperands(ExprResult
&LHS
, ExprResult
&RHS
,
13965 SourceLocation Loc
,
13966 BinaryOperatorKind Opc
) {
13967 checkArithmeticNull(*this, LHS
, RHS
, Loc
, /*IsCompare=*/false);
13969 bool IsCompAssign
=
13970 Opc
== BO_AndAssign
|| Opc
== BO_OrAssign
|| Opc
== BO_XorAssign
;
13972 bool LegalBoolVecOperator
= isLegalBoolVectorBinaryOp(Opc
);
13974 if (LHS
.get()->getType()->isVectorType() ||
13975 RHS
.get()->getType()->isVectorType()) {
13976 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13977 RHS
.get()->getType()->hasIntegerRepresentation())
13978 return CheckVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
13979 /*AllowBothBool*/ true,
13980 /*AllowBoolConversions*/ getLangOpts().ZVector
,
13981 /*AllowBooleanOperation*/ LegalBoolVecOperator
,
13982 /*ReportInvalid*/ true);
13983 return InvalidOperands(Loc
, LHS
, RHS
);
13986 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
13987 RHS
.get()->getType()->isSveVLSBuiltinType()) {
13988 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13989 RHS
.get()->getType()->hasIntegerRepresentation())
13990 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
13992 return InvalidOperands(Loc
, LHS
, RHS
);
13995 if (LHS
.get()->getType()->isSveVLSBuiltinType() ||
13996 RHS
.get()->getType()->isSveVLSBuiltinType()) {
13997 if (LHS
.get()->getType()->hasIntegerRepresentation() &&
13998 RHS
.get()->getType()->hasIntegerRepresentation())
13999 return CheckSizelessVectorOperands(LHS
, RHS
, Loc
, IsCompAssign
,
14001 return InvalidOperands(Loc
, LHS
, RHS
);
14005 diagnoseLogicalNotOnLHSofCheck(*this, LHS
, RHS
, Loc
, Opc
);
14007 if (LHS
.get()->getType()->hasFloatingRepresentation() ||
14008 RHS
.get()->getType()->hasFloatingRepresentation())
14009 return InvalidOperands(Loc
, LHS
, RHS
);
14011 ExprResult LHSResult
= LHS
, RHSResult
= RHS
;
14012 QualType compType
= UsualArithmeticConversions(
14013 LHSResult
, RHSResult
, Loc
, IsCompAssign
? ACK_CompAssign
: ACK_BitwiseOp
);
14014 if (LHSResult
.isInvalid() || RHSResult
.isInvalid())
14016 LHS
= LHSResult
.get();
14017 RHS
= RHSResult
.get();
14020 diagnoseXorMisusedAsPow(*this, LHS
, RHS
, Loc
);
14022 if (!compType
.isNull() && compType
->isIntegralOrUnscopedEnumerationType())
14024 return InvalidOperands(Loc
, LHS
, RHS
);
14028 inline QualType
Sema::CheckLogicalOperands(ExprResult
&LHS
, ExprResult
&RHS
,
14029 SourceLocation Loc
,
14030 BinaryOperatorKind Opc
) {
14031 // Check vector operands differently.
14032 if (LHS
.get()->getType()->isVectorType() ||
14033 RHS
.get()->getType()->isVectorType())
14034 return CheckVectorLogicalOperands(LHS
, RHS
, Loc
);
14036 bool EnumConstantInBoolContext
= false;
14037 for (const ExprResult
&HS
: {LHS
, RHS
}) {
14038 if (const auto *DREHS
= dyn_cast
<DeclRefExpr
>(HS
.get())) {
14039 const auto *ECDHS
= dyn_cast
<EnumConstantDecl
>(DREHS
->getDecl());
14040 if (ECDHS
&& ECDHS
->getInitVal() != 0 && ECDHS
->getInitVal() != 1)
14041 EnumConstantInBoolContext
= true;
14045 if (EnumConstantInBoolContext
)
14046 Diag(Loc
, diag::warn_enum_constant_in_bool_context
);
14048 // WebAssembly tables can't be used with logical operators.
14049 QualType LHSTy
= LHS
.get()->getType();
14050 QualType RHSTy
= RHS
.get()->getType();
14051 const auto *LHSATy
= dyn_cast
<ArrayType
>(LHSTy
);
14052 const auto *RHSATy
= dyn_cast
<ArrayType
>(RHSTy
);
14053 if ((LHSATy
&& LHSATy
->getElementType().isWebAssemblyReferenceType()) ||
14054 (RHSATy
&& RHSATy
->getElementType().isWebAssemblyReferenceType())) {
14055 return InvalidOperands(Loc
, LHS
, RHS
);
14058 // Diagnose cases where the user write a logical and/or but probably meant a
14059 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
14061 if (!EnumConstantInBoolContext
&& LHS
.get()->getType()->isIntegerType() &&
14062 !LHS
.get()->getType()->isBooleanType() &&
14063 RHS
.get()->getType()->isIntegerType() && !RHS
.get()->isValueDependent() &&
14064 // Don't warn in macros or template instantiations.
14065 !Loc
.isMacroID() && !inTemplateInstantiation()) {
14066 // If the RHS can be constant folded, and if it constant folds to something
14067 // that isn't 0 or 1 (which indicate a potential logical operation that
14068 // happened to fold to true/false) then warn.
14069 // Parens on the RHS are ignored.
14070 Expr::EvalResult EVResult
;
14071 if (RHS
.get()->EvaluateAsInt(EVResult
, Context
)) {
14072 llvm::APSInt Result
= EVResult
.Val
.getInt();
14073 if ((getLangOpts().Bool
&& !RHS
.get()->getType()->isBooleanType() &&
14074 !RHS
.get()->getExprLoc().isMacroID()) ||
14075 (Result
!= 0 && Result
!= 1)) {
14076 Diag(Loc
, diag::warn_logical_instead_of_bitwise
)
14077 << RHS
.get()->getSourceRange() << (Opc
== BO_LAnd
? "&&" : "||");
14078 // Suggest replacing the logical operator with the bitwise version
14079 Diag(Loc
, diag::note_logical_instead_of_bitwise_change_operator
)
14080 << (Opc
== BO_LAnd
? "&" : "|")
14081 << FixItHint::CreateReplacement(
14082 SourceRange(Loc
, getLocForEndOfToken(Loc
)),
14083 Opc
== BO_LAnd
? "&" : "|");
14084 if (Opc
== BO_LAnd
)
14085 // Suggest replacing "Foo() && kNonZero" with "Foo()"
14086 Diag(Loc
, diag::note_logical_instead_of_bitwise_remove_constant
)
14087 << FixItHint::CreateRemoval(
14088 SourceRange(getLocForEndOfToken(LHS
.get()->getEndLoc()),
14089 RHS
.get()->getEndLoc()));
14094 if (!Context
.getLangOpts().CPlusPlus
) {
14095 // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
14096 // not operate on the built-in scalar and vector float types.
14097 if (Context
.getLangOpts().OpenCL
&&
14098 Context
.getLangOpts().OpenCLVersion
< 120) {
14099 if (LHS
.get()->getType()->isFloatingType() ||
14100 RHS
.get()->getType()->isFloatingType())
14101 return InvalidOperands(Loc
, LHS
, RHS
);
14104 LHS
= UsualUnaryConversions(LHS
.get());
14105 if (LHS
.isInvalid())
14108 RHS
= UsualUnaryConversions(RHS
.get());
14109 if (RHS
.isInvalid())
14112 if (!LHS
.get()->getType()->isScalarType() ||
14113 !RHS
.get()->getType()->isScalarType())
14114 return InvalidOperands(Loc
, LHS
, RHS
);
14116 return Context
.IntTy
;
14119 // The following is safe because we only use this method for
14120 // non-overloadable operands.
14122 // C++ [expr.log.and]p1
14123 // C++ [expr.log.or]p1
14124 // The operands are both contextually converted to type bool.
14125 ExprResult LHSRes
= PerformContextuallyConvertToBool(LHS
.get());
14126 if (LHSRes
.isInvalid())
14127 return InvalidOperands(Loc
, LHS
, RHS
);
14130 ExprResult RHSRes
= PerformContextuallyConvertToBool(RHS
.get());
14131 if (RHSRes
.isInvalid())
14132 return InvalidOperands(Loc
, LHS
, RHS
);
14135 // C++ [expr.log.and]p2
14136 // C++ [expr.log.or]p2
14137 // The result is a bool.
14138 return Context
.BoolTy
;
14141 static bool IsReadonlyMessage(Expr
*E
, Sema
&S
) {
14142 const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
);
14143 if (!ME
) return false;
14144 if (!isa
<FieldDecl
>(ME
->getMemberDecl())) return false;
14145 ObjCMessageExpr
*Base
= dyn_cast
<ObjCMessageExpr
>(
14146 ME
->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
14147 if (!Base
) return false;
14148 return Base
->getMethodDecl() != nullptr;
14151 /// Is the given expression (which must be 'const') a reference to a
14152 /// variable which was originally non-const, but which has become
14153 /// 'const' due to being captured within a block?
14154 enum NonConstCaptureKind
{ NCCK_None
, NCCK_Block
, NCCK_Lambda
};
14155 static NonConstCaptureKind
isReferenceToNonConstCapture(Sema
&S
, Expr
*E
) {
14156 assert(E
->isLValue() && E
->getType().isConstQualified());
14157 E
= E
->IgnoreParens();
14159 // Must be a reference to a declaration from an enclosing scope.
14160 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
);
14161 if (!DRE
) return NCCK_None
;
14162 if (!DRE
->refersToEnclosingVariableOrCapture()) return NCCK_None
;
14164 // The declaration must be a variable which is not declared 'const'.
14165 VarDecl
*var
= dyn_cast
<VarDecl
>(DRE
->getDecl());
14166 if (!var
) return NCCK_None
;
14167 if (var
->getType().isConstQualified()) return NCCK_None
;
14168 assert(var
->hasLocalStorage() && "capture added 'const' to non-local?");
14170 // Decide whether the first capture was for a block or a lambda.
14171 DeclContext
*DC
= S
.CurContext
, *Prev
= nullptr;
14172 // Decide whether the first capture was for a block or a lambda.
14174 // For init-capture, it is possible that the variable belongs to the
14175 // template pattern of the current context.
14176 if (auto *FD
= dyn_cast
<FunctionDecl
>(DC
))
14177 if (var
->isInitCapture() &&
14178 FD
->getTemplateInstantiationPattern() == var
->getDeclContext())
14180 if (DC
== var
->getDeclContext())
14183 DC
= DC
->getParent();
14185 // Unless we have an init-capture, we've gone one step too far.
14186 if (!var
->isInitCapture())
14188 return (isa
<BlockDecl
>(DC
) ? NCCK_Block
: NCCK_Lambda
);
14191 static bool IsTypeModifiable(QualType Ty
, bool IsDereference
) {
14192 Ty
= Ty
.getNonReferenceType();
14193 if (IsDereference
&& Ty
->isPointerType())
14194 Ty
= Ty
->getPointeeType();
14195 return !Ty
.isConstQualified();
14198 // Update err_typecheck_assign_const and note_typecheck_assign_const
14199 // when this enum is changed.
14206 ConstUnknown
, // Keep as last element
14209 /// Emit the "read-only variable not assignable" error and print notes to give
14210 /// more information about why the variable is not assignable, such as pointing
14211 /// to the declaration of a const variable, showing that a method is const, or
14212 /// that the function is returning a const reference.
14213 static void DiagnoseConstAssignment(Sema
&S
, const Expr
*E
,
14214 SourceLocation Loc
) {
14215 SourceRange ExprRange
= E
->getSourceRange();
14217 // Only emit one error on the first const found. All other consts will emit
14218 // a note to the error.
14219 bool DiagnosticEmitted
= false;
14221 // Track if the current expression is the result of a dereference, and if the
14222 // next checked expression is the result of a dereference.
14223 bool IsDereference
= false;
14224 bool NextIsDereference
= false;
14226 // Loop to process MemberExpr chains.
14228 IsDereference
= NextIsDereference
;
14230 E
= E
->IgnoreImplicit()->IgnoreParenImpCasts();
14231 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
)) {
14232 NextIsDereference
= ME
->isArrow();
14233 const ValueDecl
*VD
= ME
->getMemberDecl();
14234 if (const FieldDecl
*Field
= dyn_cast
<FieldDecl
>(VD
)) {
14235 // Mutable fields can be modified even if the class is const.
14236 if (Field
->isMutable()) {
14237 assert(DiagnosticEmitted
&& "Expected diagnostic not emitted.");
14241 if (!IsTypeModifiable(Field
->getType(), IsDereference
)) {
14242 if (!DiagnosticEmitted
) {
14243 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
14244 << ExprRange
<< ConstMember
<< false /*static*/ << Field
14245 << Field
->getType();
14246 DiagnosticEmitted
= true;
14248 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
14249 << ConstMember
<< false /*static*/ << Field
<< Field
->getType()
14250 << Field
->getSourceRange();
14254 } else if (const VarDecl
*VDecl
= dyn_cast
<VarDecl
>(VD
)) {
14255 if (VDecl
->getType().isConstQualified()) {
14256 if (!DiagnosticEmitted
) {
14257 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
14258 << ExprRange
<< ConstMember
<< true /*static*/ << VDecl
14259 << VDecl
->getType();
14260 DiagnosticEmitted
= true;
14262 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
14263 << ConstMember
<< true /*static*/ << VDecl
<< VDecl
->getType()
14264 << VDecl
->getSourceRange();
14266 // Static fields do not inherit constness from parents.
14269 break; // End MemberExpr
14270 } else if (const ArraySubscriptExpr
*ASE
=
14271 dyn_cast
<ArraySubscriptExpr
>(E
)) {
14272 E
= ASE
->getBase()->IgnoreParenImpCasts();
14274 } else if (const ExtVectorElementExpr
*EVE
=
14275 dyn_cast
<ExtVectorElementExpr
>(E
)) {
14276 E
= EVE
->getBase()->IgnoreParenImpCasts();
14282 if (const CallExpr
*CE
= dyn_cast
<CallExpr
>(E
)) {
14284 const FunctionDecl
*FD
= CE
->getDirectCallee();
14285 if (FD
&& !IsTypeModifiable(FD
->getReturnType(), IsDereference
)) {
14286 if (!DiagnosticEmitted
) {
14287 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
14288 << ConstFunction
<< FD
;
14289 DiagnosticEmitted
= true;
14291 S
.Diag(FD
->getReturnTypeSourceRange().getBegin(),
14292 diag::note_typecheck_assign_const
)
14293 << ConstFunction
<< FD
<< FD
->getReturnType()
14294 << FD
->getReturnTypeSourceRange();
14296 } else if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
14297 // Point to variable declaration.
14298 if (const ValueDecl
*VD
= DRE
->getDecl()) {
14299 if (!IsTypeModifiable(VD
->getType(), IsDereference
)) {
14300 if (!DiagnosticEmitted
) {
14301 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
14302 << ExprRange
<< ConstVariable
<< VD
<< VD
->getType();
14303 DiagnosticEmitted
= true;
14305 S
.Diag(VD
->getLocation(), diag::note_typecheck_assign_const
)
14306 << ConstVariable
<< VD
<< VD
->getType() << VD
->getSourceRange();
14309 } else if (isa
<CXXThisExpr
>(E
)) {
14310 if (const DeclContext
*DC
= S
.getFunctionLevelDeclContext()) {
14311 if (const CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(DC
)) {
14312 if (MD
->isConst()) {
14313 if (!DiagnosticEmitted
) {
14314 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
14315 << ConstMethod
<< MD
;
14316 DiagnosticEmitted
= true;
14318 S
.Diag(MD
->getLocation(), diag::note_typecheck_assign_const
)
14319 << ConstMethod
<< MD
<< MD
->getSourceRange();
14325 if (DiagnosticEmitted
)
14328 // Can't determine a more specific message, so display the generic error.
14329 S
.Diag(Loc
, diag::err_typecheck_assign_const
) << ExprRange
<< ConstUnknown
;
14332 enum OriginalExprKind
{
14338 static void DiagnoseRecursiveConstFields(Sema
&S
, const ValueDecl
*VD
,
14339 const RecordType
*Ty
,
14340 SourceLocation Loc
, SourceRange Range
,
14341 OriginalExprKind OEK
,
14342 bool &DiagnosticEmitted
) {
14343 std::vector
<const RecordType
*> RecordTypeList
;
14344 RecordTypeList
.push_back(Ty
);
14345 unsigned NextToCheckIndex
= 0;
14346 // We walk the record hierarchy breadth-first to ensure that we print
14347 // diagnostics in field nesting order.
14348 while (RecordTypeList
.size() > NextToCheckIndex
) {
14349 bool IsNested
= NextToCheckIndex
> 0;
14350 for (const FieldDecl
*Field
:
14351 RecordTypeList
[NextToCheckIndex
]->getDecl()->fields()) {
14352 // First, check every field for constness.
14353 QualType FieldTy
= Field
->getType();
14354 if (FieldTy
.isConstQualified()) {
14355 if (!DiagnosticEmitted
) {
14356 S
.Diag(Loc
, diag::err_typecheck_assign_const
)
14357 << Range
<< NestedConstMember
<< OEK
<< VD
14358 << IsNested
<< Field
;
14359 DiagnosticEmitted
= true;
14361 S
.Diag(Field
->getLocation(), diag::note_typecheck_assign_const
)
14362 << NestedConstMember
<< IsNested
<< Field
14363 << FieldTy
<< Field
->getSourceRange();
14366 // Then we append it to the list to check next in order.
14367 FieldTy
= FieldTy
.getCanonicalType();
14368 if (const auto *FieldRecTy
= FieldTy
->getAs
<RecordType
>()) {
14369 if (!llvm::is_contained(RecordTypeList
, FieldRecTy
))
14370 RecordTypeList
.push_back(FieldRecTy
);
14373 ++NextToCheckIndex
;
14377 /// Emit an error for the case where a record we are trying to assign to has a
14378 /// const-qualified field somewhere in its hierarchy.
14379 static void DiagnoseRecursiveConstFields(Sema
&S
, const Expr
*E
,
14380 SourceLocation Loc
) {
14381 QualType Ty
= E
->getType();
14382 assert(Ty
->isRecordType() && "lvalue was not record?");
14383 SourceRange Range
= E
->getSourceRange();
14384 const RecordType
*RTy
= Ty
.getCanonicalType()->getAs
<RecordType
>();
14385 bool DiagEmitted
= false;
14387 if (const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
))
14388 DiagnoseRecursiveConstFields(S
, ME
->getMemberDecl(), RTy
, Loc
,
14389 Range
, OEK_Member
, DiagEmitted
);
14390 else if (const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
))
14391 DiagnoseRecursiveConstFields(S
, DRE
->getDecl(), RTy
, Loc
,
14392 Range
, OEK_Variable
, DiagEmitted
);
14394 DiagnoseRecursiveConstFields(S
, nullptr, RTy
, Loc
,
14395 Range
, OEK_LValue
, DiagEmitted
);
14397 DiagnoseConstAssignment(S
, E
, Loc
);
14400 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
14401 /// emit an error and return true. If so, return false.
14402 static bool CheckForModifiableLvalue(Expr
*E
, SourceLocation Loc
, Sema
&S
) {
14403 assert(!E
->hasPlaceholderType(BuiltinType::PseudoObject
));
14405 S
.CheckShadowingDeclModification(E
, Loc
);
14407 SourceLocation OrigLoc
= Loc
;
14408 Expr::isModifiableLvalueResult IsLV
= E
->isModifiableLvalue(S
.Context
,
14410 if (IsLV
== Expr::MLV_ClassTemporary
&& IsReadonlyMessage(E
, S
))
14411 IsLV
= Expr::MLV_InvalidMessageExpression
;
14412 if (IsLV
== Expr::MLV_Valid
)
14415 unsigned DiagID
= 0;
14416 bool NeedType
= false;
14417 switch (IsLV
) { // C99 6.5.16p2
14418 case Expr::MLV_ConstQualified
:
14419 // Use a specialized diagnostic when we're assigning to an object
14420 // from an enclosing function or block.
14421 if (NonConstCaptureKind NCCK
= isReferenceToNonConstCapture(S
, E
)) {
14422 if (NCCK
== NCCK_Block
)
14423 DiagID
= diag::err_block_decl_ref_not_modifiable_lvalue
;
14425 DiagID
= diag::err_lambda_decl_ref_not_modifiable_lvalue
;
14429 // In ARC, use some specialized diagnostics for occasions where we
14430 // infer 'const'. These are always pseudo-strong variables.
14431 if (S
.getLangOpts().ObjCAutoRefCount
) {
14432 DeclRefExpr
*declRef
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenCasts());
14433 if (declRef
&& isa
<VarDecl
>(declRef
->getDecl())) {
14434 VarDecl
*var
= cast
<VarDecl
>(declRef
->getDecl());
14436 // Use the normal diagnostic if it's pseudo-__strong but the
14437 // user actually wrote 'const'.
14438 if (var
->isARCPseudoStrong() &&
14439 (!var
->getTypeSourceInfo() ||
14440 !var
->getTypeSourceInfo()->getType().isConstQualified())) {
14441 // There are three pseudo-strong cases:
14443 ObjCMethodDecl
*method
= S
.getCurMethodDecl();
14444 if (method
&& var
== method
->getSelfDecl()) {
14445 DiagID
= method
->isClassMethod()
14446 ? diag::err_typecheck_arc_assign_self_class_method
14447 : diag::err_typecheck_arc_assign_self
;
14449 // - Objective-C externally_retained attribute.
14450 } else if (var
->hasAttr
<ObjCExternallyRetainedAttr
>() ||
14451 isa
<ParmVarDecl
>(var
)) {
14452 DiagID
= diag::err_typecheck_arc_assign_externally_retained
;
14454 // - fast enumeration variables
14456 DiagID
= diag::err_typecheck_arr_assign_enumeration
;
14459 SourceRange Assign
;
14460 if (Loc
!= OrigLoc
)
14461 Assign
= SourceRange(OrigLoc
, OrigLoc
);
14462 S
.Diag(Loc
, DiagID
) << E
->getSourceRange() << Assign
;
14463 // We need to preserve the AST regardless, so migration tool
14470 // If none of the special cases above are triggered, then this is a
14471 // simple const assignment.
14473 DiagnoseConstAssignment(S
, E
, Loc
);
14478 case Expr::MLV_ConstAddrSpace
:
14479 DiagnoseConstAssignment(S
, E
, Loc
);
14481 case Expr::MLV_ConstQualifiedField
:
14482 DiagnoseRecursiveConstFields(S
, E
, Loc
);
14484 case Expr::MLV_ArrayType
:
14485 case Expr::MLV_ArrayTemporary
:
14486 DiagID
= diag::err_typecheck_array_not_modifiable_lvalue
;
14489 case Expr::MLV_NotObjectType
:
14490 DiagID
= diag::err_typecheck_non_object_not_modifiable_lvalue
;
14493 case Expr::MLV_LValueCast
:
14494 DiagID
= diag::err_typecheck_lvalue_casts_not_supported
;
14496 case Expr::MLV_Valid
:
14497 llvm_unreachable("did not take early return for MLV_Valid");
14498 case Expr::MLV_InvalidExpression
:
14499 case Expr::MLV_MemberFunction
:
14500 case Expr::MLV_ClassTemporary
:
14501 DiagID
= diag::err_typecheck_expression_not_modifiable_lvalue
;
14503 case Expr::MLV_IncompleteType
:
14504 case Expr::MLV_IncompleteVoidType
:
14505 return S
.RequireCompleteType(Loc
, E
->getType(),
14506 diag::err_typecheck_incomplete_type_not_modifiable_lvalue
, E
);
14507 case Expr::MLV_DuplicateVectorComponents
:
14508 DiagID
= diag::err_typecheck_duplicate_vector_components_not_mlvalue
;
14510 case Expr::MLV_NoSetterProperty
:
14511 llvm_unreachable("readonly properties should be processed differently");
14512 case Expr::MLV_InvalidMessageExpression
:
14513 DiagID
= diag::err_readonly_message_assignment
;
14515 case Expr::MLV_SubObjCPropertySetting
:
14516 DiagID
= diag::err_no_subobject_property_setting
;
14520 SourceRange Assign
;
14521 if (Loc
!= OrigLoc
)
14522 Assign
= SourceRange(OrigLoc
, OrigLoc
);
14524 S
.Diag(Loc
, DiagID
) << E
->getType() << E
->getSourceRange() << Assign
;
14526 S
.Diag(Loc
, DiagID
) << E
->getSourceRange() << Assign
;
14530 static void CheckIdentityFieldAssignment(Expr
*LHSExpr
, Expr
*RHSExpr
,
14531 SourceLocation Loc
,
14533 if (Sema
.inTemplateInstantiation())
14535 if (Sema
.isUnevaluatedContext())
14537 if (Loc
.isInvalid() || Loc
.isMacroID())
14539 if (LHSExpr
->getExprLoc().isMacroID() || RHSExpr
->getExprLoc().isMacroID())
14543 MemberExpr
*ML
= dyn_cast
<MemberExpr
>(LHSExpr
);
14544 MemberExpr
*MR
= dyn_cast
<MemberExpr
>(RHSExpr
);
14546 if (!(isa
<CXXThisExpr
>(ML
->getBase()) && isa
<CXXThisExpr
>(MR
->getBase())))
14548 const ValueDecl
*LHSDecl
=
14549 cast
<ValueDecl
>(ML
->getMemberDecl()->getCanonicalDecl());
14550 const ValueDecl
*RHSDecl
=
14551 cast
<ValueDecl
>(MR
->getMemberDecl()->getCanonicalDecl());
14552 if (LHSDecl
!= RHSDecl
)
14554 if (LHSDecl
->getType().isVolatileQualified())
14556 if (const ReferenceType
*RefTy
= LHSDecl
->getType()->getAs
<ReferenceType
>())
14557 if (RefTy
->getPointeeType().isVolatileQualified())
14560 Sema
.Diag(Loc
, diag::warn_identity_field_assign
) << 0;
14563 // Objective-C instance variables
14564 ObjCIvarRefExpr
*OL
= dyn_cast
<ObjCIvarRefExpr
>(LHSExpr
);
14565 ObjCIvarRefExpr
*OR
= dyn_cast
<ObjCIvarRefExpr
>(RHSExpr
);
14566 if (OL
&& OR
&& OL
->getDecl() == OR
->getDecl()) {
14567 DeclRefExpr
*RL
= dyn_cast
<DeclRefExpr
>(OL
->getBase()->IgnoreImpCasts());
14568 DeclRefExpr
*RR
= dyn_cast
<DeclRefExpr
>(OR
->getBase()->IgnoreImpCasts());
14569 if (RL
&& RR
&& RL
->getDecl() == RR
->getDecl())
14570 Sema
.Diag(Loc
, diag::warn_identity_field_assign
) << 1;
14575 QualType
Sema::CheckAssignmentOperands(Expr
*LHSExpr
, ExprResult
&RHS
,
14576 SourceLocation Loc
,
14577 QualType CompoundType
,
14578 BinaryOperatorKind Opc
) {
14579 assert(!LHSExpr
->hasPlaceholderType(BuiltinType::PseudoObject
));
14581 // Verify that LHS is a modifiable lvalue, and emit error if not.
14582 if (CheckForModifiableLvalue(LHSExpr
, Loc
, *this))
14585 QualType LHSType
= LHSExpr
->getType();
14586 QualType RHSType
= CompoundType
.isNull() ? RHS
.get()->getType() :
14588 // OpenCL v1.2 s6.1.1.1 p2:
14589 // The half data type can only be used to declare a pointer to a buffer that
14590 // contains half values
14591 if (getLangOpts().OpenCL
&&
14592 !getOpenCLOptions().isAvailableOption("cl_khr_fp16", getLangOpts()) &&
14593 LHSType
->isHalfType()) {
14594 Diag(Loc
, diag::err_opencl_half_load_store
) << 1
14595 << LHSType
.getUnqualifiedType();
14599 // WebAssembly tables can't be used on RHS of an assignment expression.
14600 if (RHSType
->isWebAssemblyTableType()) {
14601 Diag(Loc
, diag::err_wasm_table_art
) << 0;
14605 AssignConvertType ConvTy
;
14606 if (CompoundType
.isNull()) {
14607 Expr
*RHSCheck
= RHS
.get();
14609 CheckIdentityFieldAssignment(LHSExpr
, RHSCheck
, Loc
, *this);
14611 QualType
LHSTy(LHSType
);
14612 ConvTy
= CheckSingleAssignmentConstraints(LHSTy
, RHS
);
14613 if (RHS
.isInvalid())
14615 // Special case of NSObject attributes on c-style pointer types.
14616 if (ConvTy
== IncompatiblePointer
&&
14617 ((Context
.isObjCNSObjectType(LHSType
) &&
14618 RHSType
->isObjCObjectPointerType()) ||
14619 (Context
.isObjCNSObjectType(RHSType
) &&
14620 LHSType
->isObjCObjectPointerType())))
14621 ConvTy
= Compatible
;
14623 if (ConvTy
== Compatible
&&
14624 LHSType
->isObjCObjectType())
14625 Diag(Loc
, diag::err_objc_object_assignment
)
14628 // If the RHS is a unary plus or minus, check to see if they = and + are
14629 // right next to each other. If so, the user may have typo'd "x =+ 4"
14630 // instead of "x += 4".
14631 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(RHSCheck
))
14632 RHSCheck
= ICE
->getSubExpr();
14633 if (UnaryOperator
*UO
= dyn_cast
<UnaryOperator
>(RHSCheck
)) {
14634 if ((UO
->getOpcode() == UO_Plus
|| UO
->getOpcode() == UO_Minus
) &&
14635 Loc
.isFileID() && UO
->getOperatorLoc().isFileID() &&
14636 // Only if the two operators are exactly adjacent.
14637 Loc
.getLocWithOffset(1) == UO
->getOperatorLoc() &&
14638 // And there is a space or other character before the subexpr of the
14639 // unary +/-. We don't want to warn on "x=-1".
14640 Loc
.getLocWithOffset(2) != UO
->getSubExpr()->getBeginLoc() &&
14641 UO
->getSubExpr()->getBeginLoc().isFileID()) {
14642 Diag(Loc
, diag::warn_not_compound_assign
)
14643 << (UO
->getOpcode() == UO_Plus
? "+" : "-")
14644 << SourceRange(UO
->getOperatorLoc(), UO
->getOperatorLoc());
14648 if (ConvTy
== Compatible
) {
14649 if (LHSType
.getObjCLifetime() == Qualifiers::OCL_Strong
) {
14650 // Warn about retain cycles where a block captures the LHS, but
14651 // not if the LHS is a simple variable into which the block is
14652 // being stored...unless that variable can be captured by reference!
14653 const Expr
*InnerLHS
= LHSExpr
->IgnoreParenCasts();
14654 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(InnerLHS
);
14655 if (!DRE
|| DRE
->getDecl()->hasAttr
<BlocksAttr
>())
14656 checkRetainCycles(LHSExpr
, RHS
.get());
14659 if (LHSType
.getObjCLifetime() == Qualifiers::OCL_Strong
||
14660 LHSType
.isNonWeakInMRRWithObjCWeak(Context
)) {
14661 // It is safe to assign a weak reference into a strong variable.
14662 // Although this code can still have problems:
14663 // id x = self.weakProp;
14664 // id y = self.weakProp;
14665 // we do not warn to warn spuriously when 'x' and 'y' are on separate
14666 // paths through the function. This should be revisited if
14667 // -Wrepeated-use-of-weak is made flow-sensitive.
14668 // For ObjCWeak only, we do not warn if the assign is to a non-weak
14669 // variable, which will be valid for the current autorelease scope.
14670 if (!Diags
.isIgnored(diag::warn_arc_repeated_use_of_weak
,
14671 RHS
.get()->getBeginLoc()))
14672 getCurFunction()->markSafeWeakUse(RHS
.get());
14674 } else if (getLangOpts().ObjCAutoRefCount
|| getLangOpts().ObjCWeak
) {
14675 checkUnsafeExprAssigns(Loc
, LHSExpr
, RHS
.get());
14679 // Compound assignment "x += y"
14680 ConvTy
= CheckAssignmentConstraints(Loc
, LHSType
, RHSType
);
14683 if (DiagnoseAssignmentResult(ConvTy
, Loc
, LHSType
, RHSType
,
14684 RHS
.get(), AA_Assigning
))
14687 CheckForNullPointerDereference(*this, LHSExpr
);
14689 if (getLangOpts().CPlusPlus20
&& LHSType
.isVolatileQualified()) {
14690 if (CompoundType
.isNull()) {
14691 // C++2a [expr.ass]p5:
14692 // A simple-assignment whose left operand is of a volatile-qualified
14693 // type is deprecated unless the assignment is either a discarded-value
14694 // expression or an unevaluated operand
14695 ExprEvalContexts
.back().VolatileAssignmentLHSs
.push_back(LHSExpr
);
14699 // C11 6.5.16p3: The type of an assignment expression is the type of the
14700 // left operand would have after lvalue conversion.
14701 // C11 6.3.2.1p2: ...this is called lvalue conversion. If the lvalue has
14702 // qualified type, the value has the unqualified version of the type of the
14703 // lvalue; additionally, if the lvalue has atomic type, the value has the
14704 // non-atomic version of the type of the lvalue.
14705 // C++ 5.17p1: the type of the assignment expression is that of its left
14707 return getLangOpts().CPlusPlus
? LHSType
: LHSType
.getAtomicUnqualifiedType();
14710 // Scenarios to ignore if expression E is:
14711 // 1. an explicit cast expression into void
14712 // 2. a function call expression that returns void
14713 static bool IgnoreCommaOperand(const Expr
*E
, const ASTContext
&Context
) {
14714 E
= E
->IgnoreParens();
14716 if (const CastExpr
*CE
= dyn_cast
<CastExpr
>(E
)) {
14717 if (CE
->getCastKind() == CK_ToVoid
) {
14721 // static_cast<void> on a dependent type will not show up as CK_ToVoid.
14722 if (CE
->getCastKind() == CK_Dependent
&& E
->getType()->isVoidType() &&
14723 CE
->getSubExpr()->getType()->isDependentType()) {
14728 if (const auto *CE
= dyn_cast
<CallExpr
>(E
))
14729 return CE
->getCallReturnType(Context
)->isVoidType();
14733 // Look for instances where it is likely the comma operator is confused with
14734 // another operator. There is an explicit list of acceptable expressions for
14735 // the left hand side of the comma operator, otherwise emit a warning.
14736 void Sema::DiagnoseCommaOperator(const Expr
*LHS
, SourceLocation Loc
) {
14737 // No warnings in macros
14738 if (Loc
.isMacroID())
14741 // Don't warn in template instantiations.
14742 if (inTemplateInstantiation())
14745 // Scope isn't fine-grained enough to explicitly list the specific cases, so
14746 // instead, skip more than needed, then call back into here with the
14747 // CommaVisitor in SemaStmt.cpp.
14748 // The listed locations are the initialization and increment portions
14749 // of a for loop. The additional checks are on the condition of
14750 // if statements, do/while loops, and for loops.
14751 // Differences in scope flags for C89 mode requires the extra logic.
14752 const unsigned ForIncrementFlags
=
14753 getLangOpts().C99
|| getLangOpts().CPlusPlus
14754 ? Scope::ControlScope
| Scope::ContinueScope
| Scope::BreakScope
14755 : Scope::ContinueScope
| Scope::BreakScope
;
14756 const unsigned ForInitFlags
= Scope::ControlScope
| Scope::DeclScope
;
14757 const unsigned ScopeFlags
= getCurScope()->getFlags();
14758 if ((ScopeFlags
& ForIncrementFlags
) == ForIncrementFlags
||
14759 (ScopeFlags
& ForInitFlags
) == ForInitFlags
)
14762 // If there are multiple comma operators used together, get the RHS of the
14763 // of the comma operator as the LHS.
14764 while (const BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(LHS
)) {
14765 if (BO
->getOpcode() != BO_Comma
)
14767 LHS
= BO
->getRHS();
14770 // Only allow some expressions on LHS to not warn.
14771 if (IgnoreCommaOperand(LHS
, Context
))
14774 Diag(Loc
, diag::warn_comma_operator
);
14775 Diag(LHS
->getBeginLoc(), diag::note_cast_to_void
)
14776 << LHS
->getSourceRange()
14777 << FixItHint::CreateInsertion(LHS
->getBeginLoc(),
14778 LangOpts
.CPlusPlus
? "static_cast<void>("
14780 << FixItHint::CreateInsertion(PP
.getLocForEndOfToken(LHS
->getEndLoc()),
14785 static QualType
CheckCommaOperands(Sema
&S
, ExprResult
&LHS
, ExprResult
&RHS
,
14786 SourceLocation Loc
) {
14787 LHS
= S
.CheckPlaceholderExpr(LHS
.get());
14788 RHS
= S
.CheckPlaceholderExpr(RHS
.get());
14789 if (LHS
.isInvalid() || RHS
.isInvalid())
14792 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
14793 // operands, but not unary promotions.
14794 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
14796 // So we treat the LHS as a ignored value, and in C++ we allow the
14797 // containing site to determine what should be done with the RHS.
14798 LHS
= S
.IgnoredValueConversions(LHS
.get());
14799 if (LHS
.isInvalid())
14802 S
.DiagnoseUnusedExprResult(LHS
.get(), diag::warn_unused_comma_left_operand
);
14804 if (!S
.getLangOpts().CPlusPlus
) {
14805 RHS
= S
.DefaultFunctionArrayLvalueConversion(RHS
.get());
14806 if (RHS
.isInvalid())
14808 if (!RHS
.get()->getType()->isVoidType())
14809 S
.RequireCompleteType(Loc
, RHS
.get()->getType(),
14810 diag::err_incomplete_type
);
14813 if (!S
.getDiagnostics().isIgnored(diag::warn_comma_operator
, Loc
))
14814 S
.DiagnoseCommaOperator(LHS
.get(), Loc
);
14816 return RHS
.get()->getType();
14819 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
14820 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
14821 static QualType
CheckIncrementDecrementOperand(Sema
&S
, Expr
*Op
,
14823 ExprObjectKind
&OK
,
14824 SourceLocation OpLoc
,
14825 bool IsInc
, bool IsPrefix
) {
14826 if (Op
->isTypeDependent())
14827 return S
.Context
.DependentTy
;
14829 QualType ResType
= Op
->getType();
14830 // Atomic types can be used for increment / decrement where the non-atomic
14831 // versions can, so ignore the _Atomic() specifier for the purpose of
14833 if (const AtomicType
*ResAtomicType
= ResType
->getAs
<AtomicType
>())
14834 ResType
= ResAtomicType
->getValueType();
14836 assert(!ResType
.isNull() && "no type for increment/decrement expression");
14838 if (S
.getLangOpts().CPlusPlus
&& ResType
->isBooleanType()) {
14839 // Decrement of bool is not allowed.
14841 S
.Diag(OpLoc
, diag::err_decrement_bool
) << Op
->getSourceRange();
14844 // Increment of bool sets it to true, but is deprecated.
14845 S
.Diag(OpLoc
, S
.getLangOpts().CPlusPlus17
? diag::ext_increment_bool
14846 : diag::warn_increment_bool
)
14847 << Op
->getSourceRange();
14848 } else if (S
.getLangOpts().CPlusPlus
&& ResType
->isEnumeralType()) {
14849 // Error on enum increments and decrements in C++ mode
14850 S
.Diag(OpLoc
, diag::err_increment_decrement_enum
) << IsInc
<< ResType
;
14852 } else if (ResType
->isRealType()) {
14854 } else if (ResType
->isPointerType()) {
14855 // C99 6.5.2.4p2, 6.5.6p2
14856 if (!checkArithmeticOpPointerOperand(S
, OpLoc
, Op
))
14858 } else if (ResType
->isObjCObjectPointerType()) {
14859 // On modern runtimes, ObjC pointer arithmetic is forbidden.
14860 // Otherwise, we just need a complete type.
14861 if (checkArithmeticIncompletePointerType(S
, OpLoc
, Op
) ||
14862 checkArithmeticOnObjCPointer(S
, OpLoc
, Op
))
14864 } else if (ResType
->isAnyComplexType()) {
14865 // C99 does not support ++/-- on complex types, we allow as an extension.
14866 S
.Diag(OpLoc
, diag::ext_integer_increment_complex
)
14867 << ResType
<< Op
->getSourceRange();
14868 } else if (ResType
->isPlaceholderType()) {
14869 ExprResult PR
= S
.CheckPlaceholderExpr(Op
);
14870 if (PR
.isInvalid()) return QualType();
14871 return CheckIncrementDecrementOperand(S
, PR
.get(), VK
, OK
, OpLoc
,
14873 } else if (S
.getLangOpts().AltiVec
&& ResType
->isVectorType()) {
14874 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
14875 } else if (S
.getLangOpts().ZVector
&& ResType
->isVectorType() &&
14876 (ResType
->castAs
<VectorType
>()->getVectorKind() !=
14877 VectorKind::AltiVecBool
)) {
14878 // The z vector extensions allow ++ and -- for non-bool vectors.
14879 } else if (S
.getLangOpts().OpenCL
&& ResType
->isVectorType() &&
14880 ResType
->castAs
<VectorType
>()->getElementType()->isIntegerType()) {
14881 // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
14883 S
.Diag(OpLoc
, diag::err_typecheck_illegal_increment_decrement
)
14884 << ResType
<< int(IsInc
) << Op
->getSourceRange();
14887 // At this point, we know we have a real, complex or pointer type.
14888 // Now make sure the operand is a modifiable lvalue.
14889 if (CheckForModifiableLvalue(Op
, OpLoc
, S
))
14891 if (S
.getLangOpts().CPlusPlus20
&& ResType
.isVolatileQualified()) {
14892 // C++2a [expr.pre.inc]p1, [expr.post.inc]p1:
14893 // An operand with volatile-qualified type is deprecated
14894 S
.Diag(OpLoc
, diag::warn_deprecated_increment_decrement_volatile
)
14895 << IsInc
<< ResType
;
14897 // In C++, a prefix increment is the same type as the operand. Otherwise
14898 // (in C or with postfix), the increment is the unqualified type of the
14900 if (IsPrefix
&& S
.getLangOpts().CPlusPlus
) {
14902 OK
= Op
->getObjectKind();
14906 return ResType
.getUnqualifiedType();
14911 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
14912 /// This routine allows us to typecheck complex/recursive expressions
14913 /// where the declaration is needed for type checking. We only need to
14914 /// handle cases when the expression references a function designator
14915 /// or is an lvalue. Here are some examples:
14917 /// - &*****f => f for f a function designator.
14919 /// - &s.zz[1].yy -> s, if zz is an array
14920 /// - *(x + 1) -> x, if x is an array
14921 /// - &"123"[2] -> 0
14922 /// - & __real__ x -> x
14924 /// FIXME: We don't recurse to the RHS of a comma, nor handle pointers to
14926 static ValueDecl
*getPrimaryDecl(Expr
*E
) {
14927 switch (E
->getStmtClass()) {
14928 case Stmt::DeclRefExprClass
:
14929 return cast
<DeclRefExpr
>(E
)->getDecl();
14930 case Stmt::MemberExprClass
:
14931 // If this is an arrow operator, the address is an offset from
14932 // the base's value, so the object the base refers to is
14934 if (cast
<MemberExpr
>(E
)->isArrow())
14936 // Otherwise, the expression refers to a part of the base
14937 return getPrimaryDecl(cast
<MemberExpr
>(E
)->getBase());
14938 case Stmt::ArraySubscriptExprClass
: {
14939 // FIXME: This code shouldn't be necessary! We should catch the implicit
14940 // promotion of register arrays earlier.
14941 Expr
* Base
= cast
<ArraySubscriptExpr
>(E
)->getBase();
14942 if (ImplicitCastExpr
* ICE
= dyn_cast
<ImplicitCastExpr
>(Base
)) {
14943 if (ICE
->getSubExpr()->getType()->isArrayType())
14944 return getPrimaryDecl(ICE
->getSubExpr());
14948 case Stmt::UnaryOperatorClass
: {
14949 UnaryOperator
*UO
= cast
<UnaryOperator
>(E
);
14951 switch(UO
->getOpcode()) {
14955 return getPrimaryDecl(UO
->getSubExpr());
14960 case Stmt::ParenExprClass
:
14961 return getPrimaryDecl(cast
<ParenExpr
>(E
)->getSubExpr());
14962 case Stmt::ImplicitCastExprClass
:
14963 // If the result of an implicit cast is an l-value, we care about
14964 // the sub-expression; otherwise, the result here doesn't matter.
14965 return getPrimaryDecl(cast
<ImplicitCastExpr
>(E
)->getSubExpr());
14966 case Stmt::CXXUuidofExprClass
:
14967 return cast
<CXXUuidofExpr
>(E
)->getGuidDecl();
14976 AO_Vector_Element
= 1,
14977 AO_Property_Expansion
= 2,
14978 AO_Register_Variable
= 3,
14979 AO_Matrix_Element
= 4,
14983 /// Diagnose invalid operand for address of operations.
14985 /// \param Type The type of operand which cannot have its address taken.
14986 static void diagnoseAddressOfInvalidType(Sema
&S
, SourceLocation Loc
,
14987 Expr
*E
, unsigned Type
) {
14988 S
.Diag(Loc
, diag::err_typecheck_address_of
) << Type
<< E
->getSourceRange();
14991 bool Sema::CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc
,
14993 const CXXMethodDecl
*MD
) {
14994 const auto *DRE
= cast
<DeclRefExpr
>(Op
->IgnoreParens());
14997 return Diag(OpLoc
, diag::err_parens_pointer_member_function
)
14998 << Op
->getSourceRange();
15000 // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
15001 if (isa
<CXXDestructorDecl
>(MD
))
15002 return Diag(OpLoc
, diag::err_typecheck_addrof_dtor
)
15003 << DRE
->getSourceRange();
15005 if (DRE
->getQualifier())
15008 if (MD
->getParent()->getName().empty())
15009 return Diag(OpLoc
, diag::err_unqualified_pointer_member_function
)
15010 << DRE
->getSourceRange();
15012 SmallString
<32> Str
;
15013 StringRef Qual
= (MD
->getParent()->getName() + "::").toStringRef(Str
);
15014 return Diag(OpLoc
, diag::err_unqualified_pointer_member_function
)
15015 << DRE
->getSourceRange()
15016 << FixItHint::CreateInsertion(DRE
->getSourceRange().getBegin(), Qual
);
15019 /// CheckAddressOfOperand - The operand of & must be either a function
15020 /// designator or an lvalue designating an object. If it is an lvalue, the
15021 /// object cannot be declared with storage class register or be a bit field.
15022 /// Note: The usual conversions are *not* applied to the operand of the &
15023 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
15024 /// In C++, the operand might be an overloaded function name, in which case
15025 /// we allow the '&' but retain the overloaded-function type.
15026 QualType
Sema::CheckAddressOfOperand(ExprResult
&OrigOp
, SourceLocation OpLoc
) {
15027 if (const BuiltinType
*PTy
= OrigOp
.get()->getType()->getAsPlaceholderType()){
15028 if (PTy
->getKind() == BuiltinType::Overload
) {
15029 Expr
*E
= OrigOp
.get()->IgnoreParens();
15030 if (!isa
<OverloadExpr
>(E
)) {
15031 assert(cast
<UnaryOperator
>(E
)->getOpcode() == UO_AddrOf
);
15032 Diag(OpLoc
, diag::err_typecheck_invalid_lvalue_addrof_addrof_function
)
15033 << OrigOp
.get()->getSourceRange();
15037 OverloadExpr
*Ovl
= cast
<OverloadExpr
>(E
);
15038 if (isa
<UnresolvedMemberExpr
>(Ovl
))
15039 if (!ResolveSingleFunctionTemplateSpecialization(Ovl
)) {
15040 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
15041 << OrigOp
.get()->getSourceRange();
15045 return Context
.OverloadTy
;
15048 if (PTy
->getKind() == BuiltinType::UnknownAny
)
15049 return Context
.UnknownAnyTy
;
15051 if (PTy
->getKind() == BuiltinType::BoundMember
) {
15052 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
15053 << OrigOp
.get()->getSourceRange();
15057 OrigOp
= CheckPlaceholderExpr(OrigOp
.get());
15058 if (OrigOp
.isInvalid()) return QualType();
15061 if (OrigOp
.get()->isTypeDependent())
15062 return Context
.DependentTy
;
15064 assert(!OrigOp
.get()->hasPlaceholderType());
15066 // Make sure to ignore parentheses in subsequent checks
15067 Expr
*op
= OrigOp
.get()->IgnoreParens();
15069 // In OpenCL captures for blocks called as lambda functions
15070 // are located in the private address space. Blocks used in
15071 // enqueue_kernel can be located in a different address space
15072 // depending on a vendor implementation. Thus preventing
15073 // taking an address of the capture to avoid invalid AS casts.
15074 if (LangOpts
.OpenCL
) {
15075 auto* VarRef
= dyn_cast
<DeclRefExpr
>(op
);
15076 if (VarRef
&& VarRef
->refersToEnclosingVariableOrCapture()) {
15077 Diag(op
->getExprLoc(), diag::err_opencl_taking_address_capture
);
15082 if (getLangOpts().C99
) {
15083 // Implement C99-only parts of addressof rules.
15084 if (UnaryOperator
* uOp
= dyn_cast
<UnaryOperator
>(op
)) {
15085 if (uOp
->getOpcode() == UO_Deref
)
15086 // Per C99 6.5.3.2, the address of a deref always returns a valid result
15087 // (assuming the deref expression is valid).
15088 return uOp
->getSubExpr()->getType();
15090 // Technically, there should be a check for array subscript
15091 // expressions here, but the result of one is always an lvalue anyway.
15093 ValueDecl
*dcl
= getPrimaryDecl(op
);
15095 if (auto *FD
= dyn_cast_or_null
<FunctionDecl
>(dcl
))
15096 if (!checkAddressOfFunctionIsAvailable(FD
, /*Complain=*/true,
15097 op
->getBeginLoc()))
15100 Expr::LValueClassification lval
= op
->ClassifyLValue(Context
);
15101 unsigned AddressOfError
= AO_No_Error
;
15103 if (lval
== Expr::LV_ClassTemporary
|| lval
== Expr::LV_ArrayTemporary
) {
15104 bool sfinae
= (bool)isSFINAEContext();
15105 Diag(OpLoc
, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
15106 : diag::ext_typecheck_addrof_temporary
)
15107 << op
->getType() << op
->getSourceRange();
15110 // Materialize the temporary as an lvalue so that we can take its address.
15112 CreateMaterializeTemporaryExpr(op
->getType(), OrigOp
.get(), true);
15113 } else if (isa
<ObjCSelectorExpr
>(op
)) {
15114 return Context
.getPointerType(op
->getType());
15115 } else if (lval
== Expr::LV_MemberFunction
) {
15116 // If it's an instance method, make a member pointer.
15117 // The expression must have exactly the form &A::foo.
15119 // If the underlying expression isn't a decl ref, give up.
15120 if (!isa
<DeclRefExpr
>(op
)) {
15121 Diag(OpLoc
, diag::err_invalid_form_pointer_member_function
)
15122 << OrigOp
.get()->getSourceRange();
15125 DeclRefExpr
*DRE
= cast
<DeclRefExpr
>(op
);
15126 CXXMethodDecl
*MD
= cast
<CXXMethodDecl
>(DRE
->getDecl());
15128 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc
, OrigOp
.get(), MD
);
15130 QualType MPTy
= Context
.getMemberPointerType(
15131 op
->getType(), Context
.getTypeDeclType(MD
->getParent()).getTypePtr());
15132 // Under the MS ABI, lock down the inheritance model now.
15133 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
15134 (void)isCompleteType(OpLoc
, MPTy
);
15136 } else if (lval
!= Expr::LV_Valid
&& lval
!= Expr::LV_IncompleteVoidType
) {
15138 // The operand must be either an l-value or a function designator
15139 if (!op
->getType()->isFunctionType()) {
15140 // Use a special diagnostic for loads from property references.
15141 if (isa
<PseudoObjectExpr
>(op
)) {
15142 AddressOfError
= AO_Property_Expansion
;
15144 Diag(OpLoc
, diag::err_typecheck_invalid_lvalue_addrof
)
15145 << op
->getType() << op
->getSourceRange();
15148 } else if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(op
)) {
15149 if (const auto *MD
= dyn_cast_or_null
<CXXMethodDecl
>(DRE
->getDecl()))
15150 CheckUseOfCXXMethodAsAddressOfOperand(OpLoc
, OrigOp
.get(), MD
);
15153 } else if (op
->getObjectKind() == OK_BitField
) { // C99 6.5.3.2p1
15154 // The operand cannot be a bit-field
15155 AddressOfError
= AO_Bit_Field
;
15156 } else if (op
->getObjectKind() == OK_VectorComponent
) {
15157 // The operand cannot be an element of a vector
15158 AddressOfError
= AO_Vector_Element
;
15159 } else if (op
->getObjectKind() == OK_MatrixComponent
) {
15160 // The operand cannot be an element of a matrix.
15161 AddressOfError
= AO_Matrix_Element
;
15162 } else if (dcl
) { // C99 6.5.3.2p1
15163 // We have an lvalue with a decl. Make sure the decl is not declared
15164 // with the register storage-class specifier.
15165 if (const VarDecl
*vd
= dyn_cast
<VarDecl
>(dcl
)) {
15166 // in C++ it is not error to take address of a register
15167 // variable (c++03 7.1.1P3)
15168 if (vd
->getStorageClass() == SC_Register
&&
15169 !getLangOpts().CPlusPlus
) {
15170 AddressOfError
= AO_Register_Variable
;
15172 } else if (isa
<MSPropertyDecl
>(dcl
)) {
15173 AddressOfError
= AO_Property_Expansion
;
15174 } else if (isa
<FunctionTemplateDecl
>(dcl
)) {
15175 return Context
.OverloadTy
;
15176 } else if (isa
<FieldDecl
>(dcl
) || isa
<IndirectFieldDecl
>(dcl
)) {
15177 // Okay: we can take the address of a field.
15178 // Could be a pointer to member, though, if there is an explicit
15179 // scope qualifier for the class.
15180 if (isa
<DeclRefExpr
>(op
) && cast
<DeclRefExpr
>(op
)->getQualifier()) {
15181 DeclContext
*Ctx
= dcl
->getDeclContext();
15182 if (Ctx
&& Ctx
->isRecord()) {
15183 if (dcl
->getType()->isReferenceType()) {
15185 diag::err_cannot_form_pointer_to_member_of_reference_type
)
15186 << dcl
->getDeclName() << dcl
->getType();
15190 while (cast
<RecordDecl
>(Ctx
)->isAnonymousStructOrUnion())
15191 Ctx
= Ctx
->getParent();
15193 QualType MPTy
= Context
.getMemberPointerType(
15195 Context
.getTypeDeclType(cast
<RecordDecl
>(Ctx
)).getTypePtr());
15196 // Under the MS ABI, lock down the inheritance model now.
15197 if (Context
.getTargetInfo().getCXXABI().isMicrosoft())
15198 (void)isCompleteType(OpLoc
, MPTy
);
15202 } else if (!isa
<FunctionDecl
, NonTypeTemplateParmDecl
, BindingDecl
,
15203 MSGuidDecl
, UnnamedGlobalConstantDecl
>(dcl
))
15204 llvm_unreachable("Unknown/unexpected decl type");
15207 if (AddressOfError
!= AO_No_Error
) {
15208 diagnoseAddressOfInvalidType(*this, OpLoc
, op
, AddressOfError
);
15212 if (lval
== Expr::LV_IncompleteVoidType
) {
15213 // Taking the address of a void variable is technically illegal, but we
15214 // allow it in cases which are otherwise valid.
15215 // Example: "extern void x; void* y = &x;".
15216 Diag(OpLoc
, diag::ext_typecheck_addrof_void
) << op
->getSourceRange();
15219 // If the operand has type "type", the result has type "pointer to type".
15220 if (op
->getType()->isObjCObjectType())
15221 return Context
.getObjCObjectPointerType(op
->getType());
15223 // Cannot take the address of WebAssembly references or tables.
15224 if (Context
.getTargetInfo().getTriple().isWasm()) {
15225 QualType OpTy
= op
->getType();
15226 if (OpTy
.isWebAssemblyReferenceType()) {
15227 Diag(OpLoc
, diag::err_wasm_ca_reference
)
15228 << 1 << OrigOp
.get()->getSourceRange();
15231 if (OpTy
->isWebAssemblyTableType()) {
15232 Diag(OpLoc
, diag::err_wasm_table_pr
)
15233 << 1 << OrigOp
.get()->getSourceRange();
15238 CheckAddressOfPackedMember(op
);
15240 return Context
.getPointerType(op
->getType());
15243 static void RecordModifiableNonNullParam(Sema
&S
, const Expr
*Exp
) {
15244 const DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(Exp
);
15247 const Decl
*D
= DRE
->getDecl();
15250 const ParmVarDecl
*Param
= dyn_cast
<ParmVarDecl
>(D
);
15253 if (const FunctionDecl
* FD
= dyn_cast
<FunctionDecl
>(Param
->getDeclContext()))
15254 if (!FD
->hasAttr
<NonNullAttr
>() && !Param
->hasAttr
<NonNullAttr
>())
15256 if (FunctionScopeInfo
*FD
= S
.getCurFunction())
15257 FD
->ModifiedNonNullParams
.insert(Param
);
15260 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
15261 static QualType
CheckIndirectionOperand(Sema
&S
, Expr
*Op
, ExprValueKind
&VK
,
15262 SourceLocation OpLoc
,
15263 bool IsAfterAmp
= false) {
15264 if (Op
->isTypeDependent())
15265 return S
.Context
.DependentTy
;
15267 ExprResult ConvResult
= S
.UsualUnaryConversions(Op
);
15268 if (ConvResult
.isInvalid())
15270 Op
= ConvResult
.get();
15271 QualType OpTy
= Op
->getType();
15274 if (isa
<CXXReinterpretCastExpr
>(Op
)) {
15275 QualType OpOrigType
= Op
->IgnoreParenCasts()->getType();
15276 S
.CheckCompatibleReinterpretCast(OpOrigType
, OpTy
, /*IsDereference*/true,
15277 Op
->getSourceRange());
15280 if (const PointerType
*PT
= OpTy
->getAs
<PointerType
>())
15282 Result
= PT
->getPointeeType();
15284 else if (const ObjCObjectPointerType
*OPT
=
15285 OpTy
->getAs
<ObjCObjectPointerType
>())
15286 Result
= OPT
->getPointeeType();
15288 ExprResult PR
= S
.CheckPlaceholderExpr(Op
);
15289 if (PR
.isInvalid()) return QualType();
15290 if (PR
.get() != Op
)
15291 return CheckIndirectionOperand(S
, PR
.get(), VK
, OpLoc
);
15294 if (Result
.isNull()) {
15295 S
.Diag(OpLoc
, diag::err_typecheck_indirection_requires_pointer
)
15296 << OpTy
<< Op
->getSourceRange();
15300 if (Result
->isVoidType()) {
15301 // C++ [expr.unary.op]p1:
15302 // [...] the expression to which [the unary * operator] is applied shall
15303 // be a pointer to an object type, or a pointer to a function type
15304 LangOptions LO
= S
.getLangOpts();
15306 S
.Diag(OpLoc
, diag::err_typecheck_indirection_through_void_pointer_cpp
)
15307 << OpTy
<< Op
->getSourceRange();
15308 else if (!(LO
.C99
&& IsAfterAmp
) && !S
.isUnevaluatedContext())
15309 S
.Diag(OpLoc
, diag::ext_typecheck_indirection_through_void_pointer
)
15310 << OpTy
<< Op
->getSourceRange();
15313 // Dereferences are usually l-values...
15316 // ...except that certain expressions are never l-values in C.
15317 if (!S
.getLangOpts().CPlusPlus
&& Result
.isCForbiddenLValueType())
15323 BinaryOperatorKind
Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind
) {
15324 BinaryOperatorKind Opc
;
15326 default: llvm_unreachable("Unknown binop!");
15327 case tok::periodstar
: Opc
= BO_PtrMemD
; break;
15328 case tok::arrowstar
: Opc
= BO_PtrMemI
; break;
15329 case tok::star
: Opc
= BO_Mul
; break;
15330 case tok::slash
: Opc
= BO_Div
; break;
15331 case tok::percent
: Opc
= BO_Rem
; break;
15332 case tok::plus
: Opc
= BO_Add
; break;
15333 case tok::minus
: Opc
= BO_Sub
; break;
15334 case tok::lessless
: Opc
= BO_Shl
; break;
15335 case tok::greatergreater
: Opc
= BO_Shr
; break;
15336 case tok::lessequal
: Opc
= BO_LE
; break;
15337 case tok::less
: Opc
= BO_LT
; break;
15338 case tok::greaterequal
: Opc
= BO_GE
; break;
15339 case tok::greater
: Opc
= BO_GT
; break;
15340 case tok::exclaimequal
: Opc
= BO_NE
; break;
15341 case tok::equalequal
: Opc
= BO_EQ
; break;
15342 case tok::spaceship
: Opc
= BO_Cmp
; break;
15343 case tok::amp
: Opc
= BO_And
; break;
15344 case tok::caret
: Opc
= BO_Xor
; break;
15345 case tok::pipe
: Opc
= BO_Or
; break;
15346 case tok::ampamp
: Opc
= BO_LAnd
; break;
15347 case tok::pipepipe
: Opc
= BO_LOr
; break;
15348 case tok::equal
: Opc
= BO_Assign
; break;
15349 case tok::starequal
: Opc
= BO_MulAssign
; break;
15350 case tok::slashequal
: Opc
= BO_DivAssign
; break;
15351 case tok::percentequal
: Opc
= BO_RemAssign
; break;
15352 case tok::plusequal
: Opc
= BO_AddAssign
; break;
15353 case tok::minusequal
: Opc
= BO_SubAssign
; break;
15354 case tok::lesslessequal
: Opc
= BO_ShlAssign
; break;
15355 case tok::greatergreaterequal
: Opc
= BO_ShrAssign
; break;
15356 case tok::ampequal
: Opc
= BO_AndAssign
; break;
15357 case tok::caretequal
: Opc
= BO_XorAssign
; break;
15358 case tok::pipeequal
: Opc
= BO_OrAssign
; break;
15359 case tok::comma
: Opc
= BO_Comma
; break;
15364 static inline UnaryOperatorKind
ConvertTokenKindToUnaryOpcode(
15365 tok::TokenKind Kind
) {
15366 UnaryOperatorKind Opc
;
15368 default: llvm_unreachable("Unknown unary op!");
15369 case tok::plusplus
: Opc
= UO_PreInc
; break;
15370 case tok::minusminus
: Opc
= UO_PreDec
; break;
15371 case tok::amp
: Opc
= UO_AddrOf
; break;
15372 case tok::star
: Opc
= UO_Deref
; break;
15373 case tok::plus
: Opc
= UO_Plus
; break;
15374 case tok::minus
: Opc
= UO_Minus
; break;
15375 case tok::tilde
: Opc
= UO_Not
; break;
15376 case tok::exclaim
: Opc
= UO_LNot
; break;
15377 case tok::kw___real
: Opc
= UO_Real
; break;
15378 case tok::kw___imag
: Opc
= UO_Imag
; break;
15379 case tok::kw___extension__
: Opc
= UO_Extension
; break;
15385 Sema::getSelfAssignmentClassMemberCandidate(const ValueDecl
*SelfAssigned
) {
15386 // Explore the case for adding 'this->' to the LHS of a self assignment, very
15387 // common for setters.
15390 // -void setX(int X) { X = X; }
15391 // +void setX(int X) { this->X = X; }
15394 // Only consider parameters for self assignment fixes.
15395 if (!isa
<ParmVarDecl
>(SelfAssigned
))
15397 const auto *Method
=
15398 dyn_cast_or_null
<CXXMethodDecl
>(getCurFunctionDecl(true));
15402 const CXXRecordDecl
*Parent
= Method
->getParent();
15403 // In theory this is fixable if the lambda explicitly captures this, but
15404 // that's added complexity that's rarely going to be used.
15405 if (Parent
->isLambda())
15408 // FIXME: Use an actual Lookup operation instead of just traversing fields
15409 // in order to get base class fields.
15411 llvm::find_if(Parent
->fields(),
15412 [Name(SelfAssigned
->getDeclName())](const FieldDecl
*F
) {
15413 return F
->getDeclName() == Name
;
15415 return (Field
!= Parent
->field_end()) ? *Field
: nullptr;
15418 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
15419 /// This warning suppressed in the event of macro expansions.
15420 static void DiagnoseSelfAssignment(Sema
&S
, Expr
*LHSExpr
, Expr
*RHSExpr
,
15421 SourceLocation OpLoc
, bool IsBuiltin
) {
15422 if (S
.inTemplateInstantiation())
15424 if (S
.isUnevaluatedContext())
15426 if (OpLoc
.isInvalid() || OpLoc
.isMacroID())
15428 LHSExpr
= LHSExpr
->IgnoreParenImpCasts();
15429 RHSExpr
= RHSExpr
->IgnoreParenImpCasts();
15430 const DeclRefExpr
*LHSDeclRef
= dyn_cast
<DeclRefExpr
>(LHSExpr
);
15431 const DeclRefExpr
*RHSDeclRef
= dyn_cast
<DeclRefExpr
>(RHSExpr
);
15432 if (!LHSDeclRef
|| !RHSDeclRef
||
15433 LHSDeclRef
->getLocation().isMacroID() ||
15434 RHSDeclRef
->getLocation().isMacroID())
15436 const ValueDecl
*LHSDecl
=
15437 cast
<ValueDecl
>(LHSDeclRef
->getDecl()->getCanonicalDecl());
15438 const ValueDecl
*RHSDecl
=
15439 cast
<ValueDecl
>(RHSDeclRef
->getDecl()->getCanonicalDecl());
15440 if (LHSDecl
!= RHSDecl
)
15442 if (LHSDecl
->getType().isVolatileQualified())
15444 if (const ReferenceType
*RefTy
= LHSDecl
->getType()->getAs
<ReferenceType
>())
15445 if (RefTy
->getPointeeType().isVolatileQualified())
15448 auto Diag
= S
.Diag(OpLoc
, IsBuiltin
? diag::warn_self_assignment_builtin
15449 : diag::warn_self_assignment_overloaded
)
15450 << LHSDeclRef
->getType() << LHSExpr
->getSourceRange()
15451 << RHSExpr
->getSourceRange();
15452 if (const FieldDecl
*SelfAssignField
=
15453 S
.getSelfAssignmentClassMemberCandidate(RHSDecl
))
15454 Diag
<< 1 << SelfAssignField
15455 << FixItHint::CreateInsertion(LHSDeclRef
->getBeginLoc(), "this->");
15460 /// Check if a bitwise-& is performed on an Objective-C pointer. This
15461 /// is usually indicative of introspection within the Objective-C pointer.
15462 static void checkObjCPointerIntrospection(Sema
&S
, ExprResult
&L
, ExprResult
&R
,
15463 SourceLocation OpLoc
) {
15464 if (!S
.getLangOpts().ObjC
)
15467 const Expr
*ObjCPointerExpr
= nullptr, *OtherExpr
= nullptr;
15468 const Expr
*LHS
= L
.get();
15469 const Expr
*RHS
= R
.get();
15471 if (LHS
->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15472 ObjCPointerExpr
= LHS
;
15475 else if (RHS
->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
15476 ObjCPointerExpr
= RHS
;
15480 // This warning is deliberately made very specific to reduce false
15481 // positives with logic that uses '&' for hashing. This logic mainly
15482 // looks for code trying to introspect into tagged pointers, which
15483 // code should generally never do.
15484 if (ObjCPointerExpr
&& isa
<IntegerLiteral
>(OtherExpr
->IgnoreParenCasts())) {
15485 unsigned Diag
= diag::warn_objc_pointer_masking
;
15486 // Determine if we are introspecting the result of performSelectorXXX.
15487 const Expr
*Ex
= ObjCPointerExpr
->IgnoreParenCasts();
15488 // Special case messages to -performSelector and friends, which
15489 // can return non-pointer values boxed in a pointer value.
15490 // Some clients may wish to silence warnings in this subcase.
15491 if (const ObjCMessageExpr
*ME
= dyn_cast
<ObjCMessageExpr
>(Ex
)) {
15492 Selector S
= ME
->getSelector();
15493 StringRef SelArg0
= S
.getNameForSlot(0);
15494 if (SelArg0
.startswith("performSelector"))
15495 Diag
= diag::warn_objc_pointer_masking_performSelector
;
15498 S
.Diag(OpLoc
, Diag
)
15499 << ObjCPointerExpr
->getSourceRange();
15503 static NamedDecl
*getDeclFromExpr(Expr
*E
) {
15506 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
))
15507 return DRE
->getDecl();
15508 if (auto *ME
= dyn_cast
<MemberExpr
>(E
))
15509 return ME
->getMemberDecl();
15510 if (auto *IRE
= dyn_cast
<ObjCIvarRefExpr
>(E
))
15511 return IRE
->getDecl();
15515 // This helper function promotes a binary operator's operands (which are of a
15516 // half vector type) to a vector of floats and then truncates the result to
15517 // a vector of either half or short.
15518 static ExprResult
convertHalfVecBinOp(Sema
&S
, ExprResult LHS
, ExprResult RHS
,
15519 BinaryOperatorKind Opc
, QualType ResultTy
,
15520 ExprValueKind VK
, ExprObjectKind OK
,
15521 bool IsCompAssign
, SourceLocation OpLoc
,
15522 FPOptionsOverride FPFeatures
) {
15523 auto &Context
= S
.getASTContext();
15524 assert((isVector(ResultTy
, Context
.HalfTy
) ||
15525 isVector(ResultTy
, Context
.ShortTy
)) &&
15526 "Result must be a vector of half or short");
15527 assert(isVector(LHS
.get()->getType(), Context
.HalfTy
) &&
15528 isVector(RHS
.get()->getType(), Context
.HalfTy
) &&
15529 "both operands expected to be a half vector");
15531 RHS
= convertVector(RHS
.get(), Context
.FloatTy
, S
);
15532 QualType BinOpResTy
= RHS
.get()->getType();
15534 // If Opc is a comparison, ResultType is a vector of shorts. In that case,
15535 // change BinOpResTy to a vector of ints.
15536 if (isVector(ResultTy
, Context
.ShortTy
))
15537 BinOpResTy
= S
.GetSignedVectorType(BinOpResTy
);
15540 return CompoundAssignOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
,
15541 ResultTy
, VK
, OK
, OpLoc
, FPFeatures
,
15542 BinOpResTy
, BinOpResTy
);
15544 LHS
= convertVector(LHS
.get(), Context
.FloatTy
, S
);
15545 auto *BO
= BinaryOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
,
15546 BinOpResTy
, VK
, OK
, OpLoc
, FPFeatures
);
15547 return convertVector(BO
, ResultTy
->castAs
<VectorType
>()->getElementType(), S
);
15550 static std::pair
<ExprResult
, ExprResult
>
15551 CorrectDelayedTyposInBinOp(Sema
&S
, BinaryOperatorKind Opc
, Expr
*LHSExpr
,
15553 ExprResult LHS
= LHSExpr
, RHS
= RHSExpr
;
15554 if (!S
.Context
.isDependenceAllowed()) {
15555 // C cannot handle TypoExpr nodes on either side of a binop because it
15556 // doesn't handle dependent types properly, so make sure any TypoExprs have
15557 // been dealt with before checking the operands.
15558 LHS
= S
.CorrectDelayedTyposInExpr(LHS
);
15559 RHS
= S
.CorrectDelayedTyposInExpr(
15560 RHS
, /*InitDecl=*/nullptr, /*RecoverUncorrectedTypos=*/false,
15561 [Opc
, LHS
](Expr
*E
) {
15562 if (Opc
!= BO_Assign
)
15563 return ExprResult(E
);
15564 // Avoid correcting the RHS to the same Expr as the LHS.
15565 Decl
*D
= getDeclFromExpr(E
);
15566 return (D
&& D
== getDeclFromExpr(LHS
.get())) ? ExprError() : E
;
15569 return std::make_pair(LHS
, RHS
);
15572 /// Returns true if conversion between vectors of halfs and vectors of floats
15574 static bool needsConversionOfHalfVec(bool OpRequiresConversion
, ASTContext
&Ctx
,
15575 Expr
*E0
, Expr
*E1
= nullptr) {
15576 if (!OpRequiresConversion
|| Ctx
.getLangOpts().NativeHalfType
||
15577 Ctx
.getTargetInfo().useFP16ConversionIntrinsics())
15580 auto HasVectorOfHalfType
= [&Ctx
](Expr
*E
) {
15581 QualType Ty
= E
->IgnoreImplicit()->getType();
15583 // Don't promote half precision neon vectors like float16x4_t in arm_neon.h
15584 // to vectors of floats. Although the element type of the vectors is __fp16,
15585 // the vectors shouldn't be treated as storage-only types. See the
15586 // discussion here: https://reviews.llvm.org/rG825235c140e7
15587 if (const VectorType
*VT
= Ty
->getAs
<VectorType
>()) {
15588 if (VT
->getVectorKind() == VectorKind::Neon
)
15590 return VT
->getElementType().getCanonicalType() == Ctx
.HalfTy
;
15595 return HasVectorOfHalfType(E0
) && (!E1
|| HasVectorOfHalfType(E1
));
15598 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
15599 /// operator @p Opc at location @c TokLoc. This routine only supports
15600 /// built-in operations; ActOnBinOp handles overloaded operators.
15601 ExprResult
Sema::CreateBuiltinBinOp(SourceLocation OpLoc
,
15602 BinaryOperatorKind Opc
,
15603 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15604 if (getLangOpts().CPlusPlus11
&& isa
<InitListExpr
>(RHSExpr
)) {
15605 // The syntax only allows initializer lists on the RHS of assignment,
15606 // so we don't need to worry about accepting invalid code for
15607 // non-assignment operators.
15609 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
15610 // of x = {} is x = T().
15611 InitializationKind Kind
= InitializationKind::CreateDirectList(
15612 RHSExpr
->getBeginLoc(), RHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
15613 InitializedEntity Entity
=
15614 InitializedEntity::InitializeTemporary(LHSExpr
->getType());
15615 InitializationSequence
InitSeq(*this, Entity
, Kind
, RHSExpr
);
15616 ExprResult Init
= InitSeq
.Perform(*this, Entity
, Kind
, RHSExpr
);
15617 if (Init
.isInvalid())
15619 RHSExpr
= Init
.get();
15622 ExprResult LHS
= LHSExpr
, RHS
= RHSExpr
;
15623 QualType ResultTy
; // Result type of the binary operator.
15624 // The following two variables are used for compound assignment operators
15625 QualType CompLHSTy
; // Type of LHS after promotions for computation
15626 QualType CompResultTy
; // Type of computation result
15627 ExprValueKind VK
= VK_PRValue
;
15628 ExprObjectKind OK
= OK_Ordinary
;
15629 bool ConvertHalfVec
= false;
15631 std::tie(LHS
, RHS
) = CorrectDelayedTyposInBinOp(*this, Opc
, LHSExpr
, RHSExpr
);
15632 if (!LHS
.isUsable() || !RHS
.isUsable())
15633 return ExprError();
15635 if (getLangOpts().OpenCL
) {
15636 QualType LHSTy
= LHSExpr
->getType();
15637 QualType RHSTy
= RHSExpr
->getType();
15638 // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
15639 // the ATOMIC_VAR_INIT macro.
15640 if (LHSTy
->isAtomicType() || RHSTy
->isAtomicType()) {
15641 SourceRange
SR(LHSExpr
->getBeginLoc(), RHSExpr
->getEndLoc());
15642 if (BO_Assign
== Opc
)
15643 Diag(OpLoc
, diag::err_opencl_atomic_init
) << 0 << SR
;
15645 ResultTy
= InvalidOperands(OpLoc
, LHS
, RHS
);
15646 return ExprError();
15649 // OpenCL special types - image, sampler, pipe, and blocks are to be used
15650 // only with a builtin functions and therefore should be disallowed here.
15651 if (LHSTy
->isImageType() || RHSTy
->isImageType() ||
15652 LHSTy
->isSamplerT() || RHSTy
->isSamplerT() ||
15653 LHSTy
->isPipeType() || RHSTy
->isPipeType() ||
15654 LHSTy
->isBlockPointerType() || RHSTy
->isBlockPointerType()) {
15655 ResultTy
= InvalidOperands(OpLoc
, LHS
, RHS
);
15656 return ExprError();
15660 checkTypeSupport(LHSExpr
->getType(), OpLoc
, /*ValueDecl*/ nullptr);
15661 checkTypeSupport(RHSExpr
->getType(), OpLoc
, /*ValueDecl*/ nullptr);
15665 ResultTy
= CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, QualType(), Opc
);
15666 if (getLangOpts().CPlusPlus
&&
15667 LHS
.get()->getObjectKind() != OK_ObjCProperty
) {
15668 VK
= LHS
.get()->getValueKind();
15669 OK
= LHS
.get()->getObjectKind();
15671 if (!ResultTy
.isNull()) {
15672 DiagnoseSelfAssignment(*this, LHS
.get(), RHS
.get(), OpLoc
, true);
15673 DiagnoseSelfMove(LHS
.get(), RHS
.get(), OpLoc
);
15675 // Avoid copying a block to the heap if the block is assigned to a local
15676 // auto variable that is declared in the same scope as the block. This
15677 // optimization is unsafe if the local variable is declared in an outer
15678 // scope. For example:
15684 // // It is unsafe to invoke the block here if it wasn't copied to the
15688 if (auto *BE
= dyn_cast
<BlockExpr
>(RHS
.get()->IgnoreParens()))
15689 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(LHS
.get()->IgnoreParens()))
15690 if (auto *VD
= dyn_cast
<VarDecl
>(DRE
->getDecl()))
15691 if (VD
->hasLocalStorage() && getCurScope()->isDeclScope(VD
))
15692 BE
->getBlockDecl()->setCanAvoidCopyToHeap();
15694 if (LHS
.get()->getType().hasNonTrivialToPrimitiveCopyCUnion())
15695 checkNonTrivialCUnion(LHS
.get()->getType(), LHS
.get()->getExprLoc(),
15696 NTCUC_Assignment
, NTCUK_Copy
);
15698 RecordModifiableNonNullParam(*this, LHS
.get());
15702 ResultTy
= CheckPointerToMemberOperands(LHS
, RHS
, VK
, OpLoc
,
15703 Opc
== BO_PtrMemI
);
15707 ConvertHalfVec
= true;
15708 ResultTy
= CheckMultiplyDivideOperands(LHS
, RHS
, OpLoc
, false,
15712 ResultTy
= CheckRemainderOperands(LHS
, RHS
, OpLoc
);
15715 ConvertHalfVec
= true;
15716 ResultTy
= CheckAdditionOperands(LHS
, RHS
, OpLoc
, Opc
);
15719 ConvertHalfVec
= true;
15720 ResultTy
= CheckSubtractionOperands(LHS
, RHS
, OpLoc
);
15724 ResultTy
= CheckShiftOperands(LHS
, RHS
, OpLoc
, Opc
);
15730 ConvertHalfVec
= true;
15731 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
15735 ConvertHalfVec
= true;
15736 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
15739 ConvertHalfVec
= true;
15740 ResultTy
= CheckCompareOperands(LHS
, RHS
, OpLoc
, Opc
);
15741 assert(ResultTy
.isNull() || ResultTy
->getAsCXXRecordDecl());
15744 checkObjCPointerIntrospection(*this, LHS
, RHS
, OpLoc
);
15748 ResultTy
= CheckBitwiseOperands(LHS
, RHS
, OpLoc
, Opc
);
15752 ConvertHalfVec
= true;
15753 ResultTy
= CheckLogicalOperands(LHS
, RHS
, OpLoc
, Opc
);
15757 ConvertHalfVec
= true;
15758 CompResultTy
= CheckMultiplyDivideOperands(LHS
, RHS
, OpLoc
, true,
15759 Opc
== BO_DivAssign
);
15760 CompLHSTy
= CompResultTy
;
15761 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15763 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15766 CompResultTy
= CheckRemainderOperands(LHS
, RHS
, OpLoc
, true);
15767 CompLHSTy
= CompResultTy
;
15768 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15770 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15773 ConvertHalfVec
= true;
15774 CompResultTy
= CheckAdditionOperands(LHS
, RHS
, OpLoc
, Opc
, &CompLHSTy
);
15775 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15777 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15780 ConvertHalfVec
= true;
15781 CompResultTy
= CheckSubtractionOperands(LHS
, RHS
, OpLoc
, &CompLHSTy
);
15782 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15784 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15788 CompResultTy
= CheckShiftOperands(LHS
, RHS
, OpLoc
, Opc
, true);
15789 CompLHSTy
= CompResultTy
;
15790 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15792 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15795 case BO_OrAssign
: // fallthrough
15796 DiagnoseSelfAssignment(*this, LHS
.get(), RHS
.get(), OpLoc
, true);
15799 CompResultTy
= CheckBitwiseOperands(LHS
, RHS
, OpLoc
, Opc
);
15800 CompLHSTy
= CompResultTy
;
15801 if (!CompResultTy
.isNull() && !LHS
.isInvalid() && !RHS
.isInvalid())
15803 CheckAssignmentOperands(LHS
.get(), RHS
, OpLoc
, CompResultTy
, Opc
);
15806 ResultTy
= CheckCommaOperands(*this, LHS
, RHS
, OpLoc
);
15807 if (getLangOpts().CPlusPlus
&& !RHS
.isInvalid()) {
15808 VK
= RHS
.get()->getValueKind();
15809 OK
= RHS
.get()->getObjectKind();
15813 if (ResultTy
.isNull() || LHS
.isInvalid() || RHS
.isInvalid())
15814 return ExprError();
15816 // Some of the binary operations require promoting operands of half vector to
15817 // float vectors and truncating the result back to half vector. For now, we do
15818 // this only when HalfArgsAndReturn is set (that is, when the target is arm or
15821 (Opc
== BO_Comma
|| isVector(RHS
.get()->getType(), Context
.HalfTy
) ==
15822 isVector(LHS
.get()->getType(), Context
.HalfTy
)) &&
15823 "both sides are half vectors or neither sides are");
15825 needsConversionOfHalfVec(ConvertHalfVec
, Context
, LHS
.get(), RHS
.get());
15827 // Check for array bounds violations for both sides of the BinaryOperator
15828 CheckArrayAccess(LHS
.get());
15829 CheckArrayAccess(RHS
.get());
15831 if (const ObjCIsaExpr
*OISA
= dyn_cast
<ObjCIsaExpr
>(LHS
.get()->IgnoreParenCasts())) {
15832 NamedDecl
*ObjectSetClass
= LookupSingleName(TUScope
,
15833 &Context
.Idents
.get("object_setClass"),
15834 SourceLocation(), LookupOrdinaryName
);
15835 if (ObjectSetClass
&& isa
<ObjCIsaExpr
>(LHS
.get())) {
15836 SourceLocation RHSLocEnd
= getLocForEndOfToken(RHS
.get()->getEndLoc());
15837 Diag(LHS
.get()->getExprLoc(), diag::warn_objc_isa_assign
)
15838 << FixItHint::CreateInsertion(LHS
.get()->getBeginLoc(),
15839 "object_setClass(")
15840 << FixItHint::CreateReplacement(SourceRange(OISA
->getOpLoc(), OpLoc
),
15842 << FixItHint::CreateInsertion(RHSLocEnd
, ")");
15845 Diag(LHS
.get()->getExprLoc(), diag::warn_objc_isa_assign
);
15847 else if (const ObjCIvarRefExpr
*OIRE
=
15848 dyn_cast
<ObjCIvarRefExpr
>(LHS
.get()->IgnoreParenCasts()))
15849 DiagnoseDirectIsaAccess(*this, OIRE
, OpLoc
, RHS
.get());
15851 // Opc is not a compound assignment if CompResultTy is null.
15852 if (CompResultTy
.isNull()) {
15853 if (ConvertHalfVec
)
15854 return convertHalfVecBinOp(*this, LHS
, RHS
, Opc
, ResultTy
, VK
, OK
, false,
15855 OpLoc
, CurFPFeatureOverrides());
15856 return BinaryOperator::Create(Context
, LHS
.get(), RHS
.get(), Opc
, ResultTy
,
15857 VK
, OK
, OpLoc
, CurFPFeatureOverrides());
15860 // Handle compound assignments.
15861 if (getLangOpts().CPlusPlus
&& LHS
.get()->getObjectKind() !=
15864 OK
= LHS
.get()->getObjectKind();
15867 // The LHS is not converted to the result type for fixed-point compound
15868 // assignment as the common type is computed on demand. Reset the CompLHSTy
15869 // to the LHS type we would have gotten after unary conversions.
15870 if (CompResultTy
->isFixedPointType())
15871 CompLHSTy
= UsualUnaryConversions(LHS
.get()).get()->getType();
15873 if (ConvertHalfVec
)
15874 return convertHalfVecBinOp(*this, LHS
, RHS
, Opc
, ResultTy
, VK
, OK
, true,
15875 OpLoc
, CurFPFeatureOverrides());
15877 return CompoundAssignOperator::Create(
15878 Context
, LHS
.get(), RHS
.get(), Opc
, ResultTy
, VK
, OK
, OpLoc
,
15879 CurFPFeatureOverrides(), CompLHSTy
, CompResultTy
);
15882 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
15883 /// operators are mixed in a way that suggests that the programmer forgot that
15884 /// comparison operators have higher precedence. The most typical example of
15885 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
15886 static void DiagnoseBitwisePrecedence(Sema
&Self
, BinaryOperatorKind Opc
,
15887 SourceLocation OpLoc
, Expr
*LHSExpr
,
15889 BinaryOperator
*LHSBO
= dyn_cast
<BinaryOperator
>(LHSExpr
);
15890 BinaryOperator
*RHSBO
= dyn_cast
<BinaryOperator
>(RHSExpr
);
15892 // Check that one of the sides is a comparison operator and the other isn't.
15893 bool isLeftComp
= LHSBO
&& LHSBO
->isComparisonOp();
15894 bool isRightComp
= RHSBO
&& RHSBO
->isComparisonOp();
15895 if (isLeftComp
== isRightComp
)
15898 // Bitwise operations are sometimes used as eager logical ops.
15899 // Don't diagnose this.
15900 bool isLeftBitwise
= LHSBO
&& LHSBO
->isBitwiseOp();
15901 bool isRightBitwise
= RHSBO
&& RHSBO
->isBitwiseOp();
15902 if (isLeftBitwise
|| isRightBitwise
)
15905 SourceRange DiagRange
= isLeftComp
15906 ? SourceRange(LHSExpr
->getBeginLoc(), OpLoc
)
15907 : SourceRange(OpLoc
, RHSExpr
->getEndLoc());
15908 StringRef OpStr
= isLeftComp
? LHSBO
->getOpcodeStr() : RHSBO
->getOpcodeStr();
15909 SourceRange ParensRange
=
15911 ? SourceRange(LHSBO
->getRHS()->getBeginLoc(), RHSExpr
->getEndLoc())
15912 : SourceRange(LHSExpr
->getBeginLoc(), RHSBO
->getLHS()->getEndLoc());
15914 Self
.Diag(OpLoc
, diag::warn_precedence_bitwise_rel
)
15915 << DiagRange
<< BinaryOperator::getOpcodeStr(Opc
) << OpStr
;
15916 SuggestParentheses(Self
, OpLoc
,
15917 Self
.PDiag(diag::note_precedence_silence
) << OpStr
,
15918 (isLeftComp
? LHSExpr
: RHSExpr
)->getSourceRange());
15919 SuggestParentheses(Self
, OpLoc
,
15920 Self
.PDiag(diag::note_precedence_bitwise_first
)
15921 << BinaryOperator::getOpcodeStr(Opc
),
15925 /// It accepts a '&&' expr that is inside a '||' one.
15926 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
15927 /// in parentheses.
15929 EmitDiagnosticForLogicalAndInLogicalOr(Sema
&Self
, SourceLocation OpLoc
,
15930 BinaryOperator
*Bop
) {
15931 assert(Bop
->getOpcode() == BO_LAnd
);
15932 Self
.Diag(Bop
->getOperatorLoc(), diag::warn_logical_and_in_logical_or
)
15933 << Bop
->getSourceRange() << OpLoc
;
15934 SuggestParentheses(Self
, Bop
->getOperatorLoc(),
15935 Self
.PDiag(diag::note_precedence_silence
)
15936 << Bop
->getOpcodeStr(),
15937 Bop
->getSourceRange());
15940 /// Look for '&&' in the left hand of a '||' expr.
15941 static void DiagnoseLogicalAndInLogicalOrLHS(Sema
&S
, SourceLocation OpLoc
,
15942 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15943 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(LHSExpr
)) {
15944 if (Bop
->getOpcode() == BO_LAnd
) {
15945 // If it's "string_literal && a || b" don't warn since the precedence
15947 if (!isa
<StringLiteral
>(Bop
->getLHS()->IgnoreParenImpCasts()))
15948 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, Bop
);
15949 } else if (Bop
->getOpcode() == BO_LOr
) {
15950 if (BinaryOperator
*RBop
= dyn_cast
<BinaryOperator
>(Bop
->getRHS())) {
15951 // If it's "a || b && string_literal || c" we didn't warn earlier for
15952 // "a || b && string_literal", but warn now.
15953 if (RBop
->getOpcode() == BO_LAnd
&&
15954 isa
<StringLiteral
>(RBop
->getRHS()->IgnoreParenImpCasts()))
15955 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, RBop
);
15961 /// Look for '&&' in the right hand of a '||' expr.
15962 static void DiagnoseLogicalAndInLogicalOrRHS(Sema
&S
, SourceLocation OpLoc
,
15963 Expr
*LHSExpr
, Expr
*RHSExpr
) {
15964 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(RHSExpr
)) {
15965 if (Bop
->getOpcode() == BO_LAnd
) {
15966 // If it's "a || b && string_literal" don't warn since the precedence
15968 if (!isa
<StringLiteral
>(Bop
->getRHS()->IgnoreParenImpCasts()))
15969 return EmitDiagnosticForLogicalAndInLogicalOr(S
, OpLoc
, Bop
);
15974 /// Look for bitwise op in the left or right hand of a bitwise op with
15975 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
15976 /// the '&' expression in parentheses.
15977 static void DiagnoseBitwiseOpInBitwiseOp(Sema
&S
, BinaryOperatorKind Opc
,
15978 SourceLocation OpLoc
, Expr
*SubExpr
) {
15979 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(SubExpr
)) {
15980 if (Bop
->isBitwiseOp() && Bop
->getOpcode() < Opc
) {
15981 S
.Diag(Bop
->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op
)
15982 << Bop
->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc
)
15983 << Bop
->getSourceRange() << OpLoc
;
15984 SuggestParentheses(S
, Bop
->getOperatorLoc(),
15985 S
.PDiag(diag::note_precedence_silence
)
15986 << Bop
->getOpcodeStr(),
15987 Bop
->getSourceRange());
15992 static void DiagnoseAdditionInShift(Sema
&S
, SourceLocation OpLoc
,
15993 Expr
*SubExpr
, StringRef Shift
) {
15994 if (BinaryOperator
*Bop
= dyn_cast
<BinaryOperator
>(SubExpr
)) {
15995 if (Bop
->getOpcode() == BO_Add
|| Bop
->getOpcode() == BO_Sub
) {
15996 StringRef Op
= Bop
->getOpcodeStr();
15997 S
.Diag(Bop
->getOperatorLoc(), diag::warn_addition_in_bitshift
)
15998 << Bop
->getSourceRange() << OpLoc
<< Shift
<< Op
;
15999 SuggestParentheses(S
, Bop
->getOperatorLoc(),
16000 S
.PDiag(diag::note_precedence_silence
) << Op
,
16001 Bop
->getSourceRange());
16006 static void DiagnoseShiftCompare(Sema
&S
, SourceLocation OpLoc
,
16007 Expr
*LHSExpr
, Expr
*RHSExpr
) {
16008 CXXOperatorCallExpr
*OCE
= dyn_cast
<CXXOperatorCallExpr
>(LHSExpr
);
16012 FunctionDecl
*FD
= OCE
->getDirectCallee();
16013 if (!FD
|| !FD
->isOverloadedOperator())
16016 OverloadedOperatorKind Kind
= FD
->getOverloadedOperator();
16017 if (Kind
!= OO_LessLess
&& Kind
!= OO_GreaterGreater
)
16020 S
.Diag(OpLoc
, diag::warn_overloaded_shift_in_comparison
)
16021 << LHSExpr
->getSourceRange() << RHSExpr
->getSourceRange()
16022 << (Kind
== OO_LessLess
);
16023 SuggestParentheses(S
, OCE
->getOperatorLoc(),
16024 S
.PDiag(diag::note_precedence_silence
)
16025 << (Kind
== OO_LessLess
? "<<" : ">>"),
16026 OCE
->getSourceRange());
16027 SuggestParentheses(
16028 S
, OpLoc
, S
.PDiag(diag::note_evaluate_comparison_first
),
16029 SourceRange(OCE
->getArg(1)->getBeginLoc(), RHSExpr
->getEndLoc()));
16032 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
16034 static void DiagnoseBinOpPrecedence(Sema
&Self
, BinaryOperatorKind Opc
,
16035 SourceLocation OpLoc
, Expr
*LHSExpr
,
16037 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
16038 if (BinaryOperator::isBitwiseOp(Opc
))
16039 DiagnoseBitwisePrecedence(Self
, Opc
, OpLoc
, LHSExpr
, RHSExpr
);
16041 // Diagnose "arg1 & arg2 | arg3"
16042 if ((Opc
== BO_Or
|| Opc
== BO_Xor
) &&
16043 !OpLoc
.isMacroID()/* Don't warn in macros. */) {
16044 DiagnoseBitwiseOpInBitwiseOp(Self
, Opc
, OpLoc
, LHSExpr
);
16045 DiagnoseBitwiseOpInBitwiseOp(Self
, Opc
, OpLoc
, RHSExpr
);
16048 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
16049 // We don't warn for 'assert(a || b && "bad")' since this is safe.
16050 if (Opc
== BO_LOr
&& !OpLoc
.isMacroID()/* Don't warn in macros. */) {
16051 DiagnoseLogicalAndInLogicalOrLHS(Self
, OpLoc
, LHSExpr
, RHSExpr
);
16052 DiagnoseLogicalAndInLogicalOrRHS(Self
, OpLoc
, LHSExpr
, RHSExpr
);
16055 if ((Opc
== BO_Shl
&& LHSExpr
->getType()->isIntegralType(Self
.getASTContext()))
16056 || Opc
== BO_Shr
) {
16057 StringRef Shift
= BinaryOperator::getOpcodeStr(Opc
);
16058 DiagnoseAdditionInShift(Self
, OpLoc
, LHSExpr
, Shift
);
16059 DiagnoseAdditionInShift(Self
, OpLoc
, RHSExpr
, Shift
);
16062 // Warn on overloaded shift operators and comparisons, such as:
16064 if (BinaryOperator::isComparisonOp(Opc
))
16065 DiagnoseShiftCompare(Self
, OpLoc
, LHSExpr
, RHSExpr
);
16068 // Binary Operators. 'Tok' is the token for the operator.
16069 ExprResult
Sema::ActOnBinOp(Scope
*S
, SourceLocation TokLoc
,
16070 tok::TokenKind Kind
,
16071 Expr
*LHSExpr
, Expr
*RHSExpr
) {
16072 BinaryOperatorKind Opc
= ConvertTokenKindToBinaryOpcode(Kind
);
16073 assert(LHSExpr
&& "ActOnBinOp(): missing left expression");
16074 assert(RHSExpr
&& "ActOnBinOp(): missing right expression");
16076 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
16077 DiagnoseBinOpPrecedence(*this, Opc
, TokLoc
, LHSExpr
, RHSExpr
);
16079 return BuildBinOp(S
, TokLoc
, Opc
, LHSExpr
, RHSExpr
);
16082 void Sema::LookupBinOp(Scope
*S
, SourceLocation OpLoc
, BinaryOperatorKind Opc
,
16083 UnresolvedSetImpl
&Functions
) {
16084 OverloadedOperatorKind OverOp
= BinaryOperator::getOverloadedOperator(Opc
);
16085 if (OverOp
!= OO_None
&& OverOp
!= OO_Equal
)
16086 LookupOverloadedOperatorName(OverOp
, S
, Functions
);
16088 // In C++20 onwards, we may have a second operator to look up.
16089 if (getLangOpts().CPlusPlus20
) {
16090 if (OverloadedOperatorKind ExtraOp
= getRewrittenOverloadedOperator(OverOp
))
16091 LookupOverloadedOperatorName(ExtraOp
, S
, Functions
);
16095 /// Build an overloaded binary operator expression in the given scope.
16096 static ExprResult
BuildOverloadedBinOp(Sema
&S
, Scope
*Sc
, SourceLocation OpLoc
,
16097 BinaryOperatorKind Opc
,
16098 Expr
*LHS
, Expr
*RHS
) {
16101 // In the non-overloaded case, we warn about self-assignment (x = x) for
16102 // both simple assignment and certain compound assignments where algebra
16103 // tells us the operation yields a constant result. When the operator is
16104 // overloaded, we can't do the latter because we don't want to assume that
16105 // those algebraic identities still apply; for example, a path-building
16106 // library might use operator/= to append paths. But it's still reasonable
16107 // to assume that simple assignment is just moving/copying values around
16108 // and so self-assignment is likely a bug.
16109 DiagnoseSelfAssignment(S
, LHS
, RHS
, OpLoc
, false);
16117 CheckIdentityFieldAssignment(LHS
, RHS
, OpLoc
, S
);
16123 // Find all of the overloaded operators visible from this point.
16124 UnresolvedSet
<16> Functions
;
16125 S
.LookupBinOp(Sc
, OpLoc
, Opc
, Functions
);
16127 // Build the (potentially-overloaded, potentially-dependent)
16128 // binary operation.
16129 return S
.CreateOverloadedBinOp(OpLoc
, Opc
, Functions
, LHS
, RHS
);
16132 ExprResult
Sema::BuildBinOp(Scope
*S
, SourceLocation OpLoc
,
16133 BinaryOperatorKind Opc
,
16134 Expr
*LHSExpr
, Expr
*RHSExpr
) {
16135 ExprResult LHS
, RHS
;
16136 std::tie(LHS
, RHS
) = CorrectDelayedTyposInBinOp(*this, Opc
, LHSExpr
, RHSExpr
);
16137 if (!LHS
.isUsable() || !RHS
.isUsable())
16138 return ExprError();
16139 LHSExpr
= LHS
.get();
16140 RHSExpr
= RHS
.get();
16142 // We want to end up calling one of checkPseudoObjectAssignment
16143 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
16144 // both expressions are overloadable or either is type-dependent),
16145 // or CreateBuiltinBinOp (in any other case). We also want to get
16146 // any placeholder types out of the way.
16148 // Handle pseudo-objects in the LHS.
16149 if (const BuiltinType
*pty
= LHSExpr
->getType()->getAsPlaceholderType()) {
16150 // Assignments with a pseudo-object l-value need special analysis.
16151 if (pty
->getKind() == BuiltinType::PseudoObject
&&
16152 BinaryOperator::isAssignmentOp(Opc
))
16153 return checkPseudoObjectAssignment(S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
16155 // Don't resolve overloads if the other type is overloadable.
16156 if (getLangOpts().CPlusPlus
&& pty
->getKind() == BuiltinType::Overload
) {
16157 // We can't actually test that if we still have a placeholder,
16158 // though. Fortunately, none of the exceptions we see in that
16159 // code below are valid when the LHS is an overload set. Note
16160 // that an overload set can be dependently-typed, but it never
16161 // instantiates to having an overloadable type.
16162 ExprResult resolvedRHS
= CheckPlaceholderExpr(RHSExpr
);
16163 if (resolvedRHS
.isInvalid()) return ExprError();
16164 RHSExpr
= resolvedRHS
.get();
16166 if (RHSExpr
->isTypeDependent() ||
16167 RHSExpr
->getType()->isOverloadableType())
16168 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
16171 // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
16172 // template, diagnose the missing 'template' keyword instead of diagnosing
16173 // an invalid use of a bound member function.
16175 // Note that "A::x < b" might be valid if 'b' has an overloadable type due
16176 // to C++1z [over.over]/1.4, but we already checked for that case above.
16177 if (Opc
== BO_LT
&& inTemplateInstantiation() &&
16178 (pty
->getKind() == BuiltinType::BoundMember
||
16179 pty
->getKind() == BuiltinType::Overload
)) {
16180 auto *OE
= dyn_cast
<OverloadExpr
>(LHSExpr
);
16181 if (OE
&& !OE
->hasTemplateKeyword() && !OE
->hasExplicitTemplateArgs() &&
16182 llvm::any_of(OE
->decls(), [](NamedDecl
*ND
) {
16183 return isa
<FunctionTemplateDecl
>(ND
);
16185 Diag(OE
->getQualifier() ? OE
->getQualifierLoc().getBeginLoc()
16186 : OE
->getNameLoc(),
16187 diag::err_template_kw_missing
)
16188 << OE
->getName().getAsString() << "";
16189 return ExprError();
16193 ExprResult LHS
= CheckPlaceholderExpr(LHSExpr
);
16194 if (LHS
.isInvalid()) return ExprError();
16195 LHSExpr
= LHS
.get();
16198 // Handle pseudo-objects in the RHS.
16199 if (const BuiltinType
*pty
= RHSExpr
->getType()->getAsPlaceholderType()) {
16200 // An overload in the RHS can potentially be resolved by the type
16201 // being assigned to.
16202 if (Opc
== BO_Assign
&& pty
->getKind() == BuiltinType::Overload
) {
16203 if (getLangOpts().CPlusPlus
&&
16204 (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent() ||
16205 LHSExpr
->getType()->isOverloadableType()))
16206 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
16208 return CreateBuiltinBinOp(OpLoc
, Opc
, LHSExpr
, RHSExpr
);
16211 // Don't resolve overloads if the other type is overloadable.
16212 if (getLangOpts().CPlusPlus
&& pty
->getKind() == BuiltinType::Overload
&&
16213 LHSExpr
->getType()->isOverloadableType())
16214 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
16216 ExprResult resolvedRHS
= CheckPlaceholderExpr(RHSExpr
);
16217 if (!resolvedRHS
.isUsable()) return ExprError();
16218 RHSExpr
= resolvedRHS
.get();
16221 if (getLangOpts().CPlusPlus
) {
16222 // If either expression is type-dependent, always build an
16224 if (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent())
16225 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
16227 // Otherwise, build an overloaded op if either expression has an
16228 // overloadable type.
16229 if (LHSExpr
->getType()->isOverloadableType() ||
16230 RHSExpr
->getType()->isOverloadableType())
16231 return BuildOverloadedBinOp(*this, S
, OpLoc
, Opc
, LHSExpr
, RHSExpr
);
16234 if (getLangOpts().RecoveryAST
&&
16235 (LHSExpr
->isTypeDependent() || RHSExpr
->isTypeDependent())) {
16236 assert(!getLangOpts().CPlusPlus
);
16237 assert((LHSExpr
->containsErrors() || RHSExpr
->containsErrors()) &&
16238 "Should only occur in error-recovery path.");
16239 if (BinaryOperator::isCompoundAssignmentOp(Opc
))
16241 // An assignment expression has the value of the left operand after the
16242 // assignment, but is not an lvalue.
16243 return CompoundAssignOperator::Create(
16244 Context
, LHSExpr
, RHSExpr
, Opc
,
16245 LHSExpr
->getType().getUnqualifiedType(), VK_PRValue
, OK_Ordinary
,
16246 OpLoc
, CurFPFeatureOverrides());
16247 QualType ResultType
;
16250 ResultType
= LHSExpr
->getType().getUnqualifiedType();
16260 // These operators have a fixed result type regardless of operands.
16261 ResultType
= Context
.IntTy
;
16264 ResultType
= RHSExpr
->getType();
16267 ResultType
= Context
.DependentTy
;
16270 return BinaryOperator::Create(Context
, LHSExpr
, RHSExpr
, Opc
, ResultType
,
16271 VK_PRValue
, OK_Ordinary
, OpLoc
,
16272 CurFPFeatureOverrides());
16275 // Build a built-in binary operation.
16276 return CreateBuiltinBinOp(OpLoc
, Opc
, LHSExpr
, RHSExpr
);
16279 static bool isOverflowingIntegerType(ASTContext
&Ctx
, QualType T
) {
16280 if (T
.isNull() || T
->isDependentType())
16283 if (!Ctx
.isPromotableIntegerType(T
))
16286 return Ctx
.getIntWidth(T
) >= Ctx
.getIntWidth(Ctx
.IntTy
);
16289 ExprResult
Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc
,
16290 UnaryOperatorKind Opc
, Expr
*InputExpr
,
16292 ExprResult Input
= InputExpr
;
16293 ExprValueKind VK
= VK_PRValue
;
16294 ExprObjectKind OK
= OK_Ordinary
;
16295 QualType resultType
;
16296 bool CanOverflow
= false;
16298 bool ConvertHalfVec
= false;
16299 if (getLangOpts().OpenCL
) {
16300 QualType Ty
= InputExpr
->getType();
16301 // The only legal unary operation for atomics is '&'.
16302 if ((Opc
!= UO_AddrOf
&& Ty
->isAtomicType()) ||
16303 // OpenCL special types - image, sampler, pipe, and blocks are to be used
16304 // only with a builtin functions and therefore should be disallowed here.
16305 (Ty
->isImageType() || Ty
->isSamplerT() || Ty
->isPipeType()
16306 || Ty
->isBlockPointerType())) {
16307 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16308 << InputExpr
->getType()
16309 << Input
.get()->getSourceRange());
16313 if (getLangOpts().HLSL
&& OpLoc
.isValid()) {
16314 if (Opc
== UO_AddrOf
)
16315 return ExprError(Diag(OpLoc
, diag::err_hlsl_operator_unsupported
) << 0);
16316 if (Opc
== UO_Deref
)
16317 return ExprError(Diag(OpLoc
, diag::err_hlsl_operator_unsupported
) << 1);
16325 resultType
= CheckIncrementDecrementOperand(*this, Input
.get(), VK
, OK
,
16327 Opc
== UO_PreInc
||
16329 Opc
== UO_PreInc
||
16331 CanOverflow
= isOverflowingIntegerType(Context
, resultType
);
16334 resultType
= CheckAddressOfOperand(Input
, OpLoc
);
16335 CheckAddressOfNoDeref(InputExpr
);
16336 RecordModifiableNonNullParam(*this, InputExpr
);
16339 Input
= DefaultFunctionArrayLvalueConversion(Input
.get());
16340 if (Input
.isInvalid()) return ExprError();
16342 CheckIndirectionOperand(*this, Input
.get(), VK
, OpLoc
, IsAfterAmp
);
16347 CanOverflow
= Opc
== UO_Minus
&&
16348 isOverflowingIntegerType(Context
, Input
.get()->getType());
16349 Input
= UsualUnaryConversions(Input
.get());
16350 if (Input
.isInvalid()) return ExprError();
16351 // Unary plus and minus require promoting an operand of half vector to a
16352 // float vector and truncating the result back to a half vector. For now, we
16353 // do this only when HalfArgsAndReturns is set (that is, when the target is
16355 ConvertHalfVec
= needsConversionOfHalfVec(true, Context
, Input
.get());
16357 // If the operand is a half vector, promote it to a float vector.
16358 if (ConvertHalfVec
)
16359 Input
= convertVector(Input
.get(), Context
.FloatTy
, *this);
16360 resultType
= Input
.get()->getType();
16361 if (resultType
->isDependentType())
16363 if (resultType
->isArithmeticType()) // C99 6.5.3.3p1
16365 else if (resultType
->isVectorType() &&
16366 // The z vector extensions don't allow + or - with bool vectors.
16367 (!Context
.getLangOpts().ZVector
||
16368 resultType
->castAs
<VectorType
>()->getVectorKind() !=
16369 VectorKind::AltiVecBool
))
16371 else if (resultType
->isSveVLSBuiltinType()) // SVE vectors allow + and -
16373 else if (getLangOpts().CPlusPlus
&& // C++ [expr.unary.op]p6
16375 resultType
->isPointerType())
16378 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16379 << resultType
<< Input
.get()->getSourceRange());
16381 case UO_Not
: // bitwise complement
16382 Input
= UsualUnaryConversions(Input
.get());
16383 if (Input
.isInvalid())
16384 return ExprError();
16385 resultType
= Input
.get()->getType();
16386 if (resultType
->isDependentType())
16388 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
16389 if (resultType
->isComplexType() || resultType
->isComplexIntegerType())
16390 // C99 does not support '~' for complex conjugation.
16391 Diag(OpLoc
, diag::ext_integer_complement_complex
)
16392 << resultType
<< Input
.get()->getSourceRange();
16393 else if (resultType
->hasIntegerRepresentation())
16395 else if (resultType
->isExtVectorType() && Context
.getLangOpts().OpenCL
) {
16396 // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
16397 // on vector float types.
16398 QualType T
= resultType
->castAs
<ExtVectorType
>()->getElementType();
16399 if (!T
->isIntegerType())
16400 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16401 << resultType
<< Input
.get()->getSourceRange());
16403 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16404 << resultType
<< Input
.get()->getSourceRange());
16408 case UO_LNot
: // logical negation
16409 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
16410 Input
= DefaultFunctionArrayLvalueConversion(Input
.get());
16411 if (Input
.isInvalid()) return ExprError();
16412 resultType
= Input
.get()->getType();
16414 // Though we still have to promote half FP to float...
16415 if (resultType
->isHalfType() && !Context
.getLangOpts().NativeHalfType
) {
16416 Input
= ImpCastExprToType(Input
.get(), Context
.FloatTy
, CK_FloatingCast
).get();
16417 resultType
= Context
.FloatTy
;
16420 // WebAsembly tables can't be used in unary expressions.
16421 if (resultType
->isPointerType() &&
16422 resultType
->getPointeeType().isWebAssemblyReferenceType()) {
16423 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16424 << resultType
<< Input
.get()->getSourceRange());
16427 if (resultType
->isDependentType())
16429 if (resultType
->isScalarType() && !isScopedEnumerationType(resultType
)) {
16430 // C99 6.5.3.3p1: ok, fallthrough;
16431 if (Context
.getLangOpts().CPlusPlus
) {
16432 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
16433 // operand contextually converted to bool.
16434 Input
= ImpCastExprToType(Input
.get(), Context
.BoolTy
,
16435 ScalarTypeToBooleanCastKind(resultType
));
16436 } else if (Context
.getLangOpts().OpenCL
&&
16437 Context
.getLangOpts().OpenCLVersion
< 120) {
16438 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16439 // operate on scalar float types.
16440 if (!resultType
->isIntegerType() && !resultType
->isPointerType())
16441 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16442 << resultType
<< Input
.get()->getSourceRange());
16444 } else if (resultType
->isExtVectorType()) {
16445 if (Context
.getLangOpts().OpenCL
&&
16446 Context
.getLangOpts().getOpenCLCompatibleVersion() < 120) {
16447 // OpenCL v1.1 6.3.h: The logical operator not (!) does not
16448 // operate on vector float types.
16449 QualType T
= resultType
->castAs
<ExtVectorType
>()->getElementType();
16450 if (!T
->isIntegerType())
16451 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16452 << resultType
<< Input
.get()->getSourceRange());
16454 // Vector logical not returns the signed variant of the operand type.
16455 resultType
= GetSignedVectorType(resultType
);
16457 } else if (Context
.getLangOpts().CPlusPlus
&& resultType
->isVectorType()) {
16458 const VectorType
*VTy
= resultType
->castAs
<VectorType
>();
16459 if (VTy
->getVectorKind() != VectorKind::Generic
)
16460 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16461 << resultType
<< Input
.get()->getSourceRange());
16463 // Vector logical not returns the signed variant of the operand type.
16464 resultType
= GetSignedVectorType(resultType
);
16467 return ExprError(Diag(OpLoc
, diag::err_typecheck_unary_expr
)
16468 << resultType
<< Input
.get()->getSourceRange());
16471 // LNot always has type int. C99 6.5.3.3p5.
16472 // In C++, it's bool. C++ 5.3.1p8
16473 resultType
= Context
.getLogicalOperationType();
16477 resultType
= CheckRealImagOperand(*this, Input
, OpLoc
, Opc
== UO_Real
);
16478 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
16479 // complex l-values to ordinary l-values and all other values to r-values.
16480 if (Input
.isInvalid()) return ExprError();
16481 if (Opc
== UO_Real
|| Input
.get()->getType()->isAnyComplexType()) {
16482 if (Input
.get()->isGLValue() &&
16483 Input
.get()->getObjectKind() == OK_Ordinary
)
16484 VK
= Input
.get()->getValueKind();
16485 } else if (!getLangOpts().CPlusPlus
) {
16486 // In C, a volatile scalar is read by __imag. In C++, it is not.
16487 Input
= DefaultLvalueConversion(Input
.get());
16491 resultType
= Input
.get()->getType();
16492 VK
= Input
.get()->getValueKind();
16493 OK
= Input
.get()->getObjectKind();
16496 // It's unnecessary to represent the pass-through operator co_await in the
16497 // AST; just return the input expression instead.
16498 assert(!Input
.get()->getType()->isDependentType() &&
16499 "the co_await expression must be non-dependant before "
16500 "building operator co_await");
16503 if (resultType
.isNull() || Input
.isInvalid())
16504 return ExprError();
16506 // Check for array bounds violations in the operand of the UnaryOperator,
16507 // except for the '*' and '&' operators that have to be handled specially
16508 // by CheckArrayAccess (as there are special cases like &array[arraysize]
16509 // that are explicitly defined as valid by the standard).
16510 if (Opc
!= UO_AddrOf
&& Opc
!= UO_Deref
)
16511 CheckArrayAccess(Input
.get());
16514 UnaryOperator::Create(Context
, Input
.get(), Opc
, resultType
, VK
, OK
,
16515 OpLoc
, CanOverflow
, CurFPFeatureOverrides());
16517 if (Opc
== UO_Deref
&& UO
->getType()->hasAttr(attr::NoDeref
) &&
16518 !isa
<ArrayType
>(UO
->getType().getDesugaredType(Context
)) &&
16519 !isUnevaluatedContext())
16520 ExprEvalContexts
.back().PossibleDerefs
.insert(UO
);
16522 // Convert the result back to a half vector.
16523 if (ConvertHalfVec
)
16524 return convertVector(UO
, Context
.HalfTy
, *this);
16528 /// Determine whether the given expression is a qualified member
16529 /// access expression, of a form that could be turned into a pointer to member
16530 /// with the address-of operator.
16531 bool Sema::isQualifiedMemberAccess(Expr
*E
) {
16532 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
16533 if (!DRE
->getQualifier())
16536 ValueDecl
*VD
= DRE
->getDecl();
16537 if (!VD
->isCXXClassMember())
16540 if (isa
<FieldDecl
>(VD
) || isa
<IndirectFieldDecl
>(VD
))
16542 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(VD
))
16543 return Method
->isImplicitObjectMemberFunction();
16548 if (UnresolvedLookupExpr
*ULE
= dyn_cast
<UnresolvedLookupExpr
>(E
)) {
16549 if (!ULE
->getQualifier())
16552 for (NamedDecl
*D
: ULE
->decls()) {
16553 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(D
)) {
16554 if (Method
->isImplicitObjectMemberFunction())
16557 // Overload set does not contain methods.
16568 ExprResult
Sema::BuildUnaryOp(Scope
*S
, SourceLocation OpLoc
,
16569 UnaryOperatorKind Opc
, Expr
*Input
,
16571 // First things first: handle placeholders so that the
16572 // overloaded-operator check considers the right type.
16573 if (const BuiltinType
*pty
= Input
->getType()->getAsPlaceholderType()) {
16574 // Increment and decrement of pseudo-object references.
16575 if (pty
->getKind() == BuiltinType::PseudoObject
&&
16576 UnaryOperator::isIncrementDecrementOp(Opc
))
16577 return checkPseudoObjectIncDec(S
, OpLoc
, Opc
, Input
);
16579 // extension is always a builtin operator.
16580 if (Opc
== UO_Extension
)
16581 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
16583 // & gets special logic for several kinds of placeholder.
16584 // The builtin code knows what to do.
16585 if (Opc
== UO_AddrOf
&&
16586 (pty
->getKind() == BuiltinType::Overload
||
16587 pty
->getKind() == BuiltinType::UnknownAny
||
16588 pty
->getKind() == BuiltinType::BoundMember
))
16589 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
);
16591 // Anything else needs to be handled now.
16592 ExprResult Result
= CheckPlaceholderExpr(Input
);
16593 if (Result
.isInvalid()) return ExprError();
16594 Input
= Result
.get();
16597 if (getLangOpts().CPlusPlus
&& Input
->getType()->isOverloadableType() &&
16598 UnaryOperator::getOverloadedOperator(Opc
) != OO_None
&&
16599 !(Opc
== UO_AddrOf
&& isQualifiedMemberAccess(Input
))) {
16600 // Find all of the overloaded operators visible from this point.
16601 UnresolvedSet
<16> Functions
;
16602 OverloadedOperatorKind OverOp
= UnaryOperator::getOverloadedOperator(Opc
);
16603 if (S
&& OverOp
!= OO_None
)
16604 LookupOverloadedOperatorName(OverOp
, S
, Functions
);
16606 return CreateOverloadedUnaryOp(OpLoc
, Opc
, Functions
, Input
);
16609 return CreateBuiltinUnaryOp(OpLoc
, Opc
, Input
, IsAfterAmp
);
16612 // Unary Operators. 'Tok' is the token for the operator.
16613 ExprResult
Sema::ActOnUnaryOp(Scope
*S
, SourceLocation OpLoc
, tok::TokenKind Op
,
16614 Expr
*Input
, bool IsAfterAmp
) {
16615 return BuildUnaryOp(S
, OpLoc
, ConvertTokenKindToUnaryOpcode(Op
), Input
,
16619 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
16620 ExprResult
Sema::ActOnAddrLabel(SourceLocation OpLoc
, SourceLocation LabLoc
,
16621 LabelDecl
*TheDecl
) {
16622 TheDecl
->markUsed(Context
);
16623 // Create the AST node. The address of a label always has type 'void*'.
16624 auto *Res
= new (Context
) AddrLabelExpr(
16625 OpLoc
, LabLoc
, TheDecl
, Context
.getPointerType(Context
.VoidTy
));
16627 if (getCurFunction())
16628 getCurFunction()->AddrLabels
.push_back(Res
);
16633 void Sema::ActOnStartStmtExpr() {
16634 PushExpressionEvaluationContext(ExprEvalContexts
.back().Context
);
16635 // Make sure we diagnose jumping into a statement expression.
16636 setFunctionHasBranchProtectedScope();
16639 void Sema::ActOnStmtExprError() {
16640 // Note that function is also called by TreeTransform when leaving a
16641 // StmtExpr scope without rebuilding anything.
16643 DiscardCleanupsInEvaluationContext();
16644 PopExpressionEvaluationContext();
16647 ExprResult
Sema::ActOnStmtExpr(Scope
*S
, SourceLocation LPLoc
, Stmt
*SubStmt
,
16648 SourceLocation RPLoc
) {
16649 return BuildStmtExpr(LPLoc
, SubStmt
, RPLoc
, getTemplateDepth(S
));
16652 ExprResult
Sema::BuildStmtExpr(SourceLocation LPLoc
, Stmt
*SubStmt
,
16653 SourceLocation RPLoc
, unsigned TemplateDepth
) {
16654 assert(SubStmt
&& isa
<CompoundStmt
>(SubStmt
) && "Invalid action invocation!");
16655 CompoundStmt
*Compound
= cast
<CompoundStmt
>(SubStmt
);
16657 if (hasAnyUnrecoverableErrorsInThisFunction())
16658 DiscardCleanupsInEvaluationContext();
16659 assert(!Cleanup
.exprNeedsCleanups() &&
16660 "cleanups within StmtExpr not correctly bound!");
16661 PopExpressionEvaluationContext();
16663 // FIXME: there are a variety of strange constraints to enforce here, for
16664 // example, it is not possible to goto into a stmt expression apparently.
16665 // More semantic analysis is needed.
16667 // If there are sub-stmts in the compound stmt, take the type of the last one
16668 // as the type of the stmtexpr.
16669 QualType Ty
= Context
.VoidTy
;
16670 bool StmtExprMayBindToTemp
= false;
16671 if (!Compound
->body_empty()) {
16672 // For GCC compatibility we get the last Stmt excluding trailing NullStmts.
16673 if (const auto *LastStmt
=
16674 dyn_cast
<ValueStmt
>(Compound
->getStmtExprResult())) {
16675 if (const Expr
*Value
= LastStmt
->getExprStmt()) {
16676 StmtExprMayBindToTemp
= true;
16677 Ty
= Value
->getType();
16682 // FIXME: Check that expression type is complete/non-abstract; statement
16683 // expressions are not lvalues.
16684 Expr
*ResStmtExpr
=
16685 new (Context
) StmtExpr(Compound
, Ty
, LPLoc
, RPLoc
, TemplateDepth
);
16686 if (StmtExprMayBindToTemp
)
16687 return MaybeBindToTemporary(ResStmtExpr
);
16688 return ResStmtExpr
;
16691 ExprResult
Sema::ActOnStmtExprResult(ExprResult ER
) {
16692 if (ER
.isInvalid())
16693 return ExprError();
16695 // Do function/array conversion on the last expression, but not
16696 // lvalue-to-rvalue. However, initialize an unqualified type.
16697 ER
= DefaultFunctionArrayConversion(ER
.get());
16698 if (ER
.isInvalid())
16699 return ExprError();
16700 Expr
*E
= ER
.get();
16702 if (E
->isTypeDependent())
16705 // In ARC, if the final expression ends in a consume, splice
16706 // the consume out and bind it later. In the alternate case
16707 // (when dealing with a retainable type), the result
16708 // initialization will create a produce. In both cases the
16709 // result will be +1, and we'll need to balance that out with
16711 auto *Cast
= dyn_cast
<ImplicitCastExpr
>(E
);
16712 if (Cast
&& Cast
->getCastKind() == CK_ARCConsumeObject
)
16713 return Cast
->getSubExpr();
16715 // FIXME: Provide a better location for the initialization.
16716 return PerformCopyInitialization(
16717 InitializedEntity::InitializeStmtExprResult(
16718 E
->getBeginLoc(), E
->getType().getUnqualifiedType()),
16719 SourceLocation(), E
);
16722 ExprResult
Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc
,
16723 TypeSourceInfo
*TInfo
,
16724 ArrayRef
<OffsetOfComponent
> Components
,
16725 SourceLocation RParenLoc
) {
16726 QualType ArgTy
= TInfo
->getType();
16727 bool Dependent
= ArgTy
->isDependentType();
16728 SourceRange TypeRange
= TInfo
->getTypeLoc().getLocalSourceRange();
16730 // We must have at least one component that refers to the type, and the first
16731 // one is known to be a field designator. Verify that the ArgTy represents
16732 // a struct/union/class.
16733 if (!Dependent
&& !ArgTy
->isRecordType())
16734 return ExprError(Diag(BuiltinLoc
, diag::err_offsetof_record_type
)
16735 << ArgTy
<< TypeRange
);
16737 // Type must be complete per C99 7.17p3 because a declaring a variable
16738 // with an incomplete type would be ill-formed.
16740 && RequireCompleteType(BuiltinLoc
, ArgTy
,
16741 diag::err_offsetof_incomplete_type
, TypeRange
))
16742 return ExprError();
16744 bool DidWarnAboutNonPOD
= false;
16745 QualType CurrentType
= ArgTy
;
16746 SmallVector
<OffsetOfNode
, 4> Comps
;
16747 SmallVector
<Expr
*, 4> Exprs
;
16748 for (const OffsetOfComponent
&OC
: Components
) {
16749 if (OC
.isBrackets
) {
16750 // Offset of an array sub-field. TODO: Should we allow vector elements?
16751 if (!CurrentType
->isDependentType()) {
16752 const ArrayType
*AT
= Context
.getAsArrayType(CurrentType
);
16754 return ExprError(Diag(OC
.LocEnd
, diag::err_offsetof_array_type
)
16756 CurrentType
= AT
->getElementType();
16758 CurrentType
= Context
.DependentTy
;
16760 ExprResult IdxRval
= DefaultLvalueConversion(static_cast<Expr
*>(OC
.U
.E
));
16761 if (IdxRval
.isInvalid())
16762 return ExprError();
16763 Expr
*Idx
= IdxRval
.get();
16765 // The expression must be an integral expression.
16766 // FIXME: An integral constant expression?
16767 if (!Idx
->isTypeDependent() && !Idx
->isValueDependent() &&
16768 !Idx
->getType()->isIntegerType())
16770 Diag(Idx
->getBeginLoc(), diag::err_typecheck_subscript_not_integer
)
16771 << Idx
->getSourceRange());
16773 // Record this array index.
16774 Comps
.push_back(OffsetOfNode(OC
.LocStart
, Exprs
.size(), OC
.LocEnd
));
16775 Exprs
.push_back(Idx
);
16779 // Offset of a field.
16780 if (CurrentType
->isDependentType()) {
16781 // We have the offset of a field, but we can't look into the dependent
16782 // type. Just record the identifier of the field.
16783 Comps
.push_back(OffsetOfNode(OC
.LocStart
, OC
.U
.IdentInfo
, OC
.LocEnd
));
16784 CurrentType
= Context
.DependentTy
;
16788 // We need to have a complete type to look into.
16789 if (RequireCompleteType(OC
.LocStart
, CurrentType
,
16790 diag::err_offsetof_incomplete_type
))
16791 return ExprError();
16793 // Look for the designated field.
16794 const RecordType
*RC
= CurrentType
->getAs
<RecordType
>();
16796 return ExprError(Diag(OC
.LocEnd
, diag::err_offsetof_record_type
)
16798 RecordDecl
*RD
= RC
->getDecl();
16800 // C++ [lib.support.types]p5:
16801 // The macro offsetof accepts a restricted set of type arguments in this
16802 // International Standard. type shall be a POD structure or a POD union
16804 // C++11 [support.types]p4:
16805 // If type is not a standard-layout class (Clause 9), the results are
16807 if (CXXRecordDecl
*CRD
= dyn_cast
<CXXRecordDecl
>(RD
)) {
16808 bool IsSafe
= LangOpts
.CPlusPlus11
? CRD
->isStandardLayout() : CRD
->isPOD();
16810 LangOpts
.CPlusPlus11
? diag::ext_offsetof_non_standardlayout_type
16811 : diag::ext_offsetof_non_pod_type
;
16813 if (!IsSafe
&& !DidWarnAboutNonPOD
&& !isUnevaluatedContext()) {
16814 Diag(BuiltinLoc
, DiagID
)
16815 << SourceRange(Components
[0].LocStart
, OC
.LocEnd
) << CurrentType
;
16816 DidWarnAboutNonPOD
= true;
16820 // Look for the field.
16821 LookupResult
R(*this, OC
.U
.IdentInfo
, OC
.LocStart
, LookupMemberName
);
16822 LookupQualifiedName(R
, RD
);
16823 FieldDecl
*MemberDecl
= R
.getAsSingle
<FieldDecl
>();
16824 IndirectFieldDecl
*IndirectMemberDecl
= nullptr;
16826 if ((IndirectMemberDecl
= R
.getAsSingle
<IndirectFieldDecl
>()))
16827 MemberDecl
= IndirectMemberDecl
->getAnonField();
16831 // Lookup could be ambiguous when looking up a placeholder variable
16832 // __builtin_offsetof(S, _).
16833 // In that case we would already have emitted a diagnostic
16834 if (!R
.isAmbiguous())
16835 Diag(BuiltinLoc
, diag::err_no_member
)
16836 << OC
.U
.IdentInfo
<< RD
<< SourceRange(OC
.LocStart
, OC
.LocEnd
);
16837 return ExprError();
16841 // (If the specified member is a bit-field, the behavior is undefined.)
16843 // We diagnose this as an error.
16844 if (MemberDecl
->isBitField()) {
16845 Diag(OC
.LocEnd
, diag::err_offsetof_bitfield
)
16846 << MemberDecl
->getDeclName()
16847 << SourceRange(BuiltinLoc
, RParenLoc
);
16848 Diag(MemberDecl
->getLocation(), diag::note_bitfield_decl
);
16849 return ExprError();
16852 RecordDecl
*Parent
= MemberDecl
->getParent();
16853 if (IndirectMemberDecl
)
16854 Parent
= cast
<RecordDecl
>(IndirectMemberDecl
->getDeclContext());
16856 // If the member was found in a base class, introduce OffsetOfNodes for
16857 // the base class indirections.
16858 CXXBasePaths Paths
;
16859 if (IsDerivedFrom(OC
.LocStart
, CurrentType
, Context
.getTypeDeclType(Parent
),
16861 if (Paths
.getDetectedVirtual()) {
16862 Diag(OC
.LocEnd
, diag::err_offsetof_field_of_virtual_base
)
16863 << MemberDecl
->getDeclName()
16864 << SourceRange(BuiltinLoc
, RParenLoc
);
16865 return ExprError();
16868 CXXBasePath
&Path
= Paths
.front();
16869 for (const CXXBasePathElement
&B
: Path
)
16870 Comps
.push_back(OffsetOfNode(B
.Base
));
16873 if (IndirectMemberDecl
) {
16874 for (auto *FI
: IndirectMemberDecl
->chain()) {
16875 assert(isa
<FieldDecl
>(FI
));
16876 Comps
.push_back(OffsetOfNode(OC
.LocStart
,
16877 cast
<FieldDecl
>(FI
), OC
.LocEnd
));
16880 Comps
.push_back(OffsetOfNode(OC
.LocStart
, MemberDecl
, OC
.LocEnd
));
16882 CurrentType
= MemberDecl
->getType().getNonReferenceType();
16885 return OffsetOfExpr::Create(Context
, Context
.getSizeType(), BuiltinLoc
, TInfo
,
16886 Comps
, Exprs
, RParenLoc
);
16889 ExprResult
Sema::ActOnBuiltinOffsetOf(Scope
*S
,
16890 SourceLocation BuiltinLoc
,
16891 SourceLocation TypeLoc
,
16892 ParsedType ParsedArgTy
,
16893 ArrayRef
<OffsetOfComponent
> Components
,
16894 SourceLocation RParenLoc
) {
16896 TypeSourceInfo
*ArgTInfo
;
16897 QualType ArgTy
= GetTypeFromParser(ParsedArgTy
, &ArgTInfo
);
16898 if (ArgTy
.isNull())
16899 return ExprError();
16902 ArgTInfo
= Context
.getTrivialTypeSourceInfo(ArgTy
, TypeLoc
);
16904 return BuildBuiltinOffsetOf(BuiltinLoc
, ArgTInfo
, Components
, RParenLoc
);
16908 ExprResult
Sema::ActOnChooseExpr(SourceLocation BuiltinLoc
,
16910 Expr
*LHSExpr
, Expr
*RHSExpr
,
16911 SourceLocation RPLoc
) {
16912 assert((CondExpr
&& LHSExpr
&& RHSExpr
) && "Missing type argument(s)");
16914 ExprValueKind VK
= VK_PRValue
;
16915 ExprObjectKind OK
= OK_Ordinary
;
16917 bool CondIsTrue
= false;
16918 if (CondExpr
->isTypeDependent() || CondExpr
->isValueDependent()) {
16919 resType
= Context
.DependentTy
;
16921 // The conditional expression is required to be a constant expression.
16922 llvm::APSInt
condEval(32);
16923 ExprResult CondICE
= VerifyIntegerConstantExpression(
16924 CondExpr
, &condEval
, diag::err_typecheck_choose_expr_requires_constant
);
16925 if (CondICE
.isInvalid())
16926 return ExprError();
16927 CondExpr
= CondICE
.get();
16928 CondIsTrue
= condEval
.getZExtValue();
16930 // If the condition is > zero, then the AST type is the same as the LHSExpr.
16931 Expr
*ActiveExpr
= CondIsTrue
? LHSExpr
: RHSExpr
;
16933 resType
= ActiveExpr
->getType();
16934 VK
= ActiveExpr
->getValueKind();
16935 OK
= ActiveExpr
->getObjectKind();
16938 return new (Context
) ChooseExpr(BuiltinLoc
, CondExpr
, LHSExpr
, RHSExpr
,
16939 resType
, VK
, OK
, RPLoc
, CondIsTrue
);
16942 //===----------------------------------------------------------------------===//
16943 // Clang Extensions.
16944 //===----------------------------------------------------------------------===//
16946 /// ActOnBlockStart - This callback is invoked when a block literal is started.
16947 void Sema::ActOnBlockStart(SourceLocation CaretLoc
, Scope
*CurScope
) {
16948 BlockDecl
*Block
= BlockDecl::Create(Context
, CurContext
, CaretLoc
);
16950 if (LangOpts
.CPlusPlus
) {
16951 MangleNumberingContext
*MCtx
;
16952 Decl
*ManglingContextDecl
;
16953 std::tie(MCtx
, ManglingContextDecl
) =
16954 getCurrentMangleNumberContext(Block
->getDeclContext());
16956 unsigned ManglingNumber
= MCtx
->getManglingNumber(Block
);
16957 Block
->setBlockMangling(ManglingNumber
, ManglingContextDecl
);
16961 PushBlockScope(CurScope
, Block
);
16962 CurContext
->addDecl(Block
);
16964 PushDeclContext(CurScope
, Block
);
16966 CurContext
= Block
;
16968 getCurBlock()->HasImplicitReturnType
= true;
16970 // Enter a new evaluation context to insulate the block from any
16971 // cleanups from the enclosing full-expression.
16972 PushExpressionEvaluationContext(
16973 ExpressionEvaluationContext::PotentiallyEvaluated
);
16976 void Sema::ActOnBlockArguments(SourceLocation CaretLoc
, Declarator
&ParamInfo
,
16978 assert(ParamInfo
.getIdentifier() == nullptr &&
16979 "block-id should have no identifier!");
16980 assert(ParamInfo
.getContext() == DeclaratorContext::BlockLiteral
);
16981 BlockScopeInfo
*CurBlock
= getCurBlock();
16983 TypeSourceInfo
*Sig
= GetTypeForDeclarator(ParamInfo
, CurScope
);
16984 QualType T
= Sig
->getType();
16986 // FIXME: We should allow unexpanded parameter packs here, but that would,
16987 // in turn, make the block expression contain unexpanded parameter packs.
16988 if (DiagnoseUnexpandedParameterPack(CaretLoc
, Sig
, UPPC_Block
)) {
16989 // Drop the parameters.
16990 FunctionProtoType::ExtProtoInfo EPI
;
16991 EPI
.HasTrailingReturn
= false;
16992 EPI
.TypeQuals
.addConst();
16993 T
= Context
.getFunctionType(Context
.DependentTy
, std::nullopt
, EPI
);
16994 Sig
= Context
.getTrivialTypeSourceInfo(T
);
16997 // GetTypeForDeclarator always produces a function type for a block
16998 // literal signature. Furthermore, it is always a FunctionProtoType
16999 // unless the function was written with a typedef.
17000 assert(T
->isFunctionType() &&
17001 "GetTypeForDeclarator made a non-function block signature");
17003 // Look for an explicit signature in that function type.
17004 FunctionProtoTypeLoc ExplicitSignature
;
17006 if ((ExplicitSignature
= Sig
->getTypeLoc()
17007 .getAsAdjusted
<FunctionProtoTypeLoc
>())) {
17009 // Check whether that explicit signature was synthesized by
17010 // GetTypeForDeclarator. If so, don't save that as part of the
17011 // written signature.
17012 if (ExplicitSignature
.getLocalRangeBegin() ==
17013 ExplicitSignature
.getLocalRangeEnd()) {
17014 // This would be much cheaper if we stored TypeLocs instead of
17015 // TypeSourceInfos.
17016 TypeLoc Result
= ExplicitSignature
.getReturnLoc();
17017 unsigned Size
= Result
.getFullDataSize();
17018 Sig
= Context
.CreateTypeSourceInfo(Result
.getType(), Size
);
17019 Sig
->getTypeLoc().initializeFullCopy(Result
, Size
);
17021 ExplicitSignature
= FunctionProtoTypeLoc();
17025 CurBlock
->TheDecl
->setSignatureAsWritten(Sig
);
17026 CurBlock
->FunctionType
= T
;
17028 const auto *Fn
= T
->castAs
<FunctionType
>();
17029 QualType RetTy
= Fn
->getReturnType();
17031 (isa
<FunctionProtoType
>(Fn
) && cast
<FunctionProtoType
>(Fn
)->isVariadic());
17033 CurBlock
->TheDecl
->setIsVariadic(isVariadic
);
17035 // Context.DependentTy is used as a placeholder for a missing block
17036 // return type. TODO: what should we do with declarators like:
17038 // If the answer is "apply template argument deduction"....
17039 if (RetTy
!= Context
.DependentTy
) {
17040 CurBlock
->ReturnType
= RetTy
;
17041 CurBlock
->TheDecl
->setBlockMissingReturnType(false);
17042 CurBlock
->HasImplicitReturnType
= false;
17045 // Push block parameters from the declarator if we had them.
17046 SmallVector
<ParmVarDecl
*, 8> Params
;
17047 if (ExplicitSignature
) {
17048 for (unsigned I
= 0, E
= ExplicitSignature
.getNumParams(); I
!= E
; ++I
) {
17049 ParmVarDecl
*Param
= ExplicitSignature
.getParam(I
);
17050 if (Param
->getIdentifier() == nullptr && !Param
->isImplicit() &&
17051 !Param
->isInvalidDecl() && !getLangOpts().CPlusPlus
) {
17052 // Diagnose this as an extension in C17 and earlier.
17053 if (!getLangOpts().C23
)
17054 Diag(Param
->getLocation(), diag::ext_parameter_name_omitted_c23
);
17056 Params
.push_back(Param
);
17059 // Fake up parameter variables if we have a typedef, like
17060 // ^ fntype { ... }
17061 } else if (const FunctionProtoType
*Fn
= T
->getAs
<FunctionProtoType
>()) {
17062 for (const auto &I
: Fn
->param_types()) {
17063 ParmVarDecl
*Param
= BuildParmVarDeclForTypedef(
17064 CurBlock
->TheDecl
, ParamInfo
.getBeginLoc(), I
);
17065 Params
.push_back(Param
);
17069 // Set the parameters on the block decl.
17070 if (!Params
.empty()) {
17071 CurBlock
->TheDecl
->setParams(Params
);
17072 CheckParmsForFunctionDef(CurBlock
->TheDecl
->parameters(),
17073 /*CheckParameterNames=*/false);
17076 // Finally we can process decl attributes.
17077 ProcessDeclAttributes(CurScope
, CurBlock
->TheDecl
, ParamInfo
);
17079 // Put the parameter variables in scope.
17080 for (auto *AI
: CurBlock
->TheDecl
->parameters()) {
17081 AI
->setOwningFunction(CurBlock
->TheDecl
);
17083 // If this has an identifier, add it to the scope stack.
17084 if (AI
->getIdentifier()) {
17085 CheckShadow(CurBlock
->TheScope
, AI
);
17087 PushOnScopeChains(AI
, CurBlock
->TheScope
);
17090 if (AI
->isInvalidDecl())
17091 CurBlock
->TheDecl
->setInvalidDecl();
17095 /// ActOnBlockError - If there is an error parsing a block, this callback
17096 /// is invoked to pop the information about the block from the action impl.
17097 void Sema::ActOnBlockError(SourceLocation CaretLoc
, Scope
*CurScope
) {
17098 // Leave the expression-evaluation context.
17099 DiscardCleanupsInEvaluationContext();
17100 PopExpressionEvaluationContext();
17102 // Pop off CurBlock, handle nested blocks.
17104 PopFunctionScopeInfo();
17107 /// ActOnBlockStmtExpr - This is called when the body of a block statement
17108 /// literal was successfully completed. ^(int x){...}
17109 ExprResult
Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc
,
17110 Stmt
*Body
, Scope
*CurScope
) {
17111 // If blocks are disabled, emit an error.
17112 if (!LangOpts
.Blocks
)
17113 Diag(CaretLoc
, diag::err_blocks_disable
) << LangOpts
.OpenCL
;
17115 // Leave the expression-evaluation context.
17116 if (hasAnyUnrecoverableErrorsInThisFunction())
17117 DiscardCleanupsInEvaluationContext();
17118 assert(!Cleanup
.exprNeedsCleanups() &&
17119 "cleanups within block not correctly bound!");
17120 PopExpressionEvaluationContext();
17122 BlockScopeInfo
*BSI
= cast
<BlockScopeInfo
>(FunctionScopes
.back());
17123 BlockDecl
*BD
= BSI
->TheDecl
;
17125 if (BSI
->HasImplicitReturnType
)
17126 deduceClosureReturnType(*BSI
);
17128 QualType RetTy
= Context
.VoidTy
;
17129 if (!BSI
->ReturnType
.isNull())
17130 RetTy
= BSI
->ReturnType
;
17132 bool NoReturn
= BD
->hasAttr
<NoReturnAttr
>();
17135 // If the user wrote a function type in some form, try to use that.
17136 if (!BSI
->FunctionType
.isNull()) {
17137 const FunctionType
*FTy
= BSI
->FunctionType
->castAs
<FunctionType
>();
17139 FunctionType::ExtInfo Ext
= FTy
->getExtInfo();
17140 if (NoReturn
&& !Ext
.getNoReturn()) Ext
= Ext
.withNoReturn(true);
17142 // Turn protoless block types into nullary block types.
17143 if (isa
<FunctionNoProtoType
>(FTy
)) {
17144 FunctionProtoType::ExtProtoInfo EPI
;
17146 BlockTy
= Context
.getFunctionType(RetTy
, std::nullopt
, EPI
);
17148 // Otherwise, if we don't need to change anything about the function type,
17149 // preserve its sugar structure.
17150 } else if (FTy
->getReturnType() == RetTy
&&
17151 (!NoReturn
|| FTy
->getNoReturnAttr())) {
17152 BlockTy
= BSI
->FunctionType
;
17154 // Otherwise, make the minimal modifications to the function type.
17156 const FunctionProtoType
*FPT
= cast
<FunctionProtoType
>(FTy
);
17157 FunctionProtoType::ExtProtoInfo EPI
= FPT
->getExtProtoInfo();
17158 EPI
.TypeQuals
= Qualifiers();
17160 BlockTy
= Context
.getFunctionType(RetTy
, FPT
->getParamTypes(), EPI
);
17163 // If we don't have a function type, just build one from nothing.
17165 FunctionProtoType::ExtProtoInfo EPI
;
17166 EPI
.ExtInfo
= FunctionType::ExtInfo().withNoReturn(NoReturn
);
17167 BlockTy
= Context
.getFunctionType(RetTy
, std::nullopt
, EPI
);
17170 DiagnoseUnusedParameters(BD
->parameters());
17171 BlockTy
= Context
.getBlockPointerType(BlockTy
);
17173 // If needed, diagnose invalid gotos and switches in the block.
17174 if (getCurFunction()->NeedsScopeChecking() &&
17175 !PP
.isCodeCompletionEnabled())
17176 DiagnoseInvalidJumps(cast
<CompoundStmt
>(Body
));
17178 BD
->setBody(cast
<CompoundStmt
>(Body
));
17180 if (Body
&& getCurFunction()->HasPotentialAvailabilityViolations
)
17181 DiagnoseUnguardedAvailabilityViolations(BD
);
17183 // Try to apply the named return value optimization. We have to check again
17184 // if we can do this, though, because blocks keep return statements around
17185 // to deduce an implicit return type.
17186 if (getLangOpts().CPlusPlus
&& RetTy
->isRecordType() &&
17187 !BD
->isDependentContext())
17188 computeNRVO(Body
, BSI
);
17190 if (RetTy
.hasNonTrivialToPrimitiveDestructCUnion() ||
17191 RetTy
.hasNonTrivialToPrimitiveCopyCUnion())
17192 checkNonTrivialCUnion(RetTy
, BD
->getCaretLocation(), NTCUC_FunctionReturn
,
17193 NTCUK_Destruct
|NTCUK_Copy
);
17197 // Set the captured variables on the block.
17198 SmallVector
<BlockDecl::Capture
, 4> Captures
;
17199 for (Capture
&Cap
: BSI
->Captures
) {
17200 if (Cap
.isInvalid() || Cap
.isThisCapture())
17202 // Cap.getVariable() is always a VarDecl because
17203 // blocks cannot capture structured bindings or other ValueDecl kinds.
17204 auto *Var
= cast
<VarDecl
>(Cap
.getVariable());
17205 Expr
*CopyExpr
= nullptr;
17206 if (getLangOpts().CPlusPlus
&& Cap
.isCopyCapture()) {
17207 if (const RecordType
*Record
=
17208 Cap
.getCaptureType()->getAs
<RecordType
>()) {
17209 // The capture logic needs the destructor, so make sure we mark it.
17210 // Usually this is unnecessary because most local variables have
17211 // their destructors marked at declaration time, but parameters are
17212 // an exception because it's technically only the call site that
17213 // actually requires the destructor.
17214 if (isa
<ParmVarDecl
>(Var
))
17215 FinalizeVarWithDestructor(Var
, Record
);
17217 // Enter a separate potentially-evaluated context while building block
17218 // initializers to isolate their cleanups from those of the block
17220 // FIXME: Is this appropriate even when the block itself occurs in an
17221 // unevaluated operand?
17222 EnterExpressionEvaluationContext
EvalContext(
17223 *this, ExpressionEvaluationContext::PotentiallyEvaluated
);
17225 SourceLocation Loc
= Cap
.getLocation();
17227 ExprResult Result
= BuildDeclarationNameExpr(
17228 CXXScopeSpec(), DeclarationNameInfo(Var
->getDeclName(), Loc
), Var
);
17230 // According to the blocks spec, the capture of a variable from
17231 // the stack requires a const copy constructor. This is not true
17232 // of the copy/move done to move a __block variable to the heap.
17233 if (!Result
.isInvalid() &&
17234 !Result
.get()->getType().isConstQualified()) {
17235 Result
= ImpCastExprToType(Result
.get(),
17236 Result
.get()->getType().withConst(),
17237 CK_NoOp
, VK_LValue
);
17240 if (!Result
.isInvalid()) {
17241 Result
= PerformCopyInitialization(
17242 InitializedEntity::InitializeBlock(Var
->getLocation(),
17243 Cap
.getCaptureType()),
17244 Loc
, Result
.get());
17247 // Build a full-expression copy expression if initialization
17248 // succeeded and used a non-trivial constructor. Recover from
17249 // errors by pretending that the copy isn't necessary.
17250 if (!Result
.isInvalid() &&
17251 !cast
<CXXConstructExpr
>(Result
.get())->getConstructor()
17253 Result
= MaybeCreateExprWithCleanups(Result
);
17254 CopyExpr
= Result
.get();
17259 BlockDecl::Capture
NewCap(Var
, Cap
.isBlockCapture(), Cap
.isNested(),
17261 Captures
.push_back(NewCap
);
17263 BD
->setCaptures(Context
, Captures
, BSI
->CXXThisCaptureIndex
!= 0);
17265 // Pop the block scope now but keep it alive to the end of this function.
17266 AnalysisBasedWarnings::Policy WP
= AnalysisWarnings
.getDefaultPolicy();
17267 PoppedFunctionScopePtr ScopeRAII
= PopFunctionScopeInfo(&WP
, BD
, BlockTy
);
17269 BlockExpr
*Result
= new (Context
) BlockExpr(BD
, BlockTy
);
17271 // If the block isn't obviously global, i.e. it captures anything at
17272 // all, then we need to do a few things in the surrounding context:
17273 if (Result
->getBlockDecl()->hasCaptures()) {
17274 // First, this expression has a new cleanup object.
17275 ExprCleanupObjects
.push_back(Result
->getBlockDecl());
17276 Cleanup
.setExprNeedsCleanups(true);
17278 // It also gets a branch-protected scope if any of the captured
17279 // variables needs destruction.
17280 for (const auto &CI
: Result
->getBlockDecl()->captures()) {
17281 const VarDecl
*var
= CI
.getVariable();
17282 if (var
->getType().isDestructedType() != QualType::DK_none
) {
17283 setFunctionHasBranchProtectedScope();
17289 if (getCurFunction())
17290 getCurFunction()->addBlock(BD
);
17292 if (BD
->isInvalidDecl())
17293 return CreateRecoveryExpr(Result
->getBeginLoc(), Result
->getEndLoc(),
17294 {Result
}, Result
->getType());
17298 ExprResult
Sema::ActOnVAArg(SourceLocation BuiltinLoc
, Expr
*E
, ParsedType Ty
,
17299 SourceLocation RPLoc
) {
17300 TypeSourceInfo
*TInfo
;
17301 GetTypeFromParser(Ty
, &TInfo
);
17302 return BuildVAArgExpr(BuiltinLoc
, E
, TInfo
, RPLoc
);
17305 ExprResult
Sema::BuildVAArgExpr(SourceLocation BuiltinLoc
,
17306 Expr
*E
, TypeSourceInfo
*TInfo
,
17307 SourceLocation RPLoc
) {
17308 Expr
*OrigExpr
= E
;
17311 // CUDA device code does not support varargs.
17312 if (getLangOpts().CUDA
&& getLangOpts().CUDAIsDevice
) {
17313 if (const FunctionDecl
*F
= dyn_cast
<FunctionDecl
>(CurContext
)) {
17314 CUDAFunctionTarget T
= IdentifyCUDATarget(F
);
17315 if (T
== CFT_Global
|| T
== CFT_Device
|| T
== CFT_HostDevice
)
17316 return ExprError(Diag(E
->getBeginLoc(), diag::err_va_arg_in_device
));
17320 // NVPTX does not support va_arg expression.
17321 if (getLangOpts().OpenMP
&& getLangOpts().OpenMPIsTargetDevice
&&
17322 Context
.getTargetInfo().getTriple().isNVPTX())
17323 targetDiag(E
->getBeginLoc(), diag::err_va_arg_in_device
);
17325 // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
17326 // as Microsoft ABI on an actual Microsoft platform, where
17327 // __builtin_ms_va_list and __builtin_va_list are the same.)
17328 if (!E
->isTypeDependent() && Context
.getTargetInfo().hasBuiltinMSVaList() &&
17329 Context
.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList
) {
17330 QualType MSVaListType
= Context
.getBuiltinMSVaListType();
17331 if (Context
.hasSameType(MSVaListType
, E
->getType())) {
17332 if (CheckForModifiableLvalue(E
, BuiltinLoc
, *this))
17333 return ExprError();
17338 // Get the va_list type
17339 QualType VaListType
= Context
.getBuiltinVaListType();
17341 if (VaListType
->isArrayType()) {
17342 // Deal with implicit array decay; for example, on x86-64,
17343 // va_list is an array, but it's supposed to decay to
17344 // a pointer for va_arg.
17345 VaListType
= Context
.getArrayDecayedType(VaListType
);
17346 // Make sure the input expression also decays appropriately.
17347 ExprResult Result
= UsualUnaryConversions(E
);
17348 if (Result
.isInvalid())
17349 return ExprError();
17351 } else if (VaListType
->isRecordType() && getLangOpts().CPlusPlus
) {
17352 // If va_list is a record type and we are compiling in C++ mode,
17353 // check the argument using reference binding.
17354 InitializedEntity Entity
= InitializedEntity::InitializeParameter(
17355 Context
, Context
.getLValueReferenceType(VaListType
), false);
17356 ExprResult Init
= PerformCopyInitialization(Entity
, SourceLocation(), E
);
17357 if (Init
.isInvalid())
17358 return ExprError();
17359 E
= Init
.getAs
<Expr
>();
17361 // Otherwise, the va_list argument must be an l-value because
17362 // it is modified by va_arg.
17363 if (!E
->isTypeDependent() &&
17364 CheckForModifiableLvalue(E
, BuiltinLoc
, *this))
17365 return ExprError();
17369 if (!IsMS
&& !E
->isTypeDependent() &&
17370 !Context
.hasSameType(VaListType
, E
->getType()))
17372 Diag(E
->getBeginLoc(),
17373 diag::err_first_argument_to_va_arg_not_of_type_va_list
)
17374 << OrigExpr
->getType() << E
->getSourceRange());
17376 if (!TInfo
->getType()->isDependentType()) {
17377 if (RequireCompleteType(TInfo
->getTypeLoc().getBeginLoc(), TInfo
->getType(),
17378 diag::err_second_parameter_to_va_arg_incomplete
,
17379 TInfo
->getTypeLoc()))
17380 return ExprError();
17382 if (RequireNonAbstractType(TInfo
->getTypeLoc().getBeginLoc(),
17384 diag::err_second_parameter_to_va_arg_abstract
,
17385 TInfo
->getTypeLoc()))
17386 return ExprError();
17388 if (!TInfo
->getType().isPODType(Context
)) {
17389 Diag(TInfo
->getTypeLoc().getBeginLoc(),
17390 TInfo
->getType()->isObjCLifetimeType()
17391 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
17392 : diag::warn_second_parameter_to_va_arg_not_pod
)
17393 << TInfo
->getType()
17394 << TInfo
->getTypeLoc().getSourceRange();
17397 // Check for va_arg where arguments of the given type will be promoted
17398 // (i.e. this va_arg is guaranteed to have undefined behavior).
17399 QualType PromoteType
;
17400 if (Context
.isPromotableIntegerType(TInfo
->getType())) {
17401 PromoteType
= Context
.getPromotedIntegerType(TInfo
->getType());
17402 // [cstdarg.syn]p1 defers the C++ behavior to what the C standard says,
17403 // and C23 7.16.1.1p2 says, in part:
17404 // If type is not compatible with the type of the actual next argument
17405 // (as promoted according to the default argument promotions), the
17406 // behavior is undefined, except for the following cases:
17407 // - both types are pointers to qualified or unqualified versions of
17408 // compatible types;
17409 // - one type is compatible with a signed integer type, the other
17410 // type is compatible with the corresponding unsigned integer type,
17411 // and the value is representable in both types;
17412 // - one type is pointer to qualified or unqualified void and the
17413 // other is a pointer to a qualified or unqualified character type;
17414 // - or, the type of the next argument is nullptr_t and type is a
17415 // pointer type that has the same representation and alignment
17416 // requirements as a pointer to a character type.
17417 // Given that type compatibility is the primary requirement (ignoring
17418 // qualifications), you would think we could call typesAreCompatible()
17419 // directly to test this. However, in C++, that checks for *same type*,
17420 // which causes false positives when passing an enumeration type to
17421 // va_arg. Instead, get the underlying type of the enumeration and pass
17423 QualType UnderlyingType
= TInfo
->getType();
17424 if (const auto *ET
= UnderlyingType
->getAs
<EnumType
>())
17425 UnderlyingType
= ET
->getDecl()->getIntegerType();
17426 if (Context
.typesAreCompatible(PromoteType
, UnderlyingType
,
17427 /*CompareUnqualified*/ true))
17428 PromoteType
= QualType();
17430 // If the types are still not compatible, we need to test whether the
17431 // promoted type and the underlying type are the same except for
17432 // signedness. Ask the AST for the correctly corresponding type and see
17433 // if that's compatible.
17434 if (!PromoteType
.isNull() && !UnderlyingType
->isBooleanType() &&
17435 PromoteType
->isUnsignedIntegerType() !=
17436 UnderlyingType
->isUnsignedIntegerType()) {
17438 UnderlyingType
->isUnsignedIntegerType()
17439 ? Context
.getCorrespondingSignedType(UnderlyingType
)
17440 : Context
.getCorrespondingUnsignedType(UnderlyingType
);
17441 if (Context
.typesAreCompatible(PromoteType
, UnderlyingType
,
17442 /*CompareUnqualified*/ true))
17443 PromoteType
= QualType();
17446 if (TInfo
->getType()->isSpecificBuiltinType(BuiltinType::Float
))
17447 PromoteType
= Context
.DoubleTy
;
17448 if (!PromoteType
.isNull())
17449 DiagRuntimeBehavior(TInfo
->getTypeLoc().getBeginLoc(), E
,
17450 PDiag(diag::warn_second_parameter_to_va_arg_never_compatible
)
17451 << TInfo
->getType()
17453 << TInfo
->getTypeLoc().getSourceRange());
17456 QualType T
= TInfo
->getType().getNonLValueExprType(Context
);
17457 return new (Context
) VAArgExpr(BuiltinLoc
, E
, TInfo
, RPLoc
, T
, IsMS
);
17460 ExprResult
Sema::ActOnGNUNullExpr(SourceLocation TokenLoc
) {
17461 // The type of __null will be int or long, depending on the size of
17462 // pointers on the target.
17464 unsigned pw
= Context
.getTargetInfo().getPointerWidth(LangAS::Default
);
17465 if (pw
== Context
.getTargetInfo().getIntWidth())
17466 Ty
= Context
.IntTy
;
17467 else if (pw
== Context
.getTargetInfo().getLongWidth())
17468 Ty
= Context
.LongTy
;
17469 else if (pw
== Context
.getTargetInfo().getLongLongWidth())
17470 Ty
= Context
.LongLongTy
;
17472 llvm_unreachable("I don't know size of pointer!");
17475 return new (Context
) GNUNullExpr(Ty
, TokenLoc
);
17478 static CXXRecordDecl
*LookupStdSourceLocationImpl(Sema
&S
, SourceLocation Loc
) {
17479 CXXRecordDecl
*ImplDecl
= nullptr;
17481 // Fetch the std::source_location::__impl decl.
17482 if (NamespaceDecl
*Std
= S
.getStdNamespace()) {
17483 LookupResult
ResultSL(S
, &S
.PP
.getIdentifierTable().get("source_location"),
17484 Loc
, Sema::LookupOrdinaryName
);
17485 if (S
.LookupQualifiedName(ResultSL
, Std
)) {
17486 if (auto *SLDecl
= ResultSL
.getAsSingle
<RecordDecl
>()) {
17487 LookupResult
ResultImpl(S
, &S
.PP
.getIdentifierTable().get("__impl"),
17488 Loc
, Sema::LookupOrdinaryName
);
17489 if ((SLDecl
->isCompleteDefinition() || SLDecl
->isBeingDefined()) &&
17490 S
.LookupQualifiedName(ResultImpl
, SLDecl
)) {
17491 ImplDecl
= ResultImpl
.getAsSingle
<CXXRecordDecl
>();
17497 if (!ImplDecl
|| !ImplDecl
->isCompleteDefinition()) {
17498 S
.Diag(Loc
, diag::err_std_source_location_impl_not_found
);
17502 // Verify that __impl is a trivial struct type, with no base classes, and with
17503 // only the four expected fields.
17504 if (ImplDecl
->isUnion() || !ImplDecl
->isStandardLayout() ||
17505 ImplDecl
->getNumBases() != 0) {
17506 S
.Diag(Loc
, diag::err_std_source_location_impl_malformed
);
17510 unsigned Count
= 0;
17511 for (FieldDecl
*F
: ImplDecl
->fields()) {
17512 StringRef Name
= F
->getName();
17514 if (Name
== "_M_file_name") {
17515 if (F
->getType() !=
17516 S
.Context
.getPointerType(S
.Context
.CharTy
.withConst()))
17519 } else if (Name
== "_M_function_name") {
17520 if (F
->getType() !=
17521 S
.Context
.getPointerType(S
.Context
.CharTy
.withConst()))
17524 } else if (Name
== "_M_line") {
17525 if (!F
->getType()->isIntegerType())
17528 } else if (Name
== "_M_column") {
17529 if (!F
->getType()->isIntegerType())
17533 Count
= 100; // invalid
17538 S
.Diag(Loc
, diag::err_std_source_location_impl_malformed
);
17545 ExprResult
Sema::ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind
,
17546 SourceLocation BuiltinLoc
,
17547 SourceLocation RPLoc
) {
17550 case SourceLocExpr::File
:
17551 case SourceLocExpr::FileName
:
17552 case SourceLocExpr::Function
:
17553 case SourceLocExpr::FuncSig
: {
17554 QualType ArrTy
= Context
.getStringLiteralArrayType(Context
.CharTy
, 0);
17556 Context
.getPointerType(ArrTy
->getAsArrayTypeUnsafe()->getElementType());
17559 case SourceLocExpr::Line
:
17560 case SourceLocExpr::Column
:
17561 ResultTy
= Context
.UnsignedIntTy
;
17563 case SourceLocExpr::SourceLocStruct
:
17564 if (!StdSourceLocationImplDecl
) {
17565 StdSourceLocationImplDecl
=
17566 LookupStdSourceLocationImpl(*this, BuiltinLoc
);
17567 if (!StdSourceLocationImplDecl
)
17568 return ExprError();
17570 ResultTy
= Context
.getPointerType(
17571 Context
.getRecordType(StdSourceLocationImplDecl
).withConst());
17575 return BuildSourceLocExpr(Kind
, ResultTy
, BuiltinLoc
, RPLoc
, CurContext
);
17578 ExprResult
Sema::BuildSourceLocExpr(SourceLocExpr::IdentKind Kind
,
17580 SourceLocation BuiltinLoc
,
17581 SourceLocation RPLoc
,
17582 DeclContext
*ParentContext
) {
17583 return new (Context
)
17584 SourceLocExpr(Context
, Kind
, ResultTy
, BuiltinLoc
, RPLoc
, ParentContext
);
17587 bool Sema::CheckConversionToObjCLiteral(QualType DstType
, Expr
*&Exp
,
17589 if (!getLangOpts().ObjC
)
17592 const ObjCObjectPointerType
*PT
= DstType
->getAs
<ObjCObjectPointerType
>();
17595 const ObjCInterfaceDecl
*ID
= PT
->getInterfaceDecl();
17597 // Ignore any parens, implicit casts (should only be
17598 // array-to-pointer decays), and not-so-opaque values. The last is
17599 // important for making this trigger for property assignments.
17600 Expr
*SrcExpr
= Exp
->IgnoreParenImpCasts();
17601 if (OpaqueValueExpr
*OV
= dyn_cast
<OpaqueValueExpr
>(SrcExpr
))
17602 if (OV
->getSourceExpr())
17603 SrcExpr
= OV
->getSourceExpr()->IgnoreParenImpCasts();
17605 if (auto *SL
= dyn_cast
<StringLiteral
>(SrcExpr
)) {
17606 if (!PT
->isObjCIdType() &&
17607 !(ID
&& ID
->getIdentifier()->isStr("NSString")))
17609 if (!SL
->isOrdinary())
17613 Diag(SL
->getBeginLoc(), diag::err_missing_atsign_prefix
)
17614 << /*string*/0 << FixItHint::CreateInsertion(SL
->getBeginLoc(), "@");
17615 Exp
= BuildObjCStringLiteral(SL
->getBeginLoc(), SL
).get();
17620 if ((isa
<IntegerLiteral
>(SrcExpr
) || isa
<CharacterLiteral
>(SrcExpr
) ||
17621 isa
<FloatingLiteral
>(SrcExpr
) || isa
<ObjCBoolLiteralExpr
>(SrcExpr
) ||
17622 isa
<CXXBoolLiteralExpr
>(SrcExpr
)) &&
17623 !SrcExpr
->isNullPointerConstant(
17624 getASTContext(), Expr::NPC_NeverValueDependent
)) {
17625 if (!ID
|| !ID
->getIdentifier()->isStr("NSNumber"))
17628 Diag(SrcExpr
->getBeginLoc(), diag::err_missing_atsign_prefix
)
17630 << FixItHint::CreateInsertion(SrcExpr
->getBeginLoc(), "@");
17632 BuildObjCNumericLiteral(SrcExpr
->getBeginLoc(), SrcExpr
).get();
17642 static bool maybeDiagnoseAssignmentToFunction(Sema
&S
, QualType DstType
,
17643 const Expr
*SrcExpr
) {
17644 if (!DstType
->isFunctionPointerType() ||
17645 !SrcExpr
->getType()->isFunctionType())
17648 auto *DRE
= dyn_cast
<DeclRefExpr
>(SrcExpr
->IgnoreParenImpCasts());
17652 auto *FD
= dyn_cast
<FunctionDecl
>(DRE
->getDecl());
17656 return !S
.checkAddressOfFunctionIsAvailable(FD
,
17658 SrcExpr
->getBeginLoc());
17661 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy
,
17662 SourceLocation Loc
,
17663 QualType DstType
, QualType SrcType
,
17664 Expr
*SrcExpr
, AssignmentAction Action
,
17665 bool *Complained
) {
17667 *Complained
= false;
17669 // Decode the result (notice that AST's are still created for extensions).
17670 bool CheckInferredResultType
= false;
17671 bool isInvalid
= false;
17672 unsigned DiagKind
= 0;
17673 ConversionFixItGenerator ConvHints
;
17674 bool MayHaveConvFixit
= false;
17675 bool MayHaveFunctionDiff
= false;
17676 const ObjCInterfaceDecl
*IFace
= nullptr;
17677 const ObjCProtocolDecl
*PDecl
= nullptr;
17681 DiagnoseAssignmentEnum(DstType
, SrcType
, SrcExpr
);
17685 if (getLangOpts().CPlusPlus
) {
17686 DiagKind
= diag::err_typecheck_convert_pointer_int
;
17689 DiagKind
= diag::ext_typecheck_convert_pointer_int
;
17691 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17692 MayHaveConvFixit
= true;
17695 if (getLangOpts().CPlusPlus
) {
17696 DiagKind
= diag::err_typecheck_convert_int_pointer
;
17699 DiagKind
= diag::ext_typecheck_convert_int_pointer
;
17701 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17702 MayHaveConvFixit
= true;
17704 case IncompatibleFunctionPointerStrict
:
17706 diag::warn_typecheck_convert_incompatible_function_pointer_strict
;
17707 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17708 MayHaveConvFixit
= true;
17710 case IncompatibleFunctionPointer
:
17711 if (getLangOpts().CPlusPlus
) {
17712 DiagKind
= diag::err_typecheck_convert_incompatible_function_pointer
;
17715 DiagKind
= diag::ext_typecheck_convert_incompatible_function_pointer
;
17717 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17718 MayHaveConvFixit
= true;
17720 case IncompatiblePointer
:
17721 if (Action
== AA_Passing_CFAudited
) {
17722 DiagKind
= diag::err_arc_typecheck_convert_incompatible_pointer
;
17723 } else if (getLangOpts().CPlusPlus
) {
17724 DiagKind
= diag::err_typecheck_convert_incompatible_pointer
;
17727 DiagKind
= diag::ext_typecheck_convert_incompatible_pointer
;
17729 CheckInferredResultType
= DstType
->isObjCObjectPointerType() &&
17730 SrcType
->isObjCObjectPointerType();
17731 if (!CheckInferredResultType
) {
17732 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17733 } else if (CheckInferredResultType
) {
17734 SrcType
= SrcType
.getUnqualifiedType();
17735 DstType
= DstType
.getUnqualifiedType();
17737 MayHaveConvFixit
= true;
17739 case IncompatiblePointerSign
:
17740 if (getLangOpts().CPlusPlus
) {
17741 DiagKind
= diag::err_typecheck_convert_incompatible_pointer_sign
;
17744 DiagKind
= diag::ext_typecheck_convert_incompatible_pointer_sign
;
17747 case FunctionVoidPointer
:
17748 if (getLangOpts().CPlusPlus
) {
17749 DiagKind
= diag::err_typecheck_convert_pointer_void_func
;
17752 DiagKind
= diag::ext_typecheck_convert_pointer_void_func
;
17755 case IncompatiblePointerDiscardsQualifiers
: {
17756 // Perform array-to-pointer decay if necessary.
17757 if (SrcType
->isArrayType()) SrcType
= Context
.getArrayDecayedType(SrcType
);
17761 Qualifiers lhq
= SrcType
->getPointeeType().getQualifiers();
17762 Qualifiers rhq
= DstType
->getPointeeType().getQualifiers();
17763 if (lhq
.getAddressSpace() != rhq
.getAddressSpace()) {
17764 DiagKind
= diag::err_typecheck_incompatible_address_space
;
17767 } else if (lhq
.getObjCLifetime() != rhq
.getObjCLifetime()) {
17768 DiagKind
= diag::err_typecheck_incompatible_ownership
;
17772 llvm_unreachable("unknown error case for discarding qualifiers!");
17775 case CompatiblePointerDiscardsQualifiers
:
17776 // If the qualifiers lost were because we were applying the
17777 // (deprecated) C++ conversion from a string literal to a char*
17778 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
17779 // Ideally, this check would be performed in
17780 // checkPointerTypesForAssignment. However, that would require a
17781 // bit of refactoring (so that the second argument is an
17782 // expression, rather than a type), which should be done as part
17783 // of a larger effort to fix checkPointerTypesForAssignment for
17785 if (getLangOpts().CPlusPlus
&&
17786 IsStringLiteralToNonConstPointerConversion(SrcExpr
, DstType
))
17788 if (getLangOpts().CPlusPlus
) {
17789 DiagKind
= diag::err_typecheck_convert_discards_qualifiers
;
17792 DiagKind
= diag::ext_typecheck_convert_discards_qualifiers
;
17796 case IncompatibleNestedPointerQualifiers
:
17797 if (getLangOpts().CPlusPlus
) {
17799 DiagKind
= diag::err_nested_pointer_qualifier_mismatch
;
17801 DiagKind
= diag::ext_nested_pointer_qualifier_mismatch
;
17804 case IncompatibleNestedPointerAddressSpaceMismatch
:
17805 DiagKind
= diag::err_typecheck_incompatible_nested_address_space
;
17808 case IntToBlockPointer
:
17809 DiagKind
= diag::err_int_to_block_pointer
;
17812 case IncompatibleBlockPointer
:
17813 DiagKind
= diag::err_typecheck_convert_incompatible_block_pointer
;
17816 case IncompatibleObjCQualifiedId
: {
17817 if (SrcType
->isObjCQualifiedIdType()) {
17818 const ObjCObjectPointerType
*srcOPT
=
17819 SrcType
->castAs
<ObjCObjectPointerType
>();
17820 for (auto *srcProto
: srcOPT
->quals()) {
17824 if (const ObjCInterfaceType
*IFaceT
=
17825 DstType
->castAs
<ObjCObjectPointerType
>()->getInterfaceType())
17826 IFace
= IFaceT
->getDecl();
17828 else if (DstType
->isObjCQualifiedIdType()) {
17829 const ObjCObjectPointerType
*dstOPT
=
17830 DstType
->castAs
<ObjCObjectPointerType
>();
17831 for (auto *dstProto
: dstOPT
->quals()) {
17835 if (const ObjCInterfaceType
*IFaceT
=
17836 SrcType
->castAs
<ObjCObjectPointerType
>()->getInterfaceType())
17837 IFace
= IFaceT
->getDecl();
17839 if (getLangOpts().CPlusPlus
) {
17840 DiagKind
= diag::err_incompatible_qualified_id
;
17843 DiagKind
= diag::warn_incompatible_qualified_id
;
17847 case IncompatibleVectors
:
17848 if (getLangOpts().CPlusPlus
) {
17849 DiagKind
= diag::err_incompatible_vectors
;
17852 DiagKind
= diag::warn_incompatible_vectors
;
17855 case IncompatibleObjCWeakRef
:
17856 DiagKind
= diag::err_arc_weak_unavailable_assign
;
17860 if (maybeDiagnoseAssignmentToFunction(*this, DstType
, SrcExpr
)) {
17862 *Complained
= true;
17866 DiagKind
= diag::err_typecheck_convert_incompatible
;
17867 ConvHints
.tryToFixConversion(SrcExpr
, SrcType
, DstType
, *this);
17868 MayHaveConvFixit
= true;
17870 MayHaveFunctionDiff
= true;
17874 QualType FirstType
, SecondType
;
17877 case AA_Initializing
:
17878 // The destination type comes first.
17879 FirstType
= DstType
;
17880 SecondType
= SrcType
;
17885 case AA_Passing_CFAudited
:
17886 case AA_Converting
:
17889 // The source type comes first.
17890 FirstType
= SrcType
;
17891 SecondType
= DstType
;
17895 PartialDiagnostic FDiag
= PDiag(DiagKind
);
17896 AssignmentAction ActionForDiag
= Action
;
17897 if (Action
== AA_Passing_CFAudited
)
17898 ActionForDiag
= AA_Passing
;
17900 FDiag
<< FirstType
<< SecondType
<< ActionForDiag
17901 << SrcExpr
->getSourceRange();
17903 if (DiagKind
== diag::ext_typecheck_convert_incompatible_pointer_sign
||
17904 DiagKind
== diag::err_typecheck_convert_incompatible_pointer_sign
) {
17905 auto isPlainChar
= [](const clang::Type
*Type
) {
17906 return Type
->isSpecificBuiltinType(BuiltinType::Char_S
) ||
17907 Type
->isSpecificBuiltinType(BuiltinType::Char_U
);
17909 FDiag
<< (isPlainChar(FirstType
->getPointeeOrArrayElementType()) ||
17910 isPlainChar(SecondType
->getPointeeOrArrayElementType()));
17913 // If we can fix the conversion, suggest the FixIts.
17914 if (!ConvHints
.isNull()) {
17915 for (FixItHint
&H
: ConvHints
.Hints
)
17919 if (MayHaveConvFixit
) { FDiag
<< (unsigned) (ConvHints
.Kind
); }
17921 if (MayHaveFunctionDiff
)
17922 HandleFunctionTypeMismatch(FDiag
, SecondType
, FirstType
);
17925 if ((DiagKind
== diag::warn_incompatible_qualified_id
||
17926 DiagKind
== diag::err_incompatible_qualified_id
) &&
17927 PDecl
&& IFace
&& !IFace
->hasDefinition())
17928 Diag(IFace
->getLocation(), diag::note_incomplete_class_and_qualified_id
)
17931 if (SecondType
== Context
.OverloadTy
)
17932 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr
).Expression
,
17933 FirstType
, /*TakingAddress=*/true);
17935 if (CheckInferredResultType
)
17936 EmitRelatedResultTypeNote(SrcExpr
);
17938 if (Action
== AA_Returning
&& ConvTy
== IncompatiblePointer
)
17939 EmitRelatedResultTypeNoteForReturn(DstType
);
17942 *Complained
= true;
17946 ExprResult
Sema::VerifyIntegerConstantExpression(Expr
*E
,
17947 llvm::APSInt
*Result
,
17948 AllowFoldKind CanFold
) {
17949 class SimpleICEDiagnoser
: public VerifyICEDiagnoser
{
17951 SemaDiagnosticBuilder
diagnoseNotICEType(Sema
&S
, SourceLocation Loc
,
17952 QualType T
) override
{
17953 return S
.Diag(Loc
, diag::err_ice_not_integral
)
17954 << T
<< S
.LangOpts
.CPlusPlus
;
17956 SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
, SourceLocation Loc
) override
{
17957 return S
.Diag(Loc
, diag::err_expr_not_ice
) << S
.LangOpts
.CPlusPlus
;
17961 return VerifyIntegerConstantExpression(E
, Result
, Diagnoser
, CanFold
);
17964 ExprResult
Sema::VerifyIntegerConstantExpression(Expr
*E
,
17965 llvm::APSInt
*Result
,
17967 AllowFoldKind CanFold
) {
17968 class IDDiagnoser
: public VerifyICEDiagnoser
{
17972 IDDiagnoser(unsigned DiagID
)
17973 : VerifyICEDiagnoser(DiagID
== 0), DiagID(DiagID
) { }
17975 SemaDiagnosticBuilder
diagnoseNotICE(Sema
&S
, SourceLocation Loc
) override
{
17976 return S
.Diag(Loc
, DiagID
);
17978 } Diagnoser(DiagID
);
17980 return VerifyIntegerConstantExpression(E
, Result
, Diagnoser
, CanFold
);
17983 Sema::SemaDiagnosticBuilder
17984 Sema::VerifyICEDiagnoser::diagnoseNotICEType(Sema
&S
, SourceLocation Loc
,
17986 return diagnoseNotICE(S
, Loc
);
17989 Sema::SemaDiagnosticBuilder
17990 Sema::VerifyICEDiagnoser::diagnoseFold(Sema
&S
, SourceLocation Loc
) {
17991 return S
.Diag(Loc
, diag::ext_expr_not_ice
) << S
.LangOpts
.CPlusPlus
;
17995 Sema::VerifyIntegerConstantExpression(Expr
*E
, llvm::APSInt
*Result
,
17996 VerifyICEDiagnoser
&Diagnoser
,
17997 AllowFoldKind CanFold
) {
17998 SourceLocation DiagLoc
= E
->getBeginLoc();
18000 if (getLangOpts().CPlusPlus11
) {
18001 // C++11 [expr.const]p5:
18002 // If an expression of literal class type is used in a context where an
18003 // integral constant expression is required, then that class type shall
18004 // have a single non-explicit conversion function to an integral or
18005 // unscoped enumeration type
18006 ExprResult Converted
;
18007 class CXX11ConvertDiagnoser
: public ICEConvertDiagnoser
{
18008 VerifyICEDiagnoser
&BaseDiagnoser
;
18010 CXX11ConvertDiagnoser(VerifyICEDiagnoser
&BaseDiagnoser
)
18011 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false,
18012 BaseDiagnoser
.Suppress
, true),
18013 BaseDiagnoser(BaseDiagnoser
) {}
18015 SemaDiagnosticBuilder
diagnoseNotInt(Sema
&S
, SourceLocation Loc
,
18016 QualType T
) override
{
18017 return BaseDiagnoser
.diagnoseNotICEType(S
, Loc
, T
);
18020 SemaDiagnosticBuilder
diagnoseIncomplete(
18021 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
18022 return S
.Diag(Loc
, diag::err_ice_incomplete_type
) << T
;
18025 SemaDiagnosticBuilder
diagnoseExplicitConv(
18026 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
18027 return S
.Diag(Loc
, diag::err_ice_explicit_conversion
) << T
<< ConvTy
;
18030 SemaDiagnosticBuilder
noteExplicitConv(
18031 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
18032 return S
.Diag(Conv
->getLocation(), diag::note_ice_conversion_here
)
18033 << ConvTy
->isEnumeralType() << ConvTy
;
18036 SemaDiagnosticBuilder
diagnoseAmbiguous(
18037 Sema
&S
, SourceLocation Loc
, QualType T
) override
{
18038 return S
.Diag(Loc
, diag::err_ice_ambiguous_conversion
) << T
;
18041 SemaDiagnosticBuilder
noteAmbiguous(
18042 Sema
&S
, CXXConversionDecl
*Conv
, QualType ConvTy
) override
{
18043 return S
.Diag(Conv
->getLocation(), diag::note_ice_conversion_here
)
18044 << ConvTy
->isEnumeralType() << ConvTy
;
18047 SemaDiagnosticBuilder
diagnoseConversion(
18048 Sema
&S
, SourceLocation Loc
, QualType T
, QualType ConvTy
) override
{
18049 llvm_unreachable("conversion functions are permitted");
18051 } ConvertDiagnoser(Diagnoser
);
18053 Converted
= PerformContextualImplicitConversion(DiagLoc
, E
,
18055 if (Converted
.isInvalid())
18057 E
= Converted
.get();
18058 if (!E
->getType()->isIntegralOrUnscopedEnumerationType())
18059 return ExprError();
18060 } else if (!E
->getType()->isIntegralOrUnscopedEnumerationType()) {
18061 // An ICE must be of integral or unscoped enumeration type.
18062 if (!Diagnoser
.Suppress
)
18063 Diagnoser
.diagnoseNotICEType(*this, DiagLoc
, E
->getType())
18064 << E
->getSourceRange();
18065 return ExprError();
18068 ExprResult RValueExpr
= DefaultLvalueConversion(E
);
18069 if (RValueExpr
.isInvalid())
18070 return ExprError();
18072 E
= RValueExpr
.get();
18074 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
18075 // in the non-ICE case.
18076 if (!getLangOpts().CPlusPlus11
&& E
->isIntegerConstantExpr(Context
)) {
18078 *Result
= E
->EvaluateKnownConstIntCheckOverflow(Context
);
18079 if (!isa
<ConstantExpr
>(E
))
18080 E
= Result
? ConstantExpr::Create(Context
, E
, APValue(*Result
))
18081 : ConstantExpr::Create(Context
, E
);
18085 Expr::EvalResult EvalResult
;
18086 SmallVector
<PartialDiagnosticAt
, 8> Notes
;
18087 EvalResult
.Diag
= &Notes
;
18089 // Try to evaluate the expression, and produce diagnostics explaining why it's
18090 // not a constant expression as a side-effect.
18092 E
->EvaluateAsRValue(EvalResult
, Context
, /*isConstantContext*/ true) &&
18093 EvalResult
.Val
.isInt() && !EvalResult
.HasSideEffects
;
18095 if (!isa
<ConstantExpr
>(E
))
18096 E
= ConstantExpr::Create(Context
, E
, EvalResult
.Val
);
18098 // In C++11, we can rely on diagnostics being produced for any expression
18099 // which is not a constant expression. If no diagnostics were produced, then
18100 // this is a constant expression.
18101 if (Folded
&& getLangOpts().CPlusPlus11
&& Notes
.empty()) {
18103 *Result
= EvalResult
.Val
.getInt();
18107 // If our only note is the usual "invalid subexpression" note, just point
18108 // the caret at its location rather than producing an essentially
18110 if (Notes
.size() == 1 && Notes
[0].second
.getDiagID() ==
18111 diag::note_invalid_subexpr_in_const_expr
) {
18112 DiagLoc
= Notes
[0].first
;
18116 if (!Folded
|| !CanFold
) {
18117 if (!Diagnoser
.Suppress
) {
18118 Diagnoser
.diagnoseNotICE(*this, DiagLoc
) << E
->getSourceRange();
18119 for (const PartialDiagnosticAt
&Note
: Notes
)
18120 Diag(Note
.first
, Note
.second
);
18123 return ExprError();
18126 Diagnoser
.diagnoseFold(*this, DiagLoc
) << E
->getSourceRange();
18127 for (const PartialDiagnosticAt
&Note
: Notes
)
18128 Diag(Note
.first
, Note
.second
);
18131 *Result
= EvalResult
.Val
.getInt();
18136 // Handle the case where we conclude a expression which we speculatively
18137 // considered to be unevaluated is actually evaluated.
18138 class TransformToPE
: public TreeTransform
<TransformToPE
> {
18139 typedef TreeTransform
<TransformToPE
> BaseTransform
;
18142 TransformToPE(Sema
&SemaRef
) : BaseTransform(SemaRef
) { }
18144 // Make sure we redo semantic analysis
18145 bool AlwaysRebuild() { return true; }
18146 bool ReplacingOriginal() { return true; }
18148 // We need to special-case DeclRefExprs referring to FieldDecls which
18149 // are not part of a member pointer formation; normal TreeTransforming
18150 // doesn't catch this case because of the way we represent them in the AST.
18151 // FIXME: This is a bit ugly; is it really the best way to handle this
18154 // Error on DeclRefExprs referring to FieldDecls.
18155 ExprResult
TransformDeclRefExpr(DeclRefExpr
*E
) {
18156 if (isa
<FieldDecl
>(E
->getDecl()) &&
18157 !SemaRef
.isUnevaluatedContext())
18158 return SemaRef
.Diag(E
->getLocation(),
18159 diag::err_invalid_non_static_member_use
)
18160 << E
->getDecl() << E
->getSourceRange();
18162 return BaseTransform::TransformDeclRefExpr(E
);
18165 // Exception: filter out member pointer formation
18166 ExprResult
TransformUnaryOperator(UnaryOperator
*E
) {
18167 if (E
->getOpcode() == UO_AddrOf
&& E
->getType()->isMemberPointerType())
18170 return BaseTransform::TransformUnaryOperator(E
);
18173 // The body of a lambda-expression is in a separate expression evaluation
18174 // context so never needs to be transformed.
18175 // FIXME: Ideally we wouldn't transform the closure type either, and would
18176 // just recreate the capture expressions and lambda expression.
18177 StmtResult
TransformLambdaBody(LambdaExpr
*E
, Stmt
*Body
) {
18178 return SkipLambdaBody(E
, Body
);
18183 ExprResult
Sema::TransformToPotentiallyEvaluated(Expr
*E
) {
18184 assert(isUnevaluatedContext() &&
18185 "Should only transform unevaluated expressions");
18186 ExprEvalContexts
.back().Context
=
18187 ExprEvalContexts
[ExprEvalContexts
.size()-2].Context
;
18188 if (isUnevaluatedContext())
18190 return TransformToPE(*this).TransformExpr(E
);
18193 TypeSourceInfo
*Sema::TransformToPotentiallyEvaluated(TypeSourceInfo
*TInfo
) {
18194 assert(isUnevaluatedContext() &&
18195 "Should only transform unevaluated expressions");
18196 ExprEvalContexts
.back().Context
=
18197 ExprEvalContexts
[ExprEvalContexts
.size() - 2].Context
;
18198 if (isUnevaluatedContext())
18200 return TransformToPE(*this).TransformType(TInfo
);
18204 Sema::PushExpressionEvaluationContext(
18205 ExpressionEvaluationContext NewContext
, Decl
*LambdaContextDecl
,
18206 ExpressionEvaluationContextRecord::ExpressionKind ExprContext
) {
18207 ExprEvalContexts
.emplace_back(NewContext
, ExprCleanupObjects
.size(), Cleanup
,
18208 LambdaContextDecl
, ExprContext
);
18210 // Discarded statements and immediate contexts nested in other
18211 // discarded statements or immediate context are themselves
18212 // a discarded statement or an immediate context, respectively.
18213 ExprEvalContexts
.back().InDiscardedStatement
=
18214 ExprEvalContexts
[ExprEvalContexts
.size() - 2]
18215 .isDiscardedStatementContext();
18217 // C++23 [expr.const]/p15
18218 // An expression or conversion is in an immediate function context if [...]
18219 // it is a subexpression of a manifestly constant-evaluated expression or
18221 const auto &Prev
= ExprEvalContexts
[ExprEvalContexts
.size() - 2];
18222 ExprEvalContexts
.back().InImmediateFunctionContext
=
18223 Prev
.isImmediateFunctionContext() || Prev
.isConstantEvaluated();
18225 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
=
18226 Prev
.InImmediateEscalatingFunctionContext
;
18229 if (!MaybeODRUseExprs
.empty())
18230 std::swap(MaybeODRUseExprs
, ExprEvalContexts
.back().SavedMaybeODRUseExprs
);
18234 Sema::PushExpressionEvaluationContext(
18235 ExpressionEvaluationContext NewContext
, ReuseLambdaContextDecl_t
,
18236 ExpressionEvaluationContextRecord::ExpressionKind ExprContext
) {
18237 Decl
*ClosureContextDecl
= ExprEvalContexts
.back().ManglingContextDecl
;
18238 PushExpressionEvaluationContext(NewContext
, ClosureContextDecl
, ExprContext
);
18243 const DeclRefExpr
*CheckPossibleDeref(Sema
&S
, const Expr
*PossibleDeref
) {
18244 PossibleDeref
= PossibleDeref
->IgnoreParenImpCasts();
18245 if (const auto *E
= dyn_cast
<UnaryOperator
>(PossibleDeref
)) {
18246 if (E
->getOpcode() == UO_Deref
)
18247 return CheckPossibleDeref(S
, E
->getSubExpr());
18248 } else if (const auto *E
= dyn_cast
<ArraySubscriptExpr
>(PossibleDeref
)) {
18249 return CheckPossibleDeref(S
, E
->getBase());
18250 } else if (const auto *E
= dyn_cast
<MemberExpr
>(PossibleDeref
)) {
18251 return CheckPossibleDeref(S
, E
->getBase());
18252 } else if (const auto E
= dyn_cast
<DeclRefExpr
>(PossibleDeref
)) {
18254 QualType Ty
= E
->getType();
18255 if (const auto *Ptr
= Ty
->getAs
<PointerType
>())
18256 Inner
= Ptr
->getPointeeType();
18257 else if (const auto *Arr
= S
.Context
.getAsArrayType(Ty
))
18258 Inner
= Arr
->getElementType();
18262 if (Inner
->hasAttr(attr::NoDeref
))
18270 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord
&Rec
) {
18271 for (const Expr
*E
: Rec
.PossibleDerefs
) {
18272 const DeclRefExpr
*DeclRef
= CheckPossibleDeref(*this, E
);
18274 const ValueDecl
*Decl
= DeclRef
->getDecl();
18275 Diag(E
->getExprLoc(), diag::warn_dereference_of_noderef_type
)
18276 << Decl
->getName() << E
->getSourceRange();
18277 Diag(Decl
->getLocation(), diag::note_previous_decl
) << Decl
->getName();
18279 Diag(E
->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl
)
18280 << E
->getSourceRange();
18283 Rec
.PossibleDerefs
.clear();
18286 /// Check whether E, which is either a discarded-value expression or an
18287 /// unevaluated operand, is a simple-assignment to a volatlie-qualified lvalue,
18288 /// and if so, remove it from the list of volatile-qualified assignments that
18289 /// we are going to warn are deprecated.
18290 void Sema::CheckUnusedVolatileAssignment(Expr
*E
) {
18291 if (!E
->getType().isVolatileQualified() || !getLangOpts().CPlusPlus20
)
18294 // Note: ignoring parens here is not justified by the standard rules, but
18295 // ignoring parentheses seems like a more reasonable approach, and this only
18296 // drives a deprecation warning so doesn't affect conformance.
18297 if (auto *BO
= dyn_cast
<BinaryOperator
>(E
->IgnoreParenImpCasts())) {
18298 if (BO
->getOpcode() == BO_Assign
) {
18299 auto &LHSs
= ExprEvalContexts
.back().VolatileAssignmentLHSs
;
18300 llvm::erase(LHSs
, BO
->getLHS());
18305 void Sema::MarkExpressionAsImmediateEscalating(Expr
*E
) {
18306 assert(!FunctionScopes
.empty() && "Expected a function scope");
18307 assert(getLangOpts().CPlusPlus20
&&
18308 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
&&
18309 "Cannot mark an immediate escalating expression outside of an "
18310 "immediate escalating context");
18311 if (auto *Call
= dyn_cast
<CallExpr
>(E
->IgnoreImplicit());
18312 Call
&& Call
->getCallee()) {
18313 if (auto *DeclRef
=
18314 dyn_cast
<DeclRefExpr
>(Call
->getCallee()->IgnoreImplicit()))
18315 DeclRef
->setIsImmediateEscalating(true);
18316 } else if (auto *Ctr
= dyn_cast
<CXXConstructExpr
>(E
->IgnoreImplicit())) {
18317 Ctr
->setIsImmediateEscalating(true);
18318 } else if (auto *DeclRef
= dyn_cast
<DeclRefExpr
>(E
->IgnoreImplicit())) {
18319 DeclRef
->setIsImmediateEscalating(true);
18321 assert(false && "expected an immediately escalating expression");
18323 getCurFunction()->FoundImmediateEscalatingExpression
= true;
18326 ExprResult
Sema::CheckForImmediateInvocation(ExprResult E
, FunctionDecl
*Decl
) {
18327 if (isUnevaluatedContext() || !E
.isUsable() || !Decl
||
18328 !Decl
->isImmediateFunction() || isAlwaysConstantEvaluatedContext() ||
18329 isCheckingDefaultArgumentOrInitializer() ||
18330 RebuildingImmediateInvocation
|| isImmediateFunctionContext())
18333 /// Opportunistically remove the callee from ReferencesToConsteval if we can.
18334 /// It's OK if this fails; we'll also remove this in
18335 /// HandleImmediateInvocations, but catching it here allows us to avoid
18336 /// walking the AST looking for it in simple cases.
18337 if (auto *Call
= dyn_cast
<CallExpr
>(E
.get()->IgnoreImplicit()))
18338 if (auto *DeclRef
=
18339 dyn_cast
<DeclRefExpr
>(Call
->getCallee()->IgnoreImplicit()))
18340 ExprEvalContexts
.back().ReferenceToConsteval
.erase(DeclRef
);
18342 // C++23 [expr.const]/p16
18343 // An expression or conversion is immediate-escalating if it is not initially
18344 // in an immediate function context and it is [...] an immediate invocation
18345 // that is not a constant expression and is not a subexpression of an
18346 // immediate invocation.
18348 auto CheckConstantExpressionAndKeepResult
= [&]() {
18349 llvm::SmallVector
<PartialDiagnosticAt
, 8> Notes
;
18350 Expr::EvalResult Eval
;
18351 Eval
.Diag
= &Notes
;
18352 bool Res
= E
.get()->EvaluateAsConstantExpr(
18353 Eval
, getASTContext(), ConstantExprKind::ImmediateInvocation
);
18354 if (Res
&& Notes
.empty()) {
18355 Cached
= std::move(Eval
.Val
);
18361 if (!E
.get()->isValueDependent() &&
18362 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
&&
18363 !CheckConstantExpressionAndKeepResult()) {
18364 MarkExpressionAsImmediateEscalating(E
.get());
18368 if (Cleanup
.exprNeedsCleanups()) {
18369 // Since an immediate invocation is a full expression itself - it requires
18370 // an additional ExprWithCleanups node, but it can participate to a bigger
18371 // full expression which actually requires cleanups to be run after so
18372 // create ExprWithCleanups without using MaybeCreateExprWithCleanups as it
18373 // may discard cleanups for outer expression too early.
18375 // Note that ExprWithCleanups created here must always have empty cleanup
18377 // - compound literals do not create cleanup objects in C++ and immediate
18378 // invocations are C++-only.
18379 // - blocks are not allowed inside constant expressions and compiler will
18380 // issue an error if they appear there.
18382 // Hence, in correct code any cleanup objects created inside current
18383 // evaluation context must be outside the immediate invocation.
18384 E
= ExprWithCleanups::Create(getASTContext(), E
.get(),
18385 Cleanup
.cleanupsHaveSideEffects(), {});
18388 ConstantExpr
*Res
= ConstantExpr::Create(
18389 getASTContext(), E
.get(),
18390 ConstantExpr::getStorageKind(Decl
->getReturnType().getTypePtr(),
18392 /*IsImmediateInvocation*/ true);
18393 if (Cached
.hasValue())
18394 Res
->MoveIntoResult(Cached
, getASTContext());
18395 /// Value-dependent constant expressions should not be immediately
18396 /// evaluated until they are instantiated.
18397 if (!Res
->isValueDependent())
18398 ExprEvalContexts
.back().ImmediateInvocationCandidates
.emplace_back(Res
, 0);
18402 static void EvaluateAndDiagnoseImmediateInvocation(
18403 Sema
&SemaRef
, Sema::ImmediateInvocationCandidate Candidate
) {
18404 llvm::SmallVector
<PartialDiagnosticAt
, 8> Notes
;
18405 Expr::EvalResult Eval
;
18406 Eval
.Diag
= &Notes
;
18407 ConstantExpr
*CE
= Candidate
.getPointer();
18408 bool Result
= CE
->EvaluateAsConstantExpr(
18409 Eval
, SemaRef
.getASTContext(), ConstantExprKind::ImmediateInvocation
);
18410 if (!Result
|| !Notes
.empty()) {
18411 SemaRef
.FailedImmediateInvocations
.insert(CE
);
18412 Expr
*InnerExpr
= CE
->getSubExpr()->IgnoreImplicit();
18413 if (auto *FunctionalCast
= dyn_cast
<CXXFunctionalCastExpr
>(InnerExpr
))
18414 InnerExpr
= FunctionalCast
->getSubExpr()->IgnoreImplicit();
18415 FunctionDecl
*FD
= nullptr;
18416 if (auto *Call
= dyn_cast
<CallExpr
>(InnerExpr
))
18417 FD
= cast
<FunctionDecl
>(Call
->getCalleeDecl());
18418 else if (auto *Call
= dyn_cast
<CXXConstructExpr
>(InnerExpr
))
18419 FD
= Call
->getConstructor();
18420 else if (auto *Cast
= dyn_cast
<CastExpr
>(InnerExpr
))
18421 FD
= dyn_cast_or_null
<FunctionDecl
>(Cast
->getConversionFunction());
18423 assert(FD
&& FD
->isImmediateFunction() &&
18424 "could not find an immediate function in this expression");
18425 if (FD
->isInvalidDecl())
18427 SemaRef
.Diag(CE
->getBeginLoc(), diag::err_invalid_consteval_call
)
18428 << FD
<< FD
->isConsteval();
18430 SemaRef
.InnermostDeclarationWithDelayedImmediateInvocations()) {
18431 SemaRef
.Diag(Context
->Loc
, diag::note_invalid_consteval_initializer
)
18433 SemaRef
.Diag(Context
->Decl
->getBeginLoc(), diag::note_declared_at
);
18435 if (!FD
->isConsteval())
18436 SemaRef
.DiagnoseImmediateEscalatingReason(FD
);
18437 for (auto &Note
: Notes
)
18438 SemaRef
.Diag(Note
.first
, Note
.second
);
18441 CE
->MoveIntoResult(Eval
.Val
, SemaRef
.getASTContext());
18444 static void RemoveNestedImmediateInvocation(
18445 Sema
&SemaRef
, Sema::ExpressionEvaluationContextRecord
&Rec
,
18446 SmallVector
<Sema::ImmediateInvocationCandidate
, 4>::reverse_iterator It
) {
18447 struct ComplexRemove
: TreeTransform
<ComplexRemove
> {
18448 using Base
= TreeTransform
<ComplexRemove
>;
18449 llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DRSet
;
18450 SmallVector
<Sema::ImmediateInvocationCandidate
, 4> &IISet
;
18451 SmallVector
<Sema::ImmediateInvocationCandidate
, 4>::reverse_iterator
18453 ComplexRemove(Sema
&SemaRef
, llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DR
,
18454 SmallVector
<Sema::ImmediateInvocationCandidate
, 4> &II
,
18455 SmallVector
<Sema::ImmediateInvocationCandidate
,
18456 4>::reverse_iterator Current
)
18457 : Base(SemaRef
), DRSet(DR
), IISet(II
), CurrentII(Current
) {}
18458 void RemoveImmediateInvocation(ConstantExpr
* E
) {
18459 auto It
= std::find_if(CurrentII
, IISet
.rend(),
18460 [E
](Sema::ImmediateInvocationCandidate Elem
) {
18461 return Elem
.getPointer() == E
;
18463 // It is possible that some subexpression of the current immediate
18464 // invocation was handled from another expression evaluation context. Do
18465 // not handle the current immediate invocation if some of its
18466 // subexpressions failed before.
18467 if (It
== IISet
.rend()) {
18468 if (SemaRef
.FailedImmediateInvocations
.contains(E
))
18469 CurrentII
->setInt(1);
18471 It
->setInt(1); // Mark as deleted
18474 ExprResult
TransformConstantExpr(ConstantExpr
*E
) {
18475 if (!E
->isImmediateInvocation())
18476 return Base::TransformConstantExpr(E
);
18477 RemoveImmediateInvocation(E
);
18478 return Base::TransformExpr(E
->getSubExpr());
18480 /// Base::TransfromCXXOperatorCallExpr doesn't traverse the callee so
18481 /// we need to remove its DeclRefExpr from the DRSet.
18482 ExprResult
TransformCXXOperatorCallExpr(CXXOperatorCallExpr
*E
) {
18483 DRSet
.erase(cast
<DeclRefExpr
>(E
->getCallee()->IgnoreImplicit()));
18484 return Base::TransformCXXOperatorCallExpr(E
);
18486 /// Base::TransformUserDefinedLiteral doesn't preserve the
18487 /// UserDefinedLiteral node.
18488 ExprResult
TransformUserDefinedLiteral(UserDefinedLiteral
*E
) { return E
; }
18489 /// Base::TransformInitializer skips ConstantExpr so we need to visit them
18491 ExprResult
TransformInitializer(Expr
*Init
, bool NotCopyInit
) {
18494 /// ConstantExpr are the first layer of implicit node to be removed so if
18495 /// Init isn't a ConstantExpr, no ConstantExpr will be skipped.
18496 if (auto *CE
= dyn_cast
<ConstantExpr
>(Init
))
18497 if (CE
->isImmediateInvocation())
18498 RemoveImmediateInvocation(CE
);
18499 return Base::TransformInitializer(Init
, NotCopyInit
);
18501 ExprResult
TransformDeclRefExpr(DeclRefExpr
*E
) {
18505 ExprResult
TransformLambdaExpr(LambdaExpr
*E
) {
18506 // Do not rebuild lambdas to avoid creating a new type.
18507 // Lambdas have already been processed inside their eval context.
18510 bool AlwaysRebuild() { return false; }
18511 bool ReplacingOriginal() { return true; }
18512 bool AllowSkippingCXXConstructExpr() {
18513 bool Res
= AllowSkippingFirstCXXConstructExpr
;
18514 AllowSkippingFirstCXXConstructExpr
= true;
18517 bool AllowSkippingFirstCXXConstructExpr
= true;
18518 } Transformer(SemaRef
, Rec
.ReferenceToConsteval
,
18519 Rec
.ImmediateInvocationCandidates
, It
);
18521 /// CXXConstructExpr with a single argument are getting skipped by
18522 /// TreeTransform in some situtation because they could be implicit. This
18523 /// can only occur for the top-level CXXConstructExpr because it is used
18524 /// nowhere in the expression being transformed therefore will not be rebuilt.
18525 /// Setting AllowSkippingFirstCXXConstructExpr to false will prevent from
18526 /// skipping the first CXXConstructExpr.
18527 if (isa
<CXXConstructExpr
>(It
->getPointer()->IgnoreImplicit()))
18528 Transformer
.AllowSkippingFirstCXXConstructExpr
= false;
18530 ExprResult Res
= Transformer
.TransformExpr(It
->getPointer()->getSubExpr());
18531 // The result may not be usable in case of previous compilation errors.
18532 // In this case evaluation of the expression may result in crash so just
18533 // don't do anything further with the result.
18534 if (Res
.isUsable()) {
18535 Res
= SemaRef
.MaybeCreateExprWithCleanups(Res
);
18536 It
->getPointer()->setSubExpr(Res
.get());
18541 HandleImmediateInvocations(Sema
&SemaRef
,
18542 Sema::ExpressionEvaluationContextRecord
&Rec
) {
18543 if ((Rec
.ImmediateInvocationCandidates
.size() == 0 &&
18544 Rec
.ReferenceToConsteval
.size() == 0) ||
18545 SemaRef
.RebuildingImmediateInvocation
)
18548 /// When we have more than 1 ImmediateInvocationCandidates or previously
18549 /// failed immediate invocations, we need to check for nested
18550 /// ImmediateInvocationCandidates in order to avoid duplicate diagnostics.
18551 /// Otherwise we only need to remove ReferenceToConsteval in the immediate
18553 if (Rec
.ImmediateInvocationCandidates
.size() > 1 ||
18554 !SemaRef
.FailedImmediateInvocations
.empty()) {
18556 /// Prevent sema calls during the tree transform from adding pointers that
18557 /// are already in the sets.
18558 llvm::SaveAndRestore
DisableIITracking(
18559 SemaRef
.RebuildingImmediateInvocation
, true);
18561 /// Prevent diagnostic during tree transfrom as they are duplicates
18562 Sema::TentativeAnalysisScope
DisableDiag(SemaRef
);
18564 for (auto It
= Rec
.ImmediateInvocationCandidates
.rbegin();
18565 It
!= Rec
.ImmediateInvocationCandidates
.rend(); It
++)
18567 RemoveNestedImmediateInvocation(SemaRef
, Rec
, It
);
18568 } else if (Rec
.ImmediateInvocationCandidates
.size() == 1 &&
18569 Rec
.ReferenceToConsteval
.size()) {
18570 struct SimpleRemove
: RecursiveASTVisitor
<SimpleRemove
> {
18571 llvm::SmallPtrSetImpl
<DeclRefExpr
*> &DRSet
;
18572 SimpleRemove(llvm::SmallPtrSetImpl
<DeclRefExpr
*> &S
) : DRSet(S
) {}
18573 bool VisitDeclRefExpr(DeclRefExpr
*E
) {
18575 return DRSet
.size();
18577 } Visitor(Rec
.ReferenceToConsteval
);
18578 Visitor
.TraverseStmt(
18579 Rec
.ImmediateInvocationCandidates
.front().getPointer()->getSubExpr());
18581 for (auto CE
: Rec
.ImmediateInvocationCandidates
)
18583 EvaluateAndDiagnoseImmediateInvocation(SemaRef
, CE
);
18584 for (auto *DR
: Rec
.ReferenceToConsteval
) {
18585 // If the expression is immediate escalating, it is not an error;
18586 // The outer context itself becomes immediate and further errors,
18587 // if any, will be handled by DiagnoseImmediateEscalatingReason.
18588 if (DR
->isImmediateEscalating())
18590 auto *FD
= cast
<FunctionDecl
>(DR
->getDecl());
18591 const NamedDecl
*ND
= FD
;
18592 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(ND
);
18593 MD
&& (MD
->isLambdaStaticInvoker() || isLambdaCallOperator(MD
)))
18594 ND
= MD
->getParent();
18596 // C++23 [expr.const]/p16
18597 // An expression or conversion is immediate-escalating if it is not
18598 // initially in an immediate function context and it is [...] a
18599 // potentially-evaluated id-expression that denotes an immediate function
18600 // that is not a subexpression of an immediate invocation.
18601 bool ImmediateEscalating
= false;
18602 bool IsPotentiallyEvaluated
=
18604 Sema::ExpressionEvaluationContext::PotentiallyEvaluated
||
18606 Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
;
18607 if (SemaRef
.inTemplateInstantiation() && IsPotentiallyEvaluated
)
18608 ImmediateEscalating
= Rec
.InImmediateEscalatingFunctionContext
;
18610 if (!Rec
.InImmediateEscalatingFunctionContext
||
18611 (SemaRef
.inTemplateInstantiation() && !ImmediateEscalating
)) {
18612 SemaRef
.Diag(DR
->getBeginLoc(), diag::err_invalid_consteval_take_address
)
18613 << ND
<< isa
<CXXRecordDecl
>(ND
) << FD
->isConsteval();
18614 SemaRef
.Diag(ND
->getLocation(), diag::note_declared_at
);
18616 SemaRef
.InnermostDeclarationWithDelayedImmediateInvocations()) {
18617 SemaRef
.Diag(Context
->Loc
, diag::note_invalid_consteval_initializer
)
18619 SemaRef
.Diag(Context
->Decl
->getBeginLoc(), diag::note_declared_at
);
18621 if (FD
->isImmediateEscalating() && !FD
->isConsteval())
18622 SemaRef
.DiagnoseImmediateEscalatingReason(FD
);
18625 SemaRef
.MarkExpressionAsImmediateEscalating(DR
);
18630 void Sema::PopExpressionEvaluationContext() {
18631 ExpressionEvaluationContextRecord
& Rec
= ExprEvalContexts
.back();
18632 unsigned NumTypos
= Rec
.NumTypos
;
18634 if (!Rec
.Lambdas
.empty()) {
18635 using ExpressionKind
= ExpressionEvaluationContextRecord::ExpressionKind
;
18636 if (!getLangOpts().CPlusPlus20
&&
18637 (Rec
.ExprContext
== ExpressionKind::EK_TemplateArgument
||
18638 Rec
.isUnevaluated() ||
18639 (Rec
.isConstantEvaluated() && !getLangOpts().CPlusPlus17
))) {
18641 if (Rec
.isUnevaluated()) {
18642 // C++11 [expr.prim.lambda]p2:
18643 // A lambda-expression shall not appear in an unevaluated operand
18645 D
= diag::err_lambda_unevaluated_operand
;
18646 } else if (Rec
.isConstantEvaluated() && !getLangOpts().CPlusPlus17
) {
18647 // C++1y [expr.const]p2:
18648 // A conditional-expression e is a core constant expression unless the
18649 // evaluation of e, following the rules of the abstract machine, would
18650 // evaluate [...] a lambda-expression.
18651 D
= diag::err_lambda_in_constant_expression
;
18652 } else if (Rec
.ExprContext
== ExpressionKind::EK_TemplateArgument
) {
18653 // C++17 [expr.prim.lamda]p2:
18654 // A lambda-expression shall not appear [...] in a template-argument.
18655 D
= diag::err_lambda_in_invalid_context
;
18657 llvm_unreachable("Couldn't infer lambda error message.");
18659 for (const auto *L
: Rec
.Lambdas
)
18660 Diag(L
->getBeginLoc(), D
);
18664 WarnOnPendingNoDerefs(Rec
);
18665 HandleImmediateInvocations(*this, Rec
);
18667 // Warn on any volatile-qualified simple-assignments that are not discarded-
18668 // value expressions nor unevaluated operands (those cases get removed from
18669 // this list by CheckUnusedVolatileAssignment).
18670 for (auto *BO
: Rec
.VolatileAssignmentLHSs
)
18671 Diag(BO
->getBeginLoc(), diag::warn_deprecated_simple_assign_volatile
)
18674 // When are coming out of an unevaluated context, clear out any
18675 // temporaries that we may have created as part of the evaluation of
18676 // the expression in that context: they aren't relevant because they
18677 // will never be constructed.
18678 if (Rec
.isUnevaluated() || Rec
.isConstantEvaluated()) {
18679 ExprCleanupObjects
.erase(ExprCleanupObjects
.begin() + Rec
.NumCleanupObjects
,
18680 ExprCleanupObjects
.end());
18681 Cleanup
= Rec
.ParentCleanup
;
18682 CleanupVarDeclMarking();
18683 std::swap(MaybeODRUseExprs
, Rec
.SavedMaybeODRUseExprs
);
18684 // Otherwise, merge the contexts together.
18686 Cleanup
.mergeFrom(Rec
.ParentCleanup
);
18687 MaybeODRUseExprs
.insert(Rec
.SavedMaybeODRUseExprs
.begin(),
18688 Rec
.SavedMaybeODRUseExprs
.end());
18691 // Pop the current expression evaluation context off the stack.
18692 ExprEvalContexts
.pop_back();
18694 // The global expression evaluation context record is never popped.
18695 ExprEvalContexts
.back().NumTypos
+= NumTypos
;
18698 void Sema::DiscardCleanupsInEvaluationContext() {
18699 ExprCleanupObjects
.erase(
18700 ExprCleanupObjects
.begin() + ExprEvalContexts
.back().NumCleanupObjects
,
18701 ExprCleanupObjects
.end());
18703 MaybeODRUseExprs
.clear();
18706 ExprResult
Sema::HandleExprEvaluationContextForTypeof(Expr
*E
) {
18707 ExprResult Result
= CheckPlaceholderExpr(E
);
18708 if (Result
.isInvalid())
18709 return ExprError();
18711 if (!E
->getType()->isVariablyModifiedType())
18713 return TransformToPotentiallyEvaluated(E
);
18716 /// Are we in a context that is potentially constant evaluated per C++20
18717 /// [expr.const]p12?
18718 static bool isPotentiallyConstantEvaluatedContext(Sema
&SemaRef
) {
18719 /// C++2a [expr.const]p12:
18720 // An expression or conversion is potentially constant evaluated if it is
18721 switch (SemaRef
.ExprEvalContexts
.back().Context
) {
18722 case Sema::ExpressionEvaluationContext::ConstantEvaluated
:
18723 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext
:
18725 // -- a manifestly constant-evaluated expression,
18726 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated
:
18727 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
18728 case Sema::ExpressionEvaluationContext::DiscardedStatement
:
18729 // -- a potentially-evaluated expression,
18730 case Sema::ExpressionEvaluationContext::UnevaluatedList
:
18731 // -- an immediate subexpression of a braced-init-list,
18733 // -- [FIXME] an expression of the form & cast-expression that occurs
18734 // within a templated entity
18735 // -- a subexpression of one of the above that is not a subexpression of
18736 // a nested unevaluated operand.
18739 case Sema::ExpressionEvaluationContext::Unevaluated
:
18740 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract
:
18741 // Expressions in this context are never evaluated.
18744 llvm_unreachable("Invalid context");
18747 /// Return true if this function has a calling convention that requires mangling
18748 /// in the size of the parameter pack.
18749 static bool funcHasParameterSizeMangling(Sema
&S
, FunctionDecl
*FD
) {
18750 // These manglings don't do anything on non-Windows or non-x86 platforms, so
18751 // we don't need parameter type sizes.
18752 const llvm::Triple
&TT
= S
.Context
.getTargetInfo().getTriple();
18753 if (!TT
.isOSWindows() || !TT
.isX86())
18756 // If this is C++ and this isn't an extern "C" function, parameters do not
18757 // need to be complete. In this case, C++ mangling will apply, which doesn't
18758 // use the size of the parameters.
18759 if (S
.getLangOpts().CPlusPlus
&& !FD
->isExternC())
18762 // Stdcall, fastcall, and vectorcall need this special treatment.
18763 CallingConv CC
= FD
->getType()->castAs
<FunctionType
>()->getCallConv();
18765 case CC_X86StdCall
:
18766 case CC_X86FastCall
:
18767 case CC_X86VectorCall
:
18775 /// Require that all of the parameter types of function be complete. Normally,
18776 /// parameter types are only required to be complete when a function is called
18777 /// or defined, but to mangle functions with certain calling conventions, the
18778 /// mangler needs to know the size of the parameter list. In this situation,
18779 /// MSVC doesn't emit an error or instantiate templates. Instead, MSVC mangles
18780 /// the function as _foo@0, i.e. zero bytes of parameters, which will usually
18781 /// result in a linker error. Clang doesn't implement this behavior, and instead
18782 /// attempts to error at compile time.
18783 static void CheckCompleteParameterTypesForMangler(Sema
&S
, FunctionDecl
*FD
,
18784 SourceLocation Loc
) {
18785 class ParamIncompleteTypeDiagnoser
: public Sema::TypeDiagnoser
{
18787 ParmVarDecl
*Param
;
18790 ParamIncompleteTypeDiagnoser(FunctionDecl
*FD
, ParmVarDecl
*Param
)
18791 : FD(FD
), Param(Param
) {}
18793 void diagnose(Sema
&S
, SourceLocation Loc
, QualType T
) override
{
18794 CallingConv CC
= FD
->getType()->castAs
<FunctionType
>()->getCallConv();
18797 case CC_X86StdCall
:
18798 CCName
= "stdcall";
18800 case CC_X86FastCall
:
18801 CCName
= "fastcall";
18803 case CC_X86VectorCall
:
18804 CCName
= "vectorcall";
18807 llvm_unreachable("CC does not need mangling");
18810 S
.Diag(Loc
, diag::err_cconv_incomplete_param_type
)
18811 << Param
->getDeclName() << FD
->getDeclName() << CCName
;
18815 for (ParmVarDecl
*Param
: FD
->parameters()) {
18816 ParamIncompleteTypeDiagnoser
Diagnoser(FD
, Param
);
18817 S
.RequireCompleteType(Loc
, Param
->getType(), Diagnoser
);
18822 enum class OdrUseContext
{
18823 /// Declarations in this context are not odr-used.
18825 /// Declarations in this context are formally odr-used, but this is a
18826 /// dependent context.
18828 /// Declarations in this context are odr-used but not actually used (yet).
18830 /// Declarations in this context are used.
18835 /// Are we within a context in which references to resolved functions or to
18836 /// variables result in odr-use?
18837 static OdrUseContext
isOdrUseContext(Sema
&SemaRef
) {
18838 OdrUseContext Result
;
18840 switch (SemaRef
.ExprEvalContexts
.back().Context
) {
18841 case Sema::ExpressionEvaluationContext::Unevaluated
:
18842 case Sema::ExpressionEvaluationContext::UnevaluatedList
:
18843 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract
:
18844 return OdrUseContext::None
;
18846 case Sema::ExpressionEvaluationContext::ConstantEvaluated
:
18847 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext
:
18848 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated
:
18849 Result
= OdrUseContext::Used
;
18852 case Sema::ExpressionEvaluationContext::DiscardedStatement
:
18853 Result
= OdrUseContext::FormallyOdrUsed
;
18856 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
18857 // A default argument formally results in odr-use, but doesn't actually
18858 // result in a use in any real sense until it itself is used.
18859 Result
= OdrUseContext::FormallyOdrUsed
;
18863 if (SemaRef
.CurContext
->isDependentContext())
18864 return OdrUseContext::Dependent
;
18869 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl
*Func
) {
18870 if (!Func
->isConstexpr())
18873 if (Func
->isImplicitlyInstantiable() || !Func
->isUserProvided())
18875 auto *CCD
= dyn_cast
<CXXConstructorDecl
>(Func
);
18876 return CCD
&& CCD
->getInheritedConstructor();
18879 /// Mark a function referenced, and check whether it is odr-used
18880 /// (C++ [basic.def.odr]p2, C99 6.9p3)
18881 void Sema::MarkFunctionReferenced(SourceLocation Loc
, FunctionDecl
*Func
,
18882 bool MightBeOdrUse
) {
18883 assert(Func
&& "No function?");
18885 Func
->setReferenced();
18887 // Recursive functions aren't really used until they're used from some other
18889 bool IsRecursiveCall
= CurContext
== Func
;
18891 // C++11 [basic.def.odr]p3:
18892 // A function whose name appears as a potentially-evaluated expression is
18893 // odr-used if it is the unique lookup result or the selected member of a
18894 // set of overloaded functions [...].
18896 // We (incorrectly) mark overload resolution as an unevaluated context, so we
18897 // can just check that here.
18898 OdrUseContext OdrUse
=
18899 MightBeOdrUse
? isOdrUseContext(*this) : OdrUseContext::None
;
18900 if (IsRecursiveCall
&& OdrUse
== OdrUseContext::Used
)
18901 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18903 // Trivial default constructors and destructors are never actually used.
18904 // FIXME: What about other special members?
18905 if (Func
->isTrivial() && !Func
->hasAttr
<DLLExportAttr
>() &&
18906 OdrUse
== OdrUseContext::Used
) {
18907 if (auto *Constructor
= dyn_cast
<CXXConstructorDecl
>(Func
))
18908 if (Constructor
->isDefaultConstructor())
18909 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18910 if (isa
<CXXDestructorDecl
>(Func
))
18911 OdrUse
= OdrUseContext::FormallyOdrUsed
;
18914 // C++20 [expr.const]p12:
18915 // A function [...] is needed for constant evaluation if it is [...] a
18916 // constexpr function that is named by an expression that is potentially
18917 // constant evaluated
18918 bool NeededForConstantEvaluation
=
18919 isPotentiallyConstantEvaluatedContext(*this) &&
18920 isImplicitlyDefinableConstexprFunction(Func
);
18922 // Determine whether we require a function definition to exist, per
18923 // C++11 [temp.inst]p3:
18924 // Unless a function template specialization has been explicitly
18925 // instantiated or explicitly specialized, the function template
18926 // specialization is implicitly instantiated when the specialization is
18927 // referenced in a context that requires a function definition to exist.
18928 // C++20 [temp.inst]p7:
18929 // The existence of a definition of a [...] function is considered to
18930 // affect the semantics of the program if the [...] function is needed for
18931 // constant evaluation by an expression
18932 // C++20 [basic.def.odr]p10:
18933 // Every program shall contain exactly one definition of every non-inline
18934 // function or variable that is odr-used in that program outside of a
18935 // discarded statement
18936 // C++20 [special]p1:
18937 // The implementation will implicitly define [defaulted special members]
18938 // if they are odr-used or needed for constant evaluation.
18940 // Note that we skip the implicit instantiation of templates that are only
18941 // used in unused default arguments or by recursive calls to themselves.
18942 // This is formally non-conforming, but seems reasonable in practice.
18943 bool NeedDefinition
= !IsRecursiveCall
&& (OdrUse
== OdrUseContext::Used
||
18944 NeededForConstantEvaluation
);
18946 // C++14 [temp.expl.spec]p6:
18947 // If a template [...] is explicitly specialized then that specialization
18948 // shall be declared before the first use of that specialization that would
18949 // cause an implicit instantiation to take place, in every translation unit
18950 // in which such a use occurs
18951 if (NeedDefinition
&&
18952 (Func
->getTemplateSpecializationKind() != TSK_Undeclared
||
18953 Func
->getMemberSpecializationInfo()))
18954 checkSpecializationReachability(Loc
, Func
);
18956 if (getLangOpts().CUDA
)
18957 CheckCUDACall(Loc
, Func
);
18959 // If we need a definition, try to create one.
18960 if (NeedDefinition
&& !Func
->getBody()) {
18961 runWithSufficientStackSpace(Loc
, [&] {
18962 if (CXXConstructorDecl
*Constructor
=
18963 dyn_cast
<CXXConstructorDecl
>(Func
)) {
18964 Constructor
= cast
<CXXConstructorDecl
>(Constructor
->getFirstDecl());
18965 if (Constructor
->isDefaulted() && !Constructor
->isDeleted()) {
18966 if (Constructor
->isDefaultConstructor()) {
18967 if (Constructor
->isTrivial() &&
18968 !Constructor
->hasAttr
<DLLExportAttr
>())
18970 DefineImplicitDefaultConstructor(Loc
, Constructor
);
18971 } else if (Constructor
->isCopyConstructor()) {
18972 DefineImplicitCopyConstructor(Loc
, Constructor
);
18973 } else if (Constructor
->isMoveConstructor()) {
18974 DefineImplicitMoveConstructor(Loc
, Constructor
);
18976 } else if (Constructor
->getInheritedConstructor()) {
18977 DefineInheritingConstructor(Loc
, Constructor
);
18979 } else if (CXXDestructorDecl
*Destructor
=
18980 dyn_cast
<CXXDestructorDecl
>(Func
)) {
18981 Destructor
= cast
<CXXDestructorDecl
>(Destructor
->getFirstDecl());
18982 if (Destructor
->isDefaulted() && !Destructor
->isDeleted()) {
18983 if (Destructor
->isTrivial() && !Destructor
->hasAttr
<DLLExportAttr
>())
18985 DefineImplicitDestructor(Loc
, Destructor
);
18987 if (Destructor
->isVirtual() && getLangOpts().AppleKext
)
18988 MarkVTableUsed(Loc
, Destructor
->getParent());
18989 } else if (CXXMethodDecl
*MethodDecl
= dyn_cast
<CXXMethodDecl
>(Func
)) {
18990 if (MethodDecl
->isOverloadedOperator() &&
18991 MethodDecl
->getOverloadedOperator() == OO_Equal
) {
18992 MethodDecl
= cast
<CXXMethodDecl
>(MethodDecl
->getFirstDecl());
18993 if (MethodDecl
->isDefaulted() && !MethodDecl
->isDeleted()) {
18994 if (MethodDecl
->isCopyAssignmentOperator())
18995 DefineImplicitCopyAssignment(Loc
, MethodDecl
);
18996 else if (MethodDecl
->isMoveAssignmentOperator())
18997 DefineImplicitMoveAssignment(Loc
, MethodDecl
);
18999 } else if (isa
<CXXConversionDecl
>(MethodDecl
) &&
19000 MethodDecl
->getParent()->isLambda()) {
19001 CXXConversionDecl
*Conversion
=
19002 cast
<CXXConversionDecl
>(MethodDecl
->getFirstDecl());
19003 if (Conversion
->isLambdaToBlockPointerConversion())
19004 DefineImplicitLambdaToBlockPointerConversion(Loc
, Conversion
);
19006 DefineImplicitLambdaToFunctionPointerConversion(Loc
, Conversion
);
19007 } else if (MethodDecl
->isVirtual() && getLangOpts().AppleKext
)
19008 MarkVTableUsed(Loc
, MethodDecl
->getParent());
19011 if (Func
->isDefaulted() && !Func
->isDeleted()) {
19012 DefaultedComparisonKind DCK
= getDefaultedComparisonKind(Func
);
19013 if (DCK
!= DefaultedComparisonKind::None
)
19014 DefineDefaultedComparison(Loc
, Func
, DCK
);
19017 // Implicit instantiation of function templates and member functions of
19018 // class templates.
19019 if (Func
->isImplicitlyInstantiable()) {
19020 TemplateSpecializationKind TSK
=
19021 Func
->getTemplateSpecializationKindForInstantiation();
19022 SourceLocation PointOfInstantiation
= Func
->getPointOfInstantiation();
19023 bool FirstInstantiation
= PointOfInstantiation
.isInvalid();
19024 if (FirstInstantiation
) {
19025 PointOfInstantiation
= Loc
;
19026 if (auto *MSI
= Func
->getMemberSpecializationInfo())
19027 MSI
->setPointOfInstantiation(Loc
);
19028 // FIXME: Notify listener.
19030 Func
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
19031 } else if (TSK
!= TSK_ImplicitInstantiation
) {
19032 // Use the point of use as the point of instantiation, instead of the
19033 // point of explicit instantiation (which we track as the actual point
19034 // of instantiation). This gives better backtraces in diagnostics.
19035 PointOfInstantiation
= Loc
;
19038 if (FirstInstantiation
|| TSK
!= TSK_ImplicitInstantiation
||
19039 Func
->isConstexpr()) {
19040 if (isa
<CXXRecordDecl
>(Func
->getDeclContext()) &&
19041 cast
<CXXRecordDecl
>(Func
->getDeclContext())->isLocalClass() &&
19042 CodeSynthesisContexts
.size())
19043 PendingLocalImplicitInstantiations
.push_back(
19044 std::make_pair(Func
, PointOfInstantiation
));
19045 else if (Func
->isConstexpr())
19046 // Do not defer instantiations of constexpr functions, to avoid the
19047 // expression evaluator needing to call back into Sema if it sees a
19048 // call to such a function.
19049 InstantiateFunctionDefinition(PointOfInstantiation
, Func
);
19051 Func
->setInstantiationIsPending(true);
19052 PendingInstantiations
.push_back(
19053 std::make_pair(Func
, PointOfInstantiation
));
19054 // Notify the consumer that a function was implicitly instantiated.
19055 Consumer
.HandleCXXImplicitFunctionInstantiation(Func
);
19059 // Walk redefinitions, as some of them may be instantiable.
19060 for (auto *i
: Func
->redecls()) {
19061 if (!i
->isUsed(false) && i
->isImplicitlyInstantiable())
19062 MarkFunctionReferenced(Loc
, i
, MightBeOdrUse
);
19068 // If a constructor was defined in the context of a default parameter
19069 // or of another default member initializer (ie a PotentiallyEvaluatedIfUsed
19070 // context), its initializers may not be referenced yet.
19071 if (CXXConstructorDecl
*Constructor
= dyn_cast
<CXXConstructorDecl
>(Func
)) {
19072 EnterExpressionEvaluationContext
EvalContext(
19074 Constructor
->isImmediateFunction()
19075 ? ExpressionEvaluationContext::ImmediateFunctionContext
19076 : ExpressionEvaluationContext::PotentiallyEvaluated
,
19078 for (CXXCtorInitializer
*Init
: Constructor
->inits()) {
19079 if (Init
->isInClassMemberInitializer())
19080 runWithSufficientStackSpace(Init
->getSourceLocation(), [&]() {
19081 MarkDeclarationsReferencedInExpr(Init
->getInit());
19086 // C++14 [except.spec]p17:
19087 // An exception-specification is considered to be needed when:
19088 // - the function is odr-used or, if it appears in an unevaluated operand,
19089 // would be odr-used if the expression were potentially-evaluated;
19091 // Note, we do this even if MightBeOdrUse is false. That indicates that the
19092 // function is a pure virtual function we're calling, and in that case the
19093 // function was selected by overload resolution and we need to resolve its
19094 // exception specification for a different reason.
19095 const FunctionProtoType
*FPT
= Func
->getType()->getAs
<FunctionProtoType
>();
19096 if (FPT
&& isUnresolvedExceptionSpec(FPT
->getExceptionSpecType()))
19097 ResolveExceptionSpec(Loc
, FPT
);
19099 // If this is the first "real" use, act on that.
19100 if (OdrUse
== OdrUseContext::Used
&& !Func
->isUsed(/*CheckUsedAttr=*/false)) {
19101 // Keep track of used but undefined functions.
19102 if (!Func
->isDefined()) {
19103 if (mightHaveNonExternalLinkage(Func
))
19104 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
19105 else if (Func
->getMostRecentDecl()->isInlined() &&
19106 !LangOpts
.GNUInline
&&
19107 !Func
->getMostRecentDecl()->hasAttr
<GNUInlineAttr
>())
19108 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
19109 else if (isExternalWithNoLinkageType(Func
))
19110 UndefinedButUsed
.insert(std::make_pair(Func
->getCanonicalDecl(), Loc
));
19113 // Some x86 Windows calling conventions mangle the size of the parameter
19114 // pack into the name. Computing the size of the parameters requires the
19115 // parameter types to be complete. Check that now.
19116 if (funcHasParameterSizeMangling(*this, Func
))
19117 CheckCompleteParameterTypesForMangler(*this, Func
, Loc
);
19119 // In the MS C++ ABI, the compiler emits destructor variants where they are
19120 // used. If the destructor is used here but defined elsewhere, mark the
19121 // virtual base destructors referenced. If those virtual base destructors
19122 // are inline, this will ensure they are defined when emitting the complete
19123 // destructor variant. This checking may be redundant if the destructor is
19124 // provided later in this TU.
19125 if (Context
.getTargetInfo().getCXXABI().isMicrosoft()) {
19126 if (auto *Dtor
= dyn_cast
<CXXDestructorDecl
>(Func
)) {
19127 CXXRecordDecl
*Parent
= Dtor
->getParent();
19128 if (Parent
->getNumVBases() > 0 && !Dtor
->getBody())
19129 CheckCompleteDestructorVariant(Loc
, Dtor
);
19133 Func
->markUsed(Context
);
19137 /// Directly mark a variable odr-used. Given a choice, prefer to use
19138 /// MarkVariableReferenced since it does additional checks and then
19139 /// calls MarkVarDeclODRUsed.
19140 /// If the variable must be captured:
19141 /// - if FunctionScopeIndexToStopAt is null, capture it in the CurContext
19142 /// - else capture it in the DeclContext that maps to the
19143 /// *FunctionScopeIndexToStopAt on the FunctionScopeInfo stack.
19145 MarkVarDeclODRUsed(ValueDecl
*V
, SourceLocation Loc
, Sema
&SemaRef
,
19146 const unsigned *const FunctionScopeIndexToStopAt
= nullptr) {
19147 // Keep track of used but undefined variables.
19148 // FIXME: We shouldn't suppress this warning for static data members.
19149 VarDecl
*Var
= V
->getPotentiallyDecomposedVarDecl();
19150 assert(Var
&& "expected a capturable variable");
19152 if (Var
->hasDefinition(SemaRef
.Context
) == VarDecl::DeclarationOnly
&&
19153 (!Var
->isExternallyVisible() || Var
->isInline() ||
19154 SemaRef
.isExternalWithNoLinkageType(Var
)) &&
19155 !(Var
->isStaticDataMember() && Var
->hasInit())) {
19156 SourceLocation
&old
= SemaRef
.UndefinedButUsed
[Var
->getCanonicalDecl()];
19157 if (old
.isInvalid())
19160 QualType CaptureType
, DeclRefType
;
19161 if (SemaRef
.LangOpts
.OpenMP
)
19162 SemaRef
.tryCaptureOpenMPLambdas(V
);
19163 SemaRef
.tryCaptureVariable(V
, Loc
, Sema::TryCapture_Implicit
,
19164 /*EllipsisLoc*/ SourceLocation(),
19165 /*BuildAndDiagnose*/ true, CaptureType
,
19166 DeclRefType
, FunctionScopeIndexToStopAt
);
19168 if (SemaRef
.LangOpts
.CUDA
&& Var
->hasGlobalStorage()) {
19169 auto *FD
= dyn_cast_or_null
<FunctionDecl
>(SemaRef
.CurContext
);
19170 auto VarTarget
= SemaRef
.IdentifyCUDATarget(Var
);
19171 auto UserTarget
= SemaRef
.IdentifyCUDATarget(FD
);
19172 if (VarTarget
== Sema::CVT_Host
&&
19173 (UserTarget
== Sema::CFT_Device
|| UserTarget
== Sema::CFT_HostDevice
||
19174 UserTarget
== Sema::CFT_Global
)) {
19175 // Diagnose ODR-use of host global variables in device functions.
19176 // Reference of device global variables in host functions is allowed
19177 // through shadow variables therefore it is not diagnosed.
19178 if (SemaRef
.LangOpts
.CUDAIsDevice
&& !SemaRef
.LangOpts
.HIPStdPar
) {
19179 SemaRef
.targetDiag(Loc
, diag::err_ref_bad_target
)
19180 << /*host*/ 2 << /*variable*/ 1 << Var
<< UserTarget
;
19181 SemaRef
.targetDiag(Var
->getLocation(),
19182 Var
->getType().isConstQualified()
19183 ? diag::note_cuda_const_var_unpromoted
19184 : diag::note_cuda_host_var
);
19186 } else if (VarTarget
== Sema::CVT_Device
&&
19187 !Var
->hasAttr
<CUDASharedAttr
>() &&
19188 (UserTarget
== Sema::CFT_Host
||
19189 UserTarget
== Sema::CFT_HostDevice
)) {
19190 // Record a CUDA/HIP device side variable if it is ODR-used
19191 // by host code. This is done conservatively, when the variable is
19192 // referenced in any of the following contexts:
19193 // - a non-function context
19194 // - a host function
19195 // - a host device function
19196 // This makes the ODR-use of the device side variable by host code to
19197 // be visible in the device compilation for the compiler to be able to
19198 // emit template variables instantiated by host code only and to
19199 // externalize the static device side variable ODR-used by host code.
19200 if (!Var
->hasExternalStorage())
19201 SemaRef
.getASTContext().CUDADeviceVarODRUsedByHost
.insert(Var
);
19202 else if (SemaRef
.LangOpts
.GPURelocatableDeviceCode
)
19203 SemaRef
.getASTContext().CUDAExternalDeviceDeclODRUsedByHost
.insert(Var
);
19207 V
->markUsed(SemaRef
.Context
);
19210 void Sema::MarkCaptureUsedInEnclosingContext(ValueDecl
*Capture
,
19211 SourceLocation Loc
,
19212 unsigned CapturingScopeIndex
) {
19213 MarkVarDeclODRUsed(Capture
, Loc
, *this, &CapturingScopeIndex
);
19216 void diagnoseUncapturableValueReferenceOrBinding(Sema
&S
, SourceLocation loc
,
19218 DeclContext
*VarDC
= var
->getDeclContext();
19220 // If the parameter still belongs to the translation unit, then
19221 // we're actually just using one parameter in the declaration of
19223 if (isa
<ParmVarDecl
>(var
) &&
19224 isa
<TranslationUnitDecl
>(VarDC
))
19227 // For C code, don't diagnose about capture if we're not actually in code
19228 // right now; it's impossible to write a non-constant expression outside of
19229 // function context, so we'll get other (more useful) diagnostics later.
19231 // For C++, things get a bit more nasty... it would be nice to suppress this
19232 // diagnostic for certain cases like using a local variable in an array bound
19233 // for a member of a local class, but the correct predicate is not obvious.
19234 if (!S
.getLangOpts().CPlusPlus
&& !S
.CurContext
->isFunctionOrMethod())
19237 unsigned ValueKind
= isa
<BindingDecl
>(var
) ? 1 : 0;
19238 unsigned ContextKind
= 3; // unknown
19239 if (isa
<CXXMethodDecl
>(VarDC
) &&
19240 cast
<CXXRecordDecl
>(VarDC
->getParent())->isLambda()) {
19242 } else if (isa
<FunctionDecl
>(VarDC
)) {
19244 } else if (isa
<BlockDecl
>(VarDC
)) {
19248 S
.Diag(loc
, diag::err_reference_to_local_in_enclosing_context
)
19249 << var
<< ValueKind
<< ContextKind
<< VarDC
;
19250 S
.Diag(var
->getLocation(), diag::note_entity_declared_at
)
19253 // FIXME: Add additional diagnostic info about class etc. which prevents
19257 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo
*CSI
,
19259 bool &SubCapturesAreNested
,
19260 QualType
&CaptureType
,
19261 QualType
&DeclRefType
) {
19262 // Check whether we've already captured it.
19263 if (CSI
->CaptureMap
.count(Var
)) {
19264 // If we found a capture, any subcaptures are nested.
19265 SubCapturesAreNested
= true;
19267 // Retrieve the capture type for this variable.
19268 CaptureType
= CSI
->getCapture(Var
).getCaptureType();
19270 // Compute the type of an expression that refers to this variable.
19271 DeclRefType
= CaptureType
.getNonReferenceType();
19273 // Similarly to mutable captures in lambda, all the OpenMP captures by copy
19274 // are mutable in the sense that user can change their value - they are
19275 // private instances of the captured declarations.
19276 const Capture
&Cap
= CSI
->getCapture(Var
);
19277 if (Cap
.isCopyCapture() &&
19278 !(isa
<LambdaScopeInfo
>(CSI
) &&
19279 !cast
<LambdaScopeInfo
>(CSI
)->lambdaCaptureShouldBeConst()) &&
19280 !(isa
<CapturedRegionScopeInfo
>(CSI
) &&
19281 cast
<CapturedRegionScopeInfo
>(CSI
)->CapRegionKind
== CR_OpenMP
))
19282 DeclRefType
.addConst();
19288 // Only block literals, captured statements, and lambda expressions can
19289 // capture; other scopes don't work.
19290 static DeclContext
*getParentOfCapturingContextOrNull(DeclContext
*DC
,
19292 SourceLocation Loc
,
19293 const bool Diagnose
,
19295 if (isa
<BlockDecl
>(DC
) || isa
<CapturedDecl
>(DC
) || isLambdaCallOperator(DC
))
19296 return getLambdaAwareParentOfDeclContext(DC
);
19298 VarDecl
*Underlying
= Var
->getPotentiallyDecomposedVarDecl();
19300 if (Underlying
->hasLocalStorage() && Diagnose
)
19301 diagnoseUncapturableValueReferenceOrBinding(S
, Loc
, Var
);
19306 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19307 // certain types of variables (unnamed, variably modified types etc.)
19308 // so check for eligibility.
19309 static bool isVariableCapturable(CapturingScopeInfo
*CSI
, ValueDecl
*Var
,
19310 SourceLocation Loc
, const bool Diagnose
,
19313 assert((isa
<VarDecl
, BindingDecl
>(Var
)) &&
19314 "Only variables and structured bindings can be captured");
19316 bool IsBlock
= isa
<BlockScopeInfo
>(CSI
);
19317 bool IsLambda
= isa
<LambdaScopeInfo
>(CSI
);
19319 // Lambdas are not allowed to capture unnamed variables
19320 // (e.g. anonymous unions).
19321 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
19322 // assuming that's the intent.
19323 if (IsLambda
&& !Var
->getDeclName()) {
19325 S
.Diag(Loc
, diag::err_lambda_capture_anonymous_var
);
19326 S
.Diag(Var
->getLocation(), diag::note_declared_at
);
19331 // Prohibit variably-modified types in blocks; they're difficult to deal with.
19332 if (Var
->getType()->isVariablyModifiedType() && IsBlock
) {
19334 S
.Diag(Loc
, diag::err_ref_vm_type
);
19335 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19339 // Prohibit structs with flexible array members too.
19340 // We cannot capture what is in the tail end of the struct.
19341 if (const RecordType
*VTTy
= Var
->getType()->getAs
<RecordType
>()) {
19342 if (VTTy
->getDecl()->hasFlexibleArrayMember()) {
19345 S
.Diag(Loc
, diag::err_ref_flexarray_type
);
19347 S
.Diag(Loc
, diag::err_lambda_capture_flexarray_type
) << Var
;
19348 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19353 const bool HasBlocksAttr
= Var
->hasAttr
<BlocksAttr
>();
19354 // Lambdas and captured statements are not allowed to capture __block
19355 // variables; they don't support the expected semantics.
19356 if (HasBlocksAttr
&& (IsLambda
|| isa
<CapturedRegionScopeInfo
>(CSI
))) {
19358 S
.Diag(Loc
, diag::err_capture_block_variable
) << Var
<< !IsLambda
;
19359 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19363 // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
19364 if (S
.getLangOpts().OpenCL
&& IsBlock
&&
19365 Var
->getType()->isBlockPointerType()) {
19367 S
.Diag(Loc
, diag::err_opencl_block_ref_block
);
19371 if (isa
<BindingDecl
>(Var
)) {
19372 if (!IsLambda
|| !S
.getLangOpts().CPlusPlus
) {
19374 diagnoseUncapturableValueReferenceOrBinding(S
, Loc
, Var
);
19376 } else if (Diagnose
&& S
.getLangOpts().CPlusPlus
) {
19377 S
.Diag(Loc
, S
.LangOpts
.CPlusPlus20
19378 ? diag::warn_cxx17_compat_capture_binding
19379 : diag::ext_capture_binding
)
19381 S
.Diag(Var
->getLocation(), diag::note_entity_declared_at
) << Var
;
19388 // Returns true if the capture by block was successful.
19389 static bool captureInBlock(BlockScopeInfo
*BSI
, ValueDecl
*Var
,
19390 SourceLocation Loc
, const bool BuildAndDiagnose
,
19391 QualType
&CaptureType
, QualType
&DeclRefType
,
19392 const bool Nested
, Sema
&S
, bool Invalid
) {
19393 bool ByRef
= false;
19395 // Blocks are not allowed to capture arrays, excepting OpenCL.
19396 // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
19397 // (decayed to pointers).
19398 if (!Invalid
&& !S
.getLangOpts().OpenCL
&& CaptureType
->isArrayType()) {
19399 if (BuildAndDiagnose
) {
19400 S
.Diag(Loc
, diag::err_ref_array_type
);
19401 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19408 // Forbid the block-capture of autoreleasing variables.
19410 CaptureType
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
) {
19411 if (BuildAndDiagnose
) {
19412 S
.Diag(Loc
, diag::err_arc_autoreleasing_capture
)
19414 S
.Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19421 // Warn about implicitly autoreleasing indirect parameters captured by blocks.
19422 if (const auto *PT
= CaptureType
->getAs
<PointerType
>()) {
19423 QualType PointeeTy
= PT
->getPointeeType();
19425 if (!Invalid
&& PointeeTy
->getAs
<ObjCObjectPointerType
>() &&
19426 PointeeTy
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
&&
19427 !S
.Context
.hasDirectOwnershipQualifier(PointeeTy
)) {
19428 if (BuildAndDiagnose
) {
19429 SourceLocation VarLoc
= Var
->getLocation();
19430 S
.Diag(Loc
, diag::warn_block_capture_autoreleasing
);
19431 S
.Diag(VarLoc
, diag::note_declare_parameter_strong
);
19436 const bool HasBlocksAttr
= Var
->hasAttr
<BlocksAttr
>();
19437 if (HasBlocksAttr
|| CaptureType
->isReferenceType() ||
19438 (S
.getLangOpts().OpenMP
&& S
.isOpenMPCapturedDecl(Var
))) {
19439 // Block capture by reference does not change the capture or
19440 // declaration reference types.
19443 // Block capture by copy introduces 'const'.
19444 CaptureType
= CaptureType
.getNonReferenceType().withConst();
19445 DeclRefType
= CaptureType
;
19448 // Actually capture the variable.
19449 if (BuildAndDiagnose
)
19450 BSI
->addCapture(Var
, HasBlocksAttr
, ByRef
, Nested
, Loc
, SourceLocation(),
19451 CaptureType
, Invalid
);
19456 /// Capture the given variable in the captured region.
19457 static bool captureInCapturedRegion(
19458 CapturedRegionScopeInfo
*RSI
, ValueDecl
*Var
, SourceLocation Loc
,
19459 const bool BuildAndDiagnose
, QualType
&CaptureType
, QualType
&DeclRefType
,
19460 const bool RefersToCapturedVariable
, Sema::TryCaptureKind Kind
,
19461 bool IsTopScope
, Sema
&S
, bool Invalid
) {
19462 // By default, capture variables by reference.
19464 if (IsTopScope
&& Kind
!= Sema::TryCapture_Implicit
) {
19465 ByRef
= (Kind
== Sema::TryCapture_ExplicitByRef
);
19466 } else if (S
.getLangOpts().OpenMP
&& RSI
->CapRegionKind
== CR_OpenMP
) {
19467 // Using an LValue reference type is consistent with Lambdas (see below).
19468 if (S
.isOpenMPCapturedDecl(Var
)) {
19469 bool HasConst
= DeclRefType
.isConstQualified();
19470 DeclRefType
= DeclRefType
.getUnqualifiedType();
19471 // Don't lose diagnostics about assignments to const.
19473 DeclRefType
.addConst();
19475 // Do not capture firstprivates in tasks.
19476 if (S
.isOpenMPPrivateDecl(Var
, RSI
->OpenMPLevel
, RSI
->OpenMPCaptureLevel
) !=
19479 ByRef
= S
.isOpenMPCapturedByRef(Var
, RSI
->OpenMPLevel
,
19480 RSI
->OpenMPCaptureLevel
);
19484 CaptureType
= S
.Context
.getLValueReferenceType(DeclRefType
);
19486 CaptureType
= DeclRefType
;
19488 // Actually capture the variable.
19489 if (BuildAndDiagnose
)
19490 RSI
->addCapture(Var
, /*isBlock*/ false, ByRef
, RefersToCapturedVariable
,
19491 Loc
, SourceLocation(), CaptureType
, Invalid
);
19496 /// Capture the given variable in the lambda.
19497 static bool captureInLambda(LambdaScopeInfo
*LSI
, ValueDecl
*Var
,
19498 SourceLocation Loc
, const bool BuildAndDiagnose
,
19499 QualType
&CaptureType
, QualType
&DeclRefType
,
19500 const bool RefersToCapturedVariable
,
19501 const Sema::TryCaptureKind Kind
,
19502 SourceLocation EllipsisLoc
, const bool IsTopScope
,
19503 Sema
&S
, bool Invalid
) {
19504 // Determine whether we are capturing by reference or by value.
19505 bool ByRef
= false;
19506 if (IsTopScope
&& Kind
!= Sema::TryCapture_Implicit
) {
19507 ByRef
= (Kind
== Sema::TryCapture_ExplicitByRef
);
19509 ByRef
= (LSI
->ImpCaptureStyle
== LambdaScopeInfo::ImpCap_LambdaByref
);
19512 BindingDecl
*BD
= dyn_cast
<BindingDecl
>(Var
);
19513 // FIXME: We should support capturing structured bindings in OpenMP.
19514 if (!Invalid
&& BD
&& S
.LangOpts
.OpenMP
) {
19515 if (BuildAndDiagnose
) {
19516 S
.Diag(Loc
, diag::err_capture_binding_openmp
) << Var
;
19517 S
.Diag(Var
->getLocation(), diag::note_entity_declared_at
) << Var
;
19522 if (BuildAndDiagnose
&& S
.Context
.getTargetInfo().getTriple().isWasm() &&
19523 CaptureType
.getNonReferenceType().isWebAssemblyReferenceType()) {
19524 S
.Diag(Loc
, diag::err_wasm_ca_reference
) << 0;
19528 // Compute the type of the field that will capture this variable.
19530 // C++11 [expr.prim.lambda]p15:
19531 // An entity is captured by reference if it is implicitly or
19532 // explicitly captured but not captured by copy. It is
19533 // unspecified whether additional unnamed non-static data
19534 // members are declared in the closure type for entities
19535 // captured by reference.
19537 // FIXME: It is not clear whether we want to build an lvalue reference
19538 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
19539 // to do the former, while EDG does the latter. Core issue 1249 will
19540 // clarify, but for now we follow GCC because it's a more permissive and
19541 // easily defensible position.
19542 CaptureType
= S
.Context
.getLValueReferenceType(DeclRefType
);
19544 // C++11 [expr.prim.lambda]p14:
19545 // For each entity captured by copy, an unnamed non-static
19546 // data member is declared in the closure type. The
19547 // declaration order of these members is unspecified. The type
19548 // of such a data member is the type of the corresponding
19549 // captured entity if the entity is not a reference to an
19550 // object, or the referenced type otherwise. [Note: If the
19551 // captured entity is a reference to a function, the
19552 // corresponding data member is also a reference to a
19553 // function. - end note ]
19554 if (const ReferenceType
*RefType
= CaptureType
->getAs
<ReferenceType
>()){
19555 if (!RefType
->getPointeeType()->isFunctionType())
19556 CaptureType
= RefType
->getPointeeType();
19559 // Forbid the lambda copy-capture of autoreleasing variables.
19561 CaptureType
.getObjCLifetime() == Qualifiers::OCL_Autoreleasing
) {
19562 if (BuildAndDiagnose
) {
19563 S
.Diag(Loc
, diag::err_arc_autoreleasing_capture
) << /*lambda*/ 1;
19564 S
.Diag(Var
->getLocation(), diag::note_previous_decl
)
19565 << Var
->getDeclName();
19572 // Make sure that by-copy captures are of a complete and non-abstract type.
19573 if (!Invalid
&& BuildAndDiagnose
) {
19574 if (!CaptureType
->isDependentType() &&
19575 S
.RequireCompleteSizedType(
19577 diag::err_capture_of_incomplete_or_sizeless_type
,
19578 Var
->getDeclName()))
19580 else if (S
.RequireNonAbstractType(Loc
, CaptureType
,
19581 diag::err_capture_of_abstract_type
))
19586 // Compute the type of a reference to this captured variable.
19588 DeclRefType
= CaptureType
.getNonReferenceType();
19590 // C++ [expr.prim.lambda]p5:
19591 // The closure type for a lambda-expression has a public inline
19592 // function call operator [...]. This function call operator is
19593 // declared const (9.3.1) if and only if the lambda-expression's
19594 // parameter-declaration-clause is not followed by mutable.
19595 DeclRefType
= CaptureType
.getNonReferenceType();
19596 bool Const
= LSI
->lambdaCaptureShouldBeConst();
19597 if (Const
&& !CaptureType
->isReferenceType())
19598 DeclRefType
.addConst();
19601 // Add the capture.
19602 if (BuildAndDiagnose
)
19603 LSI
->addCapture(Var
, /*isBlock=*/false, ByRef
, RefersToCapturedVariable
,
19604 Loc
, EllipsisLoc
, CaptureType
, Invalid
);
19609 static bool canCaptureVariableByCopy(ValueDecl
*Var
,
19610 const ASTContext
&Context
) {
19611 // Offer a Copy fix even if the type is dependent.
19612 if (Var
->getType()->isDependentType())
19614 QualType T
= Var
->getType().getNonReferenceType();
19615 if (T
.isTriviallyCopyableType(Context
))
19617 if (CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl()) {
19619 if (!(RD
= RD
->getDefinition()))
19621 if (RD
->hasSimpleCopyConstructor())
19623 if (RD
->hasUserDeclaredCopyConstructor())
19624 for (CXXConstructorDecl
*Ctor
: RD
->ctors())
19625 if (Ctor
->isCopyConstructor())
19626 return !Ctor
->isDeleted();
19631 /// Create up to 4 fix-its for explicit reference and value capture of \p Var or
19632 /// default capture. Fixes may be omitted if they aren't allowed by the
19633 /// standard, for example we can't emit a default copy capture fix-it if we
19634 /// already explicitly copy capture capture another variable.
19635 static void buildLambdaCaptureFixit(Sema
&Sema
, LambdaScopeInfo
*LSI
,
19637 assert(LSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
);
19638 // Don't offer Capture by copy of default capture by copy fixes if Var is
19639 // known not to be copy constructible.
19640 bool ShouldOfferCopyFix
= canCaptureVariableByCopy(Var
, Sema
.getASTContext());
19642 SmallString
<32> FixBuffer
;
19643 StringRef Separator
= LSI
->NumExplicitCaptures
> 0 ? ", " : "";
19644 if (Var
->getDeclName().isIdentifier() && !Var
->getName().empty()) {
19645 SourceLocation VarInsertLoc
= LSI
->IntroducerRange
.getEnd();
19646 if (ShouldOfferCopyFix
) {
19647 // Offer fixes to insert an explicit capture for the variable.
19649 // [OtherCapture] -> [OtherCapture, VarName]
19650 FixBuffer
.assign({Separator
, Var
->getName()});
19651 Sema
.Diag(VarInsertLoc
, diag::note_lambda_variable_capture_fixit
)
19652 << Var
<< /*value*/ 0
19653 << FixItHint::CreateInsertion(VarInsertLoc
, FixBuffer
);
19655 // As above but capture by reference.
19656 FixBuffer
.assign({Separator
, "&", Var
->getName()});
19657 Sema
.Diag(VarInsertLoc
, diag::note_lambda_variable_capture_fixit
)
19658 << Var
<< /*reference*/ 1
19659 << FixItHint::CreateInsertion(VarInsertLoc
, FixBuffer
);
19662 // Only try to offer default capture if there are no captures excluding this
19663 // and init captures.
19666 // [&A, &B]: Don't offer.
19667 // [A, B]: Don't offer.
19668 if (llvm::any_of(LSI
->Captures
, [](Capture
&C
) {
19669 return !C
.isThisCapture() && !C
.isInitCapture();
19673 // The default capture specifiers, '=' or '&', must appear first in the
19675 SourceLocation DefaultInsertLoc
=
19676 LSI
->IntroducerRange
.getBegin().getLocWithOffset(1);
19678 if (ShouldOfferCopyFix
) {
19679 bool CanDefaultCopyCapture
= true;
19680 // [=, *this] OK since c++17
19681 // [=, this] OK since c++20
19682 if (LSI
->isCXXThisCaptured() && !Sema
.getLangOpts().CPlusPlus20
)
19683 CanDefaultCopyCapture
= Sema
.getLangOpts().CPlusPlus17
19684 ? LSI
->getCXXThisCapture().isCopyCapture()
19686 // We can't use default capture by copy if any captures already specified
19687 // capture by copy.
19688 if (CanDefaultCopyCapture
&& llvm::none_of(LSI
->Captures
, [](Capture
&C
) {
19689 return !C
.isThisCapture() && !C
.isInitCapture() && C
.isCopyCapture();
19691 FixBuffer
.assign({"=", Separator
});
19692 Sema
.Diag(DefaultInsertLoc
, diag::note_lambda_default_capture_fixit
)
19694 << FixItHint::CreateInsertion(DefaultInsertLoc
, FixBuffer
);
19698 // We can't use default capture by reference if any captures already specified
19699 // capture by reference.
19700 if (llvm::none_of(LSI
->Captures
, [](Capture
&C
) {
19701 return !C
.isInitCapture() && C
.isReferenceCapture() &&
19702 !C
.isThisCapture();
19704 FixBuffer
.assign({"&", Separator
});
19705 Sema
.Diag(DefaultInsertLoc
, diag::note_lambda_default_capture_fixit
)
19707 << FixItHint::CreateInsertion(DefaultInsertLoc
, FixBuffer
);
19711 bool Sema::tryCaptureVariable(
19712 ValueDecl
*Var
, SourceLocation ExprLoc
, TryCaptureKind Kind
,
19713 SourceLocation EllipsisLoc
, bool BuildAndDiagnose
, QualType
&CaptureType
,
19714 QualType
&DeclRefType
, const unsigned *const FunctionScopeIndexToStopAt
) {
19715 // An init-capture is notionally from the context surrounding its
19716 // declaration, but its parent DC is the lambda class.
19717 DeclContext
*VarDC
= Var
->getDeclContext();
19718 DeclContext
*DC
= CurContext
;
19720 // tryCaptureVariable is called every time a DeclRef is formed,
19721 // it can therefore have non-negigible impact on performances.
19722 // For local variables and when there is no capturing scope,
19723 // we can bailout early.
19724 if (CapturingFunctionScopes
== 0 && (!BuildAndDiagnose
|| VarDC
== DC
))
19727 const auto *VD
= dyn_cast
<VarDecl
>(Var
);
19729 if (VD
->isInitCapture())
19730 VarDC
= VarDC
->getParent();
19732 VD
= Var
->getPotentiallyDecomposedVarDecl();
19734 assert(VD
&& "Cannot capture a null variable");
19736 const unsigned MaxFunctionScopesIndex
= FunctionScopeIndexToStopAt
19737 ? *FunctionScopeIndexToStopAt
: FunctionScopes
.size() - 1;
19738 // We need to sync up the Declaration Context with the
19739 // FunctionScopeIndexToStopAt
19740 if (FunctionScopeIndexToStopAt
) {
19741 unsigned FSIndex
= FunctionScopes
.size() - 1;
19742 while (FSIndex
!= MaxFunctionScopesIndex
) {
19743 DC
= getLambdaAwareParentOfDeclContext(DC
);
19748 // Capture global variables if it is required to use private copy of this
19750 bool IsGlobal
= !VD
->hasLocalStorage();
19752 !(LangOpts
.OpenMP
&& isOpenMPCapturedDecl(Var
, /*CheckScopeInfo=*/true,
19753 MaxFunctionScopesIndex
)))
19756 if (isa
<VarDecl
>(Var
))
19757 Var
= cast
<VarDecl
>(Var
->getCanonicalDecl());
19759 // Walk up the stack to determine whether we can capture the variable,
19760 // performing the "simple" checks that don't depend on type. We stop when
19761 // we've either hit the declared scope of the variable or find an existing
19762 // capture of that variable. We start from the innermost capturing-entity
19763 // (the DC) and ensure that all intervening capturing-entities
19764 // (blocks/lambdas etc.) between the innermost capturer and the variable`s
19765 // declcontext can either capture the variable or have already captured
19767 CaptureType
= Var
->getType();
19768 DeclRefType
= CaptureType
.getNonReferenceType();
19769 bool Nested
= false;
19770 bool Explicit
= (Kind
!= TryCapture_Implicit
);
19771 unsigned FunctionScopesIndex
= MaxFunctionScopesIndex
;
19774 LambdaScopeInfo
*LSI
= nullptr;
19775 if (!FunctionScopes
.empty())
19776 LSI
= dyn_cast_or_null
<LambdaScopeInfo
>(
19777 FunctionScopes
[FunctionScopesIndex
]);
19779 bool IsInScopeDeclarationContext
=
19780 !LSI
|| LSI
->AfterParameterList
|| CurContext
== LSI
->CallOperator
;
19782 if (LSI
&& !LSI
->AfterParameterList
) {
19783 // This allows capturing parameters from a default value which does not
19785 if (isa
<ParmVarDecl
>(Var
) && !Var
->getDeclContext()->isFunctionOrMethod())
19788 // If the variable is declared in the current context, there is no need to
19790 if (IsInScopeDeclarationContext
&&
19791 FunctionScopesIndex
== MaxFunctionScopesIndex
&& VarDC
== DC
)
19794 // Only block literals, captured statements, and lambda expressions can
19795 // capture; other scopes don't work.
19796 DeclContext
*ParentDC
=
19797 !IsInScopeDeclarationContext
19799 : getParentOfCapturingContextOrNull(DC
, Var
, ExprLoc
,
19800 BuildAndDiagnose
, *this);
19801 // We need to check for the parent *first* because, if we *have*
19802 // private-captured a global variable, we need to recursively capture it in
19803 // intermediate blocks, lambdas, etc.
19806 FunctionScopesIndex
= MaxFunctionScopesIndex
- 1;
19812 FunctionScopeInfo
*FSI
= FunctionScopes
[FunctionScopesIndex
];
19813 CapturingScopeInfo
*CSI
= cast
<CapturingScopeInfo
>(FSI
);
19815 // Check whether we've already captured it.
19816 if (isVariableAlreadyCapturedInScopeInfo(CSI
, Var
, Nested
, CaptureType
,
19818 CSI
->getCapture(Var
).markUsed(BuildAndDiagnose
);
19822 // When evaluating some attributes (like enable_if) we might refer to a
19823 // function parameter appertaining to the same declaration as that
19825 if (const auto *Parm
= dyn_cast
<ParmVarDecl
>(Var
);
19826 Parm
&& Parm
->getDeclContext() == DC
)
19829 // If we are instantiating a generic lambda call operator body,
19830 // we do not want to capture new variables. What was captured
19831 // during either a lambdas transformation or initial parsing
19833 if (isGenericLambdaCallOperatorSpecialization(DC
)) {
19834 if (BuildAndDiagnose
) {
19835 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(CSI
);
19836 if (LSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
) {
19837 Diag(ExprLoc
, diag::err_lambda_impcap
) << Var
;
19838 Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19839 Diag(LSI
->Lambda
->getBeginLoc(), diag::note_lambda_decl
);
19840 buildLambdaCaptureFixit(*this, LSI
, Var
);
19842 diagnoseUncapturableValueReferenceOrBinding(*this, ExprLoc
, Var
);
19847 // Try to capture variable-length arrays types.
19848 if (Var
->getType()->isVariablyModifiedType()) {
19849 // We're going to walk down into the type and look for VLA
19851 QualType QTy
= Var
->getType();
19852 if (ParmVarDecl
*PVD
= dyn_cast_or_null
<ParmVarDecl
>(Var
))
19853 QTy
= PVD
->getOriginalType();
19854 captureVariablyModifiedType(Context
, QTy
, CSI
);
19857 if (getLangOpts().OpenMP
) {
19858 if (auto *RSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
)) {
19859 // OpenMP private variables should not be captured in outer scope, so
19860 // just break here. Similarly, global variables that are captured in a
19861 // target region should not be captured outside the scope of the region.
19862 if (RSI
->CapRegionKind
== CR_OpenMP
) {
19863 OpenMPClauseKind IsOpenMPPrivateDecl
= isOpenMPPrivateDecl(
19864 Var
, RSI
->OpenMPLevel
, RSI
->OpenMPCaptureLevel
);
19865 // If the variable is private (i.e. not captured) and has variably
19866 // modified type, we still need to capture the type for correct
19867 // codegen in all regions, associated with the construct. Currently,
19868 // it is captured in the innermost captured region only.
19869 if (IsOpenMPPrivateDecl
!= OMPC_unknown
&&
19870 Var
->getType()->isVariablyModifiedType()) {
19871 QualType QTy
= Var
->getType();
19872 if (ParmVarDecl
*PVD
= dyn_cast_or_null
<ParmVarDecl
>(Var
))
19873 QTy
= PVD
->getOriginalType();
19874 for (int I
= 1, E
= getNumberOfConstructScopes(RSI
->OpenMPLevel
);
19876 auto *OuterRSI
= cast
<CapturedRegionScopeInfo
>(
19877 FunctionScopes
[FunctionScopesIndex
- I
]);
19878 assert(RSI
->OpenMPLevel
== OuterRSI
->OpenMPLevel
&&
19879 "Wrong number of captured regions associated with the "
19880 "OpenMP construct.");
19881 captureVariablyModifiedType(Context
, QTy
, OuterRSI
);
19885 IsOpenMPPrivateDecl
!= OMPC_private
&&
19886 isOpenMPTargetCapturedDecl(Var
, RSI
->OpenMPLevel
,
19887 RSI
->OpenMPCaptureLevel
);
19888 // Do not capture global if it is not privatized in outer regions.
19890 IsGlobal
&& isOpenMPGlobalCapturedDecl(Var
, RSI
->OpenMPLevel
,
19891 RSI
->OpenMPCaptureLevel
);
19893 // When we detect target captures we are looking from inside the
19894 // target region, therefore we need to propagate the capture from the
19895 // enclosing region. Therefore, the capture is not initially nested.
19897 adjustOpenMPTargetScopeIndex(FunctionScopesIndex
, RSI
->OpenMPLevel
);
19899 if (IsTargetCap
|| IsOpenMPPrivateDecl
== OMPC_private
||
19900 (IsGlobal
&& !IsGlobalCap
)) {
19901 Nested
= !IsTargetCap
;
19902 bool HasConst
= DeclRefType
.isConstQualified();
19903 DeclRefType
= DeclRefType
.getUnqualifiedType();
19904 // Don't lose diagnostics about assignments to const.
19906 DeclRefType
.addConst();
19907 CaptureType
= Context
.getLValueReferenceType(DeclRefType
);
19913 if (CSI
->ImpCaptureStyle
== CapturingScopeInfo::ImpCap_None
&& !Explicit
) {
19914 // No capture-default, and this is not an explicit capture
19915 // so cannot capture this variable.
19916 if (BuildAndDiagnose
) {
19917 Diag(ExprLoc
, diag::err_lambda_impcap
) << Var
;
19918 Diag(Var
->getLocation(), diag::note_previous_decl
) << Var
;
19919 auto *LSI
= cast
<LambdaScopeInfo
>(CSI
);
19921 Diag(LSI
->Lambda
->getBeginLoc(), diag::note_lambda_decl
);
19922 buildLambdaCaptureFixit(*this, LSI
, Var
);
19924 // FIXME: If we error out because an outer lambda can not implicitly
19925 // capture a variable that an inner lambda explicitly captures, we
19926 // should have the inner lambda do the explicit capture - because
19927 // it makes for cleaner diagnostics later. This would purely be done
19928 // so that the diagnostic does not misleadingly claim that a variable
19929 // can not be captured by a lambda implicitly even though it is captured
19930 // explicitly. Suggestion:
19931 // - create const bool VariableCaptureWasInitiallyExplicit = Explicit
19932 // at the function head
19933 // - cache the StartingDeclContext - this must be a lambda
19934 // - captureInLambda in the innermost lambda the variable.
19939 FunctionScopesIndex
--;
19940 if (IsInScopeDeclarationContext
)
19942 } while (!VarDC
->Equals(DC
));
19944 // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
19945 // computing the type of the capture at each step, checking type-specific
19946 // requirements, and adding captures if requested.
19947 // If the variable had already been captured previously, we start capturing
19948 // at the lambda nested within that one.
19949 bool Invalid
= false;
19950 for (unsigned I
= ++FunctionScopesIndex
, N
= MaxFunctionScopesIndex
+ 1; I
!= N
;
19952 CapturingScopeInfo
*CSI
= cast
<CapturingScopeInfo
>(FunctionScopes
[I
]);
19954 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
19955 // certain types of variables (unnamed, variably modified types etc.)
19956 // so check for eligibility.
19959 !isVariableCapturable(CSI
, Var
, ExprLoc
, BuildAndDiagnose
, *this);
19961 // After encountering an error, if we're actually supposed to capture, keep
19962 // capturing in nested contexts to suppress any follow-on diagnostics.
19963 if (Invalid
&& !BuildAndDiagnose
)
19966 if (BlockScopeInfo
*BSI
= dyn_cast
<BlockScopeInfo
>(CSI
)) {
19967 Invalid
= !captureInBlock(BSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
,
19968 DeclRefType
, Nested
, *this, Invalid
);
19970 } else if (CapturedRegionScopeInfo
*RSI
= dyn_cast
<CapturedRegionScopeInfo
>(CSI
)) {
19971 Invalid
= !captureInCapturedRegion(
19972 RSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
, DeclRefType
, Nested
,
19973 Kind
, /*IsTopScope*/ I
== N
- 1, *this, Invalid
);
19976 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(CSI
);
19978 !captureInLambda(LSI
, Var
, ExprLoc
, BuildAndDiagnose
, CaptureType
,
19979 DeclRefType
, Nested
, Kind
, EllipsisLoc
,
19980 /*IsTopScope*/ I
== N
- 1, *this, Invalid
);
19984 if (Invalid
&& !BuildAndDiagnose
)
19990 bool Sema::tryCaptureVariable(ValueDecl
*Var
, SourceLocation Loc
,
19991 TryCaptureKind Kind
, SourceLocation EllipsisLoc
) {
19992 QualType CaptureType
;
19993 QualType DeclRefType
;
19994 return tryCaptureVariable(Var
, Loc
, Kind
, EllipsisLoc
,
19995 /*BuildAndDiagnose=*/true, CaptureType
,
19996 DeclRefType
, nullptr);
19999 bool Sema::NeedToCaptureVariable(ValueDecl
*Var
, SourceLocation Loc
) {
20000 QualType CaptureType
;
20001 QualType DeclRefType
;
20002 return !tryCaptureVariable(Var
, Loc
, TryCapture_Implicit
, SourceLocation(),
20003 /*BuildAndDiagnose=*/false, CaptureType
,
20004 DeclRefType
, nullptr);
20007 QualType
Sema::getCapturedDeclRefType(ValueDecl
*Var
, SourceLocation Loc
) {
20008 QualType CaptureType
;
20009 QualType DeclRefType
;
20011 // Determine whether we can capture this variable.
20012 if (tryCaptureVariable(Var
, Loc
, TryCapture_Implicit
, SourceLocation(),
20013 /*BuildAndDiagnose=*/false, CaptureType
,
20014 DeclRefType
, nullptr))
20017 return DeclRefType
;
20021 // Helper to copy the template arguments from a DeclRefExpr or MemberExpr.
20022 // The produced TemplateArgumentListInfo* points to data stored within this
20023 // object, so should only be used in contexts where the pointer will not be
20024 // used after the CopiedTemplateArgs object is destroyed.
20025 class CopiedTemplateArgs
{
20027 TemplateArgumentListInfo TemplateArgStorage
;
20029 template<typename RefExpr
>
20030 CopiedTemplateArgs(RefExpr
*E
) : HasArgs(E
->hasExplicitTemplateArgs()) {
20032 E
->copyTemplateArgumentsInto(TemplateArgStorage
);
20034 operator TemplateArgumentListInfo
*()
20035 #ifdef __has_cpp_attribute
20036 #if __has_cpp_attribute(clang::lifetimebound)
20037 [[clang::lifetimebound
]]
20041 return HasArgs
? &TemplateArgStorage
: nullptr;
20046 /// Walk the set of potential results of an expression and mark them all as
20047 /// non-odr-uses if they satisfy the side-conditions of the NonOdrUseReason.
20049 /// \return A new expression if we found any potential results, ExprEmpty() if
20050 /// not, and ExprError() if we diagnosed an error.
20051 static ExprResult
rebuildPotentialResultsAsNonOdrUsed(Sema
&S
, Expr
*E
,
20052 NonOdrUseReason NOUR
) {
20053 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
20054 // an object that satisfies the requirements for appearing in a
20055 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
20056 // is immediately applied." This function handles the lvalue-to-rvalue
20057 // conversion part.
20059 // If we encounter a node that claims to be an odr-use but shouldn't be, we
20060 // transform it into the relevant kind of non-odr-use node and rebuild the
20061 // tree of nodes leading to it.
20063 // This is a mini-TreeTransform that only transforms a restricted subset of
20064 // nodes (and only certain operands of them).
20066 // Rebuild a subexpression.
20067 auto Rebuild
= [&](Expr
*Sub
) {
20068 return rebuildPotentialResultsAsNonOdrUsed(S
, Sub
, NOUR
);
20071 // Check whether a potential result satisfies the requirements of NOUR.
20072 auto IsPotentialResultOdrUsed
= [&](NamedDecl
*D
) {
20073 // Any entity other than a VarDecl is always odr-used whenever it's named
20074 // in a potentially-evaluated expression.
20075 auto *VD
= dyn_cast
<VarDecl
>(D
);
20079 // C++2a [basic.def.odr]p4:
20080 // A variable x whose name appears as a potentially-evalauted expression
20081 // e is odr-used by e unless
20082 // -- x is a reference that is usable in constant expressions, or
20083 // -- x is a variable of non-reference type that is usable in constant
20084 // expressions and has no mutable subobjects, and e is an element of
20085 // the set of potential results of an expression of
20086 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20087 // conversion is applied, or
20088 // -- x is a variable of non-reference type, and e is an element of the
20089 // set of potential results of a discarded-value expression to which
20090 // the lvalue-to-rvalue conversion is not applied
20092 // We check the first bullet and the "potentially-evaluated" condition in
20093 // BuildDeclRefExpr. We check the type requirements in the second bullet
20094 // in CheckLValueToRValueConversionOperand below.
20097 case NOUR_Unevaluated
:
20098 llvm_unreachable("unexpected non-odr-use-reason");
20100 case NOUR_Constant
:
20101 // Constant references were handled when they were built.
20102 if (VD
->getType()->isReferenceType())
20104 if (auto *RD
= VD
->getType()->getAsCXXRecordDecl())
20105 if (RD
->hasMutableFields())
20107 if (!VD
->isUsableInConstantExpressions(S
.Context
))
20111 case NOUR_Discarded
:
20112 if (VD
->getType()->isReferenceType())
20119 // Mark that this expression does not constitute an odr-use.
20120 auto MarkNotOdrUsed
= [&] {
20121 S
.MaybeODRUseExprs
.remove(E
);
20122 if (LambdaScopeInfo
*LSI
= S
.getCurLambda())
20123 LSI
->markVariableExprAsNonODRUsed(E
);
20126 // C++2a [basic.def.odr]p2:
20127 // The set of potential results of an expression e is defined as follows:
20128 switch (E
->getStmtClass()) {
20129 // -- If e is an id-expression, ...
20130 case Expr::DeclRefExprClass
: {
20131 auto *DRE
= cast
<DeclRefExpr
>(E
);
20132 if (DRE
->isNonOdrUse() || IsPotentialResultOdrUsed(DRE
->getDecl()))
20135 // Rebuild as a non-odr-use DeclRefExpr.
20137 return DeclRefExpr::Create(
20138 S
.Context
, DRE
->getQualifierLoc(), DRE
->getTemplateKeywordLoc(),
20139 DRE
->getDecl(), DRE
->refersToEnclosingVariableOrCapture(),
20140 DRE
->getNameInfo(), DRE
->getType(), DRE
->getValueKind(),
20141 DRE
->getFoundDecl(), CopiedTemplateArgs(DRE
), NOUR
);
20144 case Expr::FunctionParmPackExprClass
: {
20145 auto *FPPE
= cast
<FunctionParmPackExpr
>(E
);
20146 // If any of the declarations in the pack is odr-used, then the expression
20147 // as a whole constitutes an odr-use.
20148 for (VarDecl
*D
: *FPPE
)
20149 if (IsPotentialResultOdrUsed(D
))
20150 return ExprEmpty();
20152 // FIXME: Rebuild as a non-odr-use FunctionParmPackExpr? In practice,
20153 // nothing cares about whether we marked this as an odr-use, but it might
20154 // be useful for non-compiler tools.
20159 // -- If e is a subscripting operation with an array operand...
20160 case Expr::ArraySubscriptExprClass
: {
20161 auto *ASE
= cast
<ArraySubscriptExpr
>(E
);
20162 Expr
*OldBase
= ASE
->getBase()->IgnoreImplicit();
20163 if (!OldBase
->getType()->isArrayType())
20165 ExprResult Base
= Rebuild(OldBase
);
20166 if (!Base
.isUsable())
20168 Expr
*LHS
= ASE
->getBase() == ASE
->getLHS() ? Base
.get() : ASE
->getLHS();
20169 Expr
*RHS
= ASE
->getBase() == ASE
->getRHS() ? Base
.get() : ASE
->getRHS();
20170 SourceLocation LBracketLoc
= ASE
->getBeginLoc(); // FIXME: Not stored.
20171 return S
.ActOnArraySubscriptExpr(nullptr, LHS
, LBracketLoc
, RHS
,
20172 ASE
->getRBracketLoc());
20175 case Expr::MemberExprClass
: {
20176 auto *ME
= cast
<MemberExpr
>(E
);
20177 // -- If e is a class member access expression [...] naming a non-static
20179 if (isa
<FieldDecl
>(ME
->getMemberDecl())) {
20180 ExprResult Base
= Rebuild(ME
->getBase());
20181 if (!Base
.isUsable())
20183 return MemberExpr::Create(
20184 S
.Context
, Base
.get(), ME
->isArrow(), ME
->getOperatorLoc(),
20185 ME
->getQualifierLoc(), ME
->getTemplateKeywordLoc(),
20186 ME
->getMemberDecl(), ME
->getFoundDecl(), ME
->getMemberNameInfo(),
20187 CopiedTemplateArgs(ME
), ME
->getType(), ME
->getValueKind(),
20188 ME
->getObjectKind(), ME
->isNonOdrUse());
20191 if (ME
->getMemberDecl()->isCXXInstanceMember())
20194 // -- If e is a class member access expression naming a static data member,
20196 if (ME
->isNonOdrUse() || IsPotentialResultOdrUsed(ME
->getMemberDecl()))
20199 // Rebuild as a non-odr-use MemberExpr.
20201 return MemberExpr::Create(
20202 S
.Context
, ME
->getBase(), ME
->isArrow(), ME
->getOperatorLoc(),
20203 ME
->getQualifierLoc(), ME
->getTemplateKeywordLoc(), ME
->getMemberDecl(),
20204 ME
->getFoundDecl(), ME
->getMemberNameInfo(), CopiedTemplateArgs(ME
),
20205 ME
->getType(), ME
->getValueKind(), ME
->getObjectKind(), NOUR
);
20208 case Expr::BinaryOperatorClass
: {
20209 auto *BO
= cast
<BinaryOperator
>(E
);
20210 Expr
*LHS
= BO
->getLHS();
20211 Expr
*RHS
= BO
->getRHS();
20212 // -- If e is a pointer-to-member expression of the form e1 .* e2 ...
20213 if (BO
->getOpcode() == BO_PtrMemD
) {
20214 ExprResult Sub
= Rebuild(LHS
);
20215 if (!Sub
.isUsable())
20218 // -- If e is a comma expression, ...
20219 } else if (BO
->getOpcode() == BO_Comma
) {
20220 ExprResult Sub
= Rebuild(RHS
);
20221 if (!Sub
.isUsable())
20227 return S
.BuildBinOp(nullptr, BO
->getOperatorLoc(), BO
->getOpcode(),
20231 // -- If e has the form (e1)...
20232 case Expr::ParenExprClass
: {
20233 auto *PE
= cast
<ParenExpr
>(E
);
20234 ExprResult Sub
= Rebuild(PE
->getSubExpr());
20235 if (!Sub
.isUsable())
20237 return S
.ActOnParenExpr(PE
->getLParen(), PE
->getRParen(), Sub
.get());
20240 // -- If e is a glvalue conditional expression, ...
20241 // We don't apply this to a binary conditional operator. FIXME: Should we?
20242 case Expr::ConditionalOperatorClass
: {
20243 auto *CO
= cast
<ConditionalOperator
>(E
);
20244 ExprResult LHS
= Rebuild(CO
->getLHS());
20245 if (LHS
.isInvalid())
20246 return ExprError();
20247 ExprResult RHS
= Rebuild(CO
->getRHS());
20248 if (RHS
.isInvalid())
20249 return ExprError();
20250 if (!LHS
.isUsable() && !RHS
.isUsable())
20251 return ExprEmpty();
20252 if (!LHS
.isUsable())
20253 LHS
= CO
->getLHS();
20254 if (!RHS
.isUsable())
20255 RHS
= CO
->getRHS();
20256 return S
.ActOnConditionalOp(CO
->getQuestionLoc(), CO
->getColonLoc(),
20257 CO
->getCond(), LHS
.get(), RHS
.get());
20260 // [Clang extension]
20261 // -- If e has the form __extension__ e1...
20262 case Expr::UnaryOperatorClass
: {
20263 auto *UO
= cast
<UnaryOperator
>(E
);
20264 if (UO
->getOpcode() != UO_Extension
)
20266 ExprResult Sub
= Rebuild(UO
->getSubExpr());
20267 if (!Sub
.isUsable())
20269 return S
.BuildUnaryOp(nullptr, UO
->getOperatorLoc(), UO_Extension
,
20273 // [Clang extension]
20274 // -- If e has the form _Generic(...), the set of potential results is the
20275 // union of the sets of potential results of the associated expressions.
20276 case Expr::GenericSelectionExprClass
: {
20277 auto *GSE
= cast
<GenericSelectionExpr
>(E
);
20279 SmallVector
<Expr
*, 4> AssocExprs
;
20280 bool AnyChanged
= false;
20281 for (Expr
*OrigAssocExpr
: GSE
->getAssocExprs()) {
20282 ExprResult AssocExpr
= Rebuild(OrigAssocExpr
);
20283 if (AssocExpr
.isInvalid())
20284 return ExprError();
20285 if (AssocExpr
.isUsable()) {
20286 AssocExprs
.push_back(AssocExpr
.get());
20289 AssocExprs
.push_back(OrigAssocExpr
);
20293 void *ExOrTy
= nullptr;
20294 bool IsExpr
= GSE
->isExprPredicate();
20296 ExOrTy
= GSE
->getControllingExpr();
20298 ExOrTy
= GSE
->getControllingType();
20299 return AnyChanged
? S
.CreateGenericSelectionExpr(
20300 GSE
->getGenericLoc(), GSE
->getDefaultLoc(),
20301 GSE
->getRParenLoc(), IsExpr
, ExOrTy
,
20302 GSE
->getAssocTypeSourceInfos(), AssocExprs
)
20306 // [Clang extension]
20307 // -- If e has the form __builtin_choose_expr(...), the set of potential
20308 // results is the union of the sets of potential results of the
20309 // second and third subexpressions.
20310 case Expr::ChooseExprClass
: {
20311 auto *CE
= cast
<ChooseExpr
>(E
);
20313 ExprResult LHS
= Rebuild(CE
->getLHS());
20314 if (LHS
.isInvalid())
20315 return ExprError();
20317 ExprResult RHS
= Rebuild(CE
->getLHS());
20318 if (RHS
.isInvalid())
20319 return ExprError();
20321 if (!LHS
.get() && !RHS
.get())
20322 return ExprEmpty();
20323 if (!LHS
.isUsable())
20324 LHS
= CE
->getLHS();
20325 if (!RHS
.isUsable())
20326 RHS
= CE
->getRHS();
20328 return S
.ActOnChooseExpr(CE
->getBuiltinLoc(), CE
->getCond(), LHS
.get(),
20329 RHS
.get(), CE
->getRParenLoc());
20332 // Step through non-syntactic nodes.
20333 case Expr::ConstantExprClass
: {
20334 auto *CE
= cast
<ConstantExpr
>(E
);
20335 ExprResult Sub
= Rebuild(CE
->getSubExpr());
20336 if (!Sub
.isUsable())
20338 return ConstantExpr::Create(S
.Context
, Sub
.get());
20341 // We could mostly rely on the recursive rebuilding to rebuild implicit
20342 // casts, but not at the top level, so rebuild them here.
20343 case Expr::ImplicitCastExprClass
: {
20344 auto *ICE
= cast
<ImplicitCastExpr
>(E
);
20345 // Only step through the narrow set of cast kinds we expect to encounter.
20346 // Anything else suggests we've left the region in which potential results
20348 switch (ICE
->getCastKind()) {
20350 case CK_DerivedToBase
:
20351 case CK_UncheckedDerivedToBase
: {
20352 ExprResult Sub
= Rebuild(ICE
->getSubExpr());
20353 if (!Sub
.isUsable())
20355 CXXCastPath
Path(ICE
->path());
20356 return S
.ImpCastExprToType(Sub
.get(), ICE
->getType(), ICE
->getCastKind(),
20357 ICE
->getValueKind(), &Path
);
20370 // Can't traverse through this node. Nothing to do.
20371 return ExprEmpty();
20374 ExprResult
Sema::CheckLValueToRValueConversionOperand(Expr
*E
) {
20375 // Check whether the operand is or contains an object of non-trivial C union
20377 if (E
->getType().isVolatileQualified() &&
20378 (E
->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
20379 E
->getType().hasNonTrivialToPrimitiveCopyCUnion()))
20380 checkNonTrivialCUnion(E
->getType(), E
->getExprLoc(),
20381 Sema::NTCUC_LValueToRValueVolatile
,
20382 NTCUK_Destruct
|NTCUK_Copy
);
20384 // C++2a [basic.def.odr]p4:
20385 // [...] an expression of non-volatile-qualified non-class type to which
20386 // the lvalue-to-rvalue conversion is applied [...]
20387 if (E
->getType().isVolatileQualified() || E
->getType()->getAs
<RecordType
>())
20390 ExprResult Result
=
20391 rebuildPotentialResultsAsNonOdrUsed(*this, E
, NOUR_Constant
);
20392 if (Result
.isInvalid())
20393 return ExprError();
20394 return Result
.get() ? Result
: E
;
20397 ExprResult
Sema::ActOnConstantExpression(ExprResult Res
) {
20398 Res
= CorrectDelayedTyposInExpr(Res
);
20400 if (!Res
.isUsable())
20403 // If a constant-expression is a reference to a variable where we delay
20404 // deciding whether it is an odr-use, just assume we will apply the
20405 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
20406 // (a non-type template argument), we have special handling anyway.
20407 return CheckLValueToRValueConversionOperand(Res
.get());
20410 void Sema::CleanupVarDeclMarking() {
20411 // Iterate through a local copy in case MarkVarDeclODRUsed makes a recursive
20413 MaybeODRUseExprSet LocalMaybeODRUseExprs
;
20414 std::swap(LocalMaybeODRUseExprs
, MaybeODRUseExprs
);
20416 for (Expr
*E
: LocalMaybeODRUseExprs
) {
20417 if (auto *DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
20418 MarkVarDeclODRUsed(cast
<VarDecl
>(DRE
->getDecl()),
20419 DRE
->getLocation(), *this);
20420 } else if (auto *ME
= dyn_cast
<MemberExpr
>(E
)) {
20421 MarkVarDeclODRUsed(cast
<VarDecl
>(ME
->getMemberDecl()), ME
->getMemberLoc(),
20423 } else if (auto *FP
= dyn_cast
<FunctionParmPackExpr
>(E
)) {
20424 for (VarDecl
*VD
: *FP
)
20425 MarkVarDeclODRUsed(VD
, FP
->getParameterPackLocation(), *this);
20427 llvm_unreachable("Unexpected expression");
20431 assert(MaybeODRUseExprs
.empty() &&
20432 "MarkVarDeclODRUsed failed to cleanup MaybeODRUseExprs?");
20435 static void DoMarkPotentialCapture(Sema
&SemaRef
, SourceLocation Loc
,
20436 ValueDecl
*Var
, Expr
*E
) {
20437 VarDecl
*VD
= Var
->getPotentiallyDecomposedVarDecl();
20441 const bool RefersToEnclosingScope
=
20442 (SemaRef
.CurContext
!= VD
->getDeclContext() &&
20443 VD
->getDeclContext()->isFunctionOrMethod() && VD
->hasLocalStorage());
20444 if (RefersToEnclosingScope
) {
20445 LambdaScopeInfo
*const LSI
=
20446 SemaRef
.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
20447 if (LSI
&& (!LSI
->CallOperator
||
20448 !LSI
->CallOperator
->Encloses(Var
->getDeclContext()))) {
20449 // If a variable could potentially be odr-used, defer marking it so
20450 // until we finish analyzing the full expression for any
20451 // lvalue-to-rvalue
20452 // or discarded value conversions that would obviate odr-use.
20453 // Add it to the list of potential captures that will be analyzed
20454 // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
20455 // unless the variable is a reference that was initialized by a constant
20456 // expression (this will never need to be captured or odr-used).
20458 // FIXME: We can simplify this a lot after implementing P0588R1.
20459 assert(E
&& "Capture variable should be used in an expression.");
20460 if (!Var
->getType()->isReferenceType() ||
20461 !VD
->isUsableInConstantExpressions(SemaRef
.Context
))
20462 LSI
->addPotentialCapture(E
->IgnoreParens());
20467 static void DoMarkVarDeclReferenced(
20468 Sema
&SemaRef
, SourceLocation Loc
, VarDecl
*Var
, Expr
*E
,
20469 llvm::DenseMap
<const VarDecl
*, int> &RefsMinusAssignments
) {
20470 assert((!E
|| isa
<DeclRefExpr
>(E
) || isa
<MemberExpr
>(E
) ||
20471 isa
<FunctionParmPackExpr
>(E
)) &&
20472 "Invalid Expr argument to DoMarkVarDeclReferenced");
20473 Var
->setReferenced();
20475 if (Var
->isInvalidDecl())
20478 auto *MSI
= Var
->getMemberSpecializationInfo();
20479 TemplateSpecializationKind TSK
= MSI
? MSI
->getTemplateSpecializationKind()
20480 : Var
->getTemplateSpecializationKind();
20482 OdrUseContext OdrUse
= isOdrUseContext(SemaRef
);
20483 bool UsableInConstantExpr
=
20484 Var
->mightBeUsableInConstantExpressions(SemaRef
.Context
);
20486 if (Var
->isLocalVarDeclOrParm() && !Var
->hasExternalStorage()) {
20487 RefsMinusAssignments
.insert({Var
, 0}).first
->getSecond()++;
20490 // C++20 [expr.const]p12:
20491 // A variable [...] is needed for constant evaluation if it is [...] a
20492 // variable whose name appears as a potentially constant evaluated
20493 // expression that is either a contexpr variable or is of non-volatile
20494 // const-qualified integral type or of reference type
20495 bool NeededForConstantEvaluation
=
20496 isPotentiallyConstantEvaluatedContext(SemaRef
) && UsableInConstantExpr
;
20498 bool NeedDefinition
=
20499 OdrUse
== OdrUseContext::Used
|| NeededForConstantEvaluation
;
20501 assert(!isa
<VarTemplatePartialSpecializationDecl
>(Var
) &&
20502 "Can't instantiate a partial template specialization.");
20504 // If this might be a member specialization of a static data member, check
20505 // the specialization is visible. We already did the checks for variable
20506 // template specializations when we created them.
20507 if (NeedDefinition
&& TSK
!= TSK_Undeclared
&&
20508 !isa
<VarTemplateSpecializationDecl
>(Var
))
20509 SemaRef
.checkSpecializationVisibility(Loc
, Var
);
20511 // Perform implicit instantiation of static data members, static data member
20512 // templates of class templates, and variable template specializations. Delay
20513 // instantiations of variable templates, except for those that could be used
20514 // in a constant expression.
20515 if (NeedDefinition
&& isTemplateInstantiation(TSK
)) {
20516 // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
20517 // instantiation declaration if a variable is usable in a constant
20518 // expression (among other cases).
20519 bool TryInstantiating
=
20520 TSK
== TSK_ImplicitInstantiation
||
20521 (TSK
== TSK_ExplicitInstantiationDeclaration
&& UsableInConstantExpr
);
20523 if (TryInstantiating
) {
20524 SourceLocation PointOfInstantiation
=
20525 MSI
? MSI
->getPointOfInstantiation() : Var
->getPointOfInstantiation();
20526 bool FirstInstantiation
= PointOfInstantiation
.isInvalid();
20527 if (FirstInstantiation
) {
20528 PointOfInstantiation
= Loc
;
20530 MSI
->setPointOfInstantiation(PointOfInstantiation
);
20531 // FIXME: Notify listener.
20533 Var
->setTemplateSpecializationKind(TSK
, PointOfInstantiation
);
20536 if (UsableInConstantExpr
) {
20537 // Do not defer instantiations of variables that could be used in a
20538 // constant expression.
20539 SemaRef
.runWithSufficientStackSpace(PointOfInstantiation
, [&] {
20540 SemaRef
.InstantiateVariableDefinition(PointOfInstantiation
, Var
);
20543 // Re-set the member to trigger a recomputation of the dependence bits
20544 // for the expression.
20545 if (auto *DRE
= dyn_cast_or_null
<DeclRefExpr
>(E
))
20546 DRE
->setDecl(DRE
->getDecl());
20547 else if (auto *ME
= dyn_cast_or_null
<MemberExpr
>(E
))
20548 ME
->setMemberDecl(ME
->getMemberDecl());
20549 } else if (FirstInstantiation
) {
20550 SemaRef
.PendingInstantiations
20551 .push_back(std::make_pair(Var
, PointOfInstantiation
));
20553 bool Inserted
= false;
20554 for (auto &I
: SemaRef
.SavedPendingInstantiations
) {
20555 auto Iter
= llvm::find_if(
20556 I
, [Var
](const Sema::PendingImplicitInstantiation
&P
) {
20557 return P
.first
== Var
;
20559 if (Iter
!= I
.end()) {
20560 SemaRef
.PendingInstantiations
.push_back(*Iter
);
20567 // FIXME: For a specialization of a variable template, we don't
20568 // distinguish between "declaration and type implicitly instantiated"
20569 // and "implicit instantiation of definition requested", so we have
20570 // no direct way to avoid enqueueing the pending instantiation
20572 if (isa
<VarTemplateSpecializationDecl
>(Var
) && !Inserted
)
20573 SemaRef
.PendingInstantiations
20574 .push_back(std::make_pair(Var
, PointOfInstantiation
));
20579 // C++2a [basic.def.odr]p4:
20580 // A variable x whose name appears as a potentially-evaluated expression e
20581 // is odr-used by e unless
20582 // -- x is a reference that is usable in constant expressions
20583 // -- x is a variable of non-reference type that is usable in constant
20584 // expressions and has no mutable subobjects [FIXME], and e is an
20585 // element of the set of potential results of an expression of
20586 // non-volatile-qualified non-class type to which the lvalue-to-rvalue
20587 // conversion is applied
20588 // -- x is a variable of non-reference type, and e is an element of the set
20589 // of potential results of a discarded-value expression to which the
20590 // lvalue-to-rvalue conversion is not applied [FIXME]
20592 // We check the first part of the second bullet here, and
20593 // Sema::CheckLValueToRValueConversionOperand deals with the second part.
20594 // FIXME: To get the third bullet right, we need to delay this even for
20595 // variables that are not usable in constant expressions.
20597 // If we already know this isn't an odr-use, there's nothing more to do.
20598 if (DeclRefExpr
*DRE
= dyn_cast_or_null
<DeclRefExpr
>(E
))
20599 if (DRE
->isNonOdrUse())
20601 if (MemberExpr
*ME
= dyn_cast_or_null
<MemberExpr
>(E
))
20602 if (ME
->isNonOdrUse())
20606 case OdrUseContext::None
:
20607 // In some cases, a variable may not have been marked unevaluated, if it
20608 // appears in a defaukt initializer.
20609 assert((!E
|| isa
<FunctionParmPackExpr
>(E
) ||
20610 SemaRef
.isUnevaluatedContext()) &&
20611 "missing non-odr-use marking for unevaluated decl ref");
20614 case OdrUseContext::FormallyOdrUsed
:
20615 // FIXME: Ignoring formal odr-uses results in incorrect lambda capture
20619 case OdrUseContext::Used
:
20620 // If we might later find that this expression isn't actually an odr-use,
20621 // delay the marking.
20622 if (E
&& Var
->isUsableInConstantExpressions(SemaRef
.Context
))
20623 SemaRef
.MaybeODRUseExprs
.insert(E
);
20625 MarkVarDeclODRUsed(Var
, Loc
, SemaRef
);
20628 case OdrUseContext::Dependent
:
20629 // If this is a dependent context, we don't need to mark variables as
20630 // odr-used, but we may still need to track them for lambda capture.
20631 // FIXME: Do we also need to do this inside dependent typeid expressions
20632 // (which are modeled as unevaluated at this point)?
20633 DoMarkPotentialCapture(SemaRef
, Loc
, Var
, E
);
20638 static void DoMarkBindingDeclReferenced(Sema
&SemaRef
, SourceLocation Loc
,
20639 BindingDecl
*BD
, Expr
*E
) {
20640 BD
->setReferenced();
20642 if (BD
->isInvalidDecl())
20645 OdrUseContext OdrUse
= isOdrUseContext(SemaRef
);
20646 if (OdrUse
== OdrUseContext::Used
) {
20647 QualType CaptureType
, DeclRefType
;
20648 SemaRef
.tryCaptureVariable(BD
, Loc
, Sema::TryCapture_Implicit
,
20649 /*EllipsisLoc*/ SourceLocation(),
20650 /*BuildAndDiagnose*/ true, CaptureType
,
20652 /*FunctionScopeIndexToStopAt*/ nullptr);
20653 } else if (OdrUse
== OdrUseContext::Dependent
) {
20654 DoMarkPotentialCapture(SemaRef
, Loc
, BD
, E
);
20658 /// Mark a variable referenced, and check whether it is odr-used
20659 /// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
20660 /// used directly for normal expressions referring to VarDecl.
20661 void Sema::MarkVariableReferenced(SourceLocation Loc
, VarDecl
*Var
) {
20662 DoMarkVarDeclReferenced(*this, Loc
, Var
, nullptr, RefsMinusAssignments
);
20665 // C++ [temp.dep.expr]p3:
20666 // An id-expression is type-dependent if it contains:
20667 // - an identifier associated by name lookup with an entity captured by copy
20668 // in a lambda-expression that has an explicit object parameter whose type
20669 // is dependent ([dcl.fct]),
20670 static void FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(
20671 Sema
&SemaRef
, ValueDecl
*D
, Expr
*E
) {
20672 auto *ID
= dyn_cast
<DeclRefExpr
>(E
);
20673 if (!ID
|| ID
->isTypeDependent())
20676 auto IsDependent
= [&]() {
20677 const LambdaScopeInfo
*LSI
= SemaRef
.getCurLambda();
20680 if (!LSI
->ExplicitObjectParameter
||
20681 !LSI
->ExplicitObjectParameter
->getType()->isDependentType())
20683 if (!LSI
->CaptureMap
.count(D
))
20685 const Capture
&Cap
= LSI
->getCapture(D
);
20686 return !Cap
.isCopyCapture();
20689 ID
->setCapturedByCopyInLambdaWithExplicitObjectParameter(
20690 IsDependent
, SemaRef
.getASTContext());
20694 MarkExprReferenced(Sema
&SemaRef
, SourceLocation Loc
, Decl
*D
, Expr
*E
,
20695 bool MightBeOdrUse
,
20696 llvm::DenseMap
<const VarDecl
*, int> &RefsMinusAssignments
) {
20697 if (SemaRef
.isInOpenMPDeclareTargetContext())
20698 SemaRef
.checkDeclIsAllowedInOpenMPTarget(E
, D
);
20700 if (VarDecl
*Var
= dyn_cast
<VarDecl
>(D
)) {
20701 DoMarkVarDeclReferenced(SemaRef
, Loc
, Var
, E
, RefsMinusAssignments
);
20702 if (SemaRef
.getLangOpts().CPlusPlus
)
20703 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef
,
20708 if (BindingDecl
*Decl
= dyn_cast
<BindingDecl
>(D
)) {
20709 DoMarkBindingDeclReferenced(SemaRef
, Loc
, Decl
, E
);
20710 if (SemaRef
.getLangOpts().CPlusPlus
)
20711 FixDependencyOfIdExpressionsInLambdaWithDependentObjectParameter(SemaRef
,
20715 SemaRef
.MarkAnyDeclReferenced(Loc
, D
, MightBeOdrUse
);
20717 // If this is a call to a method via a cast, also mark the method in the
20718 // derived class used in case codegen can devirtualize the call.
20719 const MemberExpr
*ME
= dyn_cast
<MemberExpr
>(E
);
20722 CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(ME
->getMemberDecl());
20725 // Only attempt to devirtualize if this is truly a virtual call.
20726 bool IsVirtualCall
= MD
->isVirtual() &&
20727 ME
->performsVirtualDispatch(SemaRef
.getLangOpts());
20728 if (!IsVirtualCall
)
20731 // If it's possible to devirtualize the call, mark the called function
20733 CXXMethodDecl
*DM
= MD
->getDevirtualizedMethod(
20734 ME
->getBase(), SemaRef
.getLangOpts().AppleKext
);
20736 SemaRef
.MarkAnyDeclReferenced(Loc
, DM
, MightBeOdrUse
);
20739 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
20741 /// Note, this may change the dependence of the DeclRefExpr, and so needs to be
20742 /// handled with care if the DeclRefExpr is not newly-created.
20743 void Sema::MarkDeclRefReferenced(DeclRefExpr
*E
, const Expr
*Base
) {
20744 // TODO: update this with DR# once a defect report is filed.
20745 // C++11 defect. The address of a pure member should not be an ODR use, even
20746 // if it's a qualified reference.
20747 bool OdrUse
= true;
20748 if (const CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(E
->getDecl()))
20749 if (Method
->isVirtual() &&
20750 !Method
->getDevirtualizedMethod(Base
, getLangOpts().AppleKext
))
20753 if (auto *FD
= dyn_cast
<FunctionDecl
>(E
->getDecl())) {
20754 if (!isUnevaluatedContext() && !isConstantEvaluatedContext() &&
20755 !isImmediateFunctionContext() &&
20756 !isCheckingDefaultArgumentOrInitializer() &&
20757 FD
->isImmediateFunction() && !RebuildingImmediateInvocation
&&
20758 !FD
->isDependentContext())
20759 ExprEvalContexts
.back().ReferenceToConsteval
.insert(E
);
20761 MarkExprReferenced(*this, E
->getLocation(), E
->getDecl(), E
, OdrUse
,
20762 RefsMinusAssignments
);
20765 /// Perform reference-marking and odr-use handling for a MemberExpr.
20766 void Sema::MarkMemberReferenced(MemberExpr
*E
) {
20767 // C++11 [basic.def.odr]p2:
20768 // A non-overloaded function whose name appears as a potentially-evaluated
20769 // expression or a member of a set of candidate functions, if selected by
20770 // overload resolution when referred to from a potentially-evaluated
20771 // expression, is odr-used, unless it is a pure virtual function and its
20772 // name is not explicitly qualified.
20773 bool MightBeOdrUse
= true;
20774 if (E
->performsVirtualDispatch(getLangOpts())) {
20775 if (CXXMethodDecl
*Method
= dyn_cast
<CXXMethodDecl
>(E
->getMemberDecl()))
20776 if (Method
->isPure())
20777 MightBeOdrUse
= false;
20779 SourceLocation Loc
=
20780 E
->getMemberLoc().isValid() ? E
->getMemberLoc() : E
->getBeginLoc();
20781 MarkExprReferenced(*this, Loc
, E
->getMemberDecl(), E
, MightBeOdrUse
,
20782 RefsMinusAssignments
);
20785 /// Perform reference-marking and odr-use handling for a FunctionParmPackExpr.
20786 void Sema::MarkFunctionParmPackReferenced(FunctionParmPackExpr
*E
) {
20787 for (VarDecl
*VD
: *E
)
20788 MarkExprReferenced(*this, E
->getParameterPackLocation(), VD
, E
, true,
20789 RefsMinusAssignments
);
20792 /// Perform marking for a reference to an arbitrary declaration. It
20793 /// marks the declaration referenced, and performs odr-use checking for
20794 /// functions and variables. This method should not be used when building a
20795 /// normal expression which refers to a variable.
20796 void Sema::MarkAnyDeclReferenced(SourceLocation Loc
, Decl
*D
,
20797 bool MightBeOdrUse
) {
20798 if (MightBeOdrUse
) {
20799 if (auto *VD
= dyn_cast
<VarDecl
>(D
)) {
20800 MarkVariableReferenced(Loc
, VD
);
20804 if (auto *FD
= dyn_cast
<FunctionDecl
>(D
)) {
20805 MarkFunctionReferenced(Loc
, FD
, MightBeOdrUse
);
20808 D
->setReferenced();
20812 // Mark all of the declarations used by a type as referenced.
20813 // FIXME: Not fully implemented yet! We need to have a better understanding
20814 // of when we're entering a context we should not recurse into.
20815 // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
20816 // TreeTransforms rebuilding the type in a new context. Rather than
20817 // duplicating the TreeTransform logic, we should consider reusing it here.
20818 // Currently that causes problems when rebuilding LambdaExprs.
20819 class MarkReferencedDecls
: public RecursiveASTVisitor
<MarkReferencedDecls
> {
20821 SourceLocation Loc
;
20824 typedef RecursiveASTVisitor
<MarkReferencedDecls
> Inherited
;
20826 MarkReferencedDecls(Sema
&S
, SourceLocation Loc
) : S(S
), Loc(Loc
) { }
20828 bool TraverseTemplateArgument(const TemplateArgument
&Arg
);
20832 bool MarkReferencedDecls::TraverseTemplateArgument(
20833 const TemplateArgument
&Arg
) {
20835 // A non-type template argument is a constant-evaluated context.
20836 EnterExpressionEvaluationContext
Evaluated(
20837 S
, Sema::ExpressionEvaluationContext::ConstantEvaluated
);
20838 if (Arg
.getKind() == TemplateArgument::Declaration
) {
20839 if (Decl
*D
= Arg
.getAsDecl())
20840 S
.MarkAnyDeclReferenced(Loc
, D
, true);
20841 } else if (Arg
.getKind() == TemplateArgument::Expression
) {
20842 S
.MarkDeclarationsReferencedInExpr(Arg
.getAsExpr(), false);
20846 return Inherited::TraverseTemplateArgument(Arg
);
20849 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc
, QualType T
) {
20850 MarkReferencedDecls
Marker(*this, Loc
);
20851 Marker
.TraverseType(T
);
20855 /// Helper class that marks all of the declarations referenced by
20856 /// potentially-evaluated subexpressions as "referenced".
20857 class EvaluatedExprMarker
: public UsedDeclVisitor
<EvaluatedExprMarker
> {
20859 typedef UsedDeclVisitor
<EvaluatedExprMarker
> Inherited
;
20860 bool SkipLocalVariables
;
20861 ArrayRef
<const Expr
*> StopAt
;
20863 EvaluatedExprMarker(Sema
&S
, bool SkipLocalVariables
,
20864 ArrayRef
<const Expr
*> StopAt
)
20865 : Inherited(S
), SkipLocalVariables(SkipLocalVariables
), StopAt(StopAt
) {}
20867 void visitUsedDecl(SourceLocation Loc
, Decl
*D
) {
20868 S
.MarkFunctionReferenced(Loc
, cast
<FunctionDecl
>(D
));
20871 void Visit(Expr
*E
) {
20872 if (llvm::is_contained(StopAt
, E
))
20874 Inherited::Visit(E
);
20877 void VisitConstantExpr(ConstantExpr
*E
) {
20878 // Don't mark declarations within a ConstantExpression, as this expression
20879 // will be evaluated and folded to a value.
20882 void VisitDeclRefExpr(DeclRefExpr
*E
) {
20883 // If we were asked not to visit local variables, don't.
20884 if (SkipLocalVariables
) {
20885 if (VarDecl
*VD
= dyn_cast
<VarDecl
>(E
->getDecl()))
20886 if (VD
->hasLocalStorage())
20890 // FIXME: This can trigger the instantiation of the initializer of a
20891 // variable, which can cause the expression to become value-dependent
20892 // or error-dependent. Do we need to propagate the new dependence bits?
20893 S
.MarkDeclRefReferenced(E
);
20896 void VisitMemberExpr(MemberExpr
*E
) {
20897 S
.MarkMemberReferenced(E
);
20898 Visit(E
->getBase());
20903 /// Mark any declarations that appear within this expression or any
20904 /// potentially-evaluated subexpressions as "referenced".
20906 /// \param SkipLocalVariables If true, don't mark local variables as
20908 /// \param StopAt Subexpressions that we shouldn't recurse into.
20909 void Sema::MarkDeclarationsReferencedInExpr(Expr
*E
,
20910 bool SkipLocalVariables
,
20911 ArrayRef
<const Expr
*> StopAt
) {
20912 EvaluatedExprMarker(*this, SkipLocalVariables
, StopAt
).Visit(E
);
20915 /// Emit a diagnostic when statements are reachable.
20916 /// FIXME: check for reachability even in expressions for which we don't build a
20917 /// CFG (eg, in the initializer of a global or in a constant expression).
20919 /// namespace { auto *p = new double[3][false ? (1, 2) : 3]; }
20920 bool Sema::DiagIfReachable(SourceLocation Loc
, ArrayRef
<const Stmt
*> Stmts
,
20921 const PartialDiagnostic
&PD
) {
20922 if (!Stmts
.empty() && getCurFunctionOrMethodDecl()) {
20923 if (!FunctionScopes
.empty())
20924 FunctionScopes
.back()->PossiblyUnreachableDiags
.push_back(
20925 sema::PossiblyUnreachableDiag(PD
, Loc
, Stmts
));
20929 // The initializer of a constexpr variable or of the first declaration of a
20930 // static data member is not syntactically a constant evaluated constant,
20931 // but nonetheless is always required to be a constant expression, so we
20932 // can skip diagnosing.
20933 // FIXME: Using the mangling context here is a hack.
20934 if (auto *VD
= dyn_cast_or_null
<VarDecl
>(
20935 ExprEvalContexts
.back().ManglingContextDecl
)) {
20936 if (VD
->isConstexpr() ||
20937 (VD
->isStaticDataMember() && VD
->isFirstDecl() && !VD
->isInline()))
20939 // FIXME: For any other kind of variable, we should build a CFG for its
20940 // initializer and check whether the context in question is reachable.
20947 /// Emit a diagnostic that describes an effect on the run-time behavior
20948 /// of the program being compiled.
20950 /// This routine emits the given diagnostic when the code currently being
20951 /// type-checked is "potentially evaluated", meaning that there is a
20952 /// possibility that the code will actually be executable. Code in sizeof()
20953 /// expressions, code used only during overload resolution, etc., are not
20954 /// potentially evaluated. This routine will suppress such diagnostics or,
20955 /// in the absolutely nutty case of potentially potentially evaluated
20956 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
20959 /// This routine should be used for all diagnostics that describe the run-time
20960 /// behavior of a program, such as passing a non-POD value through an ellipsis.
20961 /// Failure to do so will likely result in spurious diagnostics or failures
20962 /// during overload resolution or within sizeof/alignof/typeof/typeid.
20963 bool Sema::DiagRuntimeBehavior(SourceLocation Loc
, ArrayRef
<const Stmt
*> Stmts
,
20964 const PartialDiagnostic
&PD
) {
20966 if (ExprEvalContexts
.back().isDiscardedStatementContext())
20969 switch (ExprEvalContexts
.back().Context
) {
20970 case ExpressionEvaluationContext::Unevaluated
:
20971 case ExpressionEvaluationContext::UnevaluatedList
:
20972 case ExpressionEvaluationContext::UnevaluatedAbstract
:
20973 case ExpressionEvaluationContext::DiscardedStatement
:
20974 // The argument will never be evaluated, so don't complain.
20977 case ExpressionEvaluationContext::ConstantEvaluated
:
20978 case ExpressionEvaluationContext::ImmediateFunctionContext
:
20979 // Relevant diagnostics should be produced by constant evaluation.
20982 case ExpressionEvaluationContext::PotentiallyEvaluated
:
20983 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
20984 return DiagIfReachable(Loc
, Stmts
, PD
);
20990 bool Sema::DiagRuntimeBehavior(SourceLocation Loc
, const Stmt
*Statement
,
20991 const PartialDiagnostic
&PD
) {
20992 return DiagRuntimeBehavior(
20993 Loc
, Statement
? llvm::ArrayRef(Statement
) : std::nullopt
, PD
);
20996 bool Sema::CheckCallReturnType(QualType ReturnType
, SourceLocation Loc
,
20997 CallExpr
*CE
, FunctionDecl
*FD
) {
20998 if (ReturnType
->isVoidType() || !ReturnType
->isIncompleteType())
21001 // If we're inside a decltype's expression, don't check for a valid return
21002 // type or construct temporaries until we know whether this is the last call.
21003 if (ExprEvalContexts
.back().ExprContext
==
21004 ExpressionEvaluationContextRecord::EK_Decltype
) {
21005 ExprEvalContexts
.back().DelayedDecltypeCalls
.push_back(CE
);
21009 class CallReturnIncompleteDiagnoser
: public TypeDiagnoser
{
21014 CallReturnIncompleteDiagnoser(FunctionDecl
*FD
, CallExpr
*CE
)
21015 : FD(FD
), CE(CE
) { }
21017 void diagnose(Sema
&S
, SourceLocation Loc
, QualType T
) override
{
21019 S
.Diag(Loc
, diag::err_call_incomplete_return
)
21020 << T
<< CE
->getSourceRange();
21024 S
.Diag(Loc
, diag::err_call_function_incomplete_return
)
21025 << CE
->getSourceRange() << FD
<< T
;
21026 S
.Diag(FD
->getLocation(), diag::note_entity_declared_at
)
21027 << FD
->getDeclName();
21029 } Diagnoser(FD
, CE
);
21031 if (RequireCompleteType(Loc
, ReturnType
, Diagnoser
))
21037 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
21038 // will prevent this condition from triggering, which is what we want.
21039 void Sema::DiagnoseAssignmentAsCondition(Expr
*E
) {
21040 SourceLocation Loc
;
21042 unsigned diagnostic
= diag::warn_condition_is_assignment
;
21043 bool IsOrAssign
= false;
21045 if (BinaryOperator
*Op
= dyn_cast
<BinaryOperator
>(E
)) {
21046 if (Op
->getOpcode() != BO_Assign
&& Op
->getOpcode() != BO_OrAssign
)
21049 IsOrAssign
= Op
->getOpcode() == BO_OrAssign
;
21051 // Greylist some idioms by putting them into a warning subcategory.
21052 if (ObjCMessageExpr
*ME
21053 = dyn_cast
<ObjCMessageExpr
>(Op
->getRHS()->IgnoreParenCasts())) {
21054 Selector Sel
= ME
->getSelector();
21056 // self = [<foo> init...]
21057 if (isSelfExpr(Op
->getLHS()) && ME
->getMethodFamily() == OMF_init
)
21058 diagnostic
= diag::warn_condition_is_idiomatic_assignment
;
21060 // <foo> = [<bar> nextObject]
21061 else if (Sel
.isUnarySelector() && Sel
.getNameForSlot(0) == "nextObject")
21062 diagnostic
= diag::warn_condition_is_idiomatic_assignment
;
21065 Loc
= Op
->getOperatorLoc();
21066 } else if (CXXOperatorCallExpr
*Op
= dyn_cast
<CXXOperatorCallExpr
>(E
)) {
21067 if (Op
->getOperator() != OO_Equal
&& Op
->getOperator() != OO_PipeEqual
)
21070 IsOrAssign
= Op
->getOperator() == OO_PipeEqual
;
21071 Loc
= Op
->getOperatorLoc();
21072 } else if (PseudoObjectExpr
*POE
= dyn_cast
<PseudoObjectExpr
>(E
))
21073 return DiagnoseAssignmentAsCondition(POE
->getSyntacticForm());
21075 // Not an assignment.
21079 Diag(Loc
, diagnostic
) << E
->getSourceRange();
21081 SourceLocation Open
= E
->getBeginLoc();
21082 SourceLocation Close
= getLocForEndOfToken(E
->getSourceRange().getEnd());
21083 Diag(Loc
, diag::note_condition_assign_silence
)
21084 << FixItHint::CreateInsertion(Open
, "(")
21085 << FixItHint::CreateInsertion(Close
, ")");
21088 Diag(Loc
, diag::note_condition_or_assign_to_comparison
)
21089 << FixItHint::CreateReplacement(Loc
, "!=");
21091 Diag(Loc
, diag::note_condition_assign_to_comparison
)
21092 << FixItHint::CreateReplacement(Loc
, "==");
21095 /// Redundant parentheses over an equality comparison can indicate
21096 /// that the user intended an assignment used as condition.
21097 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr
*ParenE
) {
21098 // Don't warn if the parens came from a macro.
21099 SourceLocation parenLoc
= ParenE
->getBeginLoc();
21100 if (parenLoc
.isInvalid() || parenLoc
.isMacroID())
21102 // Don't warn for dependent expressions.
21103 if (ParenE
->isTypeDependent())
21106 Expr
*E
= ParenE
->IgnoreParens();
21108 if (BinaryOperator
*opE
= dyn_cast
<BinaryOperator
>(E
))
21109 if (opE
->getOpcode() == BO_EQ
&&
21110 opE
->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context
)
21111 == Expr::MLV_Valid
) {
21112 SourceLocation Loc
= opE
->getOperatorLoc();
21114 Diag(Loc
, diag::warn_equality_with_extra_parens
) << E
->getSourceRange();
21115 SourceRange ParenERange
= ParenE
->getSourceRange();
21116 Diag(Loc
, diag::note_equality_comparison_silence
)
21117 << FixItHint::CreateRemoval(ParenERange
.getBegin())
21118 << FixItHint::CreateRemoval(ParenERange
.getEnd());
21119 Diag(Loc
, diag::note_equality_comparison_to_assign
)
21120 << FixItHint::CreateReplacement(Loc
, "=");
21124 ExprResult
Sema::CheckBooleanCondition(SourceLocation Loc
, Expr
*E
,
21125 bool IsConstexpr
) {
21126 DiagnoseAssignmentAsCondition(E
);
21127 if (ParenExpr
*parenE
= dyn_cast
<ParenExpr
>(E
))
21128 DiagnoseEqualityWithExtraParens(parenE
);
21130 ExprResult result
= CheckPlaceholderExpr(E
);
21131 if (result
.isInvalid()) return ExprError();
21134 if (!E
->isTypeDependent()) {
21135 if (getLangOpts().CPlusPlus
)
21136 return CheckCXXBooleanCondition(E
, IsConstexpr
); // C++ 6.4p4
21138 ExprResult ERes
= DefaultFunctionArrayLvalueConversion(E
);
21139 if (ERes
.isInvalid())
21140 return ExprError();
21143 QualType T
= E
->getType();
21144 if (!T
->isScalarType()) { // C99 6.8.4.1p1
21145 Diag(Loc
, diag::err_typecheck_statement_requires_scalar
)
21146 << T
<< E
->getSourceRange();
21147 return ExprError();
21149 CheckBoolLikeConversion(E
, Loc
);
21155 Sema::ConditionResult
Sema::ActOnCondition(Scope
*S
, SourceLocation Loc
,
21156 Expr
*SubExpr
, ConditionKind CK
,
21158 // MissingOK indicates whether having no condition expression is valid
21159 // (for loop) or invalid (e.g. while loop).
21161 return MissingOK
? ConditionResult() : ConditionError();
21165 case ConditionKind::Boolean
:
21166 Cond
= CheckBooleanCondition(Loc
, SubExpr
);
21169 case ConditionKind::ConstexprIf
:
21170 Cond
= CheckBooleanCondition(Loc
, SubExpr
, true);
21173 case ConditionKind::Switch
:
21174 Cond
= CheckSwitchCondition(Loc
, SubExpr
);
21177 if (Cond
.isInvalid()) {
21178 Cond
= CreateRecoveryExpr(SubExpr
->getBeginLoc(), SubExpr
->getEndLoc(),
21179 {SubExpr
}, PreferredConditionType(CK
));
21181 return ConditionError();
21183 // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
21184 FullExprArg FullExpr
= MakeFullExpr(Cond
.get(), Loc
);
21185 if (!FullExpr
.get())
21186 return ConditionError();
21188 return ConditionResult(*this, nullptr, FullExpr
,
21189 CK
== ConditionKind::ConstexprIf
);
21193 /// A visitor for rebuilding a call to an __unknown_any expression
21194 /// to have an appropriate type.
21195 struct RebuildUnknownAnyFunction
21196 : StmtVisitor
<RebuildUnknownAnyFunction
, ExprResult
> {
21200 RebuildUnknownAnyFunction(Sema
&S
) : S(S
) {}
21202 ExprResult
VisitStmt(Stmt
*S
) {
21203 llvm_unreachable("unexpected statement!");
21206 ExprResult
VisitExpr(Expr
*E
) {
21207 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_call
)
21208 << E
->getSourceRange();
21209 return ExprError();
21212 /// Rebuild an expression which simply semantically wraps another
21213 /// expression which it shares the type and value kind of.
21214 template <class T
> ExprResult
rebuildSugarExpr(T
*E
) {
21215 ExprResult SubResult
= Visit(E
->getSubExpr());
21216 if (SubResult
.isInvalid()) return ExprError();
21218 Expr
*SubExpr
= SubResult
.get();
21219 E
->setSubExpr(SubExpr
);
21220 E
->setType(SubExpr
->getType());
21221 E
->setValueKind(SubExpr
->getValueKind());
21222 assert(E
->getObjectKind() == OK_Ordinary
);
21226 ExprResult
VisitParenExpr(ParenExpr
*E
) {
21227 return rebuildSugarExpr(E
);
21230 ExprResult
VisitUnaryExtension(UnaryOperator
*E
) {
21231 return rebuildSugarExpr(E
);
21234 ExprResult
VisitUnaryAddrOf(UnaryOperator
*E
) {
21235 ExprResult SubResult
= Visit(E
->getSubExpr());
21236 if (SubResult
.isInvalid()) return ExprError();
21238 Expr
*SubExpr
= SubResult
.get();
21239 E
->setSubExpr(SubExpr
);
21240 E
->setType(S
.Context
.getPointerType(SubExpr
->getType()));
21241 assert(E
->isPRValue());
21242 assert(E
->getObjectKind() == OK_Ordinary
);
21246 ExprResult
resolveDecl(Expr
*E
, ValueDecl
*VD
) {
21247 if (!isa
<FunctionDecl
>(VD
)) return VisitExpr(E
);
21249 E
->setType(VD
->getType());
21251 assert(E
->isPRValue());
21252 if (S
.getLangOpts().CPlusPlus
&&
21253 !(isa
<CXXMethodDecl
>(VD
) &&
21254 cast
<CXXMethodDecl
>(VD
)->isInstance()))
21255 E
->setValueKind(VK_LValue
);
21260 ExprResult
VisitMemberExpr(MemberExpr
*E
) {
21261 return resolveDecl(E
, E
->getMemberDecl());
21264 ExprResult
VisitDeclRefExpr(DeclRefExpr
*E
) {
21265 return resolveDecl(E
, E
->getDecl());
21270 /// Given a function expression of unknown-any type, try to rebuild it
21271 /// to have a function type.
21272 static ExprResult
rebuildUnknownAnyFunction(Sema
&S
, Expr
*FunctionExpr
) {
21273 ExprResult Result
= RebuildUnknownAnyFunction(S
).Visit(FunctionExpr
);
21274 if (Result
.isInvalid()) return ExprError();
21275 return S
.DefaultFunctionArrayConversion(Result
.get());
21279 /// A visitor for rebuilding an expression of type __unknown_anytype
21280 /// into one which resolves the type directly on the referring
21281 /// expression. Strict preservation of the original source
21282 /// structure is not a goal.
21283 struct RebuildUnknownAnyExpr
21284 : StmtVisitor
<RebuildUnknownAnyExpr
, ExprResult
> {
21288 /// The current destination type.
21291 RebuildUnknownAnyExpr(Sema
&S
, QualType CastType
)
21292 : S(S
), DestType(CastType
) {}
21294 ExprResult
VisitStmt(Stmt
*S
) {
21295 llvm_unreachable("unexpected statement!");
21298 ExprResult
VisitExpr(Expr
*E
) {
21299 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_expr
)
21300 << E
->getSourceRange();
21301 return ExprError();
21304 ExprResult
VisitCallExpr(CallExpr
*E
);
21305 ExprResult
VisitObjCMessageExpr(ObjCMessageExpr
*E
);
21307 /// Rebuild an expression which simply semantically wraps another
21308 /// expression which it shares the type and value kind of.
21309 template <class T
> ExprResult
rebuildSugarExpr(T
*E
) {
21310 ExprResult SubResult
= Visit(E
->getSubExpr());
21311 if (SubResult
.isInvalid()) return ExprError();
21312 Expr
*SubExpr
= SubResult
.get();
21313 E
->setSubExpr(SubExpr
);
21314 E
->setType(SubExpr
->getType());
21315 E
->setValueKind(SubExpr
->getValueKind());
21316 assert(E
->getObjectKind() == OK_Ordinary
);
21320 ExprResult
VisitParenExpr(ParenExpr
*E
) {
21321 return rebuildSugarExpr(E
);
21324 ExprResult
VisitUnaryExtension(UnaryOperator
*E
) {
21325 return rebuildSugarExpr(E
);
21328 ExprResult
VisitUnaryAddrOf(UnaryOperator
*E
) {
21329 const PointerType
*Ptr
= DestType
->getAs
<PointerType
>();
21331 S
.Diag(E
->getOperatorLoc(), diag::err_unknown_any_addrof
)
21332 << E
->getSourceRange();
21333 return ExprError();
21336 if (isa
<CallExpr
>(E
->getSubExpr())) {
21337 S
.Diag(E
->getOperatorLoc(), diag::err_unknown_any_addrof_call
)
21338 << E
->getSourceRange();
21339 return ExprError();
21342 assert(E
->isPRValue());
21343 assert(E
->getObjectKind() == OK_Ordinary
);
21344 E
->setType(DestType
);
21346 // Build the sub-expression as if it were an object of the pointee type.
21347 DestType
= Ptr
->getPointeeType();
21348 ExprResult SubResult
= Visit(E
->getSubExpr());
21349 if (SubResult
.isInvalid()) return ExprError();
21350 E
->setSubExpr(SubResult
.get());
21354 ExprResult
VisitImplicitCastExpr(ImplicitCastExpr
*E
);
21356 ExprResult
resolveDecl(Expr
*E
, ValueDecl
*VD
);
21358 ExprResult
VisitMemberExpr(MemberExpr
*E
) {
21359 return resolveDecl(E
, E
->getMemberDecl());
21362 ExprResult
VisitDeclRefExpr(DeclRefExpr
*E
) {
21363 return resolveDecl(E
, E
->getDecl());
21368 /// Rebuilds a call expression which yielded __unknown_anytype.
21369 ExprResult
RebuildUnknownAnyExpr::VisitCallExpr(CallExpr
*E
) {
21370 Expr
*CalleeExpr
= E
->getCallee();
21374 FK_FunctionPointer
,
21379 QualType CalleeType
= CalleeExpr
->getType();
21380 if (CalleeType
== S
.Context
.BoundMemberTy
) {
21381 assert(isa
<CXXMemberCallExpr
>(E
) || isa
<CXXOperatorCallExpr
>(E
));
21382 Kind
= FK_MemberFunction
;
21383 CalleeType
= Expr::findBoundMemberType(CalleeExpr
);
21384 } else if (const PointerType
*Ptr
= CalleeType
->getAs
<PointerType
>()) {
21385 CalleeType
= Ptr
->getPointeeType();
21386 Kind
= FK_FunctionPointer
;
21388 CalleeType
= CalleeType
->castAs
<BlockPointerType
>()->getPointeeType();
21389 Kind
= FK_BlockPointer
;
21391 const FunctionType
*FnType
= CalleeType
->castAs
<FunctionType
>();
21393 // Verify that this is a legal result type of a function.
21394 if (DestType
->isArrayType() || DestType
->isFunctionType()) {
21395 unsigned diagID
= diag::err_func_returning_array_function
;
21396 if (Kind
== FK_BlockPointer
)
21397 diagID
= diag::err_block_returning_array_function
;
21399 S
.Diag(E
->getExprLoc(), diagID
)
21400 << DestType
->isFunctionType() << DestType
;
21401 return ExprError();
21404 // Otherwise, go ahead and set DestType as the call's result.
21405 E
->setType(DestType
.getNonLValueExprType(S
.Context
));
21406 E
->setValueKind(Expr::getValueKindForType(DestType
));
21407 assert(E
->getObjectKind() == OK_Ordinary
);
21409 // Rebuild the function type, replacing the result type with DestType.
21410 const FunctionProtoType
*Proto
= dyn_cast
<FunctionProtoType
>(FnType
);
21412 // __unknown_anytype(...) is a special case used by the debugger when
21413 // it has no idea what a function's signature is.
21415 // We want to build this call essentially under the K&R
21416 // unprototyped rules, but making a FunctionNoProtoType in C++
21417 // would foul up all sorts of assumptions. However, we cannot
21418 // simply pass all arguments as variadic arguments, nor can we
21419 // portably just call the function under a non-variadic type; see
21420 // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
21421 // However, it turns out that in practice it is generally safe to
21422 // call a function declared as "A foo(B,C,D);" under the prototype
21423 // "A foo(B,C,D,...);". The only known exception is with the
21424 // Windows ABI, where any variadic function is implicitly cdecl
21425 // regardless of its normal CC. Therefore we change the parameter
21426 // types to match the types of the arguments.
21428 // This is a hack, but it is far superior to moving the
21429 // corresponding target-specific code from IR-gen to Sema/AST.
21431 ArrayRef
<QualType
> ParamTypes
= Proto
->getParamTypes();
21432 SmallVector
<QualType
, 8> ArgTypes
;
21433 if (ParamTypes
.empty() && Proto
->isVariadic()) { // the special case
21434 ArgTypes
.reserve(E
->getNumArgs());
21435 for (unsigned i
= 0, e
= E
->getNumArgs(); i
!= e
; ++i
) {
21436 ArgTypes
.push_back(S
.Context
.getReferenceQualifiedType(E
->getArg(i
)));
21438 ParamTypes
= ArgTypes
;
21440 DestType
= S
.Context
.getFunctionType(DestType
, ParamTypes
,
21441 Proto
->getExtProtoInfo());
21443 DestType
= S
.Context
.getFunctionNoProtoType(DestType
,
21444 FnType
->getExtInfo());
21447 // Rebuild the appropriate pointer-to-function type.
21449 case FK_MemberFunction
:
21453 case FK_FunctionPointer
:
21454 DestType
= S
.Context
.getPointerType(DestType
);
21457 case FK_BlockPointer
:
21458 DestType
= S
.Context
.getBlockPointerType(DestType
);
21462 // Finally, we can recurse.
21463 ExprResult CalleeResult
= Visit(CalleeExpr
);
21464 if (!CalleeResult
.isUsable()) return ExprError();
21465 E
->setCallee(CalleeResult
.get());
21467 // Bind a temporary if necessary.
21468 return S
.MaybeBindToTemporary(E
);
21471 ExprResult
RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr
*E
) {
21472 // Verify that this is a legal result type of a call.
21473 if (DestType
->isArrayType() || DestType
->isFunctionType()) {
21474 S
.Diag(E
->getExprLoc(), diag::err_func_returning_array_function
)
21475 << DestType
->isFunctionType() << DestType
;
21476 return ExprError();
21479 // Rewrite the method result type if available.
21480 if (ObjCMethodDecl
*Method
= E
->getMethodDecl()) {
21481 assert(Method
->getReturnType() == S
.Context
.UnknownAnyTy
);
21482 Method
->setReturnType(DestType
);
21485 // Change the type of the message.
21486 E
->setType(DestType
.getNonReferenceType());
21487 E
->setValueKind(Expr::getValueKindForType(DestType
));
21489 return S
.MaybeBindToTemporary(E
);
21492 ExprResult
RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr
*E
) {
21493 // The only case we should ever see here is a function-to-pointer decay.
21494 if (E
->getCastKind() == CK_FunctionToPointerDecay
) {
21495 assert(E
->isPRValue());
21496 assert(E
->getObjectKind() == OK_Ordinary
);
21498 E
->setType(DestType
);
21500 // Rebuild the sub-expression as the pointee (function) type.
21501 DestType
= DestType
->castAs
<PointerType
>()->getPointeeType();
21503 ExprResult Result
= Visit(E
->getSubExpr());
21504 if (!Result
.isUsable()) return ExprError();
21506 E
->setSubExpr(Result
.get());
21508 } else if (E
->getCastKind() == CK_LValueToRValue
) {
21509 assert(E
->isPRValue());
21510 assert(E
->getObjectKind() == OK_Ordinary
);
21512 assert(isa
<BlockPointerType
>(E
->getType()));
21514 E
->setType(DestType
);
21516 // The sub-expression has to be a lvalue reference, so rebuild it as such.
21517 DestType
= S
.Context
.getLValueReferenceType(DestType
);
21519 ExprResult Result
= Visit(E
->getSubExpr());
21520 if (!Result
.isUsable()) return ExprError();
21522 E
->setSubExpr(Result
.get());
21525 llvm_unreachable("Unhandled cast type!");
21529 ExprResult
RebuildUnknownAnyExpr::resolveDecl(Expr
*E
, ValueDecl
*VD
) {
21530 ExprValueKind ValueKind
= VK_LValue
;
21531 QualType Type
= DestType
;
21533 // We know how to make this work for certain kinds of decls:
21536 if (FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(VD
)) {
21537 if (const PointerType
*Ptr
= Type
->getAs
<PointerType
>()) {
21538 DestType
= Ptr
->getPointeeType();
21539 ExprResult Result
= resolveDecl(E
, VD
);
21540 if (Result
.isInvalid()) return ExprError();
21541 return S
.ImpCastExprToType(Result
.get(), Type
, CK_FunctionToPointerDecay
,
21545 if (!Type
->isFunctionType()) {
21546 S
.Diag(E
->getExprLoc(), diag::err_unknown_any_function
)
21547 << VD
<< E
->getSourceRange();
21548 return ExprError();
21550 if (const FunctionProtoType
*FT
= Type
->getAs
<FunctionProtoType
>()) {
21551 // We must match the FunctionDecl's type to the hack introduced in
21552 // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
21553 // type. See the lengthy commentary in that routine.
21554 QualType FDT
= FD
->getType();
21555 const FunctionType
*FnType
= FDT
->castAs
<FunctionType
>();
21556 const FunctionProtoType
*Proto
= dyn_cast_or_null
<FunctionProtoType
>(FnType
);
21557 DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
);
21558 if (DRE
&& Proto
&& Proto
->getParamTypes().empty() && Proto
->isVariadic()) {
21559 SourceLocation Loc
= FD
->getLocation();
21560 FunctionDecl
*NewFD
= FunctionDecl::Create(
21561 S
.Context
, FD
->getDeclContext(), Loc
, Loc
,
21562 FD
->getNameInfo().getName(), DestType
, FD
->getTypeSourceInfo(),
21563 SC_None
, S
.getCurFPFeatures().isFPConstrained(),
21564 false /*isInlineSpecified*/, FD
->hasPrototype(),
21565 /*ConstexprKind*/ ConstexprSpecKind::Unspecified
);
21567 if (FD
->getQualifier())
21568 NewFD
->setQualifierInfo(FD
->getQualifierLoc());
21570 SmallVector
<ParmVarDecl
*, 16> Params
;
21571 for (const auto &AI
: FT
->param_types()) {
21572 ParmVarDecl
*Param
=
21573 S
.BuildParmVarDeclForTypedef(FD
, Loc
, AI
);
21574 Param
->setScopeInfo(0, Params
.size());
21575 Params
.push_back(Param
);
21577 NewFD
->setParams(Params
);
21578 DRE
->setDecl(NewFD
);
21579 VD
= DRE
->getDecl();
21583 if (CXXMethodDecl
*MD
= dyn_cast
<CXXMethodDecl
>(FD
))
21584 if (MD
->isInstance()) {
21585 ValueKind
= VK_PRValue
;
21586 Type
= S
.Context
.BoundMemberTy
;
21589 // Function references aren't l-values in C.
21590 if (!S
.getLangOpts().CPlusPlus
)
21591 ValueKind
= VK_PRValue
;
21594 } else if (isa
<VarDecl
>(VD
)) {
21595 if (const ReferenceType
*RefTy
= Type
->getAs
<ReferenceType
>()) {
21596 Type
= RefTy
->getPointeeType();
21597 } else if (Type
->isFunctionType()) {
21598 S
.Diag(E
->getExprLoc(), diag::err_unknown_any_var_function_type
)
21599 << VD
<< E
->getSourceRange();
21600 return ExprError();
21605 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_decl
)
21606 << VD
<< E
->getSourceRange();
21607 return ExprError();
21610 // Modifying the declaration like this is friendly to IR-gen but
21611 // also really dangerous.
21612 VD
->setType(DestType
);
21614 E
->setValueKind(ValueKind
);
21618 /// Check a cast of an unknown-any type. We intentionally only
21619 /// trigger this for C-style casts.
21620 ExprResult
Sema::checkUnknownAnyCast(SourceRange TypeRange
, QualType CastType
,
21621 Expr
*CastExpr
, CastKind
&CastKind
,
21622 ExprValueKind
&VK
, CXXCastPath
&Path
) {
21623 // The type we're casting to must be either void or complete.
21624 if (!CastType
->isVoidType() &&
21625 RequireCompleteType(TypeRange
.getBegin(), CastType
,
21626 diag::err_typecheck_cast_to_incomplete
))
21627 return ExprError();
21629 // Rewrite the casted expression from scratch.
21630 ExprResult result
= RebuildUnknownAnyExpr(*this, CastType
).Visit(CastExpr
);
21631 if (!result
.isUsable()) return ExprError();
21633 CastExpr
= result
.get();
21634 VK
= CastExpr
->getValueKind();
21635 CastKind
= CK_NoOp
;
21640 ExprResult
Sema::forceUnknownAnyToType(Expr
*E
, QualType ToType
) {
21641 return RebuildUnknownAnyExpr(*this, ToType
).Visit(E
);
21644 ExprResult
Sema::checkUnknownAnyArg(SourceLocation callLoc
,
21645 Expr
*arg
, QualType
¶mType
) {
21646 // If the syntactic form of the argument is not an explicit cast of
21647 // any sort, just do default argument promotion.
21648 ExplicitCastExpr
*castArg
= dyn_cast
<ExplicitCastExpr
>(arg
->IgnoreParens());
21650 ExprResult result
= DefaultArgumentPromotion(arg
);
21651 if (result
.isInvalid()) return ExprError();
21652 paramType
= result
.get()->getType();
21656 // Otherwise, use the type that was written in the explicit cast.
21657 assert(!arg
->hasPlaceholderType());
21658 paramType
= castArg
->getTypeAsWritten();
21660 // Copy-initialize a parameter of that type.
21661 InitializedEntity entity
=
21662 InitializedEntity::InitializeParameter(Context
, paramType
,
21663 /*consumed*/ false);
21664 return PerformCopyInitialization(entity
, callLoc
, arg
);
21667 static ExprResult
diagnoseUnknownAnyExpr(Sema
&S
, Expr
*E
) {
21669 unsigned diagID
= diag::err_uncasted_use_of_unknown_any
;
21671 E
= E
->IgnoreParenImpCasts();
21672 if (CallExpr
*call
= dyn_cast
<CallExpr
>(E
)) {
21673 E
= call
->getCallee();
21674 diagID
= diag::err_uncasted_call_of_unknown_any
;
21680 SourceLocation loc
;
21682 if (DeclRefExpr
*ref
= dyn_cast
<DeclRefExpr
>(E
)) {
21683 loc
= ref
->getLocation();
21684 d
= ref
->getDecl();
21685 } else if (MemberExpr
*mem
= dyn_cast
<MemberExpr
>(E
)) {
21686 loc
= mem
->getMemberLoc();
21687 d
= mem
->getMemberDecl();
21688 } else if (ObjCMessageExpr
*msg
= dyn_cast
<ObjCMessageExpr
>(E
)) {
21689 diagID
= diag::err_uncasted_call_of_unknown_any
;
21690 loc
= msg
->getSelectorStartLoc();
21691 d
= msg
->getMethodDecl();
21693 S
.Diag(loc
, diag::err_uncasted_send_to_unknown_any_method
)
21694 << static_cast<unsigned>(msg
->isClassMessage()) << msg
->getSelector()
21695 << orig
->getSourceRange();
21696 return ExprError();
21699 S
.Diag(E
->getExprLoc(), diag::err_unsupported_unknown_any_expr
)
21700 << E
->getSourceRange();
21701 return ExprError();
21704 S
.Diag(loc
, diagID
) << d
<< orig
->getSourceRange();
21706 // Never recoverable.
21707 return ExprError();
21710 /// Check for operands with placeholder types and complain if found.
21711 /// Returns ExprError() if there was an error and no recovery was possible.
21712 ExprResult
Sema::CheckPlaceholderExpr(Expr
*E
) {
21713 if (!Context
.isDependenceAllowed()) {
21714 // C cannot handle TypoExpr nodes on either side of a binop because it
21715 // doesn't handle dependent types properly, so make sure any TypoExprs have
21716 // been dealt with before checking the operands.
21717 ExprResult Result
= CorrectDelayedTyposInExpr(E
);
21718 if (!Result
.isUsable()) return ExprError();
21722 const BuiltinType
*placeholderType
= E
->getType()->getAsPlaceholderType();
21723 if (!placeholderType
) return E
;
21725 switch (placeholderType
->getKind()) {
21727 // Overloaded expressions.
21728 case BuiltinType::Overload
: {
21729 // Try to resolve a single function template specialization.
21730 // This is obligatory.
21731 ExprResult Result
= E
;
21732 if (ResolveAndFixSingleFunctionTemplateSpecialization(Result
, false))
21735 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
21736 // leaves Result unchanged on failure.
21738 if (resolveAndFixAddressOfSingleOverloadCandidate(Result
))
21741 // If that failed, try to recover with a call.
21742 tryToRecoverWithCall(Result
, PDiag(diag::err_ovl_unresolvable
),
21743 /*complain*/ true);
21747 // Bound member functions.
21748 case BuiltinType::BoundMember
: {
21749 ExprResult result
= E
;
21750 const Expr
*BME
= E
->IgnoreParens();
21751 PartialDiagnostic PD
= PDiag(diag::err_bound_member_function
);
21752 // Try to give a nicer diagnostic if it is a bound member that we recognize.
21753 if (isa
<CXXPseudoDestructorExpr
>(BME
)) {
21754 PD
= PDiag(diag::err_dtor_expr_without_call
) << /*pseudo-destructor*/ 1;
21755 } else if (const auto *ME
= dyn_cast
<MemberExpr
>(BME
)) {
21756 if (ME
->getMemberNameInfo().getName().getNameKind() ==
21757 DeclarationName::CXXDestructorName
)
21758 PD
= PDiag(diag::err_dtor_expr_without_call
) << /*destructor*/ 0;
21760 tryToRecoverWithCall(result
, PD
,
21761 /*complain*/ true);
21765 // ARC unbridged casts.
21766 case BuiltinType::ARCUnbridgedCast
: {
21767 Expr
*realCast
= stripARCUnbridgedCast(E
);
21768 diagnoseARCUnbridgedCast(realCast
);
21772 // Expressions of unknown type.
21773 case BuiltinType::UnknownAny
:
21774 return diagnoseUnknownAnyExpr(*this, E
);
21777 case BuiltinType::PseudoObject
:
21778 return checkPseudoObjectRValue(E
);
21780 case BuiltinType::BuiltinFn
: {
21781 // Accept __noop without parens by implicitly converting it to a call expr.
21782 auto *DRE
= dyn_cast
<DeclRefExpr
>(E
->IgnoreParenImpCasts());
21784 auto *FD
= cast
<FunctionDecl
>(DRE
->getDecl());
21785 unsigned BuiltinID
= FD
->getBuiltinID();
21786 if (BuiltinID
== Builtin::BI__noop
) {
21787 E
= ImpCastExprToType(E
, Context
.getPointerType(FD
->getType()),
21788 CK_BuiltinFnToFnPtr
)
21790 return CallExpr::Create(Context
, E
, /*Args=*/{}, Context
.IntTy
,
21791 VK_PRValue
, SourceLocation(),
21792 FPOptionsOverride());
21795 if (Context
.BuiltinInfo
.isInStdNamespace(BuiltinID
)) {
21796 // Any use of these other than a direct call is ill-formed as of C++20,
21797 // because they are not addressable functions. In earlier language
21798 // modes, warn and force an instantiation of the real body.
21799 Diag(E
->getBeginLoc(),
21800 getLangOpts().CPlusPlus20
21801 ? diag::err_use_of_unaddressable_function
21802 : diag::warn_cxx20_compat_use_of_unaddressable_function
);
21803 if (FD
->isImplicitlyInstantiable()) {
21804 // Require a definition here because a normal attempt at
21805 // instantiation for a builtin will be ignored, and we won't try
21806 // again later. We assume that the definition of the template
21807 // precedes this use.
21808 InstantiateFunctionDefinition(E
->getBeginLoc(), FD
,
21809 /*Recursive=*/false,
21810 /*DefinitionRequired=*/true,
21811 /*AtEndOfTU=*/false);
21813 // Produce a properly-typed reference to the function.
21815 SS
.Adopt(DRE
->getQualifierLoc());
21816 TemplateArgumentListInfo TemplateArgs
;
21817 DRE
->copyTemplateArgumentsInto(TemplateArgs
);
21818 return BuildDeclRefExpr(
21819 FD
, FD
->getType(), VK_LValue
, DRE
->getNameInfo(),
21820 DRE
->hasQualifier() ? &SS
: nullptr, DRE
->getFoundDecl(),
21821 DRE
->getTemplateKeywordLoc(),
21822 DRE
->hasExplicitTemplateArgs() ? &TemplateArgs
: nullptr);
21826 Diag(E
->getBeginLoc(), diag::err_builtin_fn_use
);
21827 return ExprError();
21830 case BuiltinType::IncompleteMatrixIdx
:
21831 Diag(cast
<MatrixSubscriptExpr
>(E
->IgnoreParens())
21834 diag::err_matrix_incomplete_index
);
21835 return ExprError();
21837 // Expressions of unknown type.
21838 case BuiltinType::OMPArraySection
:
21839 Diag(E
->getBeginLoc(), diag::err_omp_array_section_use
);
21840 return ExprError();
21842 // Expressions of unknown type.
21843 case BuiltinType::OMPArrayShaping
:
21844 return ExprError(Diag(E
->getBeginLoc(), diag::err_omp_array_shaping_use
));
21846 case BuiltinType::OMPIterator
:
21847 return ExprError(Diag(E
->getBeginLoc(), diag::err_omp_iterator_use
));
21849 // Everything else should be impossible.
21850 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
21851 case BuiltinType::Id:
21852 #include "clang/Basic/OpenCLImageTypes.def"
21853 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
21854 case BuiltinType::Id:
21855 #include "clang/Basic/OpenCLExtensionTypes.def"
21856 #define SVE_TYPE(Name, Id, SingletonId) \
21857 case BuiltinType::Id:
21858 #include "clang/Basic/AArch64SVEACLETypes.def"
21859 #define PPC_VECTOR_TYPE(Name, Id, Size) \
21860 case BuiltinType::Id:
21861 #include "clang/Basic/PPCTypes.def"
21862 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21863 #include "clang/Basic/RISCVVTypes.def"
21864 #define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
21865 #include "clang/Basic/WebAssemblyReferenceTypes.def"
21866 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
21867 #define PLACEHOLDER_TYPE(Id, SingletonId)
21868 #include "clang/AST/BuiltinTypes.def"
21872 llvm_unreachable("invalid placeholder type!");
21875 bool Sema::CheckCaseExpression(Expr
*E
) {
21876 if (E
->isTypeDependent())
21878 if (E
->isValueDependent() || E
->isIntegerConstantExpr(Context
))
21879 return E
->getType()->isIntegralOrEnumerationType();
21883 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
21885 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc
, tok::TokenKind Kind
) {
21886 assert((Kind
== tok::kw___objc_yes
|| Kind
== tok::kw___objc_no
) &&
21887 "Unknown Objective-C Boolean value!");
21888 QualType BoolT
= Context
.ObjCBuiltinBoolTy
;
21889 if (!Context
.getBOOLDecl()) {
21890 LookupResult
Result(*this, &Context
.Idents
.get("BOOL"), OpLoc
,
21891 Sema::LookupOrdinaryName
);
21892 if (LookupName(Result
, getCurScope()) && Result
.isSingleResult()) {
21893 NamedDecl
*ND
= Result
.getFoundDecl();
21894 if (TypedefDecl
*TD
= dyn_cast
<TypedefDecl
>(ND
))
21895 Context
.setBOOLDecl(TD
);
21898 if (Context
.getBOOLDecl())
21899 BoolT
= Context
.getBOOLType();
21900 return new (Context
)
21901 ObjCBoolLiteralExpr(Kind
== tok::kw___objc_yes
, BoolT
, OpLoc
);
21904 ExprResult
Sema::ActOnObjCAvailabilityCheckExpr(
21905 llvm::ArrayRef
<AvailabilitySpec
> AvailSpecs
, SourceLocation AtLoc
,
21906 SourceLocation RParen
) {
21907 auto FindSpecVersion
=
21908 [&](StringRef Platform
) -> std::optional
<VersionTuple
> {
21909 auto Spec
= llvm::find_if(AvailSpecs
, [&](const AvailabilitySpec
&Spec
) {
21910 return Spec
.getPlatform() == Platform
;
21912 // Transcribe the "ios" availability check to "maccatalyst" when compiling
21913 // for "maccatalyst" if "maccatalyst" is not specified.
21914 if (Spec
== AvailSpecs
.end() && Platform
== "maccatalyst") {
21915 Spec
= llvm::find_if(AvailSpecs
, [&](const AvailabilitySpec
&Spec
) {
21916 return Spec
.getPlatform() == "ios";
21919 if (Spec
== AvailSpecs
.end())
21920 return std::nullopt
;
21921 return Spec
->getVersion();
21924 VersionTuple Version
;
21925 if (auto MaybeVersion
=
21926 FindSpecVersion(Context
.getTargetInfo().getPlatformName()))
21927 Version
= *MaybeVersion
;
21929 // The use of `@available` in the enclosing context should be analyzed to
21930 // warn when it's used inappropriately (i.e. not if(@available)).
21931 if (FunctionScopeInfo
*Context
= getCurFunctionAvailabilityContext())
21932 Context
->HasPotentialAvailabilityViolations
= true;
21934 return new (Context
)
21935 ObjCAvailabilityCheckExpr(Version
, AtLoc
, RParen
, Context
.BoolTy
);
21938 ExprResult
Sema::CreateRecoveryExpr(SourceLocation Begin
, SourceLocation End
,
21939 ArrayRef
<Expr
*> SubExprs
, QualType T
) {
21940 if (!Context
.getLangOpts().RecoveryAST
)
21941 return ExprError();
21943 if (isSFINAEContext())
21944 return ExprError();
21946 if (T
.isNull() || T
->isUndeducedType() ||
21947 !Context
.getLangOpts().RecoveryASTType
)
21948 // We don't know the concrete type, fallback to dependent type.
21949 T
= Context
.DependentTy
;
21951 return RecoveryExpr::Create(Context
, T
, Begin
, End
, SubExprs
);